-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtokens.js
67 lines (59 loc) · 1.67 KB
/
tokens.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
const jwt = require("jsonwebtoken");
const TOKEN_NAME = "token";
const DB = require("./db");
const dotenv = require("dotenv");
dotenv.config();
module.exports.setTokenInResponse = (res, username) => {
let token = generateToken({ username });
// TODO: create token with username as data
res.cookie(TOKEN_NAME, token, {
maxAge: 40 * 24 * 60 * 60 * 1000, // 40 days
httpOnly: true,
});
};
module.exports.destroyLoggedInToken = (res) => {
res.cookie(TOKEN_NAME, "");
};
/**
* Checks if req is from a logged in person.
* If so, it saves the person's database info in req.person.
* Otherwise, it redirects to the login page.
* @param {*} req
* @param {*} res
* @param {*} next
*/
module.exports.mustBeLoggedIn = (req, res, next) => {
let token = req.cookies[TOKEN_NAME];
verifyToken(token)
.then((data) => {
let person = DB.getPerson(data.username, (err, person) => {
if (err) {
res.redirect("/logon");
} else {
req.person = person;
next();
}
});
})
.catch((err) => {
// send user back to login page
res.redirect("/logon");
});
};
// TODO: fix this
const { JWT_TOKEN_SECRET } = process.env;
const expiresIn = "3456000s"; // = 40 days
/** The 'data' passed looks like this:
* {username: "zach1"} **/
const generateToken = (data) => {
return jwt.sign(data, JWT_TOKEN_SECRET, { expiresIn });
};
/** Verifying a token uses promises. **/
const verifyToken = (token) => {
return new Promise((resolve, reject) => {
jwt.verify(token, JWT_TOKEN_SECRET, (err, data) => {
if (err) return reject(err); // token is invalid
resolve(data); // token in valid
});
});
};