| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- import { FastifyRequest, FastifyReply } from 'fastify'
- import { UserRole } from '../entities/user.entity'
- export async function authenticate(request: FastifyRequest, reply: FastifyReply) {
- try {
- await request.jwtVerify()
- } catch (err) {
- reply.code(401).send({
- message: 'Unauthorized',
- error: err
- })
- }
- }
- export function hasRole(role: UserRole): (request: FastifyRequest, reply: FastifyReply) => Promise<void> {
- return async (request: FastifyRequest, reply: FastifyReply) => {
- try {
- await request.jwtVerify()
- if (request.user.role !== role) {
- return reply.code(403).send({
- message: 'Access denied. Insufficient Permissions.'
- })
- }
- } catch (err) {
- reply.code(401).send({
- message: 'Unauthorized',
- error: err
- })
- }
- }
- }
- export function hasAnyRole(...roles: UserRole[]): (request: FastifyRequest, reply: FastifyReply) => Promise<void> {
- return async (request: FastifyRequest, reply: FastifyReply) => {
- try {
- await request.jwtVerify()
- if (!roles.includes(request.user.role)) {
- return reply.code(403).send({
- message: 'Access denied. Insufficient Permissions.'
- })
- }
- } catch (err) {
- reply.code(401).send({
- message: 'Unauthorized',
- error: err
- })
- }
- }
- }
|