-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
133 lines (111 loc) · 3.07 KB
/
index.js
File metadata and controls
133 lines (111 loc) · 3.07 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
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
require('dotenv').config();
const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken'); // installed this library
const db = require('./database/dbConfig.js');
const Users = require('./users/users-model.js');
// defined the secret
const secret =
process.env.JWT_SECRET || 'add a third table for many to many relationships';
const server = express();
server.use(helmet());
server.use(express.json());
server.use(cors());
server.get('/', (req, res) => {
res.send("It's alive!");
});
server.post('/api/register', (req, res) => {
let user = req.body;
// generate hash from user's password
const hash = bcrypt.hashSync(user.password, 10); // 2 ^ n
// override user.password with hash
user.password = hash;
Users.add(user)
.then(saved => {
res.status(201).json(saved);
})
.catch(error => {
res.status(500).json(error);
});
});
// added this function
function generateToken(user) {
const payload = {
subject: user.id, // sub in payload is what the token is about
username: user.username,
roles: ['Student'],
// ...otherData
};
const options = {
expiresIn: '1d',
};
return jwt.sign(payload, secret, options);
}
server.post('/api/login', (req, res) => {
let { username, password } = req.body;
Users.findBy({ username })
.first()
.then(user => {
// check that passwords match
if (user && bcrypt.compareSync(password, user.password)) {
const token = generateToken(user); // new
// return token
res.status(200).json({
message: `Welcome ${user.username}!, have a token...`,
token,
secret,
roles: token.roles,
});
} else {
res.status(401).json({ message: 'Invalid Credentials' });
}
})
.catch(error => {
res.status(500).json(error);
});
});
function restricted(req, res, next) {
const token = req.headers.authorization;
if (token) {
// is it valid?
jwt.verify(token, secret, (err, decodedToken) => {
if (err) {
// record the event
res.status(401).json({ you: "can't touch this!" });
} else {
req.decodedJwt = decodedToken;
next();
}
});
} else {
res.status(401).json({ you: 'shall not pass!' });
}
}
function checkRole(role) {
return function(req, res, next) {
if (req.decodedJwt.roles && req.decodedJwt.roles.includes(role)) {
next();
} else {
res.status(403).json({ you: 'you have no power here!' });
}
};
}
server.get('/api/users', restricted, checkRole('Student'), (req, res) => {
Users.find()
.then(users => {
res.json({ users, decodedToken: req.decodedJwt });
})
.catch(err => res.send(err));
});
server.get('/users', restricted, async (req, res) => {
try {
const users = await Users.find();
res.json(users);
} catch (error) {
res.send(error);
}
});
const port = process.env.PORT || 5000;
server.listen(port, () => console.log(`\n** Running on port ${port} **\n`));