@meghjs/cli 0.5.3 → 0.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/generators/auth-files.d.ts +37 -0
- package/dist/generators/auth-files.js +198 -0
- package/dist/generators/auth.d.ts +26 -0
- package/dist/generators/auth.js +542 -0
- package/dist/generators/make.d.ts +8 -0
- package/dist/generators/make.js +12 -0
- package/dist/generators/migration-schema.d.ts +5 -0
- package/dist/generators/migration-schema.js +17 -0
- package/dist/generators/scaffold.d.ts +76 -0
- package/dist/generators/scaffold.js +353 -0
- package/dist/program.js +125 -3
- package/dist/templates/cascade.d.ts +37 -0
- package/dist/templates/cascade.js +87 -0
- package/dist/templates/catalog/common.d.ts +1 -0
- package/dist/templates/catalog/common.js +63 -0
- package/dist/templates/catalog/construction.d.ts +1 -0
- package/dist/templates/catalog/construction.js +138 -0
- package/dist/templates/catalog/crm.d.ts +1 -0
- package/dist/templates/catalog/crm.js +81 -0
- package/dist/templates/catalog/ecommerce.d.ts +1 -0
- package/dist/templates/catalog/ecommerce.js +143 -0
- package/dist/templates/catalog/education.d.ts +1 -0
- package/dist/templates/catalog/education.js +80 -0
- package/dist/templates/catalog/hr.d.ts +1 -0
- package/dist/templates/catalog/hr.js +83 -0
- package/dist/templates/catalog/logistics.d.ts +1 -0
- package/dist/templates/catalog/logistics.js +60 -0
- package/dist/templates/catalog/marketing.d.ts +1 -0
- package/dist/templates/catalog/marketing.js +104 -0
- package/dist/templates/catalog/medical.d.ts +1 -0
- package/dist/templates/catalog/medical.js +147 -0
- package/dist/templates/catalog/pos.d.ts +1 -0
- package/dist/templates/catalog/pos.js +110 -0
- package/dist/templates/catalog/real-estate.d.ts +1 -0
- package/dist/templates/catalog/real-estate.js +171 -0
- package/dist/templates/fields.d.ts +64 -0
- package/dist/templates/fields.js +331 -0
- package/dist/templates/index.d.ts +27 -0
- package/dist/templates/index.js +175 -0
- package/dist/templates/migration.d.ts +7 -0
- package/dist/templates/migration.js +80 -0
- package/dist/templates/template.d.ts +37 -0
- package/dist/templates/template.js +36 -0
- package/dist/utils/dialect.d.ts +8 -0
- package/dist/utils/dialect.js +57 -0
- package/package.json +17 -5
- package/readme.md +26 -1
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Source of the files `scaffold:auth` and `scaffold:rbac` write. Each renderer
|
|
3
|
+
* gets the plan (strategy, role mode, permissions) and the columns the
|
|
4
|
+
* users table ends up with, so the code only uses columns that exist.
|
|
5
|
+
*/
|
|
6
|
+
export type AuthStrategy = "jwt" | "api-key" | "both";
|
|
7
|
+
export type RoleMode = "none" | "single" | "multiple";
|
|
8
|
+
export interface AuthPlan {
|
|
9
|
+
/** Undefined for `scaffold:rbac` (no sign-in endpoints). */
|
|
10
|
+
strategy?: AuthStrategy;
|
|
11
|
+
roles: RoleMode;
|
|
12
|
+
permissions: boolean;
|
|
13
|
+
/** Columns of the users table. */
|
|
14
|
+
userColumns: Set<string>;
|
|
15
|
+
}
|
|
16
|
+
/** The choices alone, before the users table is known. */
|
|
17
|
+
export type AuthChoice = Omit<AuthPlan, "userColumns">;
|
|
18
|
+
export declare const usesJwt: (p: AuthChoice) => boolean;
|
|
19
|
+
export declare const usesApiKeys: (p: AuthChoice) => boolean;
|
|
20
|
+
export declare const usesRoles: (p: AuthChoice) => boolean;
|
|
21
|
+
/** Import paths between the generated files, relative to each file. */
|
|
22
|
+
export interface Paths {
|
|
23
|
+
/** From `src/auth/` to `src/models/`, etc. */
|
|
24
|
+
rel(from: string, to: string): string;
|
|
25
|
+
}
|
|
26
|
+
/** The relation path `authenticate` eager loads: `roles.permissions`, `role`, … */
|
|
27
|
+
export declare function rolesRelation(plan: AuthPlan): string | undefined;
|
|
28
|
+
export declare function renderPassword(): string;
|
|
29
|
+
export declare function renderJwt(): string;
|
|
30
|
+
export declare function renderApiKeys(): string;
|
|
31
|
+
export declare function renderAuthentication(plan: AuthPlan, p: Paths): string;
|
|
32
|
+
export declare function renderAuthorization(plan: AuthPlan, p: Paths): string;
|
|
33
|
+
export declare function renderRbac(plan: AuthPlan, p: Paths): string;
|
|
34
|
+
export declare function renderRolesSeeder(plan: AuthPlan, p: Paths, seederFile: string): string;
|
|
35
|
+
export declare function renderAuthDto(plan: AuthPlan): string;
|
|
36
|
+
export declare function renderAuthService(plan: AuthPlan, p: Paths): string;
|
|
37
|
+
export declare function renderAuthController(plan: AuthPlan, p: Paths): string;
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Source of the files `scaffold:auth` and `scaffold:rbac` write. Each renderer
|
|
4
|
+
* gets the plan (strategy, role mode, permissions) and the columns the
|
|
5
|
+
* users table ends up with, so the code only uses columns that exist.
|
|
6
|
+
*/
|
|
7
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
8
|
+
exports.usesRoles = exports.usesApiKeys = exports.usesJwt = void 0;
|
|
9
|
+
exports.rolesRelation = rolesRelation;
|
|
10
|
+
exports.renderPassword = renderPassword;
|
|
11
|
+
exports.renderJwt = renderJwt;
|
|
12
|
+
exports.renderApiKeys = renderApiKeys;
|
|
13
|
+
exports.renderAuthentication = renderAuthentication;
|
|
14
|
+
exports.renderAuthorization = renderAuthorization;
|
|
15
|
+
exports.renderRbac = renderRbac;
|
|
16
|
+
exports.renderRolesSeeder = renderRolesSeeder;
|
|
17
|
+
exports.renderAuthDto = renderAuthDto;
|
|
18
|
+
exports.renderAuthService = renderAuthService;
|
|
19
|
+
exports.renderAuthController = renderAuthController;
|
|
20
|
+
const usesJwt = (p) => p.strategy === "jwt" || p.strategy === "both";
|
|
21
|
+
exports.usesJwt = usesJwt;
|
|
22
|
+
const usesApiKeys = (p) => p.strategy === "api-key" || p.strategy === "both";
|
|
23
|
+
exports.usesApiKeys = usesApiKeys;
|
|
24
|
+
const usesRoles = (p) => p.roles !== "none";
|
|
25
|
+
exports.usesRoles = usesRoles;
|
|
26
|
+
/** The relation path `authenticate` eager loads: `roles.permissions`, `role`, … */
|
|
27
|
+
function rolesRelation(plan) {
|
|
28
|
+
if (!(0, exports.usesRoles)(plan))
|
|
29
|
+
return undefined;
|
|
30
|
+
const base = plan.roles === "single" ? "role" : "roles";
|
|
31
|
+
return plan.permissions ? `${base}.permissions` : base;
|
|
32
|
+
}
|
|
33
|
+
const lines = (...parts) => parts.filter((p) => typeof p === "string").join("\n");
|
|
34
|
+
function renderPassword() {
|
|
35
|
+
return `import { randomBytes, scrypt, timingSafeEqual } from "crypto";
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Password hashing with scrypt (built into Node.js). Hashes are stored as
|
|
39
|
+
* \`scrypt$<salt>$<hash>\` in hex.
|
|
40
|
+
*/
|
|
41
|
+
|
|
42
|
+
const KEY_LENGTH = 64;
|
|
43
|
+
|
|
44
|
+
function derive(password: string, salt: Buffer, length: number): Promise<Buffer> {
|
|
45
|
+
return new Promise((resolve, reject) => {
|
|
46
|
+
scrypt(password, salt, length, (err, key) => (err ? reject(err) : resolve(key)));
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function hashPassword(password: string): Promise<string> {
|
|
51
|
+
const salt = randomBytes(16);
|
|
52
|
+
const hash = await derive(password, salt, KEY_LENGTH);
|
|
53
|
+
return \`scrypt$\${salt.toString("hex")}$\${hash.toString("hex")}\`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Whether \`password\` matches a hash from hashPassword(), in constant time. */
|
|
57
|
+
export async function verifyPassword(password: string, stored: string | null | undefined): Promise<boolean> {
|
|
58
|
+
const [scheme, salt, hash] = (stored ?? "").split("$");
|
|
59
|
+
if (scheme !== "scrypt" || !salt || !hash) return false;
|
|
60
|
+
const expected = Buffer.from(hash, "hex");
|
|
61
|
+
const actual = await derive(password, Buffer.from(salt, "hex"), expected.length);
|
|
62
|
+
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
63
|
+
}
|
|
64
|
+
`;
|
|
65
|
+
}
|
|
66
|
+
function renderJwt() {
|
|
67
|
+
return `import { sign, verify, type SignOptions } from "jsonwebtoken";
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* HS256 access tokens signed with JWT_SECRET, valid for JWT_EXPIRES_IN
|
|
71
|
+
* (default "1d"). Both are read from .env.
|
|
72
|
+
*/
|
|
73
|
+
|
|
74
|
+
function secret(): string {
|
|
75
|
+
const value = process.env.JWT_SECRET;
|
|
76
|
+
if (!value || value.length < 32) {
|
|
77
|
+
throw new Error("Set JWT_SECRET in .env to a random string of at least 32 characters.");
|
|
78
|
+
}
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function tokenLifetime(): string {
|
|
83
|
+
return process.env.JWT_EXPIRES_IN || "1d";
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function signToken(userId: number): string {
|
|
87
|
+
return sign({}, secret(), {
|
|
88
|
+
algorithm: "HS256",
|
|
89
|
+
subject: String(userId),
|
|
90
|
+
expiresIn: tokenLifetime() as SignOptions["expiresIn"],
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The user id of a valid, unexpired token, or null. */
|
|
95
|
+
export function verifyToken(token: string): number | null {
|
|
96
|
+
const key = secret();
|
|
97
|
+
try {
|
|
98
|
+
const payload = verify(token, key, { algorithms: ["HS256"] });
|
|
99
|
+
const id = typeof payload === "object" ? Number(payload.sub) : NaN;
|
|
100
|
+
return Number.isInteger(id) ? id : null;
|
|
101
|
+
} catch {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
`;
|
|
106
|
+
}
|
|
107
|
+
function renderApiKeys() {
|
|
108
|
+
return `import { createHash, randomBytes } from "crypto";
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* API keys: \`mk_\` and 43 random characters. Only the SHA-256 hash is stored,
|
|
112
|
+
* so a key can be shown once, when it is created.
|
|
113
|
+
*/
|
|
114
|
+
|
|
115
|
+
/** Request header carrying the key (lower-case, as Node reads headers). */
|
|
116
|
+
export const API_KEY_HEADER = "x-api-key";
|
|
117
|
+
|
|
118
|
+
export function generateApiKey(): { key: string; prefix: string; hash: string } {
|
|
119
|
+
const key = \`mk_\${randomBytes(32).toString("base64url")}\`;
|
|
120
|
+
return { key, prefix: key.slice(0, 11), hash: hashApiKey(key) };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function hashApiKey(key: string): string {
|
|
124
|
+
return createHash("sha256").update(key).digest("hex");
|
|
125
|
+
}
|
|
126
|
+
`;
|
|
127
|
+
}
|
|
128
|
+
function renderAuthentication(plan, p) {
|
|
129
|
+
const file = "src/auth/authentication.ts";
|
|
130
|
+
const relation = rolesRelation(plan);
|
|
131
|
+
const query = relation ? `User.with(${JSON.stringify(relation)}).where("id", id).first()` : `User.where("id", id).first()`;
|
|
132
|
+
const active = plan.userColumns.has("is_active");
|
|
133
|
+
const how = [(0, exports.usesJwt)(plan) && "an `Authorization: Bearer <token>` header", (0, exports.usesApiKeys)(plan) && "an `X-API-Key` header"]
|
|
134
|
+
.filter(Boolean)
|
|
135
|
+
.join(" or ");
|
|
136
|
+
return lines(`import { AppService, MeghAuthentication, type IRequest, type Row } from "@meghjs/core";`, `import { User } from "${p.rel(file, "src/models/user.model.ts")}";`, (0, exports.usesApiKeys)(plan) && `import { ApiKey } from "${p.rel(file, "src/models/api-key.model.ts")}";`, (0, exports.usesApiKeys)(plan) && `import { API_KEY_HEADER, hashApiKey } from "./api-keys";`, (0, exports.usesJwt)(plan) && `import { verifyToken } from "./jwt";`, ``, `/**`, ` * Who is calling: ${how}. The user it returns becomes \`request.user\``, ` * (\`@AuthUser()\` in controllers)${relation ? `, with \`${relation}\` loaded` : ""}. Registered with`, ` * app.useAuthentication(AppAuthentication).`, ` */`, `@AppService`, `export class AppAuthentication extends MeghAuthentication<Row<User>> {`, ` async authenticate(request: IRequest): Promise<Row<User> | null> {`, (0, exports.usesJwt)(plan) &&
|
|
137
|
+
lines(` const header = request.headers.authorization;`, ` if (typeof header === "string" && header.startsWith("Bearer ")) {`, ` const id = verifyToken(header.slice(7).trim());`, ` return id === null ? null : this.findUser(id);`, ` }`), (0, exports.usesApiKeys)(plan) &&
|
|
138
|
+
lines(``, ` const key = request.headers[API_KEY_HEADER];`, ` if (typeof key === "string" && key !== "") {`, ` const record = await ApiKey.findBy("key_hash", hashApiKey(key));`, ` if (!record || record.revoked_at || (record.expires_at && record.expires_at <= new Date())) return null;`, ` record.last_used_at = new Date();`, ` await record.save();`, ` return this.findUser(record.user_id);`, ` }`), ` return null;`, ` }`, ``, ` private async findUser(id: number): Promise<Row<User> | null> {`, ` const user = await ${query};`, active ? ` return user && user.is_active !== false ? user : null;` : ` return user ?? null;`, ` }`, `}`, ``);
|
|
139
|
+
}
|
|
140
|
+
function renderAuthorization(plan, p) {
|
|
141
|
+
const file = "src/auth/authorization.ts";
|
|
142
|
+
const roles = (0, exports.usesRoles)(plan);
|
|
143
|
+
return lines(`import { CanAuthorize, UnauthorizedException, type IRequest, type Row } from "@meghjs/core";`, `import type { User } from "${p.rel(file, "src/models/user.model.ts")}";`, roles && `import { ${plan.permissions ? "hasPermission, hasRole" : "hasRole"} } from "./rbac";`, ``, `export type AuthorizeOptions = {`, roles && ` /** Any of these roles (slug or name). */`, roles && ` roles?: string[];`, plan.permissions && ` /** Any of these permissions. */`, plan.permissions && ` permissions?: string[];`, `};`, ``, `/**`, ` * \`@Authorized()\`: the caller must be signed in (401 otherwise).`, roles && ` * \`@Authorized({ roles: ["admin"] })\`: and have one of these roles (403 otherwise).`, plan.permissions && ` * \`@Authorized({ permissions: ["users.manage"] })\`: and one of these permissions.`, ` * Registered with app.useAuthorization(AppAuthorization).`, ` */`, `@CanAuthorize`, `export class AppAuthorization {`, ` async authorize(request: IRequest, options: AuthorizeOptions = {}): Promise<boolean> {`, ` const user = request.user as Row<User> | undefined;`, ` if (!user) throw new UnauthorizedException("Sign in to continue.");`, roles && ` if (options.roles?.length && !(await hasRole(user, options.roles))) return false;`, plan.permissions &&
|
|
144
|
+
` if (options.permissions?.length && !(await hasPermission(user, options.permissions))) return false;`, roles ? ` return true;` : lines(` void options;`, ` return true;`), ` }`, `}`, ``);
|
|
145
|
+
}
|
|
146
|
+
function renderRbac(plan, p) {
|
|
147
|
+
const file = "src/auth/rbac.ts";
|
|
148
|
+
const single = plan.roles === "single";
|
|
149
|
+
return lines(`import type { Row } from "@meghjs/core";`, `import { Role } from "${p.rel(file, "src/models/role.model.ts")}";`, plan.permissions && `import type { Permission } from "${p.rel(file, "src/models/permission.model.ts")}";`, `import type { User } from "${p.rel(file, "src/models/user.model.ts")}";`, ``, `/**`, single
|
|
150
|
+
? ` * Role checks. Each user has at most one role (users.role_id).`
|
|
151
|
+
: ` * Role checks. A user has any number of roles (the user_roles table).`, plan.permissions && ` * Roles grant permissions (the role_permissions table).`, ` * Relations loaded by AppAuthentication are used as they are; otherwise they are queried.`, ` */`, ``, `/** The user's roles. */`, `export async function rolesOf(user: Row<User>): Promise<Row<Role>[]> {`, single
|
|
152
|
+
? lines(` const loaded: unknown = (user as { role?: unknown }).role;`, ` if (loaded && typeof loaded === "object") return [loaded as Row<Role>];`, ` if (user.role_id == null) return [];`, ` const role = await Role.find(user.role_id);`, ` return role ? [role] : [];`)
|
|
153
|
+
: lines(` const loaded: unknown = (user as { roles?: unknown }).roles;`, ` if (Array.isArray(loaded)) return loaded as Row<Role>[];`, ` return user.related("roles").get();`), `}`, ``, `/** Whether the user has any of these roles (slug or name). */`, `export async function hasRole(user: Row<User>, roles: string[]): Promise<boolean> {`, ` return (await rolesOf(user)).some((role) => roles.includes(role.slug) || roles.includes(role.name));`, `}`, plan.permissions &&
|
|
154
|
+
lines(``, `/** Names of the permissions the user's roles grant. */`, `export async function permissionsOf(user: Row<User>): Promise<string[]> {`, ` const names = new Set<string>();`, ` for (const role of await rolesOf(user)) {`, ` const loaded: unknown = (role as { permissions?: unknown }).permissions;`, ` const permissions = Array.isArray(loaded)`, ` ? (loaded as Row<Permission>[])`, ` : await role.related("permissions").get();`, ` for (const permission of permissions) names.add(permission.name);`, ` }`, ` return [...names];`, `}`, ``, `/** Whether the user's roles grant any of these permissions. */`, `export async function hasPermission(user: Row<User>, permissions: string[]): Promise<boolean> {`, ` const granted = await permissionsOf(user);`, ` return permissions.some((name) => granted.includes(name));`, `}`), ``, single
|
|
155
|
+
? `/** Give the user the role with this slug (replacing its role). False if there is no such role. */`
|
|
156
|
+
: `/** Give the user the role with this slug. False if there is no such role. */`, `export async function assignRole(user: Row<User>, slug: string): Promise<boolean> {`, ` const role = await Role.findBy("slug", slug);`, ` if (!role) return false;`, single
|
|
157
|
+
? lines(` user.role_id = role.id!;`, ` await user.save();`)
|
|
158
|
+
: lines(` const current = await user.related("roles").get();`, ` if (!current.some((r) => r.id === role.id)) await user.related("roles").attach(role);`), ` return true;`, `}`, ``);
|
|
159
|
+
}
|
|
160
|
+
function renderRolesSeeder(plan, p, seederFile) {
|
|
161
|
+
return lines(`import { defineSeeder } from "@meghjs/core";`, plan.permissions && `import { Permission } from "${p.rel(seederFile, "src/models/permission.model.ts")}";`, `import { Role } from "${p.rel(seederFile, "src/models/role.model.ts")}";`, ``, `/** The roles (and permissions) the app starts with. Safe to run again. */`, `const ROLES = [`, ` { name: "Admin", slug: "admin", description: "Full access" },`, ` { name: "User", slug: "user", description: "A signed-up user" },`, `];`, plan.permissions &&
|
|
162
|
+
lines(``, `/** Permissions per role slug. Check them with @Authorized({ permissions: [...] }). */`, `const PERMISSIONS: Record<string, string[]> = {`, ` admin: ["users.view", "users.manage", "roles.manage"],`, ` user: [],`, `};`), ``, `export default defineSeeder({`, ` async run() {`, ` for (const data of ROLES) {`, plan.permissions
|
|
163
|
+
? ` const role = (await Role.findBy("slug", data.slug)) ?? (await Role.create(data));`
|
|
164
|
+
: lines(` if (await Role.findBy("slug", data.slug)) continue;`, ` await Role.create(data);`), plan.permissions &&
|
|
165
|
+
lines(` const granted = await role.related("permissions").get();`, ` for (const name of PERMISSIONS[data.slug] ?? []) {`, ` const permission =`, ` (await Permission.findBy("name", name)) ??`, ` (await Permission.create({ name, group: name.split(".")[0], description: null }));`, ` if (!granted.some((p) => p.id === permission.id)) await role.related("permissions").attach(permission);`, ` }`), ` }`, ` },`, `});`, ``);
|
|
166
|
+
}
|
|
167
|
+
function renderAuthDto(plan) {
|
|
168
|
+
const api = (0, exports.usesApiKeys)(plan);
|
|
169
|
+
const name = plan.userColumns.has("name");
|
|
170
|
+
const validators = ["IsEmail", "IsString", "MaxLength", "MinLength", ...(api ? ["IsDate", "IsOptional"] : [])].sort();
|
|
171
|
+
return lines(api && `import { Type } from "class-transformer";`, `import { ${validators.join(", ")} } from "class-validator";`, ``, `/** \`POST /auth/register\` */`, `export class RegisterDto {`, name && lines(` @IsString()`, ` @MaxLength(255)`, ` name!: string;`, ``), ` @IsEmail()`, ` @MaxLength(255)`, ` email!: string;`, ``, ` @IsString()`, ` @MinLength(8)`, ` @MaxLength(128)`, ` password!: string;`, `}`, ``, `/** \`POST /auth/login\` */`, `export class LoginDto {`, ` @IsEmail()`, ` email!: string;`, ``, ` @IsString()`, ` password!: string;`, `}`, api &&
|
|
172
|
+
lines(``, `/** \`POST /auth/api-keys\` */`, `export class CreateApiKeyDto {`, ` @IsString()`, ` @MaxLength(100)`, ` name!: string;`, ``, ` @IsOptional()`, ` @Type(() => Date)`, ` @IsDate()`, ` expires_at?: Date;`, `}`), ``);
|
|
173
|
+
}
|
|
174
|
+
function renderAuthService(plan, p) {
|
|
175
|
+
const file = "src/services/auth.service.ts";
|
|
176
|
+
const jwt = (0, exports.usesJwt)(plan);
|
|
177
|
+
const api = (0, exports.usesApiKeys)(plan);
|
|
178
|
+
const cols = plan.userColumns;
|
|
179
|
+
const coreImports = ["AppService", "BadRequestException", "UnauthorizedException", ...(api ? ["NotFoundException"] : [])].sort();
|
|
180
|
+
const dtos = ["LoginDto", "RegisterDto", ...(api ? ["CreateApiKeyDto"] : [])].sort();
|
|
181
|
+
const createFields = [cols.has("name") && "name: input.name", "email: input.email", "password: await hashPassword(input.password)"]
|
|
182
|
+
.filter(Boolean)
|
|
183
|
+
.join(", ");
|
|
184
|
+
return lines(`import { ${coreImports.join(", ")}, type Row } from "@meghjs/core";`, `import { User } from "${p.rel(file, "src/models/user.model.ts")}";`, api && `import { ApiKey } from "${p.rel(file, "src/models/api-key.model.ts")}";`, `import { ${dtos.join(", ")} } from "${p.rel(file, "src/dtos/auth.dto.ts")}";`, `import { hashPassword, verifyPassword } from "${p.rel(file, "src/auth/password.ts")}";`, jwt && `import { signToken, tokenLifetime } from "${p.rel(file, "src/auth/jwt.ts")}";`, api && `import { generateApiKey } from "${p.rel(file, "src/auth/api-keys.ts")}";`, (0, exports.usesRoles)(plan) && `import { assignRole } from "${p.rel(file, "src/auth/rbac.ts")}";`, ``, (0, exports.usesRoles)(plan) && `/** Role given to users who register (created by the roles seeder). */`, (0, exports.usesRoles)(plan) && `const DEFAULT_ROLE = "user";`, (0, exports.usesRoles)(plan) && ``, `@AppService`, `export class AuthService {`, ` async register(input: RegisterDto) {`, ` if (await User.findBy("email", input.email)) {`, ` throw new BadRequestException("That email is already registered.");`, ` }`, ` const user = await User.create({ ${createFields} });`, (0, exports.usesRoles)(plan) && ` await assignRole(user, DEFAULT_ROLE);`, ` return this.issue(user);`, ` }`, ``, ` async login(input: LoginDto) {`, ` const user = await User.findBy("email", input.email);`, ` const valid = !!user && (await verifyPassword(input.password, user.password));`, cols.has("is_active")
|
|
185
|
+
? ` if (!user || !valid || user.is_active === false) throw new UnauthorizedException("Invalid email or password.");`
|
|
186
|
+
: ` if (!user || !valid) throw new UnauthorizedException("Invalid email or password.");`, cols.has("last_login_at") && lines(` user.last_login_at = new Date();`, ` await user.save();`), ` return this.issue(user);`, ` }`, ``, jwt
|
|
187
|
+
? lines(` /** A signed-in response: an access token for the Authorization header. */`, ` private async issue(user: Row<User>) {`, ` return { token_type: "Bearer", access_token: signToken(user.id!), expires_in: tokenLifetime(), user };`, ` }`)
|
|
188
|
+
: lines(` /** A signed-in response: a new API key for the X-API-Key header. */`, ` private async issue(user: Row<User>) {`, ` const { key } = await this.createApiKey(user, { name: "login" });`, ` return { api_key: key, user };`, ` }`), api &&
|
|
189
|
+
lines(``, ` listApiKeys(user: Row<User>) {`, ` return ApiKey.where("user_id", user.id!).whereNull("revoked_at").orderBy("id", "desc").get();`, ` }`, ``, ` /** A new key. The key itself is only returned here; the database keeps its hash. */`, ` async createApiKey(user: Row<User>, input: CreateApiKeyDto) {`, ` const { key, prefix, hash } = generateApiKey();`, ` const record = await ApiKey.create({`, ` user_id: user.id!,`, ` name: input.name,`, ` prefix,`, ` key_hash: hash,`, ` expires_at: input.expires_at ?? null,`, ` });`, ` return { ...record.toJSON(), key };`, ` }`, ``, ` async revokeApiKey(user: Row<User>, id: number) {`, ` const record = await ApiKey.where("user_id", user.id!).where("id", id).first();`, ` if (!record || record.revoked_at) throw new NotFoundException("API key not found.");`, ` record.revoked_at = new Date();`, ` await record.save();`, ` return { message: "API key revoked." };`, ` }`), `}`, ``);
|
|
190
|
+
}
|
|
191
|
+
function renderAuthController(plan, p) {
|
|
192
|
+
const file = "src/controllers/auth.controller.ts";
|
|
193
|
+
const api = (0, exports.usesApiKeys)(plan);
|
|
194
|
+
const core = ["ApiController", "AuthUser", "Authorized", "Body", "Get", "Post", ...(api ? ["Delete", "Param"] : [])].sort();
|
|
195
|
+
const dtos = ["LoginDto", "RegisterDto", ...(api ? ["CreateApiKeyDto"] : [])].sort();
|
|
196
|
+
return lines(`import { ${core.join(", ")}, type Row } from "@meghjs/core";`, `import { ${dtos.join(", ")} } from "${p.rel(file, "src/dtos/auth.dto.ts")}";`, `import type { User } from "${p.rel(file, "src/models/user.model.ts")}";`, `import { AuthService } from "${p.rel(file, "src/services/auth.service.ts")}";`, ``, `@ApiController("/auth")`, `export class AuthController {`, ` constructor(private readonly authService: AuthService) {}`, ``, ` @Post("/register")`, ` register(@Body() body: RegisterDto) {`, ` return this.authService.register(body);`, ` }`, ``, ` @Post("/login")`, ` login(@Body() body: LoginDto) {`, ` return this.authService.login(body);`, ` }`, ``, ` @Authorized()`, ` @Get("/me")`, ` me(@AuthUser() user: Row<User>) {`, ` return user;`, ` }`, api &&
|
|
197
|
+
lines(``, ` @Authorized()`, ` @Get("/api-keys")`, ` apiKeys(@AuthUser() user: Row<User>) {`, ` return this.authService.listApiKeys(user);`, ` }`, ``, ` @Authorized()`, ` @Post("/api-keys")`, ` createApiKey(@AuthUser() user: Row<User>, @Body() body: CreateApiKeyDto) {`, ` return this.authService.createApiKey(user, body);`, ` }`, ``, ` @Authorized()`, ` @Delete("/api-keys/:id")`, ` revokeApiKey(@AuthUser() user: Row<User>, @Param("id") id: number) {`, ` return this.authService.revokeApiKey(user, Number(id));`, ` }`), `}`, ``);
|
|
198
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { type AuthPlan, type AuthStrategy, type RoleMode } from "./auth-files";
|
|
2
|
+
export type { AuthStrategy, RoleMode } from "./auth-files";
|
|
3
|
+
export declare const AUTH_STRATEGIES: readonly AuthStrategy[];
|
|
4
|
+
export declare const ROLE_MODES: readonly RoleMode[];
|
|
5
|
+
export type AuthOptions = {
|
|
6
|
+
cwd?: string;
|
|
7
|
+
/** scaffold:auth only. Prompted for when missing in a terminal; default `jwt`. */
|
|
8
|
+
strategy?: string;
|
|
9
|
+
/** Prompted for when missing in a terminal; default `none` for scaffold:auth, `multiple` for scaffold:rbac. */
|
|
10
|
+
roles?: string;
|
|
11
|
+
/** Roles grant permissions. Prompted for when missing in a terminal. */
|
|
12
|
+
permissions?: boolean;
|
|
13
|
+
/** Overwrite generated auth files that already exist. */
|
|
14
|
+
force?: boolean;
|
|
15
|
+
/** Prompt when run in a terminal. */
|
|
16
|
+
interactive?: boolean;
|
|
17
|
+
/** Clock for migration timestamps (tests). */
|
|
18
|
+
now?: Date;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* `scaffold:auth`: sign-up and sign-in with JWTs, API keys or both, and
|
|
22
|
+
* optionally roles (one or many per user) with permissions.
|
|
23
|
+
*/
|
|
24
|
+
export declare function scaffoldAuth(opts?: AuthOptions): Promise<AuthPlan>;
|
|
25
|
+
/** `scaffold:rbac`: roles (and permissions) for an app's users, without sign-in. */
|
|
26
|
+
export declare function scaffoldRbac(opts?: AuthOptions): Promise<AuthPlan>;
|