Auth.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { AuthenticationException } from '@adonisjs/auth/build/standalone'
  2. import type { GuardsList } from '@ioc:Adonis/Addons/Auth'
  3. import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
  4. /**
  5. * Auth middleware is meant to restrict un-authenticated access to a given route
  6. * or a group of routes.
  7. *
  8. * You must register this middleware inside `start/kernel.ts` file under the list
  9. * of named middleware.
  10. */
  11. export default class AuthMiddleware {
  12. /**
  13. * The URL to redirect to when request is Unauthorized
  14. */
  15. protected redirectTo = '/login'
  16. /**
  17. * Authenticates the current HTTP request against a custom set of defined
  18. * guards.
  19. *
  20. * The authentication loop stops as soon as the user is authenticated using any
  21. * of the mentioned guards and that guard will be used by the rest of the code
  22. * during the current request.
  23. */
  24. protected async authenticate(auth: HttpContextContract['auth'], guards: (keyof GuardsList)[]) {
  25. /**
  26. * Hold reference to the guard last attempted within the for loop. We pass
  27. * the reference of the guard to the "AuthenticationException", so that
  28. * it can decide the correct response behavior based upon the guard
  29. * driver
  30. */
  31. let guardLastAttempted: string | undefined
  32. for (let guard of guards) {
  33. guardLastAttempted = guard
  34. if (await auth.use(guard).check()) {
  35. /**
  36. * Instruct auth to use the given guard as the default guard for
  37. * the rest of the request, since the user authenticated
  38. * succeeded here
  39. */
  40. auth.defaultGuard = guard
  41. return true
  42. }
  43. }
  44. /**
  45. * Unable to authenticate using any guard
  46. */
  47. throw new AuthenticationException(
  48. 'Unauthorized access',
  49. 'E_UNAUTHORIZED_ACCESS',
  50. guardLastAttempted,
  51. this.redirectTo
  52. )
  53. }
  54. /**
  55. * Handle request
  56. */
  57. public async handle(
  58. { auth }: HttpContextContract,
  59. next: () => Promise<void>,
  60. customGuards: (keyof GuardsList)[]
  61. ) {
  62. /**
  63. * Uses the user defined guards or the default guard mentioned in
  64. * the config file
  65. */
  66. const guards = customGuards.length ? customGuards : [auth.name]
  67. await this.authenticate(auth, guards)
  68. await next()
  69. }
  70. }