aboutsummaryrefslogtreecommitdiffstats
path: root/app/Middleware/AllowGuestOnly.ts
blob: ee43571c96a56eacc2ff8471a2d57df0c64dc486 (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
54
55
56
import { GuardsList } from '@ioc:Adonis/Addons/Auth';
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
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: HttpContextContract['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 }: HttpContextContract,
    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();
  }
}