forked from Sunbird-Obsrv/obsrv-web-console
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuser_update.ts
More file actions
48 lines (45 loc) · 1.88 KB
/
user_update.ts
File metadata and controls
48 lines (45 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { Request, Response, NextFunction } from 'express';
import userService from '../services/oauthUsers';
import bcrypt from 'bcryptjs';
import { transform } from '../../shared/utils/transformResponse';
import _ from 'lodash';
export default {
name: 'user:update',
handler: () => async (req: Request, res: Response, next: NextFunction) => {
try {
const { user_name, ...updateInfo } = _.get(req, ['body', 'request']);
const sessionUserName = _.get(req, ['session', 'userDetails', 'user_name']);
const userId = _.get(req, ['session', 'userDetails', 'id']);
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload');
if (user_name !== sessionUserName) {
res.status(403).json(
transform({
responseCode: 'FORBIDDEN',
params: {
err: 'FORBIDDEN',
errmsg: 'Access denied',
},
}),
);
}
if (_.isEmpty(updateInfo)) {
return res.status(400).json({ error: 'Atleast one field is required to update' });
}
const user = await userService.find({ user_name });
if (updateInfo.password) {
updateInfo.password = await bcrypt.hash(updateInfo.password, 12);
}
const result = await userService.update(
{ user_name },
{
...updateInfo,
last_updated_on: new Date().toISOString(),
updated_by: userId,
},
);
res.status(200).json(transform({ id: req.body.id, result: { id: result.id, user_name: result.user_name } }));
} catch (error) {
next(error);
}
},
};