1
0
mirror of https://github.com/sasjs/server.git synced 2026-01-11 00:10:06 +00:00

feat: user operation apis added

This commit is contained in:
Saad Jutt
2021-11-04 05:51:29 +05:00
parent 9f17b17e31
commit 728f277f5c
11 changed files with 190 additions and 26 deletions

View File

@@ -0,0 +1,54 @@
import jwt from 'jsonwebtoken'
import { verifyTokenInDB } from '../utils'
export const authenticateAccessToken = (req: any, res: any, next: any) => {
authenticateToken(
req,
res,
next,
process.env.ACCESS_TOKEN_SECRET as string,
'accessToken'
)
}
export const authenticateRefreshToken = (req: any, res: any, next: any) => {
authenticateToken(
req,
res,
next,
process.env.REFRESH_TOKEN_SECRET as string,
'refreshToken'
)
}
const authenticateToken = (
req: any,
res: any,
next: any,
key: string,
tokenType: 'accessToken' | 'refreshToken' = 'accessToken'
) => {
const authHeader = req.headers['authorization']
const token = authHeader?.split(' ')[1]
if (!token) return res.sendStatus(401)
jwt.verify(token, key, async (err: any, data: any) => {
if (err) return res.sendStatus(401)
// verify this valid token's entry in DB
const user = await verifyTokenInDB(
data?.username,
data?.clientId,
token,
tokenType
)
if (user) {
if (user.isActive) {
req.user = user
return next()
} else return res.sendStatus(401)
}
return res.sendStatus(401)
})
}