najm-auth 0.1.12 → 0.1.13

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.

Potentially problematic release.


This version of najm-auth might be problematic. Click here for more details.

package/dist/index.mjs DELETED
@@ -1,3082 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
-
4
- // src/auth/EncryptionService.ts
5
- import { Injectable } from "najm-api";
6
- import bcrypt from "bcrypt";
7
- var __decorate = function(decorators, target, key, desc) {
8
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
9
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
10
- 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;
11
- return c > 3 && r && Object.defineProperty(target, key, r), r;
12
- };
13
- var __metadata = function(k, v) {
14
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
15
- };
16
- var _a;
17
- var EncryptionService = (_a = class {
18
- constructor() {
19
- }
20
- async hashPassword(password) {
21
- if (!password)
22
- return null;
23
- if (typeof password !== "string" || password.trim().length === 0) {
24
- return null;
25
- }
26
- return bcrypt.hash(password, 10);
27
- }
28
- async comparePassword(password, hashedPassword) {
29
- return bcrypt.compare(password, hashedPassword);
30
- }
31
- }, __name(_a, "EncryptionService"), _a);
32
- EncryptionService = __decorate([
33
- Injectable(),
34
- __metadata("design:paramtypes", [])
35
- ], EncryptionService);
36
-
37
- // src/auth/CookieService.ts
38
- import { setCookie, Injectable as Injectable2, deleteCookie } from "najm-api";
39
- import timestring from "timestring";
40
- var __decorate2 = function(decorators, target, key, desc) {
41
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
42
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
43
- 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;
44
- return c > 3 && r && Object.defineProperty(target, key, r), r;
45
- };
46
- var _a2;
47
- var CookieService = (_a2 = class {
48
- setRefreshCookie(refreshToken) {
49
- const maxAge = timestring(process.env.REFRESH_EXPIRES_IN, "s");
50
- setCookie("refreshToken", refreshToken, {
51
- httpOnly: false,
52
- sameSite: "Lax",
53
- maxAge,
54
- path: "/api/auth/refresh"
55
- });
56
- }
57
- clearRefreshCookie() {
58
- deleteCookie("refreshToken", {
59
- httpOnly: false,
60
- sameSite: "Lax",
61
- path: "/api/auth/refresh",
62
- maxAge: 0
63
- });
64
- }
65
- }, __name(_a2, "CookieService"), _a2);
66
- CookieService = __decorate2([
67
- Injectable2()
68
- ], CookieService);
69
-
70
- // src/auth/AuthController.ts
71
- import { Controller as Controller3, Get as Get3, Post as Post3, Params as Params3, Body as Body3, User, t as t7 } from "najm-api";
72
-
73
- // src/auth/AuthService.ts
74
- import { t as t6 } from "najm-api";
75
- import { Injectable as Injectable9, getCurrentLanguage as getCurrentLanguage2 } from "najm-api";
76
-
77
- // src/database/schema/index.ts
78
- import { pgTable, text, boolean, timestamp } from "drizzle-orm/pg-core";
79
- import { nanoid } from "nanoid";
80
- import { sql } from "drizzle-orm";
81
-
82
- // src/lib/ENUMS.ts
83
- var ENUMS = {
84
- // Core System
85
- userType: {
86
- values: ["admin", "teacher", "student", "parent"],
87
- translationKey: "enums.userType"
88
- },
89
- userStatus: {
90
- values: ["active", "inactive", "pending"],
91
- translationKey: "enums.userStatus"
92
- },
93
- tokenStatus: {
94
- values: ["active", "revoked", "expired"],
95
- translationKey: "enums.tokenStatus"
96
- },
97
- tokenType: {
98
- values: ["access", "refresh"],
99
- translationKey: "enums.tokenType"
100
- },
101
- fileStatus: {
102
- values: ["active", "deleted", "archived"],
103
- translationKey: "enums.fileStatus"
104
- },
105
- // Educational System
106
- gender: {
107
- values: ["M", "F"],
108
- translationKey: "common.gender"
109
- },
110
- studentStatus: {
111
- values: ["active", "inactive", "graduated", "transferred"],
112
- translationKey: "students.status"
113
- },
114
- teacherStatus: {
115
- values: ["active", "inactive", "onLeave"],
116
- translationKey: "teachers.status"
117
- },
118
- employmentType: {
119
- values: ["fullTime", "partTime", "contract", "temporary"],
120
- translationKey: "teachers.employmentType"
121
- },
122
- relationshipType: {
123
- values: ["father", "mother", "guardian", "stepparent", "grandparent", "other"],
124
- translationKey: "parents.relationships"
125
- },
126
- semester: {
127
- values: ["spring", "summer", "fall", "winter"],
128
- translationKey: "academic.semester"
129
- },
130
- classStatus: {
131
- values: ["active", "completed", "cancelled"],
132
- translationKey: "classes.status"
133
- },
134
- sectionStatus: {
135
- values: ["active", "inactive", "archived"],
136
- translationKey: "sections.status"
137
- },
138
- language: {
139
- values: ["en", "fr", "ar", "es"],
140
- translationKey: "common.languages"
141
- },
142
- enrollmentStatus: {
143
- values: ["enrolled", "completed", "dropped", "failed"],
144
- translationKey: "enrollments.status"
145
- },
146
- assignmentStatus: {
147
- values: ["active", "completed", "cancelled"],
148
- translationKey: "assignments.status"
149
- },
150
- calendarSystem: {
151
- values: ["SEMESTER", "TRIMESTER", "QUARTER"],
152
- translationKey: "settings.calendarSystem"
153
- },
154
- // Assessment & Exams
155
- assessmentType: {
156
- values: ["quiz", "assignment", "project", "participation", "test", "presentation"],
157
- translationKey: "assessments.type"
158
- },
159
- assessmentStatus: {
160
- values: ["scheduled", "active", "completed", "cancelled"],
161
- translationKey: "assessments.status"
162
- },
163
- submissionType: {
164
- values: ["online", "paper", "presentation", "practical", "discussion"],
165
- translationKey: "assessments.submissionType"
166
- },
167
- examType: {
168
- values: ["midterm", "final", "standardized"],
169
- translationKey: "exams.type"
170
- },
171
- examSecurity: {
172
- values: ["low", "medium", "high"],
173
- translationKey: "exams.security"
174
- },
175
- examStatus: {
176
- values: ["scheduled", "active", "completed", "cancelled", "rescheduled"],
177
- translationKey: "exams.status"
178
- },
179
- gradeStatus: {
180
- values: ["graded", "pending", "draft", "reviewed"],
181
- translationKey: "grades.status"
182
- },
183
- attendanceStatus: {
184
- values: ["present", "absent", "late", "excused"],
185
- translationKey: "attendance.status"
186
- },
187
- proficiencyLevel: {
188
- values: ["beginner", "intermediate", "advanced", "expert"],
189
- translationKey: "common.proficiencyLevel"
190
- },
191
- dayOfWeek: {
192
- values: ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"],
193
- translationKey: "common.days"
194
- },
195
- // Alerts
196
- alertType: {
197
- values: ["academic", "attendance", "behavioral", "health", "system", "announcement", "reminder", "emergency"],
198
- translationKey: "alerts.type"
199
- },
200
- alertPriority: {
201
- values: ["low", "medium", "high", "critical"],
202
- translationKey: "alerts.priority"
203
- },
204
- alertStatus: {
205
- values: ["active", "acknowledged", "resolved", "dismissed"],
206
- translationKey: "alerts.status"
207
- },
208
- // Fees & Payments
209
- feeTypeStatus: {
210
- values: ["active", "inactive", "archived"],
211
- translationKey: "fees.typeStatus"
212
- },
213
- feeCategory: {
214
- values: ["tuition", "registration", "transport", "cafeteria", "books", "sports", "uniform", "technology", "fieldtrip", "other"],
215
- translationKey: "feeTypes.category"
216
- },
217
- paymentType: {
218
- values: ["recurring", "oneTime"],
219
- translationKey: "payments.type"
220
- },
221
- schedule: {
222
- values: ["monthly", "quarterly", "semester", "annually", "oneTime"],
223
- translationKey: "fees.schedule"
224
- },
225
- feeStatus: {
226
- values: ["pending", "partiallyPaid", "paid", "overdue"],
227
- translationKey: "fees.status"
228
- },
229
- feeInstallmentStatus: {
230
- values: ["pending", "partiallyPaid", "paid", "overdue"],
231
- translationKey: "fees.installmentStatus"
232
- },
233
- paymentMethod: {
234
- values: ["cash", "bankTransfer", "check", "creditCard", "debitCard", "online", "mobilePayment"],
235
- translationKey: "payments.methods"
236
- },
237
- paymentStatus: {
238
- values: ["completed", "pending", "failed", "refunded"],
239
- translationKey: "payments.status"
240
- },
241
- // Events
242
- eventType: {
243
- values: ["academic", "sports", "cultural", "holiday", "exam", "meeting", "workshop", "fieldtrip", "ceremony", "conference", "other"],
244
- translationKey: "events.type"
245
- },
246
- eventStatus: {
247
- values: ["scheduled", "ongoing", "completed", "cancelled", "postponed"],
248
- translationKey: "events.status"
249
- },
250
- eventVisibility: {
251
- values: ["public", "private", "teachers", "students", "parents", "staff"],
252
- translationKey: "events.visibility"
253
- },
254
- participantType: {
255
- values: ["student", "teacher", "parent", "staff"],
256
- translationKey: "events.participantType"
257
- },
258
- // Expenses
259
- expenseCategory: {
260
- values: ["salary", "utilities", "maintenance", "supplies", "equipment", "transport", "food", "security", "cleaning", "insurance", "rent", "tax", "marketing", "training", "technology", "miscellaneous"],
261
- translationKey: "expenses.categories"
262
- },
263
- expenseStatus: {
264
- values: ["pending", "approved", "paid", "rejected", "cancelled"],
265
- translationKey: "expenses.status"
266
- },
267
- // Tracker
268
- trackerMode: {
269
- values: ["tracking", "gprs", "sms", "sleepTime", "sleepShock", "sleepDeep"],
270
- translationKey: "tracker.mode"
271
- },
272
- // Transport
273
- driverStatus: {
274
- values: ["active", "inactive", "onLeave", "suspended"],
275
- translationKey: "transport.driverStatus"
276
- },
277
- vehicleStatus: {
278
- values: ["active", "inactive", "maintenance", "retired"],
279
- translationKey: "transport.vehicleStatus"
280
- },
281
- vehicleType: {
282
- values: ["sedan", "minibus", "fullbus", "shuttle"],
283
- translationKey: "transport.vehicleType"
284
- },
285
- vehicleDocumentType: {
286
- values: ["insurance", "registration", "inspection", "emission", "license"],
287
- translationKey: "transport.documentType"
288
- },
289
- busStatus: {
290
- values: ["active", "inactive", "maintenance", "retired"],
291
- translationKey: "transport.busStatus"
292
- },
293
- refuelStatus: {
294
- values: ["pending", "completed", "cancelled"],
295
- translationKey: "transport.refuelStatus"
296
- },
297
- fuelType: {
298
- values: ["gasoline", "diesel", "electric", "hybrid", "lpg", "cng"],
299
- translationKey: "transport.fuelType"
300
- },
301
- maintenanceType: {
302
- values: ["scheduled", "repair", "inspection", "oilChange", "filterChange", "other"],
303
- translationKey: "transport.maintenanceType"
304
- },
305
- maintenanceStatus: {
306
- values: ["scheduled", "inProgress", "completed", "cancelled", "overdue"],
307
- translationKey: "transport.maintenanceStatus"
308
- },
309
- // Personal
310
- maritalStatus: {
311
- values: ["single", "married", "divorced", "widowed", "separated"],
312
- translationKey: "parents.maritalStatus"
313
- }
314
- };
315
- var getEnumConfig = /* @__PURE__ */ __name((enumKey) => ENUMS[enumKey], "getEnumConfig");
316
- var getEnumValues = /* @__PURE__ */ __name((enumKey) => ENUMS[enumKey]?.values || [], "getEnumValues");
317
-
318
- // src/database/schema/PgEnum.ts
319
- import { pgEnum } from "drizzle-orm/pg-core";
320
- var createPgEnum = /* @__PURE__ */ __name((enumKey) => {
321
- const config = getEnumConfig(enumKey);
322
- if (!config)
323
- throw new Error(`Enum ${enumKey} not found`);
324
- const enumName = config.name || enumKey;
325
- return pgEnum(enumName, config.values);
326
- }, "createPgEnum");
327
- var userStatusEnum = createPgEnum("userStatus");
328
- var tokenStatusEnum = createPgEnum("tokenStatus");
329
- var tokenTypeEnum = createPgEnum("tokenType");
330
- var studentStatusEnum = createPgEnum("studentStatus");
331
-
332
- // src/database/schema/index.ts
333
- var timestamps = {
334
- createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),
335
- updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow().$onUpdate(() => sql`CURRENT_TIMESTAMP`)
336
- };
337
- var idField = /* @__PURE__ */ __name((length = 5) => text("id").primaryKey().notNull().$defaultFn(() => nanoid(length)), "idField");
338
- var rolesTable = pgTable("roles", {
339
- id: idField(),
340
- name: text("name").notNull(),
341
- description: text("description")
342
- });
343
- var usersTable = pgTable("users", {
344
- id: idField(8),
345
- email: text("email").notNull().unique(),
346
- emailVerified: boolean("email_verified").default(false),
347
- password: text("password").notNull(),
348
- image: text("image").default("noavatar.png"),
349
- status: userStatusEnum("status").default("pending"),
350
- roleId: text("role_id").references(() => rolesTable.id),
351
- lastLogin: timestamp("last_login", { mode: "string" }),
352
- ...timestamps
353
- });
354
- var tokensTable = pgTable("tokens", {
355
- id: idField(10),
356
- userId: text("user_id").references(() => usersTable.id, { onDelete: "cascade" }).unique().notNull(),
357
- token: text("token").notNull(),
358
- type: tokenTypeEnum("type").default("refresh"),
359
- status: tokenStatusEnum("status").default("active"),
360
- expiresAt: timestamp("expires_at", { mode: "string" }).notNull(),
361
- ...timestamps
362
- });
363
- var permissionsTable = pgTable("permissions", {
364
- id: idField(),
365
- name: text("name").notNull().unique(),
366
- description: text("description"),
367
- resource: text("resource").notNull(),
368
- action: text("action").notNull(),
369
- ...timestamps
370
- });
371
- var rolePermissionsTable = pgTable("role_permissions", {
372
- id: idField(),
373
- roleId: text("role_id").references(() => rolesTable.id).notNull(),
374
- permissionId: text("permission_id").references(() => permissionsTable.id).notNull(),
375
- ...timestamps
376
- });
377
-
378
- // src/users/UserRepository.ts
379
- import { eq, ne } from "drizzle-orm";
380
- import { Repository } from "najm-api";
381
- var __decorate3 = function(decorators, target, key, desc) {
382
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
383
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
384
- 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;
385
- return c > 3 && r && Object.defineProperty(target, key, r), r;
386
- };
387
- var _a3;
388
- var UserRepository = (_a3 = class {
389
- getUser() {
390
- return {
391
- id: usersTable.id,
392
- email: usersTable.email,
393
- emailVerified: usersTable.emailVerified,
394
- image: usersTable.image,
395
- status: usersTable.status,
396
- roleId: usersTable.roleId,
397
- role: rolesTable.name,
398
- createdAt: usersTable.createdAt,
399
- updatedAt: usersTable.updatedAt
400
- };
401
- }
402
- async getAll() {
403
- const allUsers = await this.db.select(this.getUser()).from(usersTable).leftJoin(rolesTable, eq(usersTable.roleId, rolesTable.id));
404
- return Promise.all(allUsers.map(async (user) => ({
405
- ...user,
406
- permissions: await this.getUserPermissions(user.id)
407
- })));
408
- }
409
- async getById(id) {
410
- const [user] = await this.db.select(this.getUser()).from(usersTable).leftJoin(rolesTable, eq(usersTable.roleId, rolesTable.id)).where(eq(usersTable.id, id)).limit(1);
411
- if (!user)
412
- return user;
413
- return {
414
- ...user,
415
- permissions: await this.getUserPermissions(user.id)
416
- };
417
- }
418
- async getByEmail(email) {
419
- const [existingUser] = await this.db.select(this.getUser()).from(usersTable).leftJoin(rolesTable, eq(usersTable.roleId, rolesTable.id)).where(eq(usersTable.email, email));
420
- return existingUser;
421
- }
422
- async create(data) {
423
- const [newUser] = await this.db.insert(usersTable).values(data).returning();
424
- return newUser;
425
- }
426
- async update(id, data) {
427
- const [updatedUser] = await this.db.update(usersTable).set(data).where(eq(usersTable.id, id)).returning();
428
- return updatedUser;
429
- }
430
- async delete(id) {
431
- const [deletedUser] = await this.db.delete(usersTable).where(eq(usersTable.id, id)).returning();
432
- return deletedUser;
433
- }
434
- async deleteAll() {
435
- const adminRole = await this.db.select({ id: rolesTable.id }).from(rolesTable).where(eq(rolesTable.name, "admin")).limit(1);
436
- if (adminRole.length === 0) {
437
- const deletedUsers2 = await this.db.delete(usersTable).returning();
438
- return deletedUsers2;
439
- }
440
- const deletedUsers = await this.db.delete(usersTable).where(ne(usersTable.roleId, adminRole[0].id)).returning();
441
- return deletedUsers;
442
- }
443
- async getRoleNameById(userId) {
444
- const [role] = await this.db.select({
445
- roleName: rolesTable.name
446
- }).from(usersTable).leftJoin(rolesTable, eq(usersTable.roleId, rolesTable.id)).where(eq(usersTable.id, userId));
447
- return role.roleName;
448
- }
449
- async getUserPassword(email) {
450
- const [user] = await this.db.select({
451
- id: usersTable.id,
452
- email: usersTable.email,
453
- password: usersTable.password
454
- }).from(usersTable).where(eq(usersTable.email, email)).limit(1);
455
- return user.password;
456
- }
457
- async getUserPermissions(userId) {
458
- const [user] = await this.db.select({ roleId: usersTable.roleId }).from(usersTable).where(eq(usersTable.id, userId)).limit(1);
459
- if (!user || !user.roleId)
460
- return [];
461
- const userPermissions = await this.db.select({
462
- name: permissionsTable.name
463
- }).from(rolePermissionsTable).leftJoin(permissionsTable, eq(rolePermissionsTable.permissionId, permissionsTable.id)).where(eq(rolePermissionsTable.roleId, user.roleId));
464
- return userPermissions.map((p) => p.name).filter((name) => name);
465
- }
466
- }, __name(_a3, "UserRepository"), _a3);
467
- UserRepository = __decorate3([
468
- Repository()
469
- ], UserRepository);
470
-
471
- // src/users/UserValidator.ts
472
- import { Injectable as Injectable3, t } from "najm-api";
473
-
474
- // src/shared/index.ts
475
- import * as fs from "fs/promises";
476
- import * as path from "path";
477
- import _isEmpty from "lodash.isempty";
478
- var avatarsPath = path.join(process.cwd(), "avatars");
479
- var parseSchema = /* @__PURE__ */ __name(async (schema, data) => {
480
- try {
481
- return await schema.parseAsync(data);
482
- } catch (error) {
483
- const errors = error.issues || error.errors || [];
484
- const errorMessage = errors.map((err) => `${err.path.join(".")}: ${err.message}`).join("; ");
485
- throw new Error(errorMessage);
486
- }
487
- }, "parseSchema");
488
- var clean = /* @__PURE__ */ __name((obj) => {
489
- const cleaned = {};
490
- for (const [key, value] of Object.entries(obj)) {
491
- if (value !== null && value !== void 0 && value !== "") {
492
- cleaned[key] = value;
493
- }
494
- }
495
- return cleaned;
496
- }, "clean");
497
- var getAvatarFile = /* @__PURE__ */ __name(async (fileName) => {
498
- try {
499
- const filePath = path.join(avatarsPath, fileName);
500
- const buffer = await fs.readFile(filePath);
501
- const file = new File([buffer], fileName, {
502
- type: "image/png"
503
- });
504
- return file;
505
- } catch (error) {
506
- return null;
507
- }
508
- }, "getAvatarFile");
509
- var formatDate = /* @__PURE__ */ __name((dateValue) => {
510
- if (!dateValue)
511
- return null;
512
- let date;
513
- if (dateValue instanceof Date) {
514
- date = dateValue;
515
- } else if (typeof dateValue === "string") {
516
- date = new Date(dateValue);
517
- } else {
518
- return null;
519
- }
520
- if (isNaN(date.getTime()))
521
- return null;
522
- return date.toISOString().split("T")[0];
523
- }, "formatDate");
524
- function calculateAge(dateOfBirth) {
525
- if (!dateOfBirth)
526
- return null;
527
- const formattedDate = formatDate(dateOfBirth);
528
- if (!formattedDate)
529
- return null;
530
- const birth = new Date(formattedDate);
531
- const today = /* @__PURE__ */ new Date();
532
- let age = today.getFullYear() - birth.getFullYear();
533
- const monthDiff = today.getMonth() - birth.getMonth();
534
- if (monthDiff < 0 || monthDiff === 0 && today.getDate() < birth.getDate()) {
535
- age--;
536
- }
537
- return age;
538
- }
539
- __name(calculateAge, "calculateAge");
540
- function calculateYearsOfExperience(hireDate) {
541
- if (!hireDate)
542
- return null;
543
- const formattedDate = formatDate(hireDate);
544
- if (!formattedDate)
545
- return null;
546
- const hire = new Date(formattedDate);
547
- const today = /* @__PURE__ */ new Date();
548
- let years = today.getFullYear() - hire.getFullYear();
549
- const monthDiff = today.getMonth() - hire.getMonth();
550
- if (monthDiff < 0 || monthDiff === 0 && today.getDate() < hire.getDate()) {
551
- years--;
552
- }
553
- return years;
554
- }
555
- __name(calculateYearsOfExperience, "calculateYearsOfExperience");
556
- function pickProps(source, keys) {
557
- const result = {};
558
- for (const key of keys) {
559
- if (source[key] !== void 0) {
560
- result[key] = source[key];
561
- }
562
- }
563
- return result;
564
- }
565
- __name(pickProps, "pickProps");
566
- var isEmpty = _isEmpty;
567
- var isPath = /* @__PURE__ */ __name((img) => typeof img === "string" && img.trim().length > 0 && (img.startsWith("/") || img.startsWith("http") || img.startsWith("storage/")), "isPath");
568
- var isFile = /* @__PURE__ */ __name((img) => !!img && typeof img !== "string" && img instanceof File, "isFile");
569
-
570
- // src/lib/validations.ts
571
- import { z as z2 } from "zod";
572
-
573
- // src/lib/ZodEnum.ts
574
- import { z } from "zod";
575
- var createZodEnum = /* @__PURE__ */ __name((enumKey) => {
576
- const values = ENUMS[enumKey]?.values;
577
- if (!values)
578
- throw new Error(`Enum ${enumKey} not found`);
579
- return z.enum(values);
580
- }, "createZodEnum");
581
- var userTypeEnum = createZodEnum("userType");
582
- var userStatusEnum2 = createZodEnum("userStatus");
583
- var tokenStatusEnum2 = createZodEnum("tokenStatus");
584
- var tokenTypeEnum2 = createZodEnum("tokenType");
585
- var fileStatusEnum = createZodEnum("fileStatus");
586
- var genderEnum = createZodEnum("gender");
587
- var studentStatusEnum2 = createZodEnum("studentStatus");
588
- var teacherStatusEnum = createZodEnum("teacherStatus");
589
- var employmentTypeEnum = createZodEnum("employmentType");
590
- var relationshipTypeEnum = createZodEnum("relationshipType");
591
- var semesterEnum = createZodEnum("semester");
592
- var classStatusEnum = createZodEnum("classStatus");
593
- var sectionStatusEnum = createZodEnum("sectionStatus");
594
- var languageEnum = createZodEnum("language");
595
- var enrollmentStatusEnum = createZodEnum("enrollmentStatus");
596
- var assignmentStatusEnum = createZodEnum("assignmentStatus");
597
- var calendarSystemEnum = createZodEnum("calendarSystem");
598
- var assessmentTypeEnum = createZodEnum("assessmentType");
599
- var assessmentStatusEnum = createZodEnum("assessmentStatus");
600
- var submissionTypeEnum = createZodEnum("submissionType");
601
- var examTypeEnum = createZodEnum("examType");
602
- var examSecurityEnum = createZodEnum("examSecurity");
603
- var examStatusEnum = createZodEnum("examStatus");
604
- var gradeStatusEnum = createZodEnum("gradeStatus");
605
- var attendanceStatusEnum = createZodEnum("attendanceStatus");
606
- var proficiencyLevelEnum = createZodEnum("proficiencyLevel");
607
- var dayOfWeekEnum = createZodEnum("dayOfWeek");
608
- var alertTypeEnum = createZodEnum("alertType");
609
- var alertPriorityEnum = createZodEnum("alertPriority");
610
- var alertStatusEnum = createZodEnum("alertStatus");
611
- var feeTypeStatusEnum = createZodEnum("feeTypeStatus");
612
- var paymentTypeEnum = createZodEnum("paymentType");
613
- var scheduleEnum = createZodEnum("schedule");
614
- var feeStatusEnum = createZodEnum("feeStatus");
615
- var feeInstallmentStatusEnum = createZodEnum("feeInstallmentStatus");
616
- var paymentMethodEnum = createZodEnum("paymentMethod");
617
- var paymentStatusEnum = createZodEnum("paymentStatus");
618
- var eventTypeEnum = createZodEnum("eventType");
619
- var eventStatusEnum = createZodEnum("eventStatus");
620
- var eventVisibilityEnum = createZodEnum("eventVisibility");
621
- var participantTypeEnum = createZodEnum("participantType");
622
- var expenseCategoryEnum = createZodEnum("expenseCategory");
623
- var expenseStatusEnum = createZodEnum("expenseStatus");
624
- var trackerModeEnum = createZodEnum("trackerMode");
625
- var driverStatusEnum = createZodEnum("driverStatus");
626
- var vehicleStatusEnum = createZodEnum("vehicleStatus");
627
- var vehicleTypeEnum = createZodEnum("vehicleType");
628
- var vehicleDocumentTypeEnum = createZodEnum("vehicleDocumentType");
629
- var busStatusEnum = createZodEnum("busStatus");
630
- var refuelStatusEnum = createZodEnum("refuelStatus");
631
- var fuelTypeEnum = createZodEnum("fuelType");
632
- var maintenanceTypeEnum = createZodEnum("maintenanceType");
633
- var maintenanceStatusEnum = createZodEnum("maintenanceStatus");
634
- var maritalStatusEnum = createZodEnum("maritalStatus");
635
-
636
- // src/lib/validations.ts
637
- var requiredId = z2.preprocess((val) => val ?? "", z2.string().min(1, "ID is required"));
638
- var optionalId = z2.string().min(1, "ID cannot be empty").nullish().optional();
639
- var emailField = z2.string().email("Invalid email format").or(z2.literal(""));
640
- var phoneField = z2.string().regex(/^[\+]?[1-9][\d]{0,15}$/, "Invalid phone number");
641
- var nameField = z2.string().min(2, "Name must be at least 2 characters").max(100, "Name too long");
642
- var dateField = z2.string().regex(/^(\d{4}-\d{2}-\d{2}|\d{2}\/\d{2}\/\d{4}|\d{2}-\d{2}-\d{2}|\d{2}-\d{2}-\d{4})$/, "Date must be in YYYY-MM-DD, MM/DD/YYYY, DD/MM/YYYY, DD-MM-YY, or DD-MM-YYYY format");
643
- var optionalDateField = z2.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Date must be in YYYY-MM-DD format").nullable().optional();
644
- var timeField = z2.string().regex(/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/, "Time must be in HH:MM format").optional().nullable();
645
- var cinField = z2.string().min(8, "CIN must be at least 8 characters").max(20, "CIN too long");
646
- var addressField = z2.string().max(500, "Address too long").optional();
647
- var academicYearField = z2.string().min(9, "Academic year is required").regex(/^\d{4}-\d{4}$/, "Academic year must be in YYYY-YYYY format");
648
- var num = /* @__PURE__ */ __name(() => {
649
- const createChainable = /* @__PURE__ */ __name((currentSchema) => {
650
- const methods = {
651
- positive: /* @__PURE__ */ __name((msg = "Must be positive") => createChainable(currentSchema.refine((val) => val > 0, { message: msg })), "positive"),
652
- min: /* @__PURE__ */ __name((value, msg) => createChainable(currentSchema.refine((val) => val >= value, { message: msg || `Must be at least ${value}` })), "min"),
653
- max: /* @__PURE__ */ __name((value, msg) => createChainable(currentSchema.refine((val) => val <= value, { message: msg || `Cannot exceed ${value}` })), "max"),
654
- int: /* @__PURE__ */ __name((msg = "Must be an integer") => createChainable(currentSchema.refine((val) => Number.isInteger(val), { message: msg })), "int")
655
- };
656
- return Object.assign(currentSchema, methods);
657
- }, "createChainable");
658
- const isValidNumber = /* @__PURE__ */ __name((val) => {
659
- if (val === null || val === void 0 || Number.isNaN(val))
660
- return false;
661
- if (typeof val === "number")
662
- return true;
663
- if (typeof val === "string") {
664
- const trimmed = val.trim();
665
- return trimmed !== "" && !isNaN(Number(trimmed));
666
- }
667
- return false;
668
- }, "isValidNumber");
669
- const baseSchema = z2.any().refine(isValidNumber, { message: "Must be a valid number" }).transform((val) => typeof val === "string" ? Number(val) : val);
670
- return createChainable(baseSchema);
671
- }, "num");
672
- var userSchema = z2.object({
673
- id: optionalId,
674
- username: nameField.max(50).optional(),
675
- email: emailField,
676
- password: z2.string().min(8, "Password must be at least 8 characters"),
677
- roleId: optionalId,
678
- roleName: nameField.max(50).optional(),
679
- lastLogin: optionalDateField,
680
- image: z2.union([z2.string(), z2.instanceof(File), z2.undefined()]).optional(),
681
- emailVerified: z2.boolean().default(false),
682
- status: userStatusEnum2,
683
- createdAt: optionalDateField
684
- });
685
- var roleSchema = z2.object({
686
- id: optionalId,
687
- name: nameField.max(50),
688
- description: z2.string().max(255, "Description too long").optional(),
689
- createdAt: optionalDateField
690
- });
691
- var studentSchema = z2.object({
692
- id: optionalId,
693
- classId: requiredId,
694
- sectionId: requiredId,
695
- studentCode: z2.string(),
696
- name: nameField,
697
- email: emailField,
698
- phone: phoneField.nullish(),
699
- address: addressField,
700
- dateOfBirth: optionalDateField,
701
- gender: genderEnum,
702
- enrollmentDate: dateField,
703
- medicalConditions: z2.string().max(1e3, "Medical conditions description too long").nullish().optional(),
704
- previousSchool: z2.string().max(500, "Previous school name too long").optional().nullable(),
705
- image: z2.union([z2.string(), z2.instanceof(File), z2.null()]).optional(),
706
- status: studentStatusEnum2.default("active")
707
- });
708
- var parentSchema = z2.object({
709
- id: optionalId,
710
- name: nameField,
711
- email: emailField.optional(),
712
- phone: phoneField,
713
- gender: genderEnum.optional(),
714
- address: addressField,
715
- dateOfBirth: optionalDateField,
716
- cin: cinField,
717
- occupation: z2.string().max(100, "Occupation too long").optional(),
718
- nationality: z2.string().max(100, "Nationality too long").optional(),
719
- maritalStatus: z2.string().max(50, "Marital status too long").optional(),
720
- relationshipType: relationshipTypeEnum,
721
- image: z2.union([z2.string(), z2.instanceof(File), z2.null()]).optional(),
722
- isEmergencyContact: z2.boolean().optional().default(false),
723
- financialResponsibility: z2.boolean().optional().default(false)
724
- });
725
- var driverSchema = z2.object({
726
- id: optionalId,
727
- name: nameField,
728
- email: emailField,
729
- cin: cinField,
730
- phone: phoneField,
731
- address: addressField,
732
- gender: genderEnum.optional(),
733
- licenseNumber: z2.string().min(5, "License number must be at least 5 characters").max(20, "License number too long"),
734
- licenseType: z2.string().max(10, "License type too long"),
735
- licenseExpiry: dateField,
736
- hireDate: dateField,
737
- salary: num().positive("Salary must be positive").optional(),
738
- yearsOfExperience: num().int().min(0, "Years of experience must be non-negative").optional(),
739
- emergencyContact: nameField.optional(),
740
- emergencyPhone: phoneField.optional(),
741
- image: z2.union([z2.string(), z2.instanceof(File), z2.null()]).optional(),
742
- status: driverStatusEnum.default("active"),
743
- notes: z2.string().max(1e3, "Notes too long").optional().nullable()
744
- });
745
- var teacherPersonalSchema = z2.object({
746
- id: optionalId,
747
- name: nameField,
748
- cin: cinField,
749
- email: emailField,
750
- phone: phoneField,
751
- address: addressField,
752
- gender: genderEnum.optional(),
753
- emergencyContact: nameField.optional(),
754
- emergencyPhone: phoneField,
755
- status: teacherStatusEnum.default("active"),
756
- image: z2.union([z2.string(), z2.instanceof(File), z2.null()]).optional()
757
- });
758
- var teacherProfessionalSchema = z2.object({
759
- specialization: z2.string().max(100, "Specialization too long").optional(),
760
- yearsOfExperience: num().int().min(0, "Years of experience must be non-negative").optional(),
761
- salary: num().positive("Salary must be positive").optional(),
762
- hireDate: dateField,
763
- bankAccount: z2.coerce.string().max(100, { message: "Bank account too long" }).optional(),
764
- employmentType: employmentTypeEnum.optional(),
765
- workloadHours: num().int().min(0, "Workload hours must be non-negative").max(60, "Workload hours cannot exceed 60").optional(),
766
- academicDegrees: z2.string().max(500, "Academic degrees description too long").optional()
767
- });
768
- var assignmentSchema = z2.object({
769
- classId: z2.string().min(1, "Class is required"),
770
- sectionIds: z2.array(z2.string()).min(1, "At least one section is required"),
771
- subjectIds: z2.array(z2.string()).min(1, "At least one subject is required"),
772
- academicYear: z2.string().optional()
773
- });
774
- var assignmentsSchema = z2.object({
775
- assignments: z2.array(assignmentSchema).min(1, "At least one parent is required")
776
- });
777
- var teacherFullSchema = z2.object({
778
- ...teacherPersonalSchema.shape,
779
- ...teacherProfessionalSchema.shape,
780
- ...assignmentsSchema.shape
781
- });
782
- var feeTypeSchema = z2.object({
783
- id: optionalId,
784
- name: z2.string().min(2, "Fee type name must be at least 2 characters").max(100, "Fee type name too long"),
785
- description: z2.string().max(500, "Description too long").optional().nullable(),
786
- category: z2.string(),
787
- amount: num().positive("Amount must be greater than 0").max(1e5, "Amount too large"),
788
- paymentType: paymentTypeEnum.default("recurring"),
789
- status: feeTypeStatusEnum.default("active").optional()
790
- });
791
- var feeSchema = z2.object({
792
- id: optionalId,
793
- studentId: requiredId,
794
- feeTypeId: requiredId,
795
- academicYear: academicYearField.optional(),
796
- status: feeStatusEnum.optional(),
797
- schedule: scheduleEnum,
798
- baseAmount: num().positive("Base amount must be positive").optional(),
799
- grossAmount: num().positive("Gross amount must be positive").optional(),
800
- netAmount: num().optional(),
801
- paidAmount: num().min(0, "Paid amount cannot be negative").optional(),
802
- discountAmount: num().min(0, "Discount cannot be negative").optional(),
803
- discountReason: z2.string().max(500, "Discount reason too long").optional().nullable(),
804
- assignedBy: optionalId.nullable(),
805
- notes: z2.string().max(1e3, "Notes too long").optional().nullable()
806
- });
807
- var bulkFeeItemSchema = feeSchema.omit({ studentId: true });
808
- var bulkFeeFormSchema = z2.object({
809
- studentId: requiredId,
810
- fees: z2.array(bulkFeeItemSchema).min(1, "At least one fee is required")
811
- });
812
- var feeInstallmentSchema = z2.object({
813
- feeId: optionalId,
814
- number: num().int().min(1, "Installment must be at least 1"),
815
- dueDate: dateField,
816
- amount: num().positive("Amount must be greater than 0").max(1e5, "Amount too large"),
817
- paidAmount: num().min(0, "Paid amount cannot be negative").max(1e5, "Amount too large").optional(),
818
- status: feeInstallmentStatusEnum.optional()
819
- });
820
- var feePaymentSchema = z2.object({
821
- studentId: optionalId,
822
- amount: num().positive("Amount must be greater than 0").max(1e5, "Amount too large").optional(),
823
- paymentMethod: paymentMethodEnum,
824
- paymentDate: dateField,
825
- checkNumber: z2.preprocess((val) => val === "" ? null : val, z2.string().max(50, "Check number too long").optional().nullable()),
826
- checkDueDate: z2.preprocess((val) => val === "" ? null : val, optionalDateField.nullable()),
827
- transactionRef: z2.preprocess((val) => val === "" ? null : val, z2.string().max(100, "Transaction reference too long").optional().nullable()),
828
- receiptNumber: z2.preprocess((val) => val === "" ? null : val, z2.string().max(50, "Receipt number too long").optional().nullable()),
829
- status: paymentStatusEnum.default("completed"),
830
- processedBy: optionalId,
831
- notes: z2.preprocess((val) => val === "" ? null : val, z2.string().max(1e3, "Notes too long").optional().nullable()),
832
- allocations: z2.array(z2.object({
833
- feeId: optionalId,
834
- number: z2.number().int().positive("Installment must be a positive number"),
835
- amount: num().positive("Amount must be greater than 0")
836
- })).optional().nullable()
837
- });
838
- var paymentAllocationSchema = z2.object({
839
- paymentId: z2.string().min(1, "Payment ID is required"),
840
- feeId: z2.string().min(1, "Fee ID is required"),
841
- installmentId: z2.string().optional(),
842
- amount: z2.number().positive("Amount must be positive"),
843
- type: z2.enum(["fee", "installment"]).default("installment"),
844
- notes: z2.string().optional()
845
- });
846
- var parentsSchema = z2.object({
847
- parents: z2.array(parentSchema).optional().default([])
848
- });
849
- var feesSchema = z2.object({
850
- fees: z2.array(bulkFeeItemSchema).min(1, "At least one fee is required")
851
- });
852
- var fullStudentSchema = z2.object({
853
- ...studentSchema.shape,
854
- ...parentsSchema.shape,
855
- ...feesSchema.shape
856
- });
857
- var subjectSchema = z2.object({
858
- id: optionalId,
859
- code: z2.string().min(2, "Subject code must be at least 2 characters").max(10, "Subject code too long"),
860
- name: z2.string().min(2, "Subject name must be at least 2 characters").max(100, "Subject name too long"),
861
- description: z2.string().max(500, "Description too long").optional(),
862
- gradeLevel: num().int().min(1).max(12).optional()
863
- });
864
- var sectionSchema = z2.object({
865
- id: optionalId,
866
- classId: requiredId,
867
- name: z2.string().min(1, "Section name is required").max(10, "Section name too long"),
868
- maxStudents: num().int().min(1, "Max students must be at least 1").max(100, "Max students cannot exceed 100").default(30),
869
- roomNumber: num().max(1e4, "Room number too long").optional(),
870
- status: sectionStatusEnum.default("active")
871
- });
872
- var classSchema = z2.object({
873
- id: optionalId,
874
- name: z2.string().min(1, "Class name is required").max(50, "Class name too long"),
875
- description: z2.string().max(500, "Description too long").optional(),
876
- academicYear: academicYearField,
877
- level: z2.string().min(1, "Class level is required")
878
- });
879
- var attendanceSchema = z2.object({
880
- studentId: requiredId,
881
- teacherId: requiredId,
882
- subjectId: requiredId,
883
- sectionId: requiredId,
884
- date: dateField,
885
- status: attendanceStatusEnum.default("present"),
886
- notes: z2.string().max(500, "Notes too long").optional()
887
- });
888
- var assessmentSchema = z2.object({
889
- classId: requiredId,
890
- sectionId: requiredId,
891
- subjectId: requiredId,
892
- teacherId: requiredId,
893
- teacherAssignmentId: optionalId,
894
- title: z2.string().min(3, "Title must be at least 3 characters").max(200, "Title too long"),
895
- description: z2.string().max(1e3, "Description too long").optional().nullable(),
896
- type: assessmentTypeEnum.default("quiz"),
897
- date: dateField,
898
- duration: num().int().min(1, "Duration must be at least 1 minute").max(480, "Duration cannot exceed 8 hours"),
899
- totalMarks: num().positive("Total marks must be greater than 0").max(1e3, "Total marks cannot exceed 1000"),
900
- passingMarks: num().min(0, "Passing marks must be non-negative").max(1e3, "Passing marks cannot exceed 1000"),
901
- instructions: z2.string().max(2e3, "Instructions too long").optional().nullable(),
902
- status: assessmentStatusEnum.default("scheduled"),
903
- assessmentId: optionalId
904
- });
905
- var bulkAssessmentSchema = z2.object({
906
- assessments: z2.array(assessmentSchema).min(1, "At least one assessment is required").max(50, "Cannot create more than 50 assessments at once")
907
- });
908
- var gradeSchema = z2.object({
909
- assessmentId: requiredId,
910
- teacherId: requiredId,
911
- subjectId: requiredId,
912
- sectionId: requiredId,
913
- studentId: requiredId,
914
- gradeId: requiredId,
915
- assessmentTitle: z2.string().min(3, "Assessment title must be at least 3 characters").max(200, "Assessment title too long").optional(),
916
- marksObtained: num().min(0, "Marks obtained must be non-negative").max(1e3, "Marks obtained cannot exceed 1000"),
917
- feedback: z2.string().max(1e3, "Feedback too long").optional().nullable(),
918
- status: gradeStatusEnum.default("graded")
919
- });
920
- var examSchema = z2.object({
921
- classId: optionalId,
922
- sectionId: requiredId,
923
- subjectId: requiredId,
924
- teacherId: requiredId,
925
- examId: requiredId,
926
- teacherAssignmentId: requiredId,
927
- title: z2.string().min(3, "Title must be at least 3 characters").max(200, "Title too long"),
928
- description: z2.string().max(1e3, "Description too long").optional().nullable(),
929
- type: examTypeEnum.default("midterm"),
930
- date: dateField,
931
- startTime: timeField,
932
- endTime: timeField,
933
- duration: num().int().min(30, "Exam duration must be at least 30 minutes").max(480, "Duration cannot exceed 8 hours"),
934
- totalMarks: num().positive("Total marks must be greater than 0").max(1e3, "Total marks cannot exceed 1000"),
935
- passingMarks: num().min(0, "Passing marks must be non-negative").max(1e3, "Passing marks cannot exceed 1000"),
936
- roomNumber: num().max(50, "Room number too long").optional().nullable(),
937
- allowedMaterials: z2.string().max(500, "Allowed materials description too long").optional().nullable(),
938
- instructions: z2.string().max(2e3, "Instructions too long").optional().nullable(),
939
- status: examStatusEnum.default("scheduled")
940
- });
941
- var announcementSchema = z2.object({
942
- title: z2.string().min(3, "Title must be at least 3 characters").max(200, "Title too long"),
943
- content: z2.string().min(10, "Content must be at least 10 characters").max(5e3, "Content too long"),
944
- authorId: optionalId,
945
- targetAudience: z2.enum(["all", "students", "teachers", "parents", "class"]),
946
- classId: optionalId,
947
- isPublished: z2.boolean().default(false),
948
- publishDate: z2.string().datetime("Invalid publish date").optional(),
949
- expiryDate: z2.string().datetime("Invalid expiry date").optional()
950
- });
951
- var alertSchema = z2.object({
952
- type: alertTypeEnum,
953
- title: z2.string().min(3, "Title must be at least 3 characters").max(200, "Title too long"),
954
- message: z2.string().min(10, "Message must be at least 10 characters").max(2e3, "Message too long"),
955
- priority: alertPriorityEnum.default("medium"),
956
- status: alertStatusEnum.default("active"),
957
- studentId: optionalId,
958
- teacherId: optionalId,
959
- classId: optionalId,
960
- subjectId: optionalId,
961
- targetAudience: z2.enum(["all", "students", "teachers", "parents"]).optional(),
962
- authorId: optionalId,
963
- isRead: z2.boolean().default(false)
964
- });
965
- var eventSchema = z2.object({
966
- title: z2.string().min(3, "Title must be at least 3 characters").max(200, "Title too long"),
967
- description: z2.string().max(5e3, "Description too long").optional().nullable(),
968
- type: eventTypeEnum,
969
- startDate: dateField,
970
- endDate: dateField,
971
- startTime: timeField,
972
- endTime: timeField,
973
- location: z2.string().max(200, "Location too long").optional().nullable(),
974
- venue: z2.string().max(200, "Venue too long").optional().nullable(),
975
- organizerId: optionalId,
976
- classId: optionalId.nullable(),
977
- sectionId: optionalId.nullable(),
978
- visibility: eventVisibilityEnum.default("public"),
979
- status: eventStatusEnum.default("scheduled"),
980
- capacity: num().int().positive("Capacity must be positive").optional().nullable(),
981
- registrationRequired: z2.boolean().default(false),
982
- registrationDeadline: optionalDateField.nullable(),
983
- attachments: z2.any().optional().nullable(),
984
- notes: z2.string().max(2e3, "Notes too long").optional().nullable()
985
- });
986
- var eventParticipantSchema = z2.object({
987
- eventId: optionalId,
988
- participantId: optionalId,
989
- participantType: participantTypeEnum,
990
- attendanceStatus: attendanceStatusEnum.optional().nullable(),
991
- notes: z2.string().max(500, "Notes too long").optional().nullable()
992
- });
993
- var expenseSchema = z2.object({
994
- id: optionalId,
995
- category: expenseCategoryEnum,
996
- title: z2.string().min(3, "Title must be at least 3 characters").max(200, "Title too long"),
997
- amount: num().positive("Amount must be greater than 0").max(1e7, "Amount too large"),
998
- expenseDate: dateField,
999
- paymentMethod: paymentMethodEnum.optional().nullable(),
1000
- paymentDate: optionalDateField.nullable(),
1001
- vendor: z2.string().max(200, "Vendor name too long").optional().nullable(),
1002
- invoiceNumber: z2.string().max(100, "Invoice number too long").optional().nullable(),
1003
- receiptNumber: z2.string().max(100, "Receipt number too long").optional().nullable(),
1004
- checkNumber: z2.string().max(50, "Check number too long").optional().nullable(),
1005
- transactionRef: z2.string().max(100, "Transaction reference too long").optional().nullable(),
1006
- status: expenseStatusEnum.default("pending"),
1007
- notes: z2.string().max(1e3, "Notes too long").optional().nullable()
1008
- });
1009
- var expenseApprovalSchema = z2.object({
1010
- action: z2.enum(["approve", "reject"]),
1011
- rejectionReason: z2.string().min(10, "Rejection reason must be at least 10 characters").max(1e3, "Rejection reason too long").optional().nullable()
1012
- });
1013
- var expensePaymentSchema = z2.object({
1014
- paymentMethod: paymentMethodEnum,
1015
- paymentDate: dateField,
1016
- checkNumber: z2.string().max(50, "Check number too long").optional().nullable(),
1017
- transactionRef: z2.string().max(100, "Transaction reference too long").optional().nullable(),
1018
- notes: z2.string().max(1e3, "Notes too long").optional().nullable()
1019
- });
1020
- var vehicleSchema = z2.object({
1021
- id: optionalId,
1022
- name: z2.string().min(2, "Vehicle name must be at least 2 characters").max(100, "Vehicle name too long"),
1023
- brand: z2.string().min(2, "Brand must be at least 2 characters").max(100, "Brand too long"),
1024
- model: z2.string().min(2, "Model must be at least 2 characters").max(100, "Model too long"),
1025
- year: num().int().min(1900, "Year must be after 1900").max((/* @__PURE__ */ new Date()).getFullYear() + 1, "Year cannot be in future"),
1026
- type: vehicleTypeEnum.default("fullbus"),
1027
- capacity: num().int().min(1, "Capacity must be at least 1").max(200, "Capacity cannot exceed 200"),
1028
- licensePlate: z2.string().min(2, "License plate must be at least 2 characters").max(50, "License plate too long"),
1029
- driverId: optionalId.nullable(),
1030
- image: z2.string().max(500, "Image path too long").optional().nullable().default("novehicle.png"),
1031
- purchaseDate: optionalDateField.nullable(),
1032
- purchasePrice: num().min(0, "Purchase price must be non-negative").max(1e7, "Purchase price too large").optional().nullable(),
1033
- initialMileage: num().min(0, "Initial mileage must be non-negative").max(1e7, "Initial mileage too large").optional().nullable(),
1034
- currentMileage: num().min(0, "Current mileage must be non-negative").max(1e7, "Current mileage too large").optional().nullable(),
1035
- status: vehicleStatusEnum.default("active"),
1036
- notes: z2.string().max(1e3, "Notes too long").optional().nullable()
1037
- });
1038
- var refuelSchema = z2.object({
1039
- id: optionalId,
1040
- busId: optionalId,
1041
- refuelDate: dateField,
1042
- quantity: num().positive("Quantity must be greater than 0").max(1e4, "Quantity too large"),
1043
- unitPrice: num().positive("Unit price must be greater than 0").max(1e5, "Unit price too large"),
1044
- totalCost: num().positive("Total cost must be greater than 0").max(1e7, "Total cost too large").optional(),
1045
- fuelType: fuelTypeEnum.default("diesel"),
1046
- odometer: num().min(0, "Odometer must be non-negative").max(1e7, "Odometer value too large").optional().nullable(),
1047
- fuelStation: z2.string().max(200, "Fuel station name too long").optional().nullable(),
1048
- invoiceNumber: z2.string().max(100, "Invoice number too long").optional().nullable(),
1049
- paymentMethod: paymentMethodEnum.optional().nullable(),
1050
- paidBy: optionalId.nullable(),
1051
- status: refuelStatusEnum.default("completed"),
1052
- notes: z2.string().max(1e3, "Notes too long").optional().nullable()
1053
- });
1054
- var settingsSchema = z2.object({
1055
- // School Information
1056
- schoolName: z2.string().min(2, "School name must be at least 2 characters").max(200, "School name too long"),
1057
- schoolAddress: z2.string().max(500, "School address too long").optional(),
1058
- schoolPhone: phoneField,
1059
- schoolEmail: emailField,
1060
- schoolWebsite: z2.string().url("Must be a valid URL").max(255, "School website URL too long").optional(),
1061
- // New
1062
- schoolLogo: z2.string().url("Must be a valid image URL").max(255, "School logo URL too long").optional(),
1063
- // New
1064
- currentAcademicYear: academicYearField,
1065
- // Academic Settings
1066
- gradingScale: z2.any().optional(),
1067
- attendanceRequirement: num().min(0, "Attendance requirement must be non-negative").max(100, "Attendance requirement cannot exceed 100").default(75),
1068
- maxClassSize: num().int("Max class size must be an integer").min(1, "Max class size must be at least 1").max(200, "Max class size cannot exceed 200").default(34),
1069
- minimumPassingGrade: num().min(0, "Minimum passing grade must be non-negative").max(100, "Minimum passing grade cannot exceed 100").default(60),
1070
- defaultExamDuration: num().int("Default exam duration must be in minutes").min(15, "Exam duration must be at least 15 minutes").max(480, "Exam duration cannot exceed 480 minutes").default(120),
1071
- calendarSystem: calendarSystemEnum.default("SEMESTER"),
1072
- startMonth: z2.string().default("september"),
1073
- endMonth: z2.string().default("june"),
1074
- // Notification Settings
1075
- academicAlerts: z2.boolean().default(true),
1076
- attendanceAlerts: z2.boolean().default(true),
1077
- eventAlerts: z2.boolean().default(true),
1078
- homeworkAlerts: z2.boolean().default(true),
1079
- feesReminder: z2.boolean().default(true),
1080
- feesOverdueAlerts: z2.boolean().default(true),
1081
- emailNotifications: z2.boolean().default(true),
1082
- smsNotifications: z2.boolean().default(false),
1083
- parentNotifications: z2.boolean().default(true),
1084
- lowGradeAlerts: z2.boolean().default(true),
1085
- allowLateSubmission: z2.boolean().default(true),
1086
- examResultsAlerts: z2.boolean().default(true),
1087
- disciplinaryAlerts: z2.boolean().default(true),
1088
- achievementAlerts: z2.boolean().default(true),
1089
- maintenanceNotifications: z2.boolean().default(true),
1090
- // Security Settings
1091
- twoFactorEnabled: z2.boolean().default(false),
1092
- sessionTimeout: z2.string().regex(/^\d{1,4}$/, "Session timeout must be a number between 1-9999 minutes").default("60"),
1093
- passwordRequireSymbols: z2.boolean().default(true),
1094
- loginNotifications: z2.boolean().default(true),
1095
- parentAccessEnabled: z2.boolean().default(true),
1096
- teacherAccessEnabled: z2.boolean().default(true),
1097
- studentAccessEnabled: z2.boolean().default(true),
1098
- // System Preferences
1099
- timeZone: z2.string().min(1, "Time zone is required").default("UTC"),
1100
- language: languageEnum.default("en"),
1101
- theme: z2.enum(["light", "dark", "system"]).default("system"),
1102
- dateFormat: z2.enum(["YYYY-MM-DD", "MM/DD/YYYY", "DD/MM/YYYY", "DD-MM-YY", "DD-MM-YYYY"]).default("MM/DD/YYYY"),
1103
- // Adjusted default to match table
1104
- timeFormat: z2.enum(["12", "24"]).default("12"),
1105
- currency: z2.string().length(3, "Currency must be a 3-letter ISO code").regex(/^[A-Z]{3}$/, "Currency must be uppercase ISO code").default("USD"),
1106
- // Academic Calendar Settings
1107
- gradingPeriods: num().int("Grading periods must be an integer").min(1, "Grading periods must be at least 1").max(12, "Grading periods cannot exceed 12").default(4),
1108
- schoolStartTime: z2.string().regex(/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/, "Invalid start time format (HH:MM)").default("08:00"),
1109
- schoolEndTime: z2.string().regex(/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/, "Invalid end time format (HH:MM)").default("15:00"),
1110
- lunchBreakDuration: num().int("Lunch break duration must be in minutes").min(15, "Lunch break must be at least 15 minutes").max(120, "Lunch break cannot exceed 120 minutes").default(30),
1111
- // Maintenance & Backup Settings
1112
- maintenanceMode: z2.boolean().default(false),
1113
- autoBackup: z2.boolean().default(true)
1114
- });
1115
- var idParamSchema = z2.object({
1116
- id: optionalId
1117
- });
1118
- var paginationSchema = z2.object({
1119
- page: num().int().min(1).default(1),
1120
- limit: num().int().min(1).max(100).default(10)
1121
- });
1122
- var dateRangeSchema = z2.object({
1123
- dateFrom: dateField,
1124
- dateTo: dateField
1125
- });
1126
-
1127
- // src/users/UserValidator.ts
1128
- var __decorate4 = function(decorators, target, key, desc) {
1129
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1130
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1131
- 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;
1132
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1133
- };
1134
- var __metadata2 = function(k, v) {
1135
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1136
- };
1137
- var _a4;
1138
- var _b;
1139
- var _a5;
1140
- var UserValidator = (_a5 = class {
1141
- constructor(userRepository, encryptionService) {
1142
- this.userRepository = userRepository;
1143
- this.encryptionService = encryptionService;
1144
- }
1145
- async validateCreateUser(data) {
1146
- return parseSchema(userSchema, data);
1147
- }
1148
- async isEmailExists(email) {
1149
- const existingUser = await this.userRepository.getByEmail(email);
1150
- return !!existingUser;
1151
- }
1152
- async isPasswordValid(password, hashedPassword) {
1153
- const isPasswordValid = await this.encryptionService.comparePassword(password, hashedPassword);
1154
- return !!isPasswordValid;
1155
- }
1156
- async isUserExist(id) {
1157
- const existingUser = await this.userRepository.getById(id);
1158
- return !!existingUser;
1159
- }
1160
- async checkUserIdIsUnique(id) {
1161
- if (!id)
1162
- return;
1163
- const existingUser = await this.userRepository.getById(id);
1164
- if (existingUser) {
1165
- throw new Error(t("users.errors.idExists"));
1166
- }
1167
- }
1168
- async isCorrectPass(password) {
1169
- return password && typeof password === "string" && password.trim().length > 0;
1170
- }
1171
- async hasRole(userId, roles) {
1172
- const roleName = await this.userRepository.getRoleNameById(userId);
1173
- if (!roleName) {
1174
- throw Error(t("auth.errors.accessDenied"));
1175
- }
1176
- const hasRole = roles.some((item) => roleName.toLowerCase() === item.toLowerCase());
1177
- if (!hasRole) {
1178
- throw Error(t("auth.errors.accessDenied"));
1179
- }
1180
- return true;
1181
- }
1182
- //======================= throw errors
1183
- async checkUserExistsByEmail(email) {
1184
- const user = await this.userRepository.getByEmail(email);
1185
- if (!user) {
1186
- throw new Error(t("auth.errors.invalidCredentials"));
1187
- }
1188
- return user;
1189
- }
1190
- async checkUserExists(id) {
1191
- const userExists = await this.isUserExist(id);
1192
- if (!userExists) {
1193
- throw new Error(t("users.errors.notFound"));
1194
- }
1195
- return userExists;
1196
- }
1197
- async checkEmailUnique(email, excludeId = null) {
1198
- if (!email)
1199
- return;
1200
- const existingUser = await this.userRepository.getByEmail(email);
1201
- if (existingUser && existingUser.id !== excludeId) {
1202
- throw new Error(t("auth.errors.emailExists"));
1203
- }
1204
- }
1205
- async checkEmailExists(email) {
1206
- const user = await this.userRepository.getByEmail(email);
1207
- if (!user) {
1208
- throw new Error(t("users.errors.notFound"));
1209
- }
1210
- return user;
1211
- }
1212
- async checkPasswordValid(password, hashedPassword) {
1213
- const isPasswordValid = await this.isPasswordValid(password, hashedPassword);
1214
- if (!isPasswordValid) {
1215
- throw new Error(t("auth.errors.invalidCredentials"));
1216
- }
1217
- }
1218
- }, __name(_a5, "UserValidator"), _a5);
1219
- UserValidator = __decorate4([
1220
- Injectable3(),
1221
- __metadata2("design:paramtypes", [typeof (_a4 = typeof UserRepository !== "undefined" && UserRepository) === "function" ? _a4 : Object, typeof (_b = typeof EncryptionService !== "undefined" && EncryptionService) === "function" ? _b : Object])
1222
- ], UserValidator);
1223
-
1224
- // src/users/UserService.ts
1225
- import { Injectable as Injectable8, setLanguage, getCurrentLanguage, Transactional } from "najm-api";
1226
-
1227
- // src/roles/RoleRepository.ts
1228
- import { eq as eq2 } from "drizzle-orm";
1229
- import { Repository as Repository2 } from "najm-api";
1230
- var __decorate5 = function(decorators, target, key, desc) {
1231
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1232
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1233
- 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;
1234
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1235
- };
1236
- var _a6;
1237
- var RoleRepository = (_a6 = class {
1238
- async getAll() {
1239
- return await this.db.select().from(rolesTable);
1240
- }
1241
- async getById(id) {
1242
- const [existingRole] = await this.db.select().from(rolesTable).where(eq2(rolesTable.id, id));
1243
- return existingRole;
1244
- }
1245
- async getByName(name) {
1246
- const [existingRole] = await this.db.select().from(rolesTable).where(eq2(rolesTable.name, name));
1247
- return existingRole;
1248
- }
1249
- async create(data) {
1250
- const [newRole] = await this.db.insert(rolesTable).values(data).returning();
1251
- return newRole;
1252
- }
1253
- async update(id, data) {
1254
- const [updatedRole] = await this.db.update(rolesTable).set(data).where(eq2(rolesTable.id, id)).returning();
1255
- return updatedRole;
1256
- }
1257
- async delete(id) {
1258
- const [deletedRole] = await this.db.delete(rolesTable).where(eq2(rolesTable.id, id)).returning();
1259
- return deletedRole;
1260
- }
1261
- }, __name(_a6, "RoleRepository"), _a6);
1262
- RoleRepository = __decorate5([
1263
- Repository2()
1264
- ], RoleRepository);
1265
-
1266
- // src/roles/RoleValidator.ts
1267
- import { Injectable as Injectable4, t as t2 } from "najm-api";
1268
- var __decorate6 = function(decorators, target, key, desc) {
1269
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1270
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1271
- 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;
1272
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1273
- };
1274
- var __metadata3 = function(k, v) {
1275
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1276
- };
1277
- var _a7;
1278
- var _a8;
1279
- var RoleValidator = (_a8 = class {
1280
- constructor(roleRepository) {
1281
- this.roleRepository = roleRepository;
1282
- }
1283
- async validateCreateRole(data) {
1284
- return parseSchema(roleSchema, data);
1285
- }
1286
- async isRoleNameExists(roleName) {
1287
- const existingRole = await this.roleRepository.getByName(roleName);
1288
- return !!existingRole;
1289
- }
1290
- async isRoleIdExists(id) {
1291
- const existingRole = await this.roleRepository.getById(id);
1292
- return !!existingRole;
1293
- }
1294
- async checkNameUnique(roleName, excludeId = null) {
1295
- if (!roleName)
1296
- return;
1297
- const existingRole = await this.roleRepository.getByName(roleName);
1298
- if (existingRole && existingRole.id !== excludeId) {
1299
- throw new Error(t2("roles.errors.exists"));
1300
- }
1301
- }
1302
- async checkRoleExists(id) {
1303
- const roleIdExists = await this.isRoleIdExists(id);
1304
- if (!roleIdExists) {
1305
- throw new Error(t2("roles.errors.notFound"));
1306
- }
1307
- }
1308
- async checkRoleExistsByName(roleName) {
1309
- const roleNameExists = await this.isRoleNameExists(roleName);
1310
- if (!roleNameExists) {
1311
- throw new Error(t2("roles.errors.notFound"));
1312
- }
1313
- }
1314
- async checkAdminRoleExists() {
1315
- const adminRole = await this.roleRepository.getByName("admin");
1316
- if (!adminRole) {
1317
- throw new Error(t2("users.errors.adminRoleNotFound"));
1318
- }
1319
- return adminRole;
1320
- }
1321
- }, __name(_a8, "RoleValidator"), _a8);
1322
- RoleValidator = __decorate6([
1323
- Injectable4(),
1324
- __metadata3("design:paramtypes", [typeof (_a7 = typeof RoleRepository !== "undefined" && RoleRepository) === "function" ? _a7 : Object])
1325
- ], RoleValidator);
1326
-
1327
- // src/roles/RoleGuards.ts
1328
- import { Injectable as Injectable6, Headers, createGuard, GuardParams, Ctx } from "najm-api";
1329
-
1330
- // src/tokens/TokenRepository.ts
1331
- import { eq as eq3 } from "drizzle-orm";
1332
- import { Repository as Repository3 } from "najm-api";
1333
- var __decorate7 = function(decorators, target, key, desc) {
1334
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1335
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1336
- 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;
1337
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1338
- };
1339
- var _a9;
1340
- var TokenRepository = (_a9 = class {
1341
- async storeRefreshToken(tokenData) {
1342
- return await this.db.insert(tokensTable).values(tokenData).onConflictDoUpdate({
1343
- target: tokensTable.userId,
1344
- set: {
1345
- token: tokenData.token,
1346
- expiresAt: tokenData.expiresAt
1347
- }
1348
- }).returning();
1349
- }
1350
- async getRefreshToken(userId) {
1351
- const [token] = await this.db.select().from(tokensTable).where(eq3(tokensTable.userId, userId));
1352
- return token?.token;
1353
- }
1354
- async revokeToken(userId) {
1355
- const [deletedToken] = await this.db.delete(tokensTable).where(eq3(tokensTable.userId, userId)).returning();
1356
- return deletedToken;
1357
- }
1358
- async isUserExists(userId) {
1359
- const [user] = await this.db.select({ id: usersTable.id }).from(usersTable).where(eq3(usersTable.id, userId)).limit(1);
1360
- return !!user;
1361
- }
1362
- async getRoleNameById(userId) {
1363
- const [role] = await this.db.select({
1364
- roleName: rolesTable.name
1365
- }).from(usersTable).leftJoin(rolesTable, eq3(usersTable.roleId, rolesTable.id)).where(eq3(usersTable.id, userId)).limit(1);
1366
- return role?.roleName;
1367
- }
1368
- async getUserPermissions(userId) {
1369
- const [user] = await this.db.select({ roleId: usersTable.roleId }).from(usersTable).where(eq3(usersTable.id, userId)).limit(1);
1370
- if (!user || !user.roleId)
1371
- return [];
1372
- const userPermissions = await this.db.select({
1373
- name: permissionsTable.name
1374
- }).from(rolePermissionsTable).leftJoin(permissionsTable, eq3(rolePermissionsTable.permissionId, permissionsTable.id)).where(eq3(rolePermissionsTable.roleId, user.roleId));
1375
- return userPermissions.map((p) => p.name).filter((name) => name);
1376
- }
1377
- async getUser(userId) {
1378
- const [user] = await this.db.select({
1379
- id: usersTable.id,
1380
- email: usersTable.email,
1381
- status: usersTable.status,
1382
- roleId: usersTable.roleId,
1383
- roleName: rolesTable.name,
1384
- createdAt: usersTable.createdAt,
1385
- updatedAt: usersTable.updatedAt
1386
- }).from(usersTable).leftJoin(rolesTable, eq3(usersTable.roleId, rolesTable.id)).where(eq3(usersTable.id, userId)).limit(1);
1387
- return user ? { ...user, role: user.roleName } : null;
1388
- }
1389
- }, __name(_a9, "TokenRepository"), _a9);
1390
- TokenRepository = __decorate7([
1391
- Repository3()
1392
- ], TokenRepository);
1393
-
1394
- // src/tokens/TokenService.ts
1395
- import { t as t3 } from "najm-api";
1396
- import { getCookie, Injectable as Injectable5 } from "najm-api";
1397
- import jwt from "jsonwebtoken";
1398
- import { jwtDecode } from "jwt-decode";
1399
- import timestring2 from "timestring";
1400
- var __decorate8 = function(decorators, target, key, desc) {
1401
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1402
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1403
- 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;
1404
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1405
- };
1406
- var __metadata4 = function(k, v) {
1407
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1408
- };
1409
- var _a10;
1410
- var _a11;
1411
- var TokenService = (_a11 = class {
1412
- constructor(tokenRepository) {
1413
- this.tokenRepository = tokenRepository;
1414
- this.accessSecretKey = process.env.JWT_ACCESS_SECRET;
1415
- this.accessExpiresIn = process.env.ACCESS_EXPIRES_IN;
1416
- this.refreshSecretKey = process.env.JWT_REFRESH_SECRET;
1417
- this.refreshExpiresIn = process.env.REFRESH_EXPIRES_IN;
1418
- }
1419
- //==== Validate tokens
1420
- extractAccessToken(authorization) {
1421
- if (authorization && authorization.startsWith("Bearer")) {
1422
- return authorization.split(" ")[1];
1423
- }
1424
- throw new Error(t3("auth.errors.tokenMissing"));
1425
- }
1426
- verifyAccessToken(token) {
1427
- try {
1428
- return jwt.verify(token, this.accessSecretKey);
1429
- } catch (error) {
1430
- throw new Error(t3("auth.errors.tokenVerificationFailed"));
1431
- }
1432
- }
1433
- verifyRefreshToken(token) {
1434
- try {
1435
- const decoded = jwt.verify(token, this.refreshSecretKey);
1436
- return decoded.userId;
1437
- } catch (error) {
1438
- throw new Error(t3("auth.errors.tokenVerificationFailed"));
1439
- }
1440
- }
1441
- async getUserIdByAccessToken(header) {
1442
- const token = this.extractAccessToken(header);
1443
- const decodedToken = this.verifyAccessToken(token);
1444
- const userId = decodedToken.userId;
1445
- const userExists = await this.tokenRepository.isUserExists(userId);
1446
- if (!userExists) {
1447
- throw new Error(t3("users.errors.notFound"));
1448
- }
1449
- return userId;
1450
- }
1451
- //=== Generate tokens
1452
- async storeRefreshToken(userId, refreshToken) {
1453
- const expireInSecond = timestring2(this.refreshExpiresIn, "s");
1454
- const tokenData = {
1455
- userId,
1456
- token: refreshToken,
1457
- expiresAt: new Date(Date.now() + expireInSecond * 1e3).toISOString()
1458
- };
1459
- await this.tokenRepository.storeRefreshToken(tokenData);
1460
- }
1461
- getTokenExpire(token) {
1462
- return jwtDecode(token).exp;
1463
- }
1464
- generateAccessToken(data) {
1465
- const options = { expiresIn: this.accessExpiresIn };
1466
- return jwt.sign(data, this.accessSecretKey, options);
1467
- }
1468
- generateRefreshToken(data) {
1469
- const options = { expiresIn: this.refreshExpiresIn };
1470
- return jwt.sign(data, this.refreshSecretKey, options);
1471
- }
1472
- async generateTokens(userId) {
1473
- const tokenData = { userId };
1474
- const accessToken = await this.generateAccessToken(tokenData);
1475
- const refreshToken = await this.generateRefreshToken(tokenData);
1476
- const accessTokenExpiresAt = this.getTokenExpire(accessToken);
1477
- const refreshTokenExpiresAt = this.getTokenExpire(refreshToken);
1478
- await this.storeRefreshToken(userId, refreshToken);
1479
- return {
1480
- accessToken,
1481
- refreshToken,
1482
- accessTokenExpiresAt,
1483
- refreshTokenExpiresAt
1484
- };
1485
- }
1486
- async refreshTokens() {
1487
- const newRefreshToken = getCookie("refreshToken");
1488
- const userId = this.verifyRefreshToken(newRefreshToken);
1489
- const userExists = await this.tokenRepository.isUserExists(userId);
1490
- if (!userExists) {
1491
- throw new Error(t3("users.errors.notFound"));
1492
- }
1493
- const storedRefreshToken = await this.tokenRepository.getRefreshToken(userId);
1494
- if (newRefreshToken != storedRefreshToken) {
1495
- throw new Error(t3("auth.errors.refreshTokenInvalid"));
1496
- }
1497
- return await this.generateTokens(userId);
1498
- }
1499
- async revokeToken(userId) {
1500
- return await this.tokenRepository.revokeToken(userId);
1501
- }
1502
- async getUserPermissions(auth) {
1503
- if (!auth)
1504
- return;
1505
- const userId = await this.getUserIdByAccessToken(auth);
1506
- const permissions = await this.tokenRepository.getUserPermissions(userId);
1507
- return permissions;
1508
- }
1509
- async getUserRole(auth) {
1510
- if (!auth)
1511
- return;
1512
- const userId = await this.getUserIdByAccessToken(auth);
1513
- const roleName = await this.tokenRepository.getRoleNameById(userId);
1514
- return roleName;
1515
- }
1516
- async getUser(auth) {
1517
- if (!auth)
1518
- return;
1519
- const userId = await this.getUserIdByAccessToken(auth);
1520
- const user = await this.tokenRepository.getUser(userId);
1521
- if (!user)
1522
- return null;
1523
- return user;
1524
- }
1525
- async storeUserInCache(auth, ctx) {
1526
- const cachedUser = ctx.get("user");
1527
- if (cachedUser)
1528
- return cachedUser;
1529
- const user = await this.getUser(auth);
1530
- if (user) {
1531
- ctx.set("user", user);
1532
- }
1533
- return user;
1534
- }
1535
- }, __name(_a11, "TokenService"), _a11);
1536
- TokenService = __decorate8([
1537
- Injectable5(),
1538
- __metadata4("design:paramtypes", [typeof (_a10 = typeof TokenRepository !== "undefined" && TokenRepository) === "function" ? _a10 : Object])
1539
- ], TokenService);
1540
-
1541
- // src/roles/RoleGuards.ts
1542
- var __decorate9 = function(decorators, target, key, desc) {
1543
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1544
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1545
- 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;
1546
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1547
- };
1548
- var __metadata5 = function(k, v) {
1549
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1550
- };
1551
- var __param = function(paramIndex, decorator) {
1552
- return function(target, key) {
1553
- decorator(target, key, paramIndex);
1554
- };
1555
- };
1556
- var _a12;
1557
- var ROLES = {
1558
- ADMIN: "admin",
1559
- PRINCIPAL: "principal",
1560
- ACCOUNTING: "accounting",
1561
- SECRETARY: "secretary",
1562
- TEACHER: "teacher",
1563
- STUDENT: "student",
1564
- PARENT: "parent"
1565
- };
1566
- var ROLE_GROUPS = {
1567
- ADMINISTRATORS: [ROLES.ADMIN, ROLES.PRINCIPAL],
1568
- FINANCIAL: [ROLES.ADMIN, ROLES.ACCOUNTING],
1569
- STAFF: [ROLES.ADMIN, ROLES.PRINCIPAL, ROLES.ACCOUNTING, ROLES.SECRETARY, ROLES.TEACHER],
1570
- END_USERS: [ROLES.STUDENT, ROLES.PARENT],
1571
- ALL: [ROLES.ADMIN, ROLES.PRINCIPAL, ROLES.ACCOUNTING, ROLES.SECRETARY, ROLES.TEACHER, ROLES.STUDENT, ROLES.PARENT]
1572
- };
1573
- var _a13;
1574
- var RoleChecker = (_a13 = class {
1575
- isInGroup(userRole, group) {
1576
- return group.includes(userRole?.toLowerCase());
1577
- }
1578
- isAdministrator(userRole) {
1579
- return this.isInGroup(userRole, ROLE_GROUPS.ADMINISTRATORS);
1580
- }
1581
- isStaff(userRole) {
1582
- return this.isInGroup(userRole, ROLE_GROUPS.STAFF);
1583
- }
1584
- hasAnyRole(userRole, roles) {
1585
- return roles.includes(userRole?.toLowerCase());
1586
- }
1587
- hasExactRole(userRole, requiredRole) {
1588
- return userRole?.toLowerCase() === requiredRole?.toLowerCase();
1589
- }
1590
- }, __name(_a13, "RoleChecker"), _a13);
1591
- RoleChecker = __decorate9([
1592
- Injectable6()
1593
- ], RoleChecker);
1594
- var _a14;
1595
- var RoleGuards = (_a14 = class {
1596
- constructor(roleChecker, tokenService) {
1597
- this.roleChecker = roleChecker;
1598
- this.tokenService = tokenService;
1599
- }
1600
- async isAuth(auth, ctx) {
1601
- const user = await this.tokenService.storeUserInCache(auth, ctx);
1602
- return !!user;
1603
- }
1604
- async hasRoles(auth, ctx, roles) {
1605
- try {
1606
- const user = await this.tokenService.storeUserInCache(auth, ctx);
1607
- if (!user?.role)
1608
- return false;
1609
- const roleArray = Array.isArray(roles) ? roles : [roles];
1610
- return this.roleChecker.hasAnyRole(user.role, roleArray);
1611
- } catch {
1612
- return false;
1613
- }
1614
- }
1615
- }, __name(_a14, "RoleGuards"), _a14);
1616
- __decorate9([
1617
- __param(0, Headers("authorization")),
1618
- __param(1, Ctx()),
1619
- __metadata5("design:type", Function),
1620
- __metadata5("design:paramtypes", [Object, Object]),
1621
- __metadata5("design:returntype", Promise)
1622
- ], RoleGuards.prototype, "isAuth", null);
1623
- __decorate9([
1624
- __param(0, Headers("authorization")),
1625
- __param(1, Ctx()),
1626
- __param(2, GuardParams()),
1627
- __metadata5("design:type", Function),
1628
- __metadata5("design:paramtypes", [Object, Object, Object]),
1629
- __metadata5("design:returntype", Promise)
1630
- ], RoleGuards.prototype, "hasRoles", null);
1631
- RoleGuards = __decorate9([
1632
- Injectable6(),
1633
- __metadata5("design:paramtypes", [RoleChecker, typeof (_a12 = typeof TokenService !== "undefined" && TokenService) === "function" ? _a12 : Object])
1634
- ], RoleGuards);
1635
- var isAdmin = /* @__PURE__ */ __name(() => Role("admin"), "isAdmin");
1636
- var isPrincipal = /* @__PURE__ */ __name(() => Role("principal"), "isPrincipal");
1637
- var isAccounting = /* @__PURE__ */ __name(() => Role("accounting"), "isAccounting");
1638
- var isSecretary = /* @__PURE__ */ __name(() => Role("secretary"), "isSecretary");
1639
- var isTeacher = /* @__PURE__ */ __name(() => Role("teacher"), "isTeacher");
1640
- var isParent = /* @__PURE__ */ __name(() => Role("parent"), "isParent");
1641
- var isStudent = /* @__PURE__ */ __name(() => Role("student"), "isStudent");
1642
- var isAdministrator = /* @__PURE__ */ __name(() => Role("admin", "principal"), "isAdministrator");
1643
- var isFinancial = /* @__PURE__ */ __name(() => Role("admin", "accounting"), "isFinancial");
1644
- var isStaff = /* @__PURE__ */ __name(() => Role("admin", "principal", "accounting", "secretary", "teacher"), "isStaff");
1645
- var isAuth = createGuard(RoleGuards, "isAuth");
1646
- var Role = /* @__PURE__ */ __name((...roles) => createGuard(RoleGuards, "hasRoles")(...roles), "Role");
1647
-
1648
- // src/roles/RoleController.ts
1649
- import { Controller, Get, Post, Put, Delete, Params, Body, t as t4 } from "najm-api";
1650
-
1651
- // src/roles/RoleService.ts
1652
- import { Injectable as Injectable7 } from "najm-api";
1653
- var __decorate10 = function(decorators, target, key, desc) {
1654
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1655
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1656
- 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;
1657
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1658
- };
1659
- var __metadata6 = function(k, v) {
1660
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1661
- };
1662
- var _a15;
1663
- var _b2;
1664
- var _a16;
1665
- var RoleService = (_a16 = class {
1666
- constructor(roleRepository, roleValidator) {
1667
- this.roleRepository = roleRepository;
1668
- this.roleValidator = roleValidator;
1669
- }
1670
- async getAll() {
1671
- return await this.roleRepository.getAll();
1672
- }
1673
- async getById(id) {
1674
- await this.roleValidator.checkRoleExists(id);
1675
- return await this.roleRepository.getById(id);
1676
- }
1677
- async getByName(name) {
1678
- return await this.roleRepository.getByName(name);
1679
- }
1680
- async create(data) {
1681
- await this.roleValidator.validateCreateRole(data);
1682
- await this.roleValidator.checkNameUnique(data.name);
1683
- return await this.roleRepository.create(data);
1684
- }
1685
- async update(id, data) {
1686
- await this.roleValidator.checkRoleExists(id);
1687
- await this.roleValidator.checkNameUnique(data.name, id);
1688
- return await this.roleRepository.update(id, data);
1689
- }
1690
- async delete(id) {
1691
- await this.roleValidator.checkRoleExists(id);
1692
- return await this.roleRepository.delete(id);
1693
- }
1694
- async seedDefaultRoles(defaultRoles) {
1695
- const rolesToCreate = [];
1696
- for (const role of defaultRoles) {
1697
- const exists = await this.roleValidator.isRoleNameExists(role.name);
1698
- if (!exists) {
1699
- rolesToCreate.push(role);
1700
- }
1701
- }
1702
- const createdRoles = await Promise.all(rolesToCreate.map((role) => this.roleRepository.create(role)));
1703
- return createdRoles;
1704
- }
1705
- async getRoleIdByName(name) {
1706
- const teacherRole = await this.getByName(name);
1707
- return teacherRole?.id;
1708
- }
1709
- }, __name(_a16, "RoleService"), _a16);
1710
- RoleService = __decorate10([
1711
- Injectable7(),
1712
- __metadata6("design:paramtypes", [typeof (_a15 = typeof RoleRepository !== "undefined" && RoleRepository) === "function" ? _a15 : Object, typeof (_b2 = typeof RoleValidator !== "undefined" && RoleValidator) === "function" ? _b2 : Object])
1713
- ], RoleService);
1714
-
1715
- // src/roles/RoleController.ts
1716
- var __decorate11 = function(decorators, target, key, desc) {
1717
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1718
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1719
- 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;
1720
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1721
- };
1722
- var __metadata7 = function(k, v) {
1723
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1724
- };
1725
- var __param2 = function(paramIndex, decorator) {
1726
- return function(target, key) {
1727
- decorator(target, key, paramIndex);
1728
- };
1729
- };
1730
- var _a17;
1731
- var _a18;
1732
- var RoleController = (_a18 = class {
1733
- constructor(roleService) {
1734
- this.roleService = roleService;
1735
- }
1736
- async getRoles() {
1737
- const roles = await this.roleService.getAll();
1738
- return {
1739
- data: roles,
1740
- message: t4("roles.success.retrieved"),
1741
- status: "success"
1742
- };
1743
- }
1744
- async getRole(id) {
1745
- const role = await this.roleService.getById(id);
1746
- return {
1747
- data: role,
1748
- message: t4("roles.success.retrieved"),
1749
- status: "success"
1750
- };
1751
- }
1752
- async createRole(body) {
1753
- const newRole = await this.roleService.create(body);
1754
- return {
1755
- data: newRole,
1756
- message: t4("roles.success.created"),
1757
- status: "success"
1758
- };
1759
- }
1760
- async updateRole(id, body) {
1761
- const updatedRole = await this.roleService.update(id, body);
1762
- return {
1763
- data: updatedRole,
1764
- message: t4("roles.success.updated"),
1765
- status: "success"
1766
- };
1767
- }
1768
- async deleteRole(id) {
1769
- const result = await this.roleService.delete(id);
1770
- return {
1771
- data: result,
1772
- message: t4("roles.success.deleted"),
1773
- status: "success"
1774
- };
1775
- }
1776
- }, __name(_a18, "RoleController"), _a18);
1777
- __decorate11([
1778
- Get(),
1779
- isAdmin(),
1780
- __metadata7("design:type", Function),
1781
- __metadata7("design:paramtypes", []),
1782
- __metadata7("design:returntype", Promise)
1783
- ], RoleController.prototype, "getRoles", null);
1784
- __decorate11([
1785
- Get("/:id"),
1786
- isAdmin(),
1787
- __param2(0, Params("id")),
1788
- __metadata7("design:type", Function),
1789
- __metadata7("design:paramtypes", [Object]),
1790
- __metadata7("design:returntype", Promise)
1791
- ], RoleController.prototype, "getRole", null);
1792
- __decorate11([
1793
- Post(),
1794
- isAdmin(),
1795
- __param2(0, Body()),
1796
- __metadata7("design:type", Function),
1797
- __metadata7("design:paramtypes", [Object]),
1798
- __metadata7("design:returntype", Promise)
1799
- ], RoleController.prototype, "createRole", null);
1800
- __decorate11([
1801
- Put("/:id"),
1802
- isAdmin(),
1803
- __param2(0, Params("id")),
1804
- __param2(1, Body()),
1805
- __metadata7("design:type", Function),
1806
- __metadata7("design:paramtypes", [Object, Object]),
1807
- __metadata7("design:returntype", Promise)
1808
- ], RoleController.prototype, "updateRole", null);
1809
- __decorate11([
1810
- Delete("/:id"),
1811
- isAdmin(),
1812
- __param2(0, Params("id")),
1813
- __metadata7("design:type", Function),
1814
- __metadata7("design:paramtypes", [Object]),
1815
- __metadata7("design:returntype", Promise)
1816
- ], RoleController.prototype, "deleteRole", null);
1817
- RoleController = __decorate11([
1818
- Controller("/roles"),
1819
- __metadata7("design:paramtypes", [typeof (_a17 = typeof RoleService !== "undefined" && RoleService) === "function" ? _a17 : Object])
1820
- ], RoleController);
1821
-
1822
- // src/users/UserService.ts
1823
- import { nanoid as nanoid2 } from "nanoid";
1824
- var __decorate12 = function(decorators, target, key, desc) {
1825
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1826
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1827
- 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;
1828
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1829
- };
1830
- var __metadata8 = function(k, v) {
1831
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1832
- };
1833
- var _a19;
1834
- var _b3;
1835
- var _c;
1836
- var _d;
1837
- var _e;
1838
- var _a20;
1839
- var UserService = (_a20 = class {
1840
- constructor(roleValidator, roleService, userRepository, userValidator, encryptionService) {
1841
- this.roleValidator = roleValidator;
1842
- this.roleService = roleService;
1843
- this.userRepository = userRepository;
1844
- this.userValidator = userValidator;
1845
- this.encryptionService = encryptionService;
1846
- }
1847
- sanitizeUser(user) {
1848
- if (!user)
1849
- return user;
1850
- const { password, ...sanitizedUser } = user;
1851
- return sanitizedUser;
1852
- }
1853
- sanitizeUsers(users) {
1854
- return users.map((user) => this.sanitizeUser(user));
1855
- }
1856
- async resolveUserRole(roleId, roleName) {
1857
- if (roleId) {
1858
- await this.roleValidator.checkRoleExists(roleId);
1859
- return roleId;
1860
- }
1861
- if (roleName) {
1862
- const roleByName = await this.roleService.getByName(roleName);
1863
- if (roleByName) {
1864
- return roleByName.id;
1865
- }
1866
- throw new Error(`Role '${roleName}' not found`);
1867
- }
1868
- const defaultRole = await this.roleService.getByName("Student");
1869
- return defaultRole.id;
1870
- }
1871
- async getAll() {
1872
- const users = await this.userRepository.getAll();
1873
- return this.sanitizeUsers(users);
1874
- }
1875
- async getById(id) {
1876
- await this.userValidator.checkUserExists(id);
1877
- const user = await this.userRepository.getById(id);
1878
- return this.sanitizeUser(user);
1879
- }
1880
- async getByEmail(email) {
1881
- const user = await this.userValidator.checkUserExistsByEmail(email);
1882
- return this.sanitizeUser(user);
1883
- }
1884
- async create(data) {
1885
- const { id, email, image, emailVerified, password, roleId, role } = data;
1886
- let userId = id || nanoid2(5);
1887
- let pass = password || "12345678";
1888
- await this.userValidator.checkEmailUnique(data.email);
1889
- await this.userValidator.checkUserIdIsUnique(id);
1890
- const hashedPassword = await this.encryptionService.hashPassword(pass);
1891
- const resolvedRoleId = await this.resolveUserRole(roleId, role);
1892
- const userDetails = {
1893
- id: userId,
1894
- email,
1895
- image,
1896
- password: hashedPassword,
1897
- roleId: resolvedRoleId,
1898
- emailVerified,
1899
- status: "pending"
1900
- };
1901
- await this.userValidator.validateCreateUser(userDetails);
1902
- const newUser = await this.userRepository.create(userDetails);
1903
- return this.sanitizeUser(newUser);
1904
- }
1905
- async update(id, data) {
1906
- const { password, image } = data;
1907
- await this.userValidator.checkUserExists(id);
1908
- await this.userValidator.checkEmailUnique(data.email, id);
1909
- const currentUser = await this.userRepository.getById(id);
1910
- const hashedPassword = await this.encryptionService.hashPassword(password);
1911
- const updateData = {
1912
- ...data,
1913
- image,
1914
- ...hashedPassword && { password: hashedPassword }
1915
- };
1916
- const cleanedUpdateData = clean(updateData);
1917
- const updatedUser = await this.userRepository.update(id, cleanedUpdateData);
1918
- return this.sanitizeUser(updatedUser);
1919
- }
1920
- async delete(id) {
1921
- await this.userValidator.checkUserExists(id);
1922
- const user = await this.userRepository.delete(id);
1923
- return this.sanitizeUser(user);
1924
- }
1925
- async deleteAll() {
1926
- const deletedUsers = await this.userRepository.deleteAll();
1927
- return this.sanitizeUsers(deletedUsers);
1928
- }
1929
- async getRoleName(id) {
1930
- await this.userValidator.checkUserExists(id);
1931
- return await this.userRepository.getRoleNameById(id);
1932
- }
1933
- async getPassword(email) {
1934
- await this.userValidator.checkUserExistsByEmail(email);
1935
- return await this.userRepository.getUserPassword(email);
1936
- }
1937
- async assignRole(id, roleId, roleName) {
1938
- await this.userValidator.checkUserExists(id);
1939
- const resolvedRoleId = await this.resolveUserRole(roleId, roleName);
1940
- const updatedUser = await this.userRepository.update(id, { roleId: resolvedRoleId });
1941
- return this.sanitizeUser(updatedUser);
1942
- }
1943
- async removeRole(id) {
1944
- await this.userValidator.checkUserExists(id);
1945
- const updatedUser = await this.userRepository.update(id, { roleId: null });
1946
- return this.sanitizeUser(updatedUser);
1947
- }
1948
- async seedAdminUser() {
1949
- const email = "admin@admin.com";
1950
- const adminRole = await this.roleValidator.checkAdminRoleExists();
1951
- const existingUser = await this.userRepository.getByEmail(email);
1952
- if (existingUser) {
1953
- await this.delete(existingUser.id);
1954
- }
1955
- const newAdminUser = await this.create({
1956
- id: "USR00",
1957
- name: "System Administrator",
1958
- email,
1959
- password: "12345678",
1960
- image: null,
1961
- roleId: adminRole.id,
1962
- status: "active",
1963
- emailVerified: true
1964
- });
1965
- return this.sanitizeUser(newAdminUser);
1966
- }
1967
- async updateLang(language) {
1968
- setLanguage(language);
1969
- return language;
1970
- }
1971
- async getLang() {
1972
- return getCurrentLanguage();
1973
- }
1974
- }, __name(_a20, "UserService"), _a20);
1975
- __decorate12([
1976
- Transactional(),
1977
- __metadata8("design:type", Function),
1978
- __metadata8("design:paramtypes", [Object]),
1979
- __metadata8("design:returntype", Promise)
1980
- ], UserService.prototype, "create", null);
1981
- UserService = __decorate12([
1982
- Injectable8(),
1983
- __metadata8("design:paramtypes", [typeof (_a19 = typeof RoleValidator !== "undefined" && RoleValidator) === "function" ? _a19 : Object, typeof (_b3 = typeof RoleService !== "undefined" && RoleService) === "function" ? _b3 : Object, typeof (_c = typeof UserRepository !== "undefined" && UserRepository) === "function" ? _c : Object, typeof (_d = typeof UserValidator !== "undefined" && UserValidator) === "function" ? _d : Object, typeof (_e = typeof EncryptionService !== "undefined" && EncryptionService) === "function" ? _e : Object])
1984
- ], UserService);
1985
-
1986
- // src/users/UserController.ts
1987
- import { Controller as Controller2, Get as Get2, Post as Post2, Put as Put2, Delete as Delete2, Params as Params2, Body as Body2, t as t5 } from "najm-api";
1988
- var __decorate13 = function(decorators, target, key, desc) {
1989
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1990
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1991
- 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;
1992
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1993
- };
1994
- var __metadata9 = function(k, v) {
1995
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1996
- };
1997
- var __param3 = function(paramIndex, decorator) {
1998
- return function(target, key) {
1999
- decorator(target, key, paramIndex);
2000
- };
2001
- };
2002
- var _a21;
2003
- var _a22;
2004
- var UserController = (_a22 = class {
2005
- constructor(userService) {
2006
- this.userService = userService;
2007
- }
2008
- async getUsers() {
2009
- const users = await this.userService.getAll();
2010
- return {
2011
- data: users,
2012
- message: t5("users.success.retrieved"),
2013
- status: "success"
2014
- };
2015
- }
2016
- async getLang() {
2017
- const language = await this.userService.getLang();
2018
- return {
2019
- data: { language },
2020
- message: t5("users.success.retrieved"),
2021
- status: "success"
2022
- };
2023
- }
2024
- async updateLang(language) {
2025
- const data = await this.userService.updateLang(language);
2026
- return {
2027
- data,
2028
- message: t5("users.success.updated"),
2029
- status: "success"
2030
- };
2031
- }
2032
- async getUser(id) {
2033
- const user = await this.userService.getById(id);
2034
- return {
2035
- data: user,
2036
- message: t5("users.success.retrieved"),
2037
- status: "success"
2038
- };
2039
- }
2040
- async getByEmail(email) {
2041
- const user = await this.userService.getByEmail(email);
2042
- return {
2043
- data: user,
2044
- message: t5("users.success.retrieved"),
2045
- status: "success"
2046
- };
2047
- }
2048
- async getRole(userId) {
2049
- const role = await this.userService.getRoleName(userId);
2050
- return {
2051
- data: role,
2052
- message: t5("users.success.retrieved"),
2053
- status: "success"
2054
- };
2055
- }
2056
- async create(body) {
2057
- const newUser = await this.userService.create(body);
2058
- return {
2059
- data: newUser,
2060
- message: t5("users.success.created"),
2061
- status: "success"
2062
- };
2063
- }
2064
- async update(id, body) {
2065
- const updatedUser = await this.userService.update(id, body);
2066
- return {
2067
- data: updatedUser,
2068
- message: t5("users.success.updated"),
2069
- status: "success"
2070
- };
2071
- }
2072
- async delete(id) {
2073
- const result = await this.userService.delete(id);
2074
- return {
2075
- data: result,
2076
- message: t5("users.success.deleted"),
2077
- status: "success"
2078
- };
2079
- }
2080
- async deleteAll() {
2081
- const result = await this.userService.deleteAll();
2082
- return {
2083
- data: result,
2084
- message: t5("users.success.allDeleted"),
2085
- status: "success"
2086
- };
2087
- }
2088
- async assignRole(userId, roleId) {
2089
- await this.userService.assignRole(userId, roleId);
2090
- return {
2091
- message: t5("users.success.updated"),
2092
- status: "success"
2093
- };
2094
- }
2095
- async removeRole(userId) {
2096
- await this.userService.removeRole(userId);
2097
- return {
2098
- message: t5("users.success.updated"),
2099
- status: "success"
2100
- };
2101
- }
2102
- }, __name(_a22, "UserController"), _a22);
2103
- __decorate13([
2104
- Get2(),
2105
- isAdmin(),
2106
- __metadata9("design:type", Function),
2107
- __metadata9("design:paramtypes", []),
2108
- __metadata9("design:returntype", Promise)
2109
- ], UserController.prototype, "getUsers", null);
2110
- __decorate13([
2111
- Get2("/lang"),
2112
- isAuth(),
2113
- __metadata9("design:type", Function),
2114
- __metadata9("design:paramtypes", []),
2115
- __metadata9("design:returntype", Promise)
2116
- ], UserController.prototype, "getLang", null);
2117
- __decorate13([
2118
- Post2("/lang/:language"),
2119
- isAuth(),
2120
- __param3(0, Params2("language")),
2121
- __metadata9("design:type", Function),
2122
- __metadata9("design:paramtypes", [Object]),
2123
- __metadata9("design:returntype", Promise)
2124
- ], UserController.prototype, "updateLang", null);
2125
- __decorate13([
2126
- Get2("/:id"),
2127
- isAdmin(),
2128
- __param3(0, Params2("id")),
2129
- __metadata9("design:type", Function),
2130
- __metadata9("design:paramtypes", [Object]),
2131
- __metadata9("design:returntype", Promise)
2132
- ], UserController.prototype, "getUser", null);
2133
- __decorate13([
2134
- Get2("/email/:email"),
2135
- isAdmin(),
2136
- __param3(0, Params2("email")),
2137
- __metadata9("design:type", Function),
2138
- __metadata9("design:paramtypes", [Object]),
2139
- __metadata9("design:returntype", Promise)
2140
- ], UserController.prototype, "getByEmail", null);
2141
- __decorate13([
2142
- Get2("/role/:userId"),
2143
- isAdmin(),
2144
- __param3(0, Params2("userId")),
2145
- __metadata9("design:type", Function),
2146
- __metadata9("design:paramtypes", [Object]),
2147
- __metadata9("design:returntype", Promise)
2148
- ], UserController.prototype, "getRole", null);
2149
- __decorate13([
2150
- Post2(),
2151
- isAdmin(),
2152
- __param3(0, Body2()),
2153
- __metadata9("design:type", Function),
2154
- __metadata9("design:paramtypes", [Object]),
2155
- __metadata9("design:returntype", Promise)
2156
- ], UserController.prototype, "create", null);
2157
- __decorate13([
2158
- Put2("/:id"),
2159
- isAdmin(),
2160
- __param3(0, Params2("id")),
2161
- __param3(1, Body2()),
2162
- __metadata9("design:type", Function),
2163
- __metadata9("design:paramtypes", [Object, Object]),
2164
- __metadata9("design:returntype", Promise)
2165
- ], UserController.prototype, "update", null);
2166
- __decorate13([
2167
- Delete2("/:id"),
2168
- isAdmin(),
2169
- __param3(0, Params2("id")),
2170
- __metadata9("design:type", Function),
2171
- __metadata9("design:paramtypes", [Object]),
2172
- __metadata9("design:returntype", Promise)
2173
- ], UserController.prototype, "delete", null);
2174
- __decorate13([
2175
- Delete2(),
2176
- isAdmin(),
2177
- __metadata9("design:type", Function),
2178
- __metadata9("design:paramtypes", []),
2179
- __metadata9("design:returntype", Promise)
2180
- ], UserController.prototype, "deleteAll", null);
2181
- __decorate13([
2182
- Post2("/assign/:userId/:roleId"),
2183
- isAdmin(),
2184
- __param3(0, Params2("userId")),
2185
- __param3(1, Params2("roleId")),
2186
- __metadata9("design:type", Function),
2187
- __metadata9("design:paramtypes", [Object, Object]),
2188
- __metadata9("design:returntype", Promise)
2189
- ], UserController.prototype, "assignRole", null);
2190
- __decorate13([
2191
- Delete2("/remove/:userId"),
2192
- isAdmin(),
2193
- __param3(0, Params2("userId")),
2194
- __metadata9("design:type", Function),
2195
- __metadata9("design:paramtypes", [Object]),
2196
- __metadata9("design:returntype", Promise)
2197
- ], UserController.prototype, "removeRole", null);
2198
- UserController = __decorate13([
2199
- Controller2("/users"),
2200
- __metadata9("design:paramtypes", [typeof (_a21 = typeof UserService !== "undefined" && UserService) === "function" ? _a21 : Object])
2201
- ], UserController);
2202
-
2203
- // src/auth/AuthService.ts
2204
- var __decorate14 = function(decorators, target, key, desc) {
2205
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2206
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2207
- 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;
2208
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2209
- };
2210
- var __metadata10 = function(k, v) {
2211
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
2212
- };
2213
- var _a23;
2214
- var _b4;
2215
- var _c2;
2216
- var _d2;
2217
- var _a24;
2218
- var AuthService = (_a24 = class {
2219
- constructor(tokenService, userService, userValidator, cookieService) {
2220
- this.tokenService = tokenService;
2221
- this.userService = userService;
2222
- this.userValidator = userValidator;
2223
- this.cookieService = cookieService;
2224
- }
2225
- async registerUser(body) {
2226
- return await this.userService.create(body);
2227
- }
2228
- async loginUser(body) {
2229
- const { email, password } = body;
2230
- if (!email || !password) {
2231
- throw new Error(t6("auth.errors.invalidCredentials"));
2232
- }
2233
- const existingPassword = await this.userService.getPassword(email);
2234
- const { id } = await this.userService.getByEmail(email);
2235
- await this.userValidator.checkPasswordValid(password, existingPassword);
2236
- const data = await this.tokenService.generateTokens(id);
2237
- this.cookieService.setRefreshCookie(data.refreshToken);
2238
- return data;
2239
- }
2240
- async refreshTokens() {
2241
- const data = await this.tokenService.refreshTokens();
2242
- this.cookieService.setRefreshCookie(data.refreshToken);
2243
- return data;
2244
- }
2245
- async logoutUser(userId) {
2246
- await this.userValidator.checkUserExists(userId);
2247
- await this.tokenService.revokeToken(userId);
2248
- this.cookieService.clearRefreshCookie();
2249
- return { data: null, message: t6("auth.success.logout") };
2250
- }
2251
- async getUserProfile(userData) {
2252
- const lang = getCurrentLanguage2();
2253
- return {
2254
- ...userData,
2255
- language: lang
2256
- };
2257
- }
2258
- async forgotPassword(email) {
2259
- }
2260
- }, __name(_a24, "AuthService"), _a24);
2261
- AuthService = __decorate14([
2262
- Injectable9(),
2263
- __metadata10("design:paramtypes", [typeof (_a23 = typeof TokenService !== "undefined" && TokenService) === "function" ? _a23 : Object, typeof (_b4 = typeof UserService !== "undefined" && UserService) === "function" ? _b4 : Object, typeof (_c2 = typeof UserValidator !== "undefined" && UserValidator) === "function" ? _c2 : Object, typeof (_d2 = typeof CookieService !== "undefined" && CookieService) === "function" ? _d2 : Object])
2264
- ], AuthService);
2265
-
2266
- // src/auth/AuthController.ts
2267
- var __decorate15 = function(decorators, target, key, desc) {
2268
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2269
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2270
- 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;
2271
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2272
- };
2273
- var __metadata11 = function(k, v) {
2274
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
2275
- };
2276
- var __param4 = function(paramIndex, decorator) {
2277
- return function(target, key) {
2278
- decorator(target, key, paramIndex);
2279
- };
2280
- };
2281
- var _a25;
2282
- var _a26;
2283
- var AuthController = (_a26 = class {
2284
- constructor(authService) {
2285
- this.authService = authService;
2286
- }
2287
- async registerUser(body) {
2288
- const data = await this.authService.registerUser(body);
2289
- return {
2290
- data,
2291
- message: t7("auth.success.register"),
2292
- status: "success"
2293
- };
2294
- }
2295
- async loginUser(body) {
2296
- const data = await this.authService.loginUser(body);
2297
- return {
2298
- data,
2299
- message: t7("auth.success.login"),
2300
- status: "success"
2301
- };
2302
- }
2303
- async refreshTokens() {
2304
- const data = await this.authService.refreshTokens();
2305
- return {
2306
- data,
2307
- message: t7("auth.success.tokenRefreshed"),
2308
- status: "success"
2309
- };
2310
- }
2311
- async logoutUser(id) {
2312
- const data = await this.authService.logoutUser(id);
2313
- return {
2314
- data,
2315
- message: t7("auth.success.logout"),
2316
- status: "success"
2317
- };
2318
- }
2319
- async userProfile(user) {
2320
- const data = await this.authService.getUserProfile(user);
2321
- return {
2322
- data,
2323
- message: t7("users.success.retrieved"),
2324
- status: "success"
2325
- };
2326
- }
2327
- async forgotPassword(body) {
2328
- const data = await this.authService.forgotPassword(body.email);
2329
- return {
2330
- data,
2331
- message: t7("auth.success.passwordReset"),
2332
- status: "success"
2333
- };
2334
- }
2335
- }, __name(_a26, "AuthController"), _a26);
2336
- __decorate15([
2337
- Post3("/register"),
2338
- __param4(0, Body3()),
2339
- __metadata11("design:type", Function),
2340
- __metadata11("design:paramtypes", [Object]),
2341
- __metadata11("design:returntype", Promise)
2342
- ], AuthController.prototype, "registerUser", null);
2343
- __decorate15([
2344
- Post3("/login"),
2345
- __param4(0, Body3()),
2346
- __metadata11("design:type", Function),
2347
- __metadata11("design:paramtypes", [Object]),
2348
- __metadata11("design:returntype", Promise)
2349
- ], AuthController.prototype, "loginUser", null);
2350
- __decorate15([
2351
- Get3("/refresh"),
2352
- __metadata11("design:type", Function),
2353
- __metadata11("design:paramtypes", []),
2354
- __metadata11("design:returntype", Promise)
2355
- ], AuthController.prototype, "refreshTokens", null);
2356
- __decorate15([
2357
- Get3("/logout/:id"),
2358
- __param4(0, Params3("id")),
2359
- __metadata11("design:type", Function),
2360
- __metadata11("design:paramtypes", [Object]),
2361
- __metadata11("design:returntype", Promise)
2362
- ], AuthController.prototype, "logoutUser", null);
2363
- __decorate15([
2364
- Get3("/me"),
2365
- isAuth(),
2366
- __param4(0, User()),
2367
- __metadata11("design:type", Function),
2368
- __metadata11("design:paramtypes", [Object]),
2369
- __metadata11("design:returntype", Promise)
2370
- ], AuthController.prototype, "userProfile", null);
2371
- __decorate15([
2372
- Post3("/forgot-password"),
2373
- isAuth(),
2374
- __param4(0, Body3()),
2375
- __metadata11("design:type", Function),
2376
- __metadata11("design:paramtypes", [Object]),
2377
- __metadata11("design:returntype", Promise)
2378
- ], AuthController.prototype, "forgotPassword", null);
2379
- AuthController = __decorate15([
2380
- Controller3("/auth"),
2381
- __metadata11("design:paramtypes", [typeof (_a25 = typeof AuthService !== "undefined" && AuthService) === "function" ? _a25 : Object])
2382
- ], AuthController);
2383
-
2384
- // src/permissions/PermissionRepository.ts
2385
- import { eq as eq4, and } from "drizzle-orm";
2386
- import { Repository as Repository4 } from "najm-api";
2387
- var __decorate16 = function(decorators, target, key, desc) {
2388
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2389
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2390
- 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;
2391
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2392
- };
2393
- var _a27;
2394
- var PermissionRepository = (_a27 = class {
2395
- async getAll() {
2396
- return await this.db.select().from(permissionsTable);
2397
- }
2398
- async getById(id) {
2399
- const [existingPermission] = await this.db.select().from(permissionsTable).where(eq4(permissionsTable.id, id));
2400
- return existingPermission;
2401
- }
2402
- async getByName(name) {
2403
- const [existingPermission] = await this.db.select().from(permissionsTable).where(eq4(permissionsTable.name, name));
2404
- return existingPermission;
2405
- }
2406
- async create(data) {
2407
- const [newPermission] = await this.db.insert(permissionsTable).values(data).returning();
2408
- return newPermission;
2409
- }
2410
- async update(id, data) {
2411
- const [updatedPermission] = await this.db.update(permissionsTable).set(data).where(eq4(permissionsTable.id, id)).returning();
2412
- return updatedPermission;
2413
- }
2414
- async delete(id) {
2415
- const [deletedPermission] = await this.db.delete(permissionsTable).where(eq4(permissionsTable.id, id)).returning();
2416
- return deletedPermission;
2417
- }
2418
- async getPermissionsByRole(roleId) {
2419
- return await this.db.select({
2420
- id: permissionsTable.id,
2421
- name: permissionsTable.name,
2422
- description: permissionsTable.description,
2423
- resource: permissionsTable.resource,
2424
- action: permissionsTable.action
2425
- }).from(rolePermissionsTable).leftJoin(permissionsTable, eq4(rolePermissionsTable.permissionId, permissionsTable.id)).where(eq4(rolePermissionsTable.roleId, roleId));
2426
- }
2427
- async getRolesByPermission(permissionId) {
2428
- return await this.db.select({
2429
- id: rolesTable.id,
2430
- name: rolesTable.name,
2431
- description: rolesTable.description
2432
- }).from(rolePermissionsTable).leftJoin(rolesTable, eq4(rolePermissionsTable.roleId, rolesTable.id)).where(eq4(rolePermissionsTable.permissionId, permissionId));
2433
- }
2434
- async assignPermissionToRole(roleId, permissionId) {
2435
- const [newRolePermission] = await this.db.insert(rolePermissionsTable).values({ roleId, permissionId }).returning();
2436
- return newRolePermission;
2437
- }
2438
- async removePermissionFromRole(roleId, permissionId) {
2439
- const [deletedRolePermission] = await this.db.delete(rolePermissionsTable).where(and(eq4(rolePermissionsTable.roleId, roleId), eq4(rolePermissionsTable.permissionId, permissionId))).returning();
2440
- return deletedRolePermission;
2441
- }
2442
- async checkRoleHasPermission(roleId, permissionId) {
2443
- const [rolePermission] = await this.db.select().from(rolePermissionsTable).where(and(eq4(rolePermissionsTable.roleId, roleId), eq4(rolePermissionsTable.permissionId, permissionId)));
2444
- return !!rolePermission;
2445
- }
2446
- async deleteAll() {
2447
- await this.db.delete(rolePermissionsTable);
2448
- const deletedPermissions = await this.db.delete(permissionsTable).returning();
2449
- return deletedPermissions;
2450
- }
2451
- }, __name(_a27, "PermissionRepository"), _a27);
2452
- PermissionRepository = __decorate16([
2453
- Repository4()
2454
- ], PermissionRepository);
2455
-
2456
- // src/permissions/PermissionGuards.ts
2457
- import { createGuard as createGuard2, Injectable as Injectable10, GuardParams as GuardParams2, Headers as Headers2, Ctx as Ctx2 } from "najm-api";
2458
- var __decorate17 = function(decorators, target, key, desc) {
2459
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2460
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2461
- 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;
2462
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2463
- };
2464
- var __metadata12 = function(k, v) {
2465
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
2466
- };
2467
- var __param5 = function(paramIndex, decorator) {
2468
- return function(target, key) {
2469
- decorator(target, key, paramIndex);
2470
- };
2471
- };
2472
- var _a28;
2473
- var _a29;
2474
- var PermissionGuards = (_a29 = class {
2475
- constructor(tokenService) {
2476
- this.tokenService = tokenService;
2477
- }
2478
- async getUserPermissions(auth) {
2479
- const permissions = await this.tokenService.getUserPermissions(auth);
2480
- if (!permissions || !Array.isArray(permissions))
2481
- return null;
2482
- return permissions;
2483
- }
2484
- checkPermissionMatch(permissions, requiredPermission) {
2485
- if (permissions.includes(requiredPermission)) {
2486
- return true;
2487
- }
2488
- const [requiredAction, requiredResource] = requiredPermission.split(":");
2489
- if (requiredAction && requiredResource) {
2490
- if (permissions.includes(`${requiredAction}:*`)) {
2491
- return true;
2492
- }
2493
- if (permissions.includes(`*:${requiredResource}`)) {
2494
- return true;
2495
- }
2496
- }
2497
- if (permissions.includes("*:*")) {
2498
- return true;
2499
- }
2500
- return false;
2501
- }
2502
- async hasPermission(auth, ctx, requiredPermission) {
2503
- await this.tokenService.storeUserInCache(auth, ctx);
2504
- const permissions = await this.getUserPermissions(auth);
2505
- if (!permissions)
2506
- return false;
2507
- const check = this.checkPermissionMatch(permissions, requiredPermission);
2508
- return check;
2509
- }
2510
- }, __name(_a29, "PermissionGuards"), _a29);
2511
- __decorate17([
2512
- __param5(0, Headers2("authorization")),
2513
- __param5(1, Ctx2()),
2514
- __param5(2, GuardParams2()),
2515
- __metadata12("design:type", Function),
2516
- __metadata12("design:paramtypes", [Object, Object, Object]),
2517
- __metadata12("design:returntype", Promise)
2518
- ], PermissionGuards.prototype, "hasPermission", null);
2519
- PermissionGuards = __decorate17([
2520
- Injectable10(),
2521
- __metadata12("design:paramtypes", [typeof (_a28 = typeof TokenService !== "undefined" && TokenService) === "function" ? _a28 : Object])
2522
- ], PermissionGuards);
2523
- var Permission = /* @__PURE__ */ __name((...permissions) => createGuard2(PermissionGuards, "hasPermission")(...permissions), "Permission");
2524
-
2525
- // src/permissions/PermissionController.ts
2526
- import { Controller as Controller4, Get as Get4, Post as Post4, Put as Put3, Delete as Delete3, Params as Params4, Body as Body4, t as t9 } from "najm-api";
2527
-
2528
- // src/permissions/PermissionService.ts
2529
- import { Injectable as Injectable12 } from "najm-api";
2530
-
2531
- // src/permissions/PermissionValidator.ts
2532
- import { Injectable as Injectable11, t as t8 } from "najm-api";
2533
- import { z as z3 } from "zod";
2534
- var __decorate18 = function(decorators, target, key, desc) {
2535
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2536
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2537
- 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;
2538
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2539
- };
2540
- var __metadata13 = function(k, v) {
2541
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
2542
- };
2543
- var _a30;
2544
- var _b5;
2545
- var permissionSchema = z3.object({
2546
- name: z3.string().min(1, "Permission name is required"),
2547
- description: z3.string().optional(),
2548
- resource: z3.string().min(1, "Resource is required"),
2549
- action: z3.string().min(1, "Action is required")
2550
- });
2551
- var _a31;
2552
- var PermissionValidator = (_a31 = class {
2553
- constructor(permissionRepository, roleValidator) {
2554
- this.permissionRepository = permissionRepository;
2555
- this.roleValidator = roleValidator;
2556
- }
2557
- async validateCreatePermission(data) {
2558
- return parseSchema(permissionSchema, data);
2559
- }
2560
- async isPermissionExists(id) {
2561
- const existingPermission = await this.permissionRepository.getById(id);
2562
- return !!existingPermission;
2563
- }
2564
- async isPermissionNameExists(name) {
2565
- const existingPermission = await this.permissionRepository.getByName(name);
2566
- return !!existingPermission;
2567
- }
2568
- //======================= throw errors
2569
- async checkPermissionExists(id) {
2570
- const permissionExists = await this.isPermissionExists(id);
2571
- if (!permissionExists) {
2572
- throw new Error(t8("permissions.errors.notFound"));
2573
- }
2574
- return permissionExists;
2575
- }
2576
- async checkPermissionExistsByName(name) {
2577
- const permissionExists = await this.isPermissionNameExists(name);
2578
- if (!permissionExists) {
2579
- throw new Error(t8("permissions.errors.notFound"));
2580
- }
2581
- return permissionExists;
2582
- }
2583
- async checkPermissionNameUnique(name, excludeId = null) {
2584
- if (!name)
2585
- return;
2586
- const existingPermission = await this.permissionRepository.getByName(name);
2587
- if (existingPermission && existingPermission.id !== excludeId) {
2588
- throw new Error(t8("permissions.errors.nameExists"));
2589
- }
2590
- }
2591
- async checkRoleExists(id) {
2592
- return await this.roleValidator.checkRoleExists(id);
2593
- }
2594
- async checkRoleExistsByName(name) {
2595
- return await this.roleValidator.checkRoleExistsByName(name);
2596
- }
2597
- async checkRoleHasPermission(roleId, permissionId) {
2598
- await this.roleValidator.checkRoleExists(roleId);
2599
- await this.checkPermissionExists(permissionId);
2600
- const hasPermission = await this.permissionRepository.checkRoleHasPermission(roleId, permissionId);
2601
- if (hasPermission) {
2602
- throw new Error(t8("permissions.errors.roleAlreadyHasPermission"));
2603
- }
2604
- }
2605
- }, __name(_a31, "PermissionValidator"), _a31);
2606
- PermissionValidator = __decorate18([
2607
- Injectable11(),
2608
- __metadata13("design:paramtypes", [typeof (_a30 = typeof PermissionRepository !== "undefined" && PermissionRepository) === "function" ? _a30 : Object, typeof (_b5 = typeof RoleValidator !== "undefined" && RoleValidator) === "function" ? _b5 : Object])
2609
- ], PermissionValidator);
2610
-
2611
- // src/permissions/PermissionService.ts
2612
- var __decorate19 = function(decorators, target, key, desc) {
2613
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2614
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2615
- 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;
2616
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2617
- };
2618
- var __metadata14 = function(k, v) {
2619
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
2620
- };
2621
- var _a32;
2622
- var _b6;
2623
- var _c3;
2624
- var _a33;
2625
- var PermissionService = (_a33 = class {
2626
- constructor(permissionRepository, permissionValidator, roleService) {
2627
- this.permissionRepository = permissionRepository;
2628
- this.permissionValidator = permissionValidator;
2629
- this.roleService = roleService;
2630
- }
2631
- async getAll() {
2632
- return await this.permissionRepository.getAll();
2633
- }
2634
- async getById(id) {
2635
- await this.permissionValidator.checkPermissionExists(id);
2636
- return await this.permissionRepository.getById(id);
2637
- }
2638
- async getByName(name) {
2639
- return await this.permissionRepository.getByName(name);
2640
- }
2641
- async getByResource(resource) {
2642
- return await this.permissionRepository.getAll().then((permissions) => permissions.filter((p) => p.resource === resource));
2643
- }
2644
- async create(data) {
2645
- await this.permissionValidator.validateCreatePermission(data);
2646
- await this.permissionValidator.checkPermissionNameUnique(data.name);
2647
- return await this.permissionRepository.create(data);
2648
- }
2649
- async update(id, data) {
2650
- await this.permissionValidator.checkPermissionExists(id);
2651
- await this.permissionValidator.checkPermissionNameUnique(data.name, id);
2652
- return await this.permissionRepository.update(id, data);
2653
- }
2654
- async delete(id) {
2655
- await this.permissionValidator.checkPermissionExists(id);
2656
- return await this.permissionRepository.delete(id);
2657
- }
2658
- async getPermissionsByRole(roleId) {
2659
- return await this.permissionRepository.getPermissionsByRole(roleId);
2660
- }
2661
- async getRolesByPermission(permissionId) {
2662
- await this.permissionValidator.checkPermissionExists(permissionId);
2663
- return await this.permissionRepository.getRolesByPermission(permissionId);
2664
- }
2665
- async assignPermissionToRole(roleId, permissionId) {
2666
- await this.permissionValidator.checkRoleHasPermission(roleId, permissionId);
2667
- return await this.permissionRepository.assignPermissionToRole(roleId, permissionId);
2668
- }
2669
- async removePermissionFromRole(roleId, permissionId) {
2670
- return await this.permissionRepository.removePermissionFromRole(roleId, permissionId);
2671
- }
2672
- async seedDefaultPermissions(defaultPermissions) {
2673
- const createdPermissions = [];
2674
- for (const permission of defaultPermissions) {
2675
- try {
2676
- const permissionEntity = await this.create(permission);
2677
- createdPermissions.push(permissionEntity);
2678
- } catch (error) {
2679
- continue;
2680
- }
2681
- }
2682
- return createdPermissions;
2683
- }
2684
- async seedDefaultRolePermissions(defaultRolePermissions) {
2685
- const results = [];
2686
- for (const { roleName, permissions } of defaultRolePermissions) {
2687
- try {
2688
- await this.permissionValidator.checkRoleExistsByName(roleName);
2689
- const role = await this.roleService.getByName(roleName);
2690
- for (const permissionName of permissions) {
2691
- try {
2692
- await this.permissionValidator.checkPermissionExistsByName(permissionName);
2693
- const permission = await this.getByName(permissionName);
2694
- await this.permissionValidator.checkRoleHasPermission(role.id, permission.id);
2695
- await this.assignPermissionToRole(role.id, permission.id);
2696
- results.push({ role: roleName, permission: permissionName });
2697
- } catch (error) {
2698
- continue;
2699
- }
2700
- }
2701
- } catch (error) {
2702
- continue;
2703
- }
2704
- }
2705
- return results;
2706
- }
2707
- async deleteAll() {
2708
- return await this.permissionRepository.deleteAll();
2709
- }
2710
- }, __name(_a33, "PermissionService"), _a33);
2711
- PermissionService = __decorate19([
2712
- Injectable12(),
2713
- __metadata14("design:paramtypes", [typeof (_a32 = typeof PermissionRepository !== "undefined" && PermissionRepository) === "function" ? _a32 : Object, typeof (_b6 = typeof PermissionValidator !== "undefined" && PermissionValidator) === "function" ? _b6 : Object, typeof (_c3 = typeof RoleService !== "undefined" && RoleService) === "function" ? _c3 : Object])
2714
- ], PermissionService);
2715
-
2716
- // src/permissions/PermissionController.ts
2717
- var __decorate20 = 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 __metadata15 = 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 _a34;
2732
- var _a35;
2733
- var PermissionController = (_a35 = class {
2734
- constructor(permissionService) {
2735
- this.permissionService = permissionService;
2736
- }
2737
- async getPermissions() {
2738
- const permissions = await this.permissionService.getAll();
2739
- return {
2740
- data: permissions,
2741
- message: t9("permissions.success.retrieved"),
2742
- status: "success"
2743
- };
2744
- }
2745
- async getPermission(id) {
2746
- const permission = await this.permissionService.getById(id);
2747
- return {
2748
- data: permission,
2749
- message: t9("permissions.success.retrieved"),
2750
- status: "success"
2751
- };
2752
- }
2753
- async create(body) {
2754
- const newPermission = await this.permissionService.create(body);
2755
- return {
2756
- data: newPermission,
2757
- message: t9("permissions.success.created"),
2758
- status: "success"
2759
- };
2760
- }
2761
- async update(id, body) {
2762
- const updatedPermission = await this.permissionService.update(id, body);
2763
- return {
2764
- data: updatedPermission,
2765
- message: t9("permissions.success.updated"),
2766
- status: "success"
2767
- };
2768
- }
2769
- async delete(id) {
2770
- const result = await this.permissionService.delete(id);
2771
- return {
2772
- data: result,
2773
- message: t9("permissions.success.deleted"),
2774
- status: "success"
2775
- };
2776
- }
2777
- async getByRole(roleId) {
2778
- const permissions = await this.permissionService.getPermissionsByRole(roleId);
2779
- return {
2780
- data: permissions,
2781
- message: t9("permissions.success.retrieved"),
2782
- status: "success"
2783
- };
2784
- }
2785
- async getRolesByPermission(permissionId) {
2786
- const roles = await this.permissionService.getRolesByPermission(permissionId);
2787
- return {
2788
- data: roles,
2789
- message: t9("permissions.success.retrieved"),
2790
- status: "success"
2791
- };
2792
- }
2793
- async assignToRole(roleId, permissionId) {
2794
- const result = await this.permissionService.assignPermissionToRole(roleId, permissionId);
2795
- return {
2796
- data: result,
2797
- message: t9("permissions.success.assigned"),
2798
- status: "success"
2799
- };
2800
- }
2801
- async removeFromRole(roleId, permissionId) {
2802
- const result = await this.permissionService.removePermissionFromRole(roleId, permissionId);
2803
- return {
2804
- data: result,
2805
- message: t9("permissions.success.removed"),
2806
- status: "success"
2807
- };
2808
- }
2809
- async deleteAll() {
2810
- const result = await this.permissionService.deleteAll();
2811
- return {
2812
- data: result,
2813
- message: t9("permissions.success.allDeleted"),
2814
- status: "success"
2815
- };
2816
- }
2817
- }, __name(_a35, "PermissionController"), _a35);
2818
- __decorate20([
2819
- Get4(),
2820
- __metadata15("design:type", Function),
2821
- __metadata15("design:paramtypes", []),
2822
- __metadata15("design:returntype", Promise)
2823
- ], PermissionController.prototype, "getPermissions", null);
2824
- __decorate20([
2825
- Get4("/:id"),
2826
- __param6(0, Params4("id")),
2827
- __metadata15("design:type", Function),
2828
- __metadata15("design:paramtypes", [String]),
2829
- __metadata15("design:returntype", Promise)
2830
- ], PermissionController.prototype, "getPermission", null);
2831
- __decorate20([
2832
- Post4(),
2833
- __param6(0, Body4()),
2834
- __metadata15("design:type", Function),
2835
- __metadata15("design:paramtypes", [Object]),
2836
- __metadata15("design:returntype", Promise)
2837
- ], PermissionController.prototype, "create", null);
2838
- __decorate20([
2839
- Put3("/:id"),
2840
- __param6(0, Params4("id")),
2841
- __param6(1, Body4()),
2842
- __metadata15("design:type", Function),
2843
- __metadata15("design:paramtypes", [String, Object]),
2844
- __metadata15("design:returntype", Promise)
2845
- ], PermissionController.prototype, "update", null);
2846
- __decorate20([
2847
- Delete3("/:id"),
2848
- __param6(0, Params4("id")),
2849
- __metadata15("design:type", Function),
2850
- __metadata15("design:paramtypes", [String]),
2851
- __metadata15("design:returntype", Promise)
2852
- ], PermissionController.prototype, "delete", null);
2853
- __decorate20([
2854
- Get4("/role/:roleId"),
2855
- __param6(0, Params4("roleId")),
2856
- __metadata15("design:type", Function),
2857
- __metadata15("design:paramtypes", [String]),
2858
- __metadata15("design:returntype", Promise)
2859
- ], PermissionController.prototype, "getByRole", null);
2860
- __decorate20([
2861
- Get4("/roles/:permissionId"),
2862
- __param6(0, Params4("permissionId")),
2863
- __metadata15("design:type", Function),
2864
- __metadata15("design:paramtypes", [String]),
2865
- __metadata15("design:returntype", Promise)
2866
- ], PermissionController.prototype, "getRolesByPermission", null);
2867
- __decorate20([
2868
- Post4("/assign/:roleId/:permissionId"),
2869
- __param6(0, Params4("roleId")),
2870
- __param6(1, Params4("permissionId")),
2871
- __metadata15("design:type", Function),
2872
- __metadata15("design:paramtypes", [String, String]),
2873
- __metadata15("design:returntype", Promise)
2874
- ], PermissionController.prototype, "assignToRole", null);
2875
- __decorate20([
2876
- Delete3("/remove/:roleId/:permissionId"),
2877
- __param6(0, Params4("roleId")),
2878
- __param6(1, Params4("permissionId")),
2879
- __metadata15("design:type", Function),
2880
- __metadata15("design:paramtypes", [String, String]),
2881
- __metadata15("design:returntype", Promise)
2882
- ], PermissionController.prototype, "removeFromRole", null);
2883
- __decorate20([
2884
- Delete3(),
2885
- isAdmin(),
2886
- __metadata15("design:type", Function),
2887
- __metadata15("design:paramtypes", []),
2888
- __metadata15("design:returntype", Promise)
2889
- ], PermissionController.prototype, "deleteAll", null);
2890
- PermissionController = __decorate20([
2891
- Controller4("/permissions"),
2892
- isAdmin(),
2893
- __metadata15("design:paramtypes", [typeof (_a34 = typeof PermissionService !== "undefined" && PermissionService) === "function" ? _a34 : Object])
2894
- ], PermissionController);
2895
-
2896
- // src/plugin.ts
2897
- var AuthPlugin = {
2898
- name: "najm-auth",
2899
- database: "default",
2900
- controllers: [
2901
- UserController,
2902
- AuthController,
2903
- RoleController,
2904
- PermissionController
2905
- ],
2906
- services: [
2907
- UserService,
2908
- AuthService,
2909
- CookieService,
2910
- EncryptionService,
2911
- RoleService,
2912
- PermissionService,
2913
- TokenService
2914
- ],
2915
- repositories: [
2916
- UserRepository,
2917
- RoleRepository,
2918
- PermissionRepository,
2919
- TokenRepository
2920
- ],
2921
- providers: [
2922
- UserValidator,
2923
- RoleValidator,
2924
- PermissionValidator,
2925
- RoleGuards,
2926
- PermissionGuards
2927
- ]
2928
- };
2929
- export {
2930
- AuthController,
2931
- AuthPlugin,
2932
- AuthService,
2933
- CookieService,
2934
- ENUMS,
2935
- EncryptionService,
2936
- Permission,
2937
- PermissionController,
2938
- PermissionGuards,
2939
- PermissionRepository,
2940
- PermissionService,
2941
- PermissionValidator,
2942
- ROLES,
2943
- ROLE_GROUPS,
2944
- Role,
2945
- RoleChecker,
2946
- RoleController,
2947
- RoleGuards,
2948
- RoleRepository,
2949
- RoleService,
2950
- RoleValidator,
2951
- TokenRepository,
2952
- TokenService,
2953
- UserController,
2954
- UserRepository,
2955
- UserService,
2956
- UserValidator,
2957
- alertPriorityEnum,
2958
- alertSchema,
2959
- alertStatusEnum,
2960
- alertTypeEnum,
2961
- announcementSchema,
2962
- assessmentSchema,
2963
- assessmentStatusEnum,
2964
- assessmentTypeEnum,
2965
- assignmentSchema,
2966
- assignmentStatusEnum,
2967
- assignmentsSchema,
2968
- attendanceSchema,
2969
- attendanceStatusEnum,
2970
- avatarsPath,
2971
- bulkAssessmentSchema,
2972
- bulkFeeFormSchema,
2973
- bulkFeeItemSchema,
2974
- busStatusEnum,
2975
- calculateAge,
2976
- calculateYearsOfExperience,
2977
- calendarSystemEnum,
2978
- classSchema,
2979
- classStatusEnum,
2980
- clean,
2981
- dateRangeSchema,
2982
- dayOfWeekEnum,
2983
- driverSchema,
2984
- driverStatusEnum,
2985
- employmentTypeEnum,
2986
- enrollmentStatusEnum,
2987
- eventParticipantSchema,
2988
- eventSchema,
2989
- eventStatusEnum,
2990
- eventTypeEnum,
2991
- eventVisibilityEnum,
2992
- examSchema,
2993
- examSecurityEnum,
2994
- examStatusEnum,
2995
- examTypeEnum,
2996
- expenseApprovalSchema,
2997
- expenseCategoryEnum,
2998
- expensePaymentSchema,
2999
- expenseSchema,
3000
- expenseStatusEnum,
3001
- feeInstallmentSchema,
3002
- feeInstallmentStatusEnum,
3003
- feePaymentSchema,
3004
- feeSchema,
3005
- feeStatusEnum,
3006
- feeTypeSchema,
3007
- feeTypeStatusEnum,
3008
- feesSchema,
3009
- fileStatusEnum,
3010
- formatDate,
3011
- fuelTypeEnum,
3012
- fullStudentSchema,
3013
- genderEnum,
3014
- getAvatarFile,
3015
- getEnumConfig,
3016
- getEnumValues,
3017
- gradeSchema,
3018
- gradeStatusEnum,
3019
- idField,
3020
- idParamSchema,
3021
- isAccounting,
3022
- isAdmin,
3023
- isAdministrator,
3024
- isAuth,
3025
- isEmpty,
3026
- isFile,
3027
- isFinancial,
3028
- isParent,
3029
- isPath,
3030
- isPrincipal,
3031
- isSecretary,
3032
- isStaff,
3033
- isStudent,
3034
- isTeacher,
3035
- languageEnum,
3036
- maintenanceStatusEnum,
3037
- maintenanceTypeEnum,
3038
- maritalStatusEnum,
3039
- paginationSchema,
3040
- parentSchema,
3041
- parentsSchema,
3042
- parseSchema,
3043
- participantTypeEnum,
3044
- paymentAllocationSchema,
3045
- paymentMethodEnum,
3046
- paymentStatusEnum,
3047
- paymentTypeEnum,
3048
- permissionsTable,
3049
- pickProps,
3050
- proficiencyLevelEnum,
3051
- refuelSchema,
3052
- refuelStatusEnum,
3053
- relationshipTypeEnum,
3054
- rolePermissionsTable,
3055
- roleSchema,
3056
- rolesTable,
3057
- scheduleEnum,
3058
- sectionSchema,
3059
- sectionStatusEnum,
3060
- semesterEnum,
3061
- settingsSchema,
3062
- studentSchema,
3063
- studentStatusEnum2 as studentStatusEnum,
3064
- subjectSchema,
3065
- submissionTypeEnum,
3066
- teacherFullSchema,
3067
- teacherPersonalSchema,
3068
- teacherProfessionalSchema,
3069
- teacherStatusEnum,
3070
- tokenStatusEnum2 as tokenStatusEnum,
3071
- tokenTypeEnum2 as tokenTypeEnum,
3072
- tokensTable,
3073
- trackerModeEnum,
3074
- userSchema,
3075
- userStatusEnum2 as userStatusEnum,
3076
- userTypeEnum,
3077
- usersTable,
3078
- vehicleDocumentTypeEnum,
3079
- vehicleSchema,
3080
- vehicleStatusEnum,
3081
- vehicleTypeEnum
3082
- };