games-express-api/middleware/auth.js

49 lines
1.2 KiB
JavaScript
Raw Normal View History

2024-09-12 15:48:27 -04:00
import jwt from 'jsonwebtoken'
import asyncHandler from './async.js'
import ErrorResponse from '../utils/errorResponse.js'
import User from '../models/User.js'
// Protect route
export const protect = asyncHandler(async (req, res, next) => {
let token
// Set token from header
if (
req.headers.authorization &&
req.headers.authorization.startsWith('Bearer')
)
token = req.headers.authorization.split(' ')[1]
// Set token from cookie
// else if (req.cookies.token) token = req.cookies.token
// Make sure token exists
if (!token)
return next(new ErrorResponse('Not authorized to access this route', 401))
try {
// Verify token
const decoded = jwt.verify(token, Bun.env.ACCESS_TOKEN_SECRET)
req.user = await User.findById(decoded.id)
next()
} catch (err) {
return next(new ErrorResponse('Not authorized to access this route', 401))
}
})
// Grants access to specific roles
export const authorize = (...roles) => {
return (req, res, next) => {
if (!roles.includes(req.user.role)) {
return next(
new ErrorResponse(
`User role ${req.user.role} is not authorized to access this route.`,
403
)
)
}
next()
}
}