-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserController.js
More file actions
108 lines (80 loc) · 2.93 KB
/
Copy pathUserController.js
File metadata and controls
108 lines (80 loc) · 2.93 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import jwt from "jsonwebtoken";
import environment from "../config/environment";
import { UserRepository } from "../repository";
import { GlobalHandler, encrypt, checkEncrypt } from "../utils";
import { UserValidator } from "../validator";
export default class UserController {
constructor(){
this.repository = new UserRepository();
}
async login(req, res) {
try {
const user = req.body;
const foundUser = await this.repository.findOneByEmail(user.email);
foundUser._doc.profile.roles.map((v, index) => foundUser._doc.profile.roles[index] = v.name);
const validPass = checkEncrypt(user.password, foundUser.password);
if(!validPass) {
throw GlobalHandler.makeError(`Invalid password!`, 401, 'VDTE')
}
const token = jwt.sign({
id: foundUser._id,
email: foundUser.email,
profile: foundUser.profile.name,
roles: foundUser.profile.roles
},
environment.privateJWT,
{ expiresIn: "7d" }
)
const returnUser = Object.assign({}, foundUser._doc)
delete returnUser['password']
return res.send({
user: returnUser,
token: token,
})
}catch (error) {
const sanitizedError = GlobalHandler.handle(error);
res.status(sanitizedError.code).send(sanitizedError)
}
}
async listUsers(req, res) {
const filters = req.filters;
let users = await this.repository.findAll(filters)
res.send(users)
}
async saveUser(req, res) {
try {
const user = req.body;
await UserValidator(user)
user.password = encrypt(user.password)
let savedUser = await this.repository.store(user)
res.send(savedUser)
} catch (error){
const sanitizedError = GlobalHandler.handle(error);
res.status(sanitizedError.code).send(sanitizedError)
}
}
async updateUser(req, res) {
try {
const { id } = req.params;
const body = req.body;
await UserValidator(body)
let updatedUser = await this.repository.update(body, id)
res.send(updatedUser)
} catch (error){
const sanitizedError = GlobalHandler.handle(error);
res.status(sanitizedError.code).send(sanitizedError)
}
}
async deleteUser(req, res) {
try {
const { id } = req.params;
await this.repository.delete(id)
res.json({
message: `User with id ${id} successful deleted!`
})
} catch (error){
const sanitizedError = GlobalHandler.handle(error);
res.status(sanitizedError.code).send(sanitizedError)
}
}
}