auth.middleware.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { FastifyRequest, FastifyReply } from 'fastify'
  2. import { UserRole } from '../entities/user.entity'
  3. export async function authenticate(request: FastifyRequest, reply: FastifyReply) {
  4. try {
  5. await request.jwtVerify()
  6. } catch (err) {
  7. reply.code(401).send({
  8. message: 'Unauthorized',
  9. error: err
  10. })
  11. }
  12. }
  13. export function hasRole(role: UserRole): (request: FastifyRequest, reply: FastifyReply) => Promise<void> {
  14. return async (request: FastifyRequest, reply: FastifyReply) => {
  15. try {
  16. await request.jwtVerify()
  17. if (request.user.role !== role) {
  18. return reply.code(403).send({
  19. message: 'Access denied. Insufficient Permissions.'
  20. })
  21. }
  22. } catch (err) {
  23. reply.code(401).send({
  24. message: 'Unauthorized',
  25. error: err
  26. })
  27. }
  28. }
  29. }
  30. export function hasAnyRole(...roles: UserRole[]): (request: FastifyRequest, reply: FastifyReply) => Promise<void> {
  31. return async (request: FastifyRequest, reply: FastifyReply) => {
  32. try {
  33. await request.jwtVerify()
  34. if (!roles.includes(request.user.role)) {
  35. return reply.code(403).send({
  36. message: 'Access denied. Insufficient Permissions.'
  37. })
  38. }
  39. } catch (err) {
  40. reply.code(401).send({
  41. message: 'Unauthorized',
  42. error: err
  43. })
  44. }
  45. }
  46. }