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
|
const base64 = require('base-64');
const sha512 = require('js-sha512');
const shortid = require('shortid');
const db = require('./db');
const owaspPw = require('owasp-password-strength-test');
const buildSessionCookie = ({ username, sessionToken, isLogout }) => {
if (!isLogout) {
const tokenData = {
username,
sessionToken,
};
const tokenDataStr = JSON.stringify(tokenData);
const encodedToken = base64.encode(tokenDataStr);
return `sessionCookie=${encodedToken}; Domain=localhost; HttpOnly; SameSite=strict;`;
} else {
return `sessionCookie=deleted; Domain=localhost; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; SameSite=strict;`;
}
};
const authMiddleware = async (req, res, next) => {
const cookies = req.cookies;
const encodedCookie = cookies.sessionCookie;
if (!encodedCookie) {
res.status(403);
return res.json({
message: 'Log in first!',
});
}
const sessionCookieStr = base64.decode(encodedCookie);
const sessionCookie = JSON.parse(sessionCookieStr);
const { username, sessionToken } = sessionCookie;
const user = await db('users').where({ username }).first();
if (!user) {
res.status(400);
res.set('Set-Cookie', buildSessionCookie({ isLogout: true }));
return res.json({
message: 'Invalid session token.',
sessionCookie,
});
}
const salt = user.salt;
const sessionTokenHash = sha512(salt + sessionToken);
const token = await db('tokens').where({ type: 'session', value: sessionTokenHash });
if (!token) {
res.status(400);
res.set('Set-Cookie', buildSessionCookie({ isLogout: true }));
return res.json({
message: 'Invalid session token.',
sessionCookie,
});
}
req.sessionTokenHash = sessionTokenHash;
req.user = user;
next();
};
const registerRoute = async (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
res.status(400);
return res.json({
error: 'Username or password missing.',
});
}
const existingUser = await db('users').where({ username }).first();
if (existingUser) {
res.status(400);
return res.json({
error: 'Username already taken.',
});
}
let validationErrors = [];
const usernameMinLength = 5;
const usernameMaxLength = 20;
if (username.length < usernameMinLength) {
validationErrors.push(`Username must be at least ${usernameMinLength} characters long.`);
}
if (username.length > usernameMaxLength) {
validationErrors.push(`Username must be at most ${usernameMaxLength} characters long.`);
}
const owaspPwTestResults = owaspPw.test(password);
if (!owaspPwTestResults.strong) {
validationErrors = validationErrors.concat(owaspPwTestResults.errors);
}
if (validationErrors.length > 0) {
res.status(400);
return res.json({
errors: validationErrors,
});
}
const salt = shortid.generate();
const pwHash = sha512(salt + password);
const sessionToken = shortid.generate();
const sessionTokenHash = sha512(salt + sessionToken);
const user = (await db('users').insert({ username, password: pwHash, salt }).returning('*'))[0];
await db('tokens').insert({ user_id: user.id, type: 'session', value: sessionTokenHash });
res.set('Set-Cookie', buildSessionCookie({ username, sessionToken, remember: false, isLogout: false }));
return res.json({
username,
});
};
const loginRoute = async (req, res) => {
const { username, password, remember } = req.body;
if (!username || !password) {
res.status(400);
return res.json({
error: 'Username or password missing.',
});
}
const user = await db('users').where({ username }).first();
const salt = user.salt;
const pwHash = sha512(salt + password);
if (!user || pwHash !== user.password) {
res.status(400);
res.json({
error: 'Wrong username or password',
});
}
const sessionToken = shortid.generate();
const sessionTokenHash = sha512(user.salt + sessionToken);
await db('tokens').insert({ user_id: user.id, type: 'session', value: sessionTokenHash });
res.set('Set-Cookie', buildSessionCookie({ username, sessionToken, remember, isLogout: false }));
return res.json({
username,
});
};
const logoutRoute = async (req, res) => {
await db('tokens').where({ type: 'session', user_id: req.user.id, value: req.sessionTokenHash }).delete();
res.status(204);
res.set('Set-Cookie', buildSessionCookie({ isLogout: true }));
res.send();
};
module.exports = {
buildSessionCookie,
authMiddleware,
registerRoute,
loginRoute,
logoutRoute,
};
|