-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
137 lines (113 loc) · 3.04 KB
/
auth.ts
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
import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';
import express from 'express';
import fieldParsers from '../utils/field-parsers';
import logger from '../utils/logger';
import { User } from '../mongo';
import config from '../utils/config';
const router = express.Router();
const { JWT_SECRET } = config;
router.post('/login', async (req, res) => {
if (!JWT_SECRET) {
return res.status(500).send({ error: 'JWT_SECRET is not set.' });
}
const { body } = req;
let loginFields: {
username: string,
password: string,
};
try {
loginFields = fieldParsers.proofLogInFields(body);
} catch (error) {
return res.status(400).send({ error: logger.getErrorMessage(error) });
}
try {
const user = await User.findOne({ username: loginFields.username });
const isUserValidated = !user
? false
: await bcrypt.compare(loginFields.password, user.passwordHash);
if (!isUserValidated) {
return res.status(401).send({
error: 'Invalid username or password.',
});
}
const userTokenInfo = {
username: user.username,
id: user.id,
};
const accessToken = jwt.sign(
userTokenInfo,
JWT_SECRET,
{ expiresIn: '15m' },
);
const refreshToken = jwt.sign(
userTokenInfo,
JWT_SECRET,
{ expiresIn: '30d' },
);
res.cookie('refreshToken', refreshToken, {
expires: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30 days
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
});
return res.status(200).send({ accessToken, username: user.username });
} catch (error) {
return res.status(500).send({ error: 'Something went wrong!' });
}
});
router.post('/refresh', async (req, res, next) => {
if (!JWT_SECRET) {
return res.status(500).send({ error: 'JWT_SECRET is not set.' });
}
let decodedRefreshToken;
const { refreshToken } = req.cookies;
if (refreshToken) {
try {
decodedRefreshToken = jwt.verify(
refreshToken,
JWT_SECRET,
) as jwt.JwtPayload;
} catch (error) {
res.clearCookie('refreshToken');
return next(error);
}
}
if (
!decodedRefreshToken
|| !decodedRefreshToken.id
|| !decodedRefreshToken.username
) {
res.clearCookie('refreshToken');
return res.status(401).send({
error: 'refresh token missing or invalid.',
});
}
const user = await User.findById(decodedRefreshToken.id);
if (!user) {
res.clearCookie('refreshToken');
return res.status(401).send({
error: 'refresh token is not valid for any user.',
});
}
// generate new access token
const userTokenInfo = {
username: user.username,
id: decodedRefreshToken.id,
};
const newAccessToken = jwt.sign(
userTokenInfo,
JWT_SECRET,
{ expiresIn: '15m' },
);
return res.status(200).send(
{
accessToken: newAccessToken,
username: user.username,
},
);
});
router.post('/logout', (_req, res) => {
res.clearCookie('refreshToken');
res.status(204).end();
});
export default router;