api: update user password and data
Parents:
ac4f34f2 file(s) changed
- api/src/controllers/users.ts +25 -17
- api/src/models/user.ts +11 -0
api/src/controllers/users.ts
@@ -43,28 +43,36 @@
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 }
api/src/models/user.ts
@@ -20,6 +20,8 @@ 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) => {
@@ -146,6 +148,15 @@ 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