-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathusers.js
62 lines (57 loc) · 1.53 KB
/
users.js
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
const model = require("../model/user-model");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
require("dotenv").config();
const SECRET = process.env.JWT_SECRET;
function createUser(req, res, next) {
const username = req.body.username;
const password = req.body.password;
bcrypt
.genSalt(10)
.then((salt) => bcrypt.hash(password, salt))
.then((hash) => {
model
.addUser(username, hash)
.then((result) => {
const token = jwt.sign({ user: result.id }, SECRET, {
expiresIn: "1h",
});
result.token = token;
res.status(201).send(result);
})
.catch(next);
})
.catch(console.error)
}
function login(req, res, next) {
const username = req.body.username;
const password = req.body.password;
console.log(req.params.id);
model
.getUserByName(username)
.then((loginObject) => {
return bcrypt.compare(password, loginObject.password);
})
.then((match) => {
if (!match) {
const error = new Error("Unauthorized access. Please try again.");
error.status = 401;
next(error);
} else {
const token = jwt.sign({ user: match.id }, SECRET, {
expiresIn: "1h",
});
res.status(200).send({ token: token });
}
})
.catch(next);
}
function getAllUsers(req, res, next) {
model
.getEveryUser()
.then((users) => {
res.status(200).send(users);
})
.catch(next);
}
module.exports = { createUser, login, getAllUsers };