Skip to content

Commit

Permalink
add
Browse files Browse the repository at this point in the history
  • Loading branch information
Hanieh-Sadeghi committed Oct 27, 2023
1 parent 670969f commit e5f8212
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions server/authServer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,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)

0 comments on commit e5f8212

Please sign in to comment.