This repository was archived by the owner on May 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathusers.js
More file actions
86 lines (82 loc) · 3.29 KB
/
Copy pathusers.js
File metadata and controls
86 lines (82 loc) · 3.29 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
const jwt = require('jsonwebtoken');
const User = require('../models').User;
const Role = require('../models').Role;
const UserRole = require('../models').UserRole;
module.exports = {
create(req, res) {
const { email, name, password } = req.body;
return User
.create({
username: email,
email,
name,
password,
})
.then(user => res.status(201).json({ data: user , message: 'User successfully got registered!'}))
.catch(error => res.status(400).json({ data: error }));
},
list(req, res) {
return User
.findAll()
.then(users => res.status(200).json({ data: users }))
.catch(error => res.status(400).json({ data: error }));
},
get(req, res) {
return res.status(200).json({data: req.user});
},
login(req, res) {
const { email, password } = req.body;
return User
.findOne({ where: { email } })
.then(user => {
if (user.password === password) {
const payload = {id: user.id};
const token = jwt.sign(payload, process.env.JWT_SECRET);
return res.json({ message: "ok", data: { token } });
} else {
return res.status(401).json({ message: "Passwords did not match" });
}
})
.catch(error => res.status(400).json({ data: error, message: 'No such user found' }));
},
addUserRole(req,res){
const { value } = req.body;
const id = req.params.id;
return User
.findOne({ where: { id } })
.then(user => {
const id = user.id;
Role
.findOne({ where: { value } })
.then(role => {
UserRole.create({
UserId : id,
RoleId : role.id,
});
res.status(200).json({message:'Role \'' + value +'\' added to user' });
} )
.catch(error => res.status(400).json({ data: error, message: 'No such role found' }))
} )
.catch(error => res.status(400).json({ data: error, message: 'No such user found' }));
},
removeUserRole(req,res){
const { value } = req.body;
const id = req.params.id;
return User
.findOne({ where: { id } })
.then(user => {
Role
.findOne({ where: { value } })
.then(role => {
const id = user.id;
UserRole
.destroy({ where: { UserId:id, RoleId:role.id }
})
.then(userrole => {res.status(200).json({message:'Role \'' + value +'\' removed from user' })})
.catch(error => res.status(400).json({ data: error, message: 'No such role assigned to user' }));
} )
.catch(error => res.status(400).json({ data: error, message: 'No such role found' }))
} )
.catch(error => res.status(400).json({ data: error, message: 'No such user found' }));
},
}