forked from WebDevSimplified/JWT-Authentication
-
Notifications
You must be signed in to change notification settings - Fork 0
/
authServer.js
43 lines (33 loc) · 1.21 KB
/
authServer.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
require('dotenv').config()
const express = require('express')
const app = express()
const jwt = require('jsonwebtoken')
app.use(express.json())
let refreshTokens = []
app.post('/token', (req, res) => {
const refreshToken = req.body.token
if (refreshToken == null) return res.sendStatus(401)
if (!refreshTokens.includes(refreshToken)) 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: accessToken })
})
})
app.delete('/logout', (req, res) => {
refreshTokens = refreshTokens.filter(token => token !== req.body.token)
res.sendStatus(204)
})
app.post('/login', (req, res) => {
// Authenticate User
const username = req.body.username
const user = { name: username }
const accessToken = generateAccessToken(user)
const refreshToken = jwt.sign(user, process.env.REFRESH_TOKEN_SECRET)
refreshTokens.push(refreshToken)
res.json({ accessToken: accessToken, refreshToken: refreshToken })
})
function generateAccessToken(user) {
return jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '15s' })
}
app.listen(4000)