forked from gitdagray/mern_stack_course
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthController.js
104 lines (84 loc) · 2.87 KB
/
authController.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
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
const User = require('../models/User')
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')
// @desc Login
// @route POST /auth
// @access Public
const login = async (req, res) => {
const { username, password } = req.body
if (!username || !password) {
return res.status(400).json({ message: 'All fields are required' })
}
const foundUser = await User.findOne({ username }).exec()
if (!foundUser || !foundUser.active) {
return res.status(401).json({ message: 'Unauthorized' })
}
const match = await bcrypt.compare(password, foundUser.password)
if (!match) return res.status(401).json({ message: 'Unauthorized' })
const accessToken = jwt.sign(
{
"UserInfo": {
"username": foundUser.username,
"roles": foundUser.roles
}
},
process.env.ACCESS_TOKEN_SECRET,
{ expiresIn: '15m' }
)
const refreshToken = jwt.sign(
{ "username": foundUser.username },
process.env.REFRESH_TOKEN_SECRET,
{ expiresIn: '7d' }
)
// Create secure cookie with refresh token
res.cookie('jwt', refreshToken, {
httpOnly: true, //accessible only by web server
secure: true, //https
sameSite: 'None', //cross-site cookie
maxAge: 7 * 24 * 60 * 60 * 1000 //cookie expiry: set to match rT
})
// Send accessToken containing username and roles
res.json({ accessToken })
}
// @desc Refresh
// @route GET /auth/refresh
// @access Public - because access token has expired
const refresh = (req, res) => {
const cookies = req.cookies
if (!cookies?.jwt) return res.status(401).json({ message: 'Unauthorized' })
const refreshToken = cookies.jwt
jwt.verify(
refreshToken,
process.env.REFRESH_TOKEN_SECRET,
async (err, decoded) => {
if (err) return res.status(403).json({ message: 'Forbidden' })
const foundUser = await User.findOne({ username: decoded.username }).exec()
if (!foundUser) return res.status(401).json({ message: 'Unauthorized' })
const accessToken = jwt.sign(
{
"UserInfo": {
"username": foundUser.username,
"roles": foundUser.roles
}
},
process.env.ACCESS_TOKEN_SECRET,
{ expiresIn: '15m' }
)
res.json({ accessToken })
}
)
}
// @desc Logout
// @route POST /auth/logout
// @access Public - just to clear cookie if exists
const logout = (req, res) => {
const cookies = req.cookies
if (!cookies?.jwt) return res.sendStatus(204) //No content
res.clearCookie('jwt', { httpOnly: true, sameSite: 'None', secure: true })
res.json({ message: 'Cookie cleared' })
}
module.exports = {
login,
refresh,
logout
}