summaryrefslogtreecommitdiffstats
path: root/app/Middleware/AllowGuestOnly.ts
blob: 5ef5c34e45b84e87f4d367e32054a6a253248bbb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { GuardsList } from '@ioc:Adonis/Addons/Auth'
import { HttpContext } from '@adonisjs/core/http'
import { AuthenticationException } from '@adonisjs/auth/build/standalone'

/**
 * This is actually a reverted a reverted auth middleware available in ./Auth.ts
 * provided by the AdonisJS project iself.
 */
export default class GuestMiddleware {
  /**
   * The URL to redirect to when request is authorized
   */
  protected redirectTo = '/dashboard'

  protected async authenticate(auth: HttpContext['auth'], guards: (keyof GuardsList)[]) {
    let guardLastAttempted: string | undefined

    for (const guard of guards) {
      guardLastAttempted = guard

      // eslint-disable-next-line no-await-in-loop
      if (await auth.use(guard).check()) {
        auth.defaultGuard = guard

        throw new AuthenticationException(
          'Unauthorized access',
          'E_UNAUTHORIZED_ACCESS',
          guardLastAttempted,
          this.redirectTo
        )
      }
    }
  }

  /**
   * Handle request
   */
  public async handle(
    { auth }: HttpContext,
    next: () => Promise<void>,
    customGuards: (keyof GuardsList)[]
  ) {
    /**
     * Uses the user defined guards or the default guard mentioned in
     * the config file
     */
    const guards = customGuards.length > 0 ? customGuards : [auth.name]

    await this.authenticate(auth, guards)

    await next()
  }
}