najm-auth 1.1.41 → 1.1.43

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/index.d.ts CHANGED
@@ -208,7 +208,16 @@ var auth = {
208
208
  passwordChanged: "Password changed successfully",
209
209
  passwordResetSent: "If that email exists, a reset link has been sent",
210
210
  passwordReset: "Password has been reset successfully",
211
+ accountInviteSent: "Invitation sent successfully",
211
212
  tokenRefreshed: "Token refreshed successfully"
213
+ },
214
+ emails: {
215
+ passwordReset: {
216
+ subject: "Reset your password"
217
+ },
218
+ accountInvite: {
219
+ subject: "You've been invited — set up your account"
220
+ }
212
221
  }
213
222
  };
214
223
  var users = {
@@ -301,8 +310,17 @@ declare const AUTH_LOCALES: {
301
310
  passwordChanged: string;
302
311
  passwordResetSent: string;
303
312
  passwordReset: string;
313
+ accountInviteSent: string;
304
314
  tokenRefreshed: string;
305
315
  };
316
+ emails: {
317
+ passwordReset: {
318
+ subject: string;
319
+ };
320
+ accountInvite: {
321
+ subject: string;
322
+ };
323
+ };
306
324
  };
307
325
  users: {
308
326
  errors: {
@@ -920,6 +938,12 @@ declare class TokenService {
920
938
  * without throwing, because logout can still fall back to revoke-all.
921
939
  */
922
940
  private resolveRefreshCookieFamily;
941
+ /**
942
+ * Generate a one-time set-password token (used by both password reset and
943
+ * account invites). Stores the jti in cache so the token can only be used
944
+ * once, with a TTL matching the JWT expiry.
945
+ */
946
+ private generateSetPasswordToken;
923
947
  /**
924
948
  * Generate secure password reset token
925
949
  * Returns both the plain token (to send via email) and userId for identification
@@ -928,6 +952,15 @@ declare class TokenService {
928
952
  token: string;
929
953
  userId: string;
930
954
  }>;
955
+ /**
956
+ * Generate secure account-invite token.
957
+ * Longer expiry (3d) than reset because an invited user may not check
958
+ * their email immediately. Consumed via the same reset-password endpoint.
959
+ */
960
+ generateInviteToken(userId: string): Promise<{
961
+ token: string;
962
+ userId: string;
963
+ }>;
931
964
  /**
932
965
  * Verify password reset token
933
966
  * Returns userId if valid, throws error if expired/invalid
@@ -962,6 +995,12 @@ declare const updateUserDto: z.ZodObject<{
962
995
  inactive: "inactive";
963
996
  }>>>;
964
997
  }, z.core.$strip>;
998
+ declare const inviteUserDto: z.ZodObject<{
999
+ name: z.ZodOptional<z.ZodString>;
1000
+ email: z.ZodString;
1001
+ roleId: z.ZodOptional<z.ZodString>;
1002
+ image: z.ZodOptional<z.ZodNullable<z.ZodString>>;
1003
+ }, z.core.$strip>;
965
1004
  declare const userIdParam: z.ZodObject<{
966
1005
  id: z.ZodString;
967
1006
  }, z.core.$strip>;
@@ -999,6 +1038,7 @@ declare const userListQuery: z.ZodObject<{
999
1038
  }, z.core.$strip>;
1000
1039
  type CreateUserDto = z.infer<typeof createUserDto>;
1001
1040
  type UpdateUserDto = z.infer<typeof updateUserDto>;
1041
+ type InviteUserDto = z.infer<typeof inviteUserDto>;
1002
1042
  type UserIdParam = z.infer<typeof userIdParam>;
1003
1043
  type LoginDto = z.infer<typeof loginDto>;
1004
1044
  type ChangePasswordDto = z.infer<typeof changePasswordDto>;
@@ -1010,6 +1050,19 @@ type UserIdInParam = z.infer<typeof userIdInParam>;
1010
1050
  type AssignRoleParams = z.infer<typeof assignRoleParams>;
1011
1051
  type UserListQuery = z.infer<typeof userListQuery>;
1012
1052
 
1053
+ /**
1054
+ * Identity fields for creating a user behind a person record (parent, student,
1055
+ * teacher, staff…). Role can be given by name (`role`) or id (`roleId`).
1056
+ */
1057
+ type ProvisionUserInput = {
1058
+ id?: string;
1059
+ name?: string;
1060
+ email: string;
1061
+ role?: string;
1062
+ roleId?: string;
1063
+ image?: string | null;
1064
+ status?: 'active' | 'inactive' | 'pending';
1065
+ };
1013
1066
  declare class AuthService {
1014
1067
  private tokenService;
1015
1068
  private userService;
@@ -1028,6 +1081,27 @@ declare class AuthService {
1028
1081
  private getDummyHash;
1029
1082
  warmupPasswordHash(): Promise<void>;
1030
1083
  registerUser(body: CreateUserDto): Promise<SanitizedUser>;
1084
+ /**
1085
+ * Admin-initiated account creation. The user is created with a random,
1086
+ * unusable password (the schema requires one) and then emailed a one-time
1087
+ * link to set their own. They can't log in until they do, since they never
1088
+ * learn the random password.
1089
+ *
1090
+ * Email is best-effort: a send failure logs a warning but never rolls back
1091
+ * account creation (and with the console provider, nothing is actually sent).
1092
+ */
1093
+ inviteUser(body: ProvisionUserInput): Promise<SanitizedUser>;
1094
+ /**
1095
+ * Create a login for a person record. The branch is intentional and is the
1096
+ * single rule callers rely on:
1097
+ * - password provided → set it directly, NO email (seeding / imports)
1098
+ * - no password → random password + emailed set-password invite
1099
+ *
1100
+ * Returns the created (sanitized) user so the caller can link `userId`.
1101
+ */
1102
+ provisionUser(body: ProvisionUserInput & {
1103
+ password?: string | null;
1104
+ }): Promise<SanitizedUser>;
1031
1105
  loginUser(body: LoginDto): Promise<TokenPair & {
1032
1106
  user: SanitizedUser;
1033
1107
  }>;
@@ -1077,6 +1151,7 @@ declare class AuthController {
1077
1151
  loginUser(body: LoginDto): Promise<TokenPair & {
1078
1152
  user: SanitizedUser;
1079
1153
  }>;
1154
+ inviteUser(body: InviteUserDto): Promise<SanitizedUser>;
1080
1155
  refreshTokens(): Promise<TokenPair>;
1081
1156
  logoutUser(userId: string, authorization?: string): Promise<{
1082
1157
  data: any;
@@ -2049,4 +2124,4 @@ declare const authSeed: (config: AuthSeedConfig) => Record<string, SeedEntry>;
2049
2124
  */
2050
2125
  declare function seedAuthData(config: SeedAuthDataConfig): Promise<SeedAuthDataResult>;
2051
2126
 
2052
- export { AUTH_CONFIG, en as AUTH_EN, AUTH_LOCALES, AUTH_MODULE, AUTH_PERMISSIONS, AUTH_ROLE, AUTH_SCHEMA, AUTH_SUPPORTED_LANGUAGES, AUTH_USER, type AssignPermissionDto, type AssignRoleDto, type AssignRoleParams, type AuthConfig, AuthController, AuthGuard, type AuthPluginConfig, AuthQueries, AuthResolver, type AuthSchema, type AuthSeedConfig, AuthService, type AuthUser, Can, CanCreate, CanDelete, CanList, CanRead, CanUpdate, type ChainableGuard, type ChangePasswordDto, type CheckPermissionDto, type ConfiguredOwnership, type ConfirmResetPasswordDto, CookieManager, type CreatePermissionDto, type CreateRoleDto, type CreateTokenDto, type CreateUserDto, type DefineRolesOptions, type EmailParam, EncryptionService, type JwtConfig, type JwtPayload, type LanguageParam, type LoginDto, NewPermission, NewRoleEntity, NewUser, Owned, type OwnedMethods, type OwnershipConfig, type OwnershipProvider, type OwnershipRule, OwnershipToken, type OwnershipTokenOptions, Permission, PermissionController, PermissionGuard, type PermissionIdParam, PermissionRepository, PermissionService, PermissionValidator, Policy, ROLES, ROLE_GROUPS, type RefreshTokenDto, type ResetPasswordDto, type ResourceAccessor, type ResourceGuards, type ResourceGuardsOptions, type RevokeTokenDto, Role, RoleController, RoleEntity, RoleGuard, type RoleIdParam, type RoleInput, RolePermission, RoleRepository, RoleService, type RoleType, RoleValidator, type RunAsUser, type SanitizedUser, ScopeContext, type ScopeResult, type SeedAuthDataConfig, type SeedAuthDataResult, type SeedUserConfig, type SessionCookieData, TOKEN_STATUS, TOKEN_TYPE, type TokenIdParam, type TokenPair, TokenRepository, TokenService, USER_STATUS, type UpdatePermissionDto, type UpdateRoleDto, type UpdateTokenDto, type UpdateUserDto, User, UserController, type UserIdInParam, type UserIdParam, type UserListQuery, UserRepository, UserService, UserValidator, type UserWithPermissions, type VerifyTokenDto, assignPermissionDto, assignRoleDto, assignRoleParams, auth$1 as auth, authSeed, avatarsPath, calculateAge, calculateYearsOfExperience, changePasswordDto, checkPermissionDto, clean, configureOwnership, confirmResetPasswordDto, createPermissionDto, createRoleDto, createTokenDto, createUserDto, defineRoles, emailParam, formatDate, getAuthLocale, getAvatarFile, isAdmin, isAdministrator, isAuth, isEmpty, isFile, isPath, join, languageParam, loginDto, own, parseSchema, permissionIdParam, pickProps, refreshTokenDto, resetPasswordDto, revokeTokenDto, roleIdParam, runAsUser, seedAuthData, tokenIdParam, updatePermissionDto, updateRoleDto, updateTokenDto, updateUserDto, userIdInParam, userIdParam, userListQuery, verifyTokenDto, where };
2127
+ export { AUTH_CONFIG, en as AUTH_EN, AUTH_LOCALES, AUTH_MODULE, AUTH_PERMISSIONS, AUTH_ROLE, AUTH_SCHEMA, AUTH_SUPPORTED_LANGUAGES, AUTH_USER, type AssignPermissionDto, type AssignRoleDto, type AssignRoleParams, type AuthConfig, AuthController, AuthGuard, type AuthPluginConfig, AuthQueries, AuthResolver, type AuthSchema, type AuthSeedConfig, AuthService, type AuthUser, Can, CanCreate, CanDelete, CanList, CanRead, CanUpdate, type ChainableGuard, type ChangePasswordDto, type CheckPermissionDto, type ConfiguredOwnership, type ConfirmResetPasswordDto, CookieManager, type CreatePermissionDto, type CreateRoleDto, type CreateTokenDto, type CreateUserDto, type DefineRolesOptions, type EmailParam, EncryptionService, type InviteUserDto, type JwtConfig, type JwtPayload, type LanguageParam, type LoginDto, NewPermission, NewRoleEntity, NewUser, Owned, type OwnedMethods, type OwnershipConfig, type OwnershipProvider, type OwnershipRule, OwnershipToken, type OwnershipTokenOptions, Permission, PermissionController, PermissionGuard, type PermissionIdParam, PermissionRepository, PermissionService, PermissionValidator, Policy, type ProvisionUserInput, ROLES, ROLE_GROUPS, type RefreshTokenDto, type ResetPasswordDto, type ResourceAccessor, type ResourceGuards, type ResourceGuardsOptions, type RevokeTokenDto, Role, RoleController, RoleEntity, RoleGuard, type RoleIdParam, type RoleInput, RolePermission, RoleRepository, RoleService, type RoleType, RoleValidator, type RunAsUser, type SanitizedUser, ScopeContext, type ScopeResult, type SeedAuthDataConfig, type SeedAuthDataResult, type SeedUserConfig, type SessionCookieData, TOKEN_STATUS, TOKEN_TYPE, type TokenIdParam, type TokenPair, TokenRepository, TokenService, USER_STATUS, type UpdatePermissionDto, type UpdateRoleDto, type UpdateTokenDto, type UpdateUserDto, User, UserController, type UserIdInParam, type UserIdParam, type UserListQuery, UserRepository, UserService, UserValidator, type UserWithPermissions, type VerifyTokenDto, assignPermissionDto, assignRoleDto, assignRoleParams, auth$1 as auth, authSeed, avatarsPath, calculateAge, calculateYearsOfExperience, changePasswordDto, checkPermissionDto, clean, configureOwnership, confirmResetPasswordDto, createPermissionDto, createRoleDto, createTokenDto, createUserDto, defineRoles, emailParam, formatDate, getAuthLocale, getAvatarFile, inviteUserDto, isAdmin, isAdministrator, isAuth, isEmpty, isFile, isPath, join, languageParam, loginDto, own, parseSchema, permissionIdParam, pickProps, refreshTokenDto, resetPasswordDto, revokeTokenDto, roleIdParam, runAsUser, seedAuthData, tokenIdParam, updatePermissionDto, updateRoleDto, updateTokenDto, updateUserDto, userIdInParam, userIdParam, userListQuery, verifyTokenDto, where };
package/dist/index.js CHANGED
@@ -373,15 +373,16 @@ CookieManager = __decorate2([
373
373
  ], CookieManager);
374
374
 
375
375
  // src/auth/AuthController.ts
376
- import { Controller } from "najm-core";
377
- import { Get, Post, ResMsg } from "najm-core";
378
- import { Body, User as User2, Headers } from "najm-core";
376
+ import { Controller as Controller2 } from "najm-core";
377
+ import { Get as Get2, Post as Post2, ResMsg as ResMsg2 } from "najm-core";
378
+ import { Body as Body2, User as User3, Headers } from "najm-core";
379
379
 
380
380
  // src/auth/AuthService.ts
381
381
  import { Injectable as Injectable7, Inject as Inject8 } from "najm-core";
382
382
  import { Err as Err6, Log } from "najm-core";
383
383
  import { I18n as I18n5, I18nService as I18nService2 } from "najm-i18n";
384
- import { EmailService, passwordResetTemplate } from "najm-email";
384
+ import { EmailService, passwordResetTemplate, accountInviteTemplate } from "najm-email";
385
+ import { nanoid as nanoid5 } from "nanoid";
385
386
 
386
387
  // src/users/UserService.ts
387
388
  import { Injectable as Injectable5, Inject as Inject5 } from "najm-core";
@@ -1861,23 +1862,39 @@ var TokenService = class TokenService2 {
1861
1862
  }
1862
1863
  // ============ PASSWORD RESET TOKENS ============
1863
1864
  /**
1864
- * Generate secure password reset token
1865
- * Returns both the plain token (to send via email) and userId for identification
1865
+ * Generate a one-time set-password token (used by both password reset and
1866
+ * account invites). Stores the jti in cache so the token can only be used
1867
+ * once, with a TTL matching the JWT expiry.
1866
1868
  */
1867
- async generateResetToken(userId) {
1869
+ async generateSetPasswordToken(userId, type, expiresIn) {
1868
1870
  const jti = nanoid4(16);
1869
- const resetData = {
1871
+ const data = {
1870
1872
  userId,
1871
- type: "reset",
1873
+ type,
1872
1874
  jti,
1873
1875
  timestamp: Date.now()
1874
1876
  };
1875
- const token = jwt.sign(resetData, this.config.jwt.refreshSecret, {
1876
- expiresIn: "1h"
1877
+ const token = jwt.sign(data, this.config.jwt.refreshSecret, {
1878
+ expiresIn
1877
1879
  });
1878
- await this.cache.set(`${this.resetTokenPrefix}${userId}`, jti, 36e5);
1880
+ await this.cache.set(`${this.resetTokenPrefix}${userId}`, jti, timestring2(expiresIn, "ms"));
1879
1881
  return { token, userId };
1880
1882
  }
1883
+ /**
1884
+ * Generate secure password reset token
1885
+ * Returns both the plain token (to send via email) and userId for identification
1886
+ */
1887
+ async generateResetToken(userId) {
1888
+ return this.generateSetPasswordToken(userId, "reset", "1h");
1889
+ }
1890
+ /**
1891
+ * Generate secure account-invite token.
1892
+ * Longer expiry (3d) than reset because an invited user may not check
1893
+ * their email immediately. Consumed via the same reset-password endpoint.
1894
+ */
1895
+ async generateInviteToken(userId) {
1896
+ return this.generateSetPasswordToken(userId, "invite", "3d");
1897
+ }
1881
1898
  /**
1882
1899
  * Verify password reset token
1883
1900
  * Returns userId if valid, throws error if expired/invalid
@@ -1889,7 +1906,7 @@ var TokenService = class TokenService2 {
1889
1906
  } catch {
1890
1907
  Err5(this.t("errors.resetTokenExpired"));
1891
1908
  }
1892
- if (decoded.type !== "reset" || !decoded.jti) {
1909
+ if (decoded.type !== "reset" && decoded.type !== "invite" || !decoded.jti) {
1893
1910
  Err5(this.t("errors.invalidResetToken"));
1894
1911
  }
1895
1912
  const key = `${this.resetTokenPrefix}${decoded.userId}`;
@@ -1978,6 +1995,64 @@ var AuthService = class AuthService2 {
1978
1995
  async registerUser(body) {
1979
1996
  return await this.userService.create(body);
1980
1997
  }
1998
+ /**
1999
+ * Admin-initiated account creation. The user is created with a random,
2000
+ * unusable password (the schema requires one) and then emailed a one-time
2001
+ * link to set their own. They can't log in until they do, since they never
2002
+ * learn the random password.
2003
+ *
2004
+ * Email is best-effort: a send failure logs a warning but never rolls back
2005
+ * account creation (and with the console provider, nothing is actually sent).
2006
+ */
2007
+ async inviteUser(body) {
2008
+ const randomPassword = `${nanoid5(24)}Aa1!`;
2009
+ const user = await this.userService.create({
2010
+ id: body.id,
2011
+ name: body.name,
2012
+ email: body.email,
2013
+ role: body.role,
2014
+ roleId: body.roleId,
2015
+ image: body.image,
2016
+ password: randomPassword,
2017
+ status: body.status ?? "active",
2018
+ emailVerified: false
2019
+ });
2020
+ const { token } = await this.tokenService.generateInviteToken(user.id);
2021
+ const inviteLink = `${this.config.frontendUrl}/reset-password?token=${token}`;
2022
+ try {
2023
+ await this.emailService.sendHtml(body.email, this.t("emails.accountInvite.subject"), accountInviteTemplate({
2024
+ inviteLink,
2025
+ userName: user.name || body.email
2026
+ }));
2027
+ } catch (error) {
2028
+ this.logger.warn("Account invite email failed", { email: body.email, error });
2029
+ }
2030
+ return user;
2031
+ }
2032
+ /**
2033
+ * Create a login for a person record. The branch is intentional and is the
2034
+ * single rule callers rely on:
2035
+ * - password provided → set it directly, NO email (seeding / imports)
2036
+ * - no password → random password + emailed set-password invite
2037
+ *
2038
+ * Returns the created (sanitized) user so the caller can link `userId`.
2039
+ */
2040
+ async provisionUser(body) {
2041
+ const password = typeof body.password === "string" ? body.password.trim() : "";
2042
+ if (password) {
2043
+ return this.userService.create({
2044
+ id: body.id,
2045
+ name: body.name,
2046
+ email: body.email,
2047
+ role: body.role,
2048
+ roleId: body.roleId,
2049
+ image: body.image,
2050
+ password,
2051
+ status: body.status ?? "active"
2052
+ });
2053
+ }
2054
+ return this.inviteUser(body);
2055
+ }
1981
2056
  async loginUser(body) {
1982
2057
  const { email: email2, password } = body;
1983
2058
  const user = await this.userService.findByEmail(email2);
@@ -2191,78 +2266,309 @@ AuthGuard = __decorate12([
2191
2266
  ], AuthGuard);
2192
2267
  var isAuth = createGuard(AuthGuard);
2193
2268
 
2194
- // src/auth/AuthController.ts
2269
+ // src/roles/index.ts
2270
+ var roles_exports = {};
2271
+ __export(roles_exports, {
2272
+ ROLES: () => ROLES,
2273
+ ROLE_GROUPS: () => ROLE_GROUPS,
2274
+ Role: () => Role,
2275
+ RoleController: () => RoleController,
2276
+ RoleGuard: () => RoleGuard,
2277
+ RoleRepository: () => RoleRepository,
2278
+ RoleService: () => RoleService,
2279
+ RoleValidator: () => RoleValidator,
2280
+ assignRoleDto: () => assignRoleDto,
2281
+ createRoleDto: () => createRoleDto,
2282
+ defineRoles: () => defineRoles,
2283
+ isAdmin: () => isAdmin,
2284
+ isAdministrator: () => isAdministrator,
2285
+ roleIdParam: () => roleIdParam,
2286
+ updateRoleDto: () => updateRoleDto
2287
+ });
2288
+
2289
+ // src/roles/defineRoles.ts
2290
+ import { composeGuards as composeGuards2, createGuard as createGuard3 } from "najm-guard";
2291
+
2292
+ // src/roles/RoleGuards.ts
2293
+ import { Service as Service3 } from "najm-core";
2294
+ import { GuardParams, User as User2 } from "najm-core";
2295
+ import { composeGuards, createGuard as createGuard2 } from "najm-guard";
2296
+ var __decorate13 = function(decorators, target, key, desc) {
2297
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2298
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2299
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2300
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2301
+ };
2302
+ var __metadata13 = function(k, v) {
2303
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
2304
+ };
2305
+ var __param4 = function(paramIndex, decorator) {
2306
+ return function(target, key) {
2307
+ decorator(target, key, paramIndex);
2308
+ };
2309
+ };
2310
+ var RoleGuard = class RoleGuard2 {
2311
+ static {
2312
+ __name(this, "RoleGuard");
2313
+ }
2314
+ canActivate(allowedRoles, userRole) {
2315
+ if (!userRole)
2316
+ return false;
2317
+ const requiredRoles = Array.isArray(allowedRoles) ? allowedRoles : [allowedRoles];
2318
+ const hasRole = requiredRoles.some((r) => r.toLowerCase() === userRole.toLowerCase());
2319
+ if (hasRole) {
2320
+ return { role: userRole };
2321
+ }
2322
+ return false;
2323
+ }
2324
+ };
2325
+ __decorate13([
2326
+ __param4(0, GuardParams()),
2327
+ __param4(1, User2("role")),
2328
+ __metadata13("design:type", Function),
2329
+ __metadata13("design:paramtypes", [Object, String]),
2330
+ __metadata13("design:returntype", void 0)
2331
+ ], RoleGuard.prototype, "canActivate", null);
2332
+ RoleGuard = __decorate13([
2333
+ Service3()
2334
+ ], RoleGuard);
2335
+ var Role = createGuard2(RoleGuard);
2336
+ var isAdmin = composeGuards(isAuth(), Role(ROLES.ADMIN));
2337
+ var isAdministrator = composeGuards(isAuth(), Role(ROLE_GROUPS.ADMINISTRATORS));
2338
+
2339
+ // src/roles/defineRoles.ts
2340
+ var Role2 = createGuard3(RoleGuard);
2341
+ function defineRoles(roles, options) {
2342
+ const ROLES2 = roles;
2343
+ const superRoleKeys = options?.superRoles ?? [];
2344
+ function resolveRoleValues(keys) {
2345
+ return Array.from(new Set([...keys, ...superRoleKeys].map((key) => roles[key])));
2346
+ }
2347
+ __name(resolveRoleValues, "resolveRoleValues");
2348
+ const guards2 = {};
2349
+ for (const [key, value] of Object.entries(roles)) {
2350
+ const name = `is${key.charAt(0).toUpperCase()}${key.slice(1).toLowerCase()}`;
2351
+ const allowedValues = resolveRoleValues([key]);
2352
+ guards2[name] = composeGuards2(isAuth(), Role2(allowedValues.length === 1 ? value : allowedValues));
2353
+ }
2354
+ function createGroupGuard(keys) {
2355
+ const values = resolveRoleValues(keys);
2356
+ return composeGuards2(isAuth(), Role2(values));
2357
+ }
2358
+ __name(createGroupGuard, "createGroupGuard");
2359
+ function hasRole(userRole, ...keys) {
2360
+ if (!userRole)
2361
+ return false;
2362
+ const normalized = userRole.toLowerCase();
2363
+ return resolveRoleValues(keys).some((role) => role === normalized);
2364
+ }
2365
+ __name(hasRole, "hasRole");
2366
+ function isInGroup(userRole, keys) {
2367
+ return hasRole(userRole, ...keys);
2368
+ }
2369
+ __name(isInGroup, "isInGroup");
2370
+ return { ROLES: ROLES2, createGroupGuard, hasRole, isInGroup, ...guards2 };
2371
+ }
2372
+ __name(defineRoles, "defineRoles");
2373
+
2374
+ // src/roles/RoleController.ts
2375
+ import { Controller } from "najm-core";
2376
+ import { Get, Post, Put, Delete, ResMsg } from "najm-core";
2377
+ import { Params, Body } from "najm-core";
2195
2378
  import { Validate } from "najm-validation";
2379
+
2380
+ // src/roles/RoleDto.ts
2381
+ import { z } from "zod";
2382
+ var nameField = z.string().min(2, "Name must be at least 2 characters").max(50, "Name too long");
2383
+ var descriptionField = z.string().max(255, "Description too long").optional();
2384
+ var createRoleDto = z.object({
2385
+ name: nameField,
2386
+ description: descriptionField
2387
+ });
2388
+ var updateRoleDto = createRoleDto.partial();
2389
+ var roleIdParam = z.object({
2390
+ id: z.string().length(5, "Role ID must be 5 characters")
2391
+ });
2392
+ var assignRoleDto = z.object({
2393
+ userId: z.string().length(8, "User ID must be 8 characters"),
2394
+ roleId: z.string().length(5, "Role ID must be 5 characters")
2395
+ });
2396
+
2397
+ // src/roles/RoleController.ts
2398
+ var __decorate14 = function(decorators, target, key, desc) {
2399
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2400
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2401
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2402
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2403
+ };
2404
+ var __metadata14 = function(k, v) {
2405
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
2406
+ };
2407
+ var __param5 = function(paramIndex, decorator) {
2408
+ return function(target, key) {
2409
+ decorator(target, key, paramIndex);
2410
+ };
2411
+ };
2412
+ var _a8;
2413
+ var RoleController = class RoleController2 {
2414
+ static {
2415
+ __name(this, "RoleController");
2416
+ }
2417
+ roleService;
2418
+ constructor(roleService) {
2419
+ this.roleService = roleService;
2420
+ }
2421
+ async getRoles() {
2422
+ return this.roleService.getAll();
2423
+ }
2424
+ async getRole(params) {
2425
+ return this.roleService.getById(params.id);
2426
+ }
2427
+ async createRole(body) {
2428
+ return this.roleService.create(body);
2429
+ }
2430
+ async updateRole(params, body) {
2431
+ return this.roleService.update(params.id, body);
2432
+ }
2433
+ async deleteRole(params) {
2434
+ return this.roleService.delete(params.id);
2435
+ }
2436
+ };
2437
+ __decorate14([
2438
+ Get(),
2439
+ isAdmin(),
2440
+ ResMsg("roles.success.retrieved"),
2441
+ __metadata14("design:type", Function),
2442
+ __metadata14("design:paramtypes", []),
2443
+ __metadata14("design:returntype", Promise)
2444
+ ], RoleController.prototype, "getRoles", null);
2445
+ __decorate14([
2446
+ Get("/:id"),
2447
+ isAdmin(),
2448
+ Validate({ params: roleIdParam }),
2449
+ ResMsg("roles.success.retrieved"),
2450
+ __param5(0, Params()),
2451
+ __metadata14("design:type", Function),
2452
+ __metadata14("design:paramtypes", [Object]),
2453
+ __metadata14("design:returntype", Promise)
2454
+ ], RoleController.prototype, "getRole", null);
2455
+ __decorate14([
2456
+ Post(),
2457
+ isAdmin(),
2458
+ Validate(createRoleDto),
2459
+ ResMsg("roles.success.created"),
2460
+ __param5(0, Body()),
2461
+ __metadata14("design:type", Function),
2462
+ __metadata14("design:paramtypes", [Object]),
2463
+ __metadata14("design:returntype", Promise)
2464
+ ], RoleController.prototype, "createRole", null);
2465
+ __decorate14([
2466
+ Put("/:id"),
2467
+ isAdmin(),
2468
+ Validate({
2469
+ params: roleIdParam,
2470
+ body: updateRoleDto
2471
+ }),
2472
+ ResMsg("roles.success.updated"),
2473
+ __param5(0, Params()),
2474
+ __param5(1, Body()),
2475
+ __metadata14("design:type", Function),
2476
+ __metadata14("design:paramtypes", [Object, Object]),
2477
+ __metadata14("design:returntype", Promise)
2478
+ ], RoleController.prototype, "updateRole", null);
2479
+ __decorate14([
2480
+ Delete("/:id"),
2481
+ isAdmin(),
2482
+ Validate({ params: roleIdParam }),
2483
+ ResMsg("roles.success.deleted"),
2484
+ __param5(0, Params()),
2485
+ __metadata14("design:type", Function),
2486
+ __metadata14("design:paramtypes", [Object]),
2487
+ __metadata14("design:returntype", Promise)
2488
+ ], RoleController.prototype, "deleteRole", null);
2489
+ RoleController = __decorate14([
2490
+ Controller("/roles"),
2491
+ __metadata14("design:paramtypes", [typeof (_a8 = typeof RoleService !== "undefined" && RoleService) === "function" ? _a8 : Object])
2492
+ ], RoleController);
2493
+
2494
+ // src/auth/AuthController.ts
2495
+ import { Validate as Validate2 } from "najm-validation";
2196
2496
  import { RateLimit } from "najm-rate";
2197
2497
  import { createHash as createHash2 } from "crypto";
2198
2498
 
2199
2499
  // src/users/UserDto.ts
2200
- import { z } from "zod";
2201
- var emailField = z.string().email("Invalid email format");
2202
- var passwordField = z.string().min(8, "Password must be at least 8 characters");
2203
- var optionalDateField = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Date must be in YYYY-MM-DD format").nullable().optional();
2204
- var createUserDto = z.object({
2205
- name: z.string().max(100).optional(),
2500
+ import { z as z2 } from "zod";
2501
+ var emailField = z2.string().email("Invalid email format");
2502
+ var passwordField = z2.string().min(8, "Password must be at least 8 characters");
2503
+ var optionalDateField = z2.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Date must be in YYYY-MM-DD format").nullable().optional();
2504
+ var createUserDto = z2.object({
2505
+ name: z2.string().max(100).optional(),
2206
2506
  email: emailField,
2207
2507
  password: passwordField,
2208
- roleId: z.string().min(1).optional(),
2209
- image: z.string().nullish(),
2210
- emailVerified: z.boolean().default(false),
2211
- status: z.enum(["active", "inactive", "pending"]).optional()
2508
+ roleId: z2.string().min(1).optional(),
2509
+ image: z2.string().nullish(),
2510
+ emailVerified: z2.boolean().default(false),
2511
+ status: z2.enum(["active", "inactive", "pending"]).optional()
2212
2512
  });
2213
2513
  var updateUserDto = createUserDto.partial();
2214
- var userIdParam = z.object({
2215
- id: z.string().min(1, "User ID is required")
2514
+ var inviteUserDto = z2.object({
2515
+ name: z2.string().max(100).optional(),
2516
+ email: emailField,
2517
+ roleId: z2.string().min(1).optional(),
2518
+ image: z2.string().nullish()
2216
2519
  });
2217
- var loginDto = z.object({
2520
+ var userIdParam = z2.object({
2521
+ id: z2.string().min(1, "User ID is required")
2522
+ });
2523
+ var loginDto = z2.object({
2218
2524
  email: emailField,
2219
2525
  password: passwordField
2220
2526
  });
2221
- var changePasswordDto = z.object({
2527
+ var changePasswordDto = z2.object({
2222
2528
  currentPassword: passwordField,
2223
2529
  newPassword: passwordField
2224
2530
  });
2225
- var resetPasswordDto = z.object({
2531
+ var resetPasswordDto = z2.object({
2226
2532
  email: emailField
2227
2533
  });
2228
- var confirmResetPasswordDto = z.object({
2229
- token: z.string().min(10, "Invalid reset token"),
2534
+ var confirmResetPasswordDto = z2.object({
2535
+ token: z2.string().min(10, "Invalid reset token"),
2230
2536
  newPassword: passwordField
2231
2537
  });
2232
- var languageParam = z.object({
2233
- language: z.string().min(2)
2538
+ var languageParam = z2.object({
2539
+ language: z2.string().min(2)
2234
2540
  });
2235
- var emailParam = z.object({
2541
+ var emailParam = z2.object({
2236
2542
  email: emailField
2237
2543
  });
2238
- var userIdInParam = z.object({
2239
- userId: z.string().min(1, "User ID is required")
2544
+ var userIdInParam = z2.object({
2545
+ userId: z2.string().min(1, "User ID is required")
2240
2546
  });
2241
- var assignRoleParams = z.object({
2242
- userId: z.string().min(1, "User ID is required"),
2243
- roleId: z.string().min(1)
2547
+ var assignRoleParams = z2.object({
2548
+ userId: z2.string().min(1, "User ID is required"),
2549
+ roleId: z2.string().min(1)
2244
2550
  });
2245
- var userListQuery = z.object({
2246
- limit: z.coerce.number().int().min(1).max(100).default(50),
2247
- offset: z.coerce.number().int().min(0).default(0)
2551
+ var userListQuery = z2.object({
2552
+ limit: z2.coerce.number().int().min(1).max(100).default(50),
2553
+ offset: z2.coerce.number().int().min(0).default(0)
2248
2554
  });
2249
2555
 
2250
2556
  // src/auth/AuthController.ts
2251
- var __decorate13 = function(decorators, target, key, desc) {
2557
+ var __decorate15 = function(decorators, target, key, desc) {
2252
2558
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2253
2559
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2254
2560
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2255
2561
  return c > 3 && r && Object.defineProperty(target, key, r), r;
2256
2562
  };
2257
- var __metadata13 = function(k, v) {
2563
+ var __metadata15 = function(k, v) {
2258
2564
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
2259
2565
  };
2260
- var __param4 = function(paramIndex, decorator) {
2566
+ var __param6 = function(paramIndex, decorator) {
2261
2567
  return function(target, key) {
2262
2568
  decorator(target, key, paramIndex);
2263
2569
  };
2264
2570
  };
2265
- var _a8;
2571
+ var _a9;
2266
2572
  var hashKeyPart = /* @__PURE__ */ __name((value) => createHash2("sha256").update(value).digest("base64url").slice(0, 32), "hashKeyPart");
2267
2573
  var cookieFingerprint = /* @__PURE__ */ __name(() => (ctx) => {
2268
2574
  const ip = ctx.req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? ctx.req.header("x-real-ip") ?? "unknown";
@@ -2297,6 +2603,9 @@ var AuthController = class AuthController2 {
2297
2603
  async loginUser(body) {
2298
2604
  return this.authService.loginUser(body);
2299
2605
  }
2606
+ async inviteUser(body) {
2607
+ return this.authService.inviteUser(body);
2608
+ }
2300
2609
  async refreshTokens() {
2301
2610
  return this.authService.refreshTokens();
2302
2611
  }
@@ -2316,102 +2625,113 @@ var AuthController = class AuthController2 {
2316
2625
  return this.authService.resetPassword(body.token, body.newPassword);
2317
2626
  }
2318
2627
  };
2319
- __decorate13([
2320
- Post("/register"),
2628
+ __decorate15([
2629
+ Post2("/register"),
2321
2630
  RateLimit({ limit: 5, window: "15m", key: ipAndEmail }),
2322
- Validate(createUserDto),
2323
- ResMsg("auth.success.register"),
2324
- __param4(0, Body()),
2325
- __metadata13("design:type", Function),
2326
- __metadata13("design:paramtypes", [Object]),
2327
- __metadata13("design:returntype", Promise)
2631
+ Validate2(createUserDto),
2632
+ ResMsg2("auth.success.register"),
2633
+ __param6(0, Body2()),
2634
+ __metadata15("design:type", Function),
2635
+ __metadata15("design:paramtypes", [Object]),
2636
+ __metadata15("design:returntype", Promise)
2328
2637
  ], AuthController.prototype, "registerUser", null);
2329
- __decorate13([
2330
- Post("/login"),
2638
+ __decorate15([
2639
+ Post2("/login"),
2331
2640
  RateLimit({ limit: 5, window: "15m", key: ipAndEmail, message: "Too many login attempts. Please try again later." }),
2332
- Validate(loginDto),
2333
- ResMsg("auth.success.login"),
2334
- __param4(0, Body()),
2335
- __metadata13("design:type", Function),
2336
- __metadata13("design:paramtypes", [Object]),
2337
- __metadata13("design:returntype", Promise)
2641
+ Validate2(loginDto),
2642
+ ResMsg2("auth.success.login"),
2643
+ __param6(0, Body2()),
2644
+ __metadata15("design:type", Function),
2645
+ __metadata15("design:paramtypes", [Object]),
2646
+ __metadata15("design:returntype", Promise)
2338
2647
  ], AuthController.prototype, "loginUser", null);
2339
- __decorate13([
2340
- Post("/refresh"),
2648
+ __decorate15([
2649
+ Post2("/invite"),
2650
+ isAdmin(),
2651
+ RateLimit({ limit: 20, window: "15m", key: "user" }),
2652
+ Validate2(inviteUserDto),
2653
+ ResMsg2("auth.success.accountInviteSent"),
2654
+ __param6(0, Body2()),
2655
+ __metadata15("design:type", Function),
2656
+ __metadata15("design:paramtypes", [Object]),
2657
+ __metadata15("design:returntype", Promise)
2658
+ ], AuthController.prototype, "inviteUser", null);
2659
+ __decorate15([
2660
+ Post2("/refresh"),
2341
2661
  RateLimit({ limit: 15, window: "15m", key: cookieFingerprint() }),
2342
- ResMsg("auth.success.tokenRefreshed"),
2343
- __metadata13("design:type", Function),
2344
- __metadata13("design:paramtypes", []),
2345
- __metadata13("design:returntype", Promise)
2662
+ ResMsg2("auth.success.tokenRefreshed"),
2663
+ __metadata15("design:type", Function),
2664
+ __metadata15("design:paramtypes", []),
2665
+ __metadata15("design:returntype", Promise)
2346
2666
  ], AuthController.prototype, "refreshTokens", null);
2347
- __decorate13([
2348
- Post("/logout"),
2667
+ __decorate15([
2668
+ Post2("/logout"),
2349
2669
  isAuth(),
2350
2670
  RateLimit({ limit: 10, window: "15m", key: "user" }),
2351
- __param4(0, User2("id")),
2352
- __param4(1, Headers("authorization")),
2353
- __metadata13("design:type", Function),
2354
- __metadata13("design:paramtypes", [String, String]),
2355
- __metadata13("design:returntype", Promise)
2671
+ __param6(0, User3("id")),
2672
+ __param6(1, Headers("authorization")),
2673
+ __metadata15("design:type", Function),
2674
+ __metadata15("design:paramtypes", [String, String]),
2675
+ __metadata15("design:returntype", Promise)
2356
2676
  ], AuthController.prototype, "logoutUser", null);
2357
- __decorate13([
2358
- Post("/change-password"),
2677
+ __decorate15([
2678
+ Post2("/change-password"),
2359
2679
  isAuth(),
2360
- Validate(changePasswordDto),
2361
- ResMsg("auth.success.passwordChanged"),
2362
- __param4(0, User2("id")),
2363
- __param4(1, Body()),
2364
- __metadata13("design:type", Function),
2365
- __metadata13("design:paramtypes", [String, Object]),
2366
- __metadata13("design:returntype", Promise)
2680
+ Validate2(changePasswordDto),
2681
+ ResMsg2("auth.success.passwordChanged"),
2682
+ __param6(0, User3("id")),
2683
+ __param6(1, Body2()),
2684
+ __metadata15("design:type", Function),
2685
+ __metadata15("design:paramtypes", [String, Object]),
2686
+ __metadata15("design:returntype", Promise)
2367
2687
  ], AuthController.prototype, "changePassword", null);
2368
- __decorate13([
2369
- Get("/me"),
2688
+ __decorate15([
2689
+ Get2("/me"),
2370
2690
  RateLimit({ limit: 30, window: "1m", key: cookieFingerprint() }),
2371
- ResMsg("auth.users.success.retrieved"),
2372
- __param4(0, Headers("authorization")),
2373
- __metadata13("design:type", Function),
2374
- __metadata13("design:paramtypes", [String]),
2375
- __metadata13("design:returntype", Promise)
2691
+ ResMsg2("auth.users.success.retrieved"),
2692
+ __param6(0, Headers("authorization")),
2693
+ __metadata15("design:type", Function),
2694
+ __metadata15("design:paramtypes", [String]),
2695
+ __metadata15("design:returntype", Promise)
2376
2696
  ], AuthController.prototype, "userProfile", null);
2377
- __decorate13([
2378
- Post("/forgot-password"),
2697
+ __decorate15([
2698
+ Post2("/forgot-password"),
2379
2699
  RateLimit({ limit: 3, window: "15m", key: ipAndEmail, message: "Too many password reset requests. Please try again later." }),
2380
- Validate(resetPasswordDto),
2381
- ResMsg("auth.success.passwordResetSent"),
2382
- __param4(0, Body()),
2383
- __metadata13("design:type", Function),
2384
- __metadata13("design:paramtypes", [Object]),
2385
- __metadata13("design:returntype", Promise)
2700
+ Validate2(resetPasswordDto),
2701
+ ResMsg2("auth.success.passwordResetSent"),
2702
+ __param6(0, Body2()),
2703
+ __metadata15("design:type", Function),
2704
+ __metadata15("design:paramtypes", [Object]),
2705
+ __metadata15("design:returntype", Promise)
2386
2706
  ], AuthController.prototype, "forgotPassword", null);
2387
- __decorate13([
2388
- Post("/reset-password"),
2707
+ __decorate15([
2708
+ Post2("/reset-password"),
2389
2709
  RateLimit({ limit: 5, window: "15m", key: "ip", message: "Too many password reset attempts. Please try again later." }),
2390
- Validate(confirmResetPasswordDto),
2391
- ResMsg("auth.success.passwordReset"),
2392
- __param4(0, Body()),
2393
- __metadata13("design:type", Function),
2394
- __metadata13("design:paramtypes", [Object]),
2395
- __metadata13("design:returntype", Promise)
2710
+ Validate2(confirmResetPasswordDto),
2711
+ ResMsg2("auth.success.passwordReset"),
2712
+ __param6(0, Body2()),
2713
+ __metadata15("design:type", Function),
2714
+ __metadata15("design:paramtypes", [Object]),
2715
+ __metadata15("design:returntype", Promise)
2396
2716
  ], AuthController.prototype, "resetPassword", null);
2397
- AuthController = __decorate13([
2398
- Controller("/auth"),
2399
- __metadata13("design:paramtypes", [typeof (_a8 = typeof AuthService !== "undefined" && AuthService) === "function" ? _a8 : Object])
2717
+ AuthController = __decorate15([
2718
+ Controller2("/auth"),
2719
+ __metadata15("design:paramtypes", [typeof (_a9 = typeof AuthService !== "undefined" && AuthService) === "function" ? _a9 : Object])
2400
2720
  ], AuthController);
2401
2721
 
2402
2722
  // src/auth/AuthResolver.ts
2403
- import { APP, Container, DI, Inject as Inject9, LOGGER, Meta, Service as Service3 } from "najm-core";
2723
+ import { APP, Container, DI, Inject as Inject9, LOGGER, Meta, Service as Service4 } from "najm-core";
2404
2724
  import { USER, ROLE, PERMISSIONS } from "najm-guard";
2405
- var __decorate14 = function(decorators, target, key, desc) {
2725
+ var __decorate16 = function(decorators, target, key, desc) {
2406
2726
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2407
2727
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2408
2728
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2409
2729
  return c > 3 && r && Object.defineProperty(target, key, r), r;
2410
2730
  };
2411
- var __metadata14 = function(k, v) {
2731
+ var __metadata16 = function(k, v) {
2412
2732
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
2413
2733
  };
2414
- var _a9;
2734
+ var _a10;
2415
2735
  var AuthResolver = class AuthResolver2 {
2416
2736
  static {
2417
2737
  __name(this, "AuthResolver");
@@ -2509,20 +2829,20 @@ var AuthResolver = class AuthResolver2 {
2509
2829
  await authService.warmupPasswordHash();
2510
2830
  }
2511
2831
  };
2512
- __decorate14([
2832
+ __decorate16([
2513
2833
  DI(),
2514
- __metadata14("design:type", typeof (_a9 = typeof Container !== "undefined" && Container) === "function" ? _a9 : Object)
2834
+ __metadata16("design:type", typeof (_a10 = typeof Container !== "undefined" && Container) === "function" ? _a10 : Object)
2515
2835
  ], AuthResolver.prototype, "container", void 0);
2516
- __decorate14([
2836
+ __decorate16([
2517
2837
  Inject9(APP),
2518
- __metadata14("design:type", Object)
2838
+ __metadata16("design:type", Object)
2519
2839
  ], AuthResolver.prototype, "app", void 0);
2520
- __decorate14([
2840
+ __decorate16([
2521
2841
  Inject9(LOGGER),
2522
- __metadata14("design:type", Object)
2842
+ __metadata16("design:type", Object)
2523
2843
  ], AuthResolver.prototype, "log", void 0);
2524
- AuthResolver = __decorate14([
2525
- Service3(),
2844
+ AuthResolver = __decorate16([
2845
+ Service4(),
2526
2846
  Meta({ layer: "plugin", order: 30 })
2527
2847
  ], AuthResolver);
2528
2848
 
@@ -2571,6 +2891,7 @@ __export(users_exports, {
2571
2891
  confirmResetPasswordDto: () => confirmResetPasswordDto,
2572
2892
  createUserDto: () => createUserDto,
2573
2893
  emailParam: () => emailParam,
2894
+ inviteUserDto: () => inviteUserDto,
2574
2895
  languageParam: () => languageParam,
2575
2896
  loginDto: () => loginDto,
2576
2897
  resetPasswordDto: () => resetPasswordDto,
@@ -2584,233 +2905,6 @@ __export(users_exports, {
2584
2905
  import { Controller as Controller3 } from "najm-core";
2585
2906
  import { Get as Get3, Post as Post3, Put as Put2, Delete as Delete2, ResMsg as ResMsg3 } from "najm-core";
2586
2907
  import { Params as Params2, Body as Body3, Query } from "najm-core";
2587
-
2588
- // src/roles/index.ts
2589
- var roles_exports = {};
2590
- __export(roles_exports, {
2591
- ROLES: () => ROLES,
2592
- ROLE_GROUPS: () => ROLE_GROUPS,
2593
- Role: () => Role,
2594
- RoleController: () => RoleController,
2595
- RoleGuard: () => RoleGuard,
2596
- RoleRepository: () => RoleRepository,
2597
- RoleService: () => RoleService,
2598
- RoleValidator: () => RoleValidator,
2599
- assignRoleDto: () => assignRoleDto,
2600
- createRoleDto: () => createRoleDto,
2601
- defineRoles: () => defineRoles,
2602
- isAdmin: () => isAdmin,
2603
- isAdministrator: () => isAdministrator,
2604
- roleIdParam: () => roleIdParam,
2605
- updateRoleDto: () => updateRoleDto
2606
- });
2607
-
2608
- // src/roles/defineRoles.ts
2609
- import { composeGuards as composeGuards2, createGuard as createGuard3 } from "najm-guard";
2610
-
2611
- // src/roles/RoleGuards.ts
2612
- import { Service as Service4 } from "najm-core";
2613
- import { GuardParams, User as User3 } from "najm-core";
2614
- import { composeGuards, createGuard as createGuard2 } from "najm-guard";
2615
- var __decorate15 = function(decorators, target, key, desc) {
2616
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2617
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2618
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2619
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2620
- };
2621
- var __metadata15 = function(k, v) {
2622
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
2623
- };
2624
- var __param5 = function(paramIndex, decorator) {
2625
- return function(target, key) {
2626
- decorator(target, key, paramIndex);
2627
- };
2628
- };
2629
- var RoleGuard = class RoleGuard2 {
2630
- static {
2631
- __name(this, "RoleGuard");
2632
- }
2633
- canActivate(allowedRoles, userRole) {
2634
- if (!userRole)
2635
- return false;
2636
- const requiredRoles = Array.isArray(allowedRoles) ? allowedRoles : [allowedRoles];
2637
- const hasRole = requiredRoles.some((r) => r.toLowerCase() === userRole.toLowerCase());
2638
- if (hasRole) {
2639
- return { role: userRole };
2640
- }
2641
- return false;
2642
- }
2643
- };
2644
- __decorate15([
2645
- __param5(0, GuardParams()),
2646
- __param5(1, User3("role")),
2647
- __metadata15("design:type", Function),
2648
- __metadata15("design:paramtypes", [Object, String]),
2649
- __metadata15("design:returntype", void 0)
2650
- ], RoleGuard.prototype, "canActivate", null);
2651
- RoleGuard = __decorate15([
2652
- Service4()
2653
- ], RoleGuard);
2654
- var Role = createGuard2(RoleGuard);
2655
- var isAdmin = composeGuards(isAuth(), Role(ROLES.ADMIN));
2656
- var isAdministrator = composeGuards(isAuth(), Role(ROLE_GROUPS.ADMINISTRATORS));
2657
-
2658
- // src/roles/defineRoles.ts
2659
- var Role2 = createGuard3(RoleGuard);
2660
- function defineRoles(roles, options) {
2661
- const ROLES2 = roles;
2662
- const superRoleKeys = options?.superRoles ?? [];
2663
- function resolveRoleValues(keys) {
2664
- return Array.from(new Set([...keys, ...superRoleKeys].map((key) => roles[key])));
2665
- }
2666
- __name(resolveRoleValues, "resolveRoleValues");
2667
- const guards2 = {};
2668
- for (const [key, value] of Object.entries(roles)) {
2669
- const name = `is${key.charAt(0).toUpperCase()}${key.slice(1).toLowerCase()}`;
2670
- const allowedValues = resolveRoleValues([key]);
2671
- guards2[name] = composeGuards2(isAuth(), Role2(allowedValues.length === 1 ? value : allowedValues));
2672
- }
2673
- function createGroupGuard(keys) {
2674
- const values = resolveRoleValues(keys);
2675
- return composeGuards2(isAuth(), Role2(values));
2676
- }
2677
- __name(createGroupGuard, "createGroupGuard");
2678
- function hasRole(userRole, ...keys) {
2679
- if (!userRole)
2680
- return false;
2681
- const normalized = userRole.toLowerCase();
2682
- return resolveRoleValues(keys).some((role) => role === normalized);
2683
- }
2684
- __name(hasRole, "hasRole");
2685
- function isInGroup(userRole, keys) {
2686
- return hasRole(userRole, ...keys);
2687
- }
2688
- __name(isInGroup, "isInGroup");
2689
- return { ROLES: ROLES2, createGroupGuard, hasRole, isInGroup, ...guards2 };
2690
- }
2691
- __name(defineRoles, "defineRoles");
2692
-
2693
- // src/roles/RoleController.ts
2694
- import { Controller as Controller2 } from "najm-core";
2695
- import { Get as Get2, Post as Post2, Put, Delete, ResMsg as ResMsg2 } from "najm-core";
2696
- import { Params, Body as Body2 } from "najm-core";
2697
- import { Validate as Validate2 } from "najm-validation";
2698
-
2699
- // src/roles/RoleDto.ts
2700
- import { z as z2 } from "zod";
2701
- var nameField = z2.string().min(2, "Name must be at least 2 characters").max(50, "Name too long");
2702
- var descriptionField = z2.string().max(255, "Description too long").optional();
2703
- var createRoleDto = z2.object({
2704
- name: nameField,
2705
- description: descriptionField
2706
- });
2707
- var updateRoleDto = createRoleDto.partial();
2708
- var roleIdParam = z2.object({
2709
- id: z2.string().length(5, "Role ID must be 5 characters")
2710
- });
2711
- var assignRoleDto = z2.object({
2712
- userId: z2.string().length(8, "User ID must be 8 characters"),
2713
- roleId: z2.string().length(5, "Role ID must be 5 characters")
2714
- });
2715
-
2716
- // src/roles/RoleController.ts
2717
- var __decorate16 = function(decorators, target, key, desc) {
2718
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2719
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2720
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2721
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2722
- };
2723
- var __metadata16 = function(k, v) {
2724
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
2725
- };
2726
- var __param6 = function(paramIndex, decorator) {
2727
- return function(target, key) {
2728
- decorator(target, key, paramIndex);
2729
- };
2730
- };
2731
- var _a10;
2732
- var RoleController = class RoleController2 {
2733
- static {
2734
- __name(this, "RoleController");
2735
- }
2736
- roleService;
2737
- constructor(roleService) {
2738
- this.roleService = roleService;
2739
- }
2740
- async getRoles() {
2741
- return this.roleService.getAll();
2742
- }
2743
- async getRole(params) {
2744
- return this.roleService.getById(params.id);
2745
- }
2746
- async createRole(body) {
2747
- return this.roleService.create(body);
2748
- }
2749
- async updateRole(params, body) {
2750
- return this.roleService.update(params.id, body);
2751
- }
2752
- async deleteRole(params) {
2753
- return this.roleService.delete(params.id);
2754
- }
2755
- };
2756
- __decorate16([
2757
- Get2(),
2758
- isAdmin(),
2759
- ResMsg2("roles.success.retrieved"),
2760
- __metadata16("design:type", Function),
2761
- __metadata16("design:paramtypes", []),
2762
- __metadata16("design:returntype", Promise)
2763
- ], RoleController.prototype, "getRoles", null);
2764
- __decorate16([
2765
- Get2("/:id"),
2766
- isAdmin(),
2767
- Validate2({ params: roleIdParam }),
2768
- ResMsg2("roles.success.retrieved"),
2769
- __param6(0, Params()),
2770
- __metadata16("design:type", Function),
2771
- __metadata16("design:paramtypes", [Object]),
2772
- __metadata16("design:returntype", Promise)
2773
- ], RoleController.prototype, "getRole", null);
2774
- __decorate16([
2775
- Post2(),
2776
- isAdmin(),
2777
- Validate2(createRoleDto),
2778
- ResMsg2("roles.success.created"),
2779
- __param6(0, Body2()),
2780
- __metadata16("design:type", Function),
2781
- __metadata16("design:paramtypes", [Object]),
2782
- __metadata16("design:returntype", Promise)
2783
- ], RoleController.prototype, "createRole", null);
2784
- __decorate16([
2785
- Put("/:id"),
2786
- isAdmin(),
2787
- Validate2({
2788
- params: roleIdParam,
2789
- body: updateRoleDto
2790
- }),
2791
- ResMsg2("roles.success.updated"),
2792
- __param6(0, Params()),
2793
- __param6(1, Body2()),
2794
- __metadata16("design:type", Function),
2795
- __metadata16("design:paramtypes", [Object, Object]),
2796
- __metadata16("design:returntype", Promise)
2797
- ], RoleController.prototype, "updateRole", null);
2798
- __decorate16([
2799
- Delete("/:id"),
2800
- isAdmin(),
2801
- Validate2({ params: roleIdParam }),
2802
- ResMsg2("roles.success.deleted"),
2803
- __param6(0, Params()),
2804
- __metadata16("design:type", Function),
2805
- __metadata16("design:paramtypes", [Object]),
2806
- __metadata16("design:returntype", Promise)
2807
- ], RoleController.prototype, "deleteRole", null);
2808
- RoleController = __decorate16([
2809
- Controller2("/roles"),
2810
- __metadata16("design:paramtypes", [typeof (_a10 = typeof RoleService !== "undefined" && RoleService) === "function" ? _a10 : Object])
2811
- ], RoleController);
2812
-
2813
- // src/users/UserController.ts
2814
2908
  import { Validate as Validate3 } from "najm-validation";
2815
2909
  var __decorate17 = function(decorators, target, key, desc) {
2816
2910
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -4294,7 +4388,16 @@ var en_default = {
4294
4388
  passwordChanged: "Password changed successfully",
4295
4389
  passwordResetSent: "If that email exists, a reset link has been sent",
4296
4390
  passwordReset: "Password has been reset successfully",
4391
+ accountInviteSent: "Invitation sent successfully",
4297
4392
  tokenRefreshed: "Token refreshed successfully"
4393
+ },
4394
+ emails: {
4395
+ passwordReset: {
4396
+ subject: "Reset your password"
4397
+ },
4398
+ accountInvite: {
4399
+ subject: "You've been invited \u2014 set up your account"
4400
+ }
4298
4401
  }
4299
4402
  },
4300
4403
  users: {
@@ -4619,6 +4722,7 @@ export {
4619
4722
  formatDate,
4620
4723
  getAuthLocale,
4621
4724
  getAvatarFile,
4725
+ inviteUserDto,
4622
4726
  isAdmin,
4623
4727
  isAdministrator,
4624
4728
  isAuth,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "najm-auth",
3
- "version": "1.1.41",
3
+ "version": "1.1.43",
4
4
  "description": "Authentication and authorization library for najm framework",
5
5
  "type": "module",
6
6
  "files": [
@@ -74,12 +74,12 @@
74
74
  "dependencies": {
75
75
  "bcryptjs": "^3.0.2",
76
76
  "najm-cookies": "^1.1.14",
77
- "najm-core": "^1.2.12",
77
+ "najm-core": "^1.2.14",
78
78
  "najm-database": "^1.1.16",
79
79
  "najm-guard": "^1.1.14",
80
80
  "najm-i18n": "^1.1.14",
81
81
  "najm-cache": "^1.2.11",
82
- "najm-email": "^1.1.14",
82
+ "najm-email": "^1.1.15",
83
83
  "najm-rate": "^1.1.14",
84
84
  "najm-validation": "^1.1.15",
85
85
  "jsonwebtoken": "^9.0.3",