-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathholdcode
297 lines (230 loc) · 8.09 KB
/
holdcode
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
const { QueryTypes } = require("sequelize");
const bcrypt = require("bcrypt");
const { generateToken } = require("../utils/authJwt");
const db = require("../utils/database");
const cf = require("../utils/customFunctions");
exports.signup = async (req, res) => {
/* REGISTER USER */
try{
let assignedRoles = [];
const { code, username, password, cpassword } = req.body;
/* -------------VALIDATIONS---------------- */
if (!code || !username || !password || !cpassword) {
return res.status(401).send("Please fill in all fields.");
}
if (password !== cpassword) {
return res.status(401).send("Check your password and confirm again.");
}
if (password.length < 6) {
return res.status(401).send("Password must be atleast 6 characters.");
}
//Make sure the username is not in use
const user_name = await db.user.findOne({ where: { username: username } });
if (user_name) {
console.log(user_name);
return res.status(401).send("Username already taken, please use another one.");
}
//Check login code authenticity
const getMemberDetails = await db.member.findOne({
where: { login_code: code.trim() },
});
if (!getMemberDetails) {
return res.status(401).send("Invalid code.");
}
/* -------------VALIDATION PASSED---------------- */
/* ----1. Save user to database.--------*/
console.log(assignedRoles)
db.user
.create({
username: username,
password: bcrypt.hashSync(password, 10),
member_id: getMemberDetails.member_id
})
.then((newUser) => {
// delete signup code and assigned roles from the member table
db.member.update(
{ login_code: "" },
{ where: { member_id: newUser.member_id } }
);
res.status(200).send({ message: "User created successfully" });
})
.catch((error) => {
console.log(error);
res.status(401).send("An error occured while creating your account. Contact the Administrator.");
});
} catch(error){
console.log(error);
res.status(401).send("An error occured while creating your account. Contact the Administrator.");
}
};
exports.signin = async(req, res, next) => {
var authorities = undefined;
var token = undefined;
var randNo = Math.floor(Math.random() * 8) + 1;
db.user.findOne({ where: { username: req.body.username } })
.then((result) =>{
if(!result){
return res.status(401).send("Incorrect username or password.");
}
//decrypt password
var passwordIsValid = bcrypt.compareSync(
req.body.password,
result.password
);
if (!passwordIsValid) {
return res.status(401).send("Incorrect username or password.");
}
token = generateToken(result.member_id);
//get roles
db.sequelize.query(`SELECT roles FROM assigned_roles WHERE member_id = '${result.member_id}' AND active <> 'false'`,{ type: db.sequelize.QueryTypes.SELECT })
.then((auth) => {
if (auth.length === 0) {
return res.status(401).send("Your account is inactive, contact the administrator.")
} else {
authorities = auth[0].roles;
}
db.sequelize.query(`SELECT CONCAT(IFNULL(firstname, ''),' ',IFNULL(middlename, ''), ' ',IFNULL(lastname, '')) AS 'user', CONCAT('http://localhost:3001/images/',passport) as 'passportUrl' FROM members WHERE member_id = '${result.member_id}'`,{type: db.sequelize.QueryTypes.SELECT})
.then((result) => {
res.status(200).send({
fullname: result[0].user,
pic: result[0].passportUrl,
accessToken: token,
rights: authorities,
});
}).catch((error) => {
console.log(error);
});
})
.catch((error) => {
console.log(error);
res.status(401).send("An error occured while logging you in. Contact the Admin.");
});
}).catch((error) => {
console.log(error);
res.status(401).send("An error occured while logging you in. Contact the Admin.");
});
};
exports.logout = ("/logout", (req, res) => {
res.json({message: "twas nice having you around!!!!!!!!"})
});
//ROLES
exports.getAllRoles = async(req, res) => {
try{
const data = await db.role.findAll({
order: [
["name", "ASC"],
]
});
res.status(200).send({result:data})
} catch(err){
console.log(err);
res.status(401).send({message: "Unable to retrieve roles."});
}
};
exports.addRole = async(req, res) => {
try{
const { name } = req.body;
const buildRole = await db.role.build({
name: name,
});
const newRole = await buildRole.save();
res.status(200).send({message: "New role added to the database successfully."})
} catch(err){
console.log(err);
res.status(401).send("Server error, unable to add new role to the database. Kindly try again later.");
}
}
exports.updateRole = async(req, res) => {
try{
const {id, name} = req.body
const updateRole = await db.role.update(
{
name: name,
},
{
where: {role_id: id},
}
);
res.status(200).send({message: "Role updated successfully."})
} catch(err){
console.log(err);
res.status(401).send("Unable to update role.");
}
}
exports.deleteRole = async(req, res) => {
// How will the user roles be updated when a role is deleted.
try{
const deleteRole = db.role.destroy({ where: { role_id: req.body.ID } });
res.status(200).send({message: "Role deleted successfully."})
} catch(err){
console.log(err);
res.status(401).send("Unable to delete role.");
}
}
//ASSIGN ROLE
exports.getAllAssignedRoles = async(req, res) => {
try{
const data = await db.sequelize.query(`SELECT ar.assigned_id, ar.roles, ar.active, CONCAT('http://localhost:3001/images/',m.passport) as passport,
CONCAT(IFNULL(m.firstname, ''),' ',IFNULL(m.middlename, ''), ' ',IFNULL(m.lastname, '')) AS 'member'
FROM assigned_roles ar JOIN members m ON (ar.member_id = m.member_id) WHERE m.firstname <> 'dev' ORDER BY 'member'`, {type:QueryTypes.SELECT});
res.status(200).send({result:data});
} catch(err){
console.log(err);
res.status(401).send({message: "Unable to retrieve ministries."});
}
}
exports.addAssignedRole = async(req, res) => {
try{
const { name, role, active } = req.body;
if (!name || name === '' || role.length === 0) {
res.status(401).send("Kindly provide the name of the user and roles assigned to the user.");
return;
}
const memberID = await cf.getMemberID(name);
const loginCode = cf.generateRandomChars(6);
//make sure only one instance of the user exists in the assigned roles table
var checkUser = await db.assignedRoles.findOne({ where: { member_id: memberID } });
if (checkUser !== null){
res.status(401).send(`'${name}' can only be updated not added as a new user.`);
return;
}
let str = /,/g;
let roleToString = role.toString().replace(str, ', ');
const buildAssignedRole = await db.assignedRoles.build({
roles: roleToString,
member_id: memberID,
active: active
});
const newRcd = await buildAssignedRole.save();
const assignLoginCode = await db.member.update(
{
login_code: loginCode.trim(),
},
{
where: {member_id: memberID},
}
);
res.status(200).send({message: "Role(s) assigned successfully."})
} catch(err){
console.log(err);
res.status(401).send("Unable to grant access user.");
}
}
exports.deleteAssignedRole = async(req, res) => {
try{
const deleteAccess = await db.assignedRoles.destroy({ where: { assigned_id: req.body.ID } });
res.status(200).send({message: "User deleted successfully."})
}catch(err){
console.log(err);
res.status(401).send("Unable to delete user.");
}
}
/*
CODE FOR LOOPING THROUGH ARRAY TO SAVE IN DATABASE
for(const e of role){
const assignedRole = db.assignedRoles.build({
member_id: memberID,
role_id: e
});
const newRec = await assignedRole.save();
} */