Skip to content

Commit

Permalink
Update authJwt.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
aelassas committed Feb 17, 2024
1 parent d096d06 commit 224f4e9
Showing 1 changed file with 21 additions and 12 deletions.
33 changes: 21 additions & 12 deletions api/src/middlewares/authJwt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ import jwt from 'jsonwebtoken'
import * as env from '../config/env.config'
import * as Helper from '../common/Helper'

/**
* Verify authentication token middleware.
*
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
*/
function verifyToken(req: Request, res: Response, next: NextFunction) {
let token: string

Expand All @@ -11,21 +18,23 @@ function verifyToken(req: Request, res: Response, next: NextFunction) {
} else if (Helper.isFrontend(req)) {
token = req.signedCookies[env.FRONTEND_AUTH_COOKIE_NAME] as string // frontend
} else {
token = req.headers['x-access-token'] as string // mobile app
token = req.headers[env.X_ACCESS_TOKEN] as string // mobile app and unit tests
}

if (!token) {
return res.status(403).send({ message: 'No token provided!' })
if (token) {
// Check token
jwt.verify(token, env.JWT_SECRET, (err) => {
if (err) {
console.log(err)
res.status(401).send({ message: 'Unauthorized!' })
} else {
next()
}
})
} else {
// Token not found!
res.status(403).send({ message: 'No token provided!' })
}

return jwt.verify(token, env.JWT_SECRET, (err) => {
if (err) {
console.log(err)
return res.status(401).send({ message: 'Unauthorized!' })
}

return next()
})
}

export default { verifyToken }

0 comments on commit 224f4e9

Please sign in to comment.