@ciscode/authentication-kit 1.2.1 → 1.4.0

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.
@@ -19,70 +19,132 @@ const user_repository_1 = require("../repositories/user.repository");
19
19
  const role_repository_1 = require("../repositories/role.repository");
20
20
  const mongoose_1 = require("mongoose");
21
21
  const helper_1 = require("../utils/helper");
22
+ const logger_service_1 = require("./logger.service");
22
23
  let UsersService = class UsersService {
23
- constructor(users, rolesRepo) {
24
+ constructor(users, rolesRepo, logger) {
24
25
  this.users = users;
25
26
  this.rolesRepo = rolesRepo;
27
+ this.logger = logger;
26
28
  }
27
29
  async create(dto) {
28
- // Generate username from fname-lname if not provided
29
- if (!dto.username || dto.username.trim() === '') {
30
- dto.username = (0, helper_1.generateUsernameFromName)(dto.fullname.fname, dto.fullname.lname);
30
+ try {
31
+ // Generate username from fname-lname if not provided
32
+ if (!dto.username || dto.username.trim() === '') {
33
+ dto.username = (0, helper_1.generateUsernameFromName)(dto.fullname.fname, dto.fullname.lname);
34
+ }
35
+ // Check for existing user
36
+ const [existingEmail, existingUsername, existingPhone] = await Promise.all([
37
+ this.users.findByEmail(dto.email),
38
+ this.users.findByUsername(dto.username),
39
+ dto.phoneNumber ? this.users.findByPhone(dto.phoneNumber) : null,
40
+ ]);
41
+ if (existingEmail || existingUsername || existingPhone) {
42
+ throw new common_1.ConflictException('An account with these credentials already exists');
43
+ }
44
+ // Hash password
45
+ let hashed;
46
+ try {
47
+ const salt = await bcryptjs_1.default.genSalt(10);
48
+ hashed = await bcryptjs_1.default.hash(dto.password, salt);
49
+ }
50
+ catch (error) {
51
+ this.logger.error(`Password hashing failed: ${error.message}`, error.stack, 'UsersService');
52
+ throw new common_1.InternalServerErrorException('User creation failed');
53
+ }
54
+ const user = await this.users.create({
55
+ fullname: dto.fullname,
56
+ username: dto.username,
57
+ email: dto.email,
58
+ phoneNumber: dto.phoneNumber,
59
+ avatar: dto.avatar,
60
+ jobTitle: dto.jobTitle,
61
+ company: dto.company,
62
+ password: hashed,
63
+ roles: [],
64
+ isVerified: true,
65
+ isBanned: false,
66
+ passwordChangedAt: new Date()
67
+ });
68
+ return { id: user._id, email: user.email };
31
69
  }
32
- if (await this.users.findByEmail(dto.email))
33
- throw new Error('Email already in use.');
34
- if (await this.users.findByUsername(dto.username))
35
- throw new Error('Username already in use.');
36
- if (dto.phoneNumber && (await this.users.findByPhone(dto.phoneNumber))) {
37
- throw new Error('Phone already in use.');
70
+ catch (error) {
71
+ if (error instanceof common_1.ConflictException || error instanceof common_1.InternalServerErrorException) {
72
+ throw error;
73
+ }
74
+ if ((error === null || error === void 0 ? void 0 : error.code) === 11000) {
75
+ throw new common_1.ConflictException('An account with these credentials already exists');
76
+ }
77
+ this.logger.error(`User creation failed: ${error.message}`, error.stack, 'UsersService');
78
+ throw new common_1.InternalServerErrorException('User creation failed');
38
79
  }
39
- const salt = await bcryptjs_1.default.genSalt(10);
40
- const hashed = await bcryptjs_1.default.hash(dto.password, salt);
41
- const user = await this.users.create({
42
- fullname: dto.fullname,
43
- username: dto.username,
44
- email: dto.email,
45
- phoneNumber: dto.phoneNumber,
46
- avatar: dto.avatar,
47
- jobTitle: dto.jobTitle,
48
- company: dto.company,
49
- password: hashed,
50
- roles: [],
51
- isVerified: true,
52
- isBanned: false,
53
- passwordChangedAt: new Date()
54
- });
55
- return { id: user._id, email: user.email };
56
80
  }
57
81
  async list(filter) {
58
- return this.users.list(filter);
82
+ try {
83
+ return this.users.list(filter);
84
+ }
85
+ catch (error) {
86
+ this.logger.error(`User list failed: ${error.message}`, error.stack, 'UsersService');
87
+ throw new common_1.InternalServerErrorException('Failed to retrieve users');
88
+ }
59
89
  }
60
90
  async setBan(id, banned) {
61
- const user = await this.users.updateById(id, { isBanned: banned });
62
- if (!user)
63
- throw new Error('User not found.');
64
- return { id: user._id, isBanned: user.isBanned };
91
+ try {
92
+ const user = await this.users.updateById(id, { isBanned: banned });
93
+ if (!user) {
94
+ throw new common_1.NotFoundException('User not found');
95
+ }
96
+ return { id: user._id, isBanned: user.isBanned };
97
+ }
98
+ catch (error) {
99
+ if (error instanceof common_1.NotFoundException) {
100
+ throw error;
101
+ }
102
+ this.logger.error(`Set ban status failed: ${error.message}`, error.stack, 'UsersService');
103
+ throw new common_1.InternalServerErrorException('Failed to update user ban status');
104
+ }
65
105
  }
66
106
  async delete(id) {
67
- const user = await this.users.deleteById(id);
68
- if (!user)
69
- throw new Error('User not found.');
70
- return { ok: true };
107
+ try {
108
+ const user = await this.users.deleteById(id);
109
+ if (!user) {
110
+ throw new common_1.NotFoundException('User not found');
111
+ }
112
+ return { ok: true };
113
+ }
114
+ catch (error) {
115
+ if (error instanceof common_1.NotFoundException) {
116
+ throw error;
117
+ }
118
+ this.logger.error(`User deletion failed: ${error.message}`, error.stack, 'UsersService');
119
+ throw new common_1.InternalServerErrorException('Failed to delete user');
120
+ }
71
121
  }
72
122
  async updateRoles(id, roles) {
73
- const existing = await this.rolesRepo.findByIds(roles);
74
- if (existing.length !== roles.length)
75
- throw new Error('One or more roles not found.');
76
- const roleIds = roles.map((r) => new mongoose_1.Types.ObjectId(r));
77
- const user = await this.users.updateById(id, { roles: roleIds });
78
- if (!user)
79
- throw new Error('User not found.');
80
- return { id: user._id, roles: user.roles };
123
+ try {
124
+ const existing = await this.rolesRepo.findByIds(roles);
125
+ if (existing.length !== roles.length) {
126
+ throw new common_1.NotFoundException('One or more roles not found');
127
+ }
128
+ const roleIds = roles.map((r) => new mongoose_1.Types.ObjectId(r));
129
+ const user = await this.users.updateById(id, { roles: roleIds });
130
+ if (!user) {
131
+ throw new common_1.NotFoundException('User not found');
132
+ }
133
+ return { id: user._id, roles: user.roles };
134
+ }
135
+ catch (error) {
136
+ if (error instanceof common_1.NotFoundException) {
137
+ throw error;
138
+ }
139
+ this.logger.error(`Update user roles failed: ${error.message}`, error.stack, 'UsersService');
140
+ throw new common_1.InternalServerErrorException('Failed to update user roles');
141
+ }
81
142
  }
82
143
  };
83
144
  exports.UsersService = UsersService;
84
145
  exports.UsersService = UsersService = __decorate([
85
146
  (0, common_1.Injectable)(),
86
147
  __metadata("design:paramtypes", [user_repository_1.UserRepository,
87
- role_repository_1.RoleRepository])
148
+ role_repository_1.RoleRepository,
149
+ logger_service_1.LoggerService])
88
150
  ], UsersService);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ciscode/authentication-kit",
3
- "version": "1.2.1",
3
+ "version": "1.4.0",
4
4
  "description": "NestJS auth kit with local + OAuth, JWT, RBAC, password reset.",
5
5
  "publishConfig": {
6
6
  "access": "public"