api: update user password and data
Pedro Lucas Porcellis porcellis@eletrotupi.com · 5 months ago
4ad3b1e9ec83ec2f5e944d38157d375ca9158c4d Browse filesParents
ac4f34fChanged files
2
Additions
+36
Deletions
-17
api/src/controllers/users.ts
1 1
import { Request, Response, NextFunction } from 'express';
2 2
import {
3 3
createUser,
4 4
findUserById,
5 5
findUserByEmail,
41 41
},
42 42
43 43
update: async (req: Request, res: Response, next: NextFunction) => {
44 44
try {
45 45
const { id } = req.params
46 -
const { email, password, firstName, lastName } = req.body;
46 +
const { user: userParams } = req.body;
47 47
48 -
const user = await findUserById(Number(id));
48 +
if (userParams) {
49 +
const { email, password, firstName, lastName } = userParams;
49 50
50 -
if (!user) {
51 -
return res.status(404).json({
52 -
error: "Usuário não encontrado"
53 -
})
54 -
}
51 +
const user = await findUserById(Number(id));
55 52
56 -
if (email || password || firstName || lastName) {
57 -
const response = await updateUser(user, {
58 -
email, firstName, lastName
59 -
})
60 -
}
53 +
if (!user) {
54 +
return res.status(404).json({
55 +
error: "Usuário não encontrado"
56 +
})
57 +
}
61 58
62 -
const updated = await findUserById(Number(id))
59 +
if (email || password || firstName || lastName) {
60 +
const response = await updateUser(user, {
61 +
email, firstName, lastName, password
62 +
})
63 +
64 +
const updated = await findUserById(Number(id))
63 65
64 -
// TODO: Drop encrypted password & token here
65 -
return res.status(200).json({
66 -
user: updated
67 -
})
66 +
// TODO: Drop encrypted password & token here
67 +
return res.status(200).json({
68 +
user: updated
69 +
})
70 +
} else {
71 +
return res.status(200).json({
72 +
user
73 +
})
74 +
}
75 +
}
68 76
} catch (err) {
69 77
next(err);
70 78
}
71 79
}
72 80
};
api/src/models/user.ts
1 1
import bcrypt from "bcryptjs";
2 2
import { prisma } from '../lib/prisma'
3 3
import {
4 4
generateToken as createJWT,
5 5
generatePasswordResetToken,
18 18
19 19
type UserOptions = {
20 20
email: string;
21 21
firstName: string;
22 22
lastName: string;
23 +
password?: string;
24 +
encryptedPassword?: string;
23 25
};
24 26
25 27
const createUser = async (email: string, firstName: string, lastName: string, password: string) => {
26 28
// Validate email format
27 29
if (!isValidEmail(email)) {
144 146
145 147
return { success: true };
146 148
};
147 149
148 150
const updateUser = async (user: any, data: UserOptions) => {
151 +
const { password } = data;
152 +
153 +
if (password) {
154 +
const encryptedPassword = bcrypt.hashSync(password, 10);
155 +
156 +
delete data.password;
157 +
data = { ...data, encryptedPassword }
158 +
}
159 +
149 160
return await prisma.user.update({
150 161
where: { id: user.id },
151 162
data
152 163
});
153 164
}
160 171
authenticateUser,
161 172
initiatePasswordReset,
162 173
resetPassword,
163 174
updateUser
164 175
}