-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathauth-server.js
77 lines (66 loc) · 2.18 KB
/
auth-server.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// todo presently this file does nothing
// would need to pull the related funcitonality out of the user controller / model
// will remove this file if the time/inclination does not exist
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const db = require('./models');
const routes = require('./routes');
const app = express();
const PORT = process.env.PORT || 8081;
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static('public'));
app.use('/', routes);
app.post('/token', (req, res) => {
const refreshToken = req.body.token;
if (refreshToken == null) {
return res.sendStatus(401);
}
db.User.findOne({
where: { refreshToken },
})
.then((result) => {
if (result.refreshToken == null) {
return res.sendStatus(403);
}
jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET, (err, user) => {
if (err) {
return res.sendStatus(403);
}
const accessToken = generateAccessToken({ name: user.name });
res.json(accessToken);
});
})
.catch((err) => {
return `Something went wrong: ${err}.`;
});
});
app.post('/login', (req, res) => {
db.User.findOne({
where: { username: req.body.username },
})
.then(async (user) => {
if (await bcrypt.compare(req.body.password, user.password)) {
const accessToken = generateAccessToken(user.dataValues);
const refreshToken = jwt.sign(user.dataValues, process.env.REFRESH_TOKEN_SECRET);
res.json({ accessToken, refreshToken });
} else {
res.send('No match!');
}
})
// res.json(results.username)) // todo, needs to return as logged in or a token
.catch((err) => res.send(`Something went wrong ${err}.`));
});
app.delete('/logout', (req, res) => {
// reassign refreshtokens to no longer include the present refresh token
res.sendStatus(204);
});
const generateAccessToken = (user) => {
return jwt.sign(user.dataValues, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '15s' });
};
db.sequelize.sync().then(() => {
app.listen(PORT, () => {
console.log(`App listening on PORT ${PORT}`);
});
});