aboutsummaryrefslogtreecommitdiffstats
path: root/app/Middleware/AllowGuestOnly.ts
diff options
context:
space:
mode:
Diffstat (limited to 'app/Middleware/AllowGuestOnly.ts')
-rw-r--r--app/Middleware/AllowGuestOnly.ts56
1 files changed, 56 insertions, 0 deletions
diff --git a/app/Middleware/AllowGuestOnly.ts b/app/Middleware/AllowGuestOnly.ts
new file mode 100644
index 0000000..ee43571
--- /dev/null
+++ b/app/Middleware/AllowGuestOnly.ts
@@ -0,0 +1,56 @@
1import { GuardsList } from '@ioc:Adonis/Addons/Auth';
2import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
3import { AuthenticationException } from '@adonisjs/auth/build/standalone';
4
5/**
6 * This is actually a reverted a reverted auth middleware available in ./Auth.ts
7 * provided by the AdonisJS project iself.
8 */
9export default class GuestMiddleware {
10 /**
11 * The URL to redirect to when request is authorized
12 */
13 protected redirectTo = '/dashboard';
14
15 protected async authenticate(
16 auth: HttpContextContract['auth'],
17 guards: (keyof GuardsList)[],
18 ) {
19 let guardLastAttempted: string | undefined;
20
21 for (const guard of guards) {
22 guardLastAttempted = guard;
23
24 // eslint-disable-next-line no-await-in-loop
25 if (await auth.use(guard).check()) {
26 auth.defaultGuard = guard;
27
28 throw new AuthenticationException(
29 'Unauthorized access',
30 'E_UNAUTHORIZED_ACCESS',
31 guardLastAttempted,
32 this.redirectTo,
33 );
34 }
35 }
36 }
37
38 /**
39 * Handle request
40 */
41 public async handle(
42 { auth }: HttpContextContract,
43 next: () => Promise<void>,
44 customGuards: (keyof GuardsList)[],
45 ) {
46 /**
47 * Uses the user defined guards or the default guard mentioned in
48 * the config file
49 */
50 const guards = customGuards.length > 0 ? customGuards : [auth.name];
51
52 await this.authenticate(auth, guards);
53
54 await next();
55 }
56}