summaryrefslogtreecommitdiffstats
path: root/app/Middleware/Auth.ts
diff options
context:
space:
mode:
authorLibravatar MCMXC <16797721+mcmxcdev@users.noreply.github.com>2024-02-10 18:37:40 -0700
committerLibravatar Vijay A <vraravam@users.noreply.github.com>2024-02-13 06:59:44 +0530
commite1c47572a6235fd8fd20af888ac3a11c7ae1369d (patch)
tree2dccff36a441916d7014037cef3f7ce84a790cad /app/Middleware/Auth.ts
parentrefactor: project maintenance (diff)
downloadferdium-server-e1c47572a6235fd8fd20af888ac3a11c7ae1369d.tar.gz
ferdium-server-e1c47572a6235fd8fd20af888ac3a11c7ae1369d.tar.zst
ferdium-server-e1c47572a6235fd8fd20af888ac3a11c7ae1369d.zip
updates
Diffstat (limited to 'app/Middleware/Auth.ts')
-rw-r--r--app/Middleware/Auth.ts57
1 files changed, 30 insertions, 27 deletions
diff --git a/app/Middleware/Auth.ts b/app/Middleware/Auth.ts
index 29620bb..b6ff446 100644
--- a/app/Middleware/Auth.ts
+++ b/app/Middleware/Auth.ts
@@ -1,9 +1,9 @@
1import { GuardsList } from '@ioc:Adonis/Addons/Auth' 1import { GuardsList } from '@ioc:Adonis/Addons/Auth';
2import { HttpContext } from '@adonisjs/core/http' 2import { HttpContext } from '@adonisjs/core/http';
3import { AuthenticationException } from '@adonisjs/auth/build/standalone' 3import { AuthenticationException } from '@adonisjs/auth/build/standalone';
4import * as jose from 'jose' 4import * as jose from 'jose';
5import { appKey } from '#config/app' 5import { appKey } from '#config/app';
6import User from '#app/Models/User' 6import User from '#app/Models/User';
7 7
8/** 8/**
9 * Auth middleware is meant to restrict un-authenticated access to a given route 9 * Auth middleware is meant to restrict un-authenticated access to a given route
@@ -16,7 +16,7 @@ export default class AuthMiddleware {
16 /** 16 /**
17 * The URL to redirect to when request is Unauthorized 17 * The URL to redirect to when request is Unauthorized
18 */ 18 */
19 protected redirectTo = '/user/login' 19 protected redirectTo = '/user/login';
20 20
21 /** 21 /**
22 * Authenticates the current HTTP request against a custom set of defined 22 * Authenticates the current HTTP request against a custom set of defined
@@ -29,7 +29,7 @@ export default class AuthMiddleware {
29 protected async authenticate( 29 protected async authenticate(
30 auth: HttpContext['auth'], 30 auth: HttpContext['auth'],
31 guards: (keyof GuardsList)[], 31 guards: (keyof GuardsList)[],
32 request: HttpContext['request'] 32 request: HttpContext['request'],
33 ) { 33 ) {
34 /** 34 /**
35 * Hold reference to the guard last attempted within the for loop. We pass 35 * Hold reference to the guard last attempted within the for loop. We pass
@@ -37,15 +37,15 @@ export default class AuthMiddleware {
37 * it can decide the correct response behavior based upon the guard 37 * it can decide the correct response behavior based upon the guard
38 * driver 38 * driver
39 */ 39 */
40 let guardLastAttempted: string | undefined 40 let guardLastAttempted: string | undefined;
41 41
42 for (const guard of guards) { 42 for (const guard of guards) {
43 guardLastAttempted = guard 43 guardLastAttempted = guard;
44 44
45 let isLoggedIn = false 45 let isLoggedIn = false;
46 try { 46 try {
47 // eslint-disable-next-line no-await-in-loop 47 // eslint-disable-next-line no-await-in-loop
48 isLoggedIn = await auth.use(guard).check() 48 isLoggedIn = await auth.use(guard).check();
49 } catch { 49 } catch {
50 // Silent fail to allow the rest of the code to handle the error 50 // Silent fail to allow the rest of the code to handle the error
51 } 51 }
@@ -56,22 +56,25 @@ export default class AuthMiddleware {
56 * the rest of the request, since the user authenticated 56 * the rest of the request, since the user authenticated
57 * succeeded here 57 * succeeded here
58 */ 58 */
59 auth.defaultGuard = guard 59 auth.defaultGuard = guard;
60 return 60 return;
61 } 61 }
62 } 62 }
63 63
64 // Manually try authenticating using the JWT (verfiy signature required) 64 // Manually try authenticating using the JWT (verfiy signature required)
65 // Legacy support for JWTs so that the client still works (older than 2.0.0) 65 // Legacy support for JWTs so that the client still works (older than 2.0.0)
66 const authToken = request.headers().authorization?.split(' ')[1] 66 const authToken = request.headers().authorization?.split(' ')[1];
67 if (authToken) { 67 if (authToken) {
68 try { 68 try {
69 const jwt = await jose.jwtVerify(authToken, new TextEncoder().encode(appKey)) 69 const jwt = await jose.jwtVerify(
70 const { uid } = jwt.payload 70 authToken,
71 new TextEncoder().encode(appKey),
72 );
73 const { uid } = jwt.payload;
71 74
72 // @ts-expect-error 75 // @ts-expect-error
73 request.user = await User.findOrFail(uid) 76 request.user = await User.findOrFail(uid);
74 return 77 return;
75 } catch { 78 } catch {
76 // Silent fail to allow the rest of the code to handle the error 79 // Silent fail to allow the rest of the code to handle the error
77 } 80 }
@@ -84,8 +87,8 @@ export default class AuthMiddleware {
84 'Unauthorized access', 87 'Unauthorized access',
85 'E_UNAUTHORIZED_ACCESS', 88 'E_UNAUTHORIZED_ACCESS',
86 guardLastAttempted, 89 guardLastAttempted,
87 this.redirectTo 90 this.redirectTo,
88 ) 91 );
89 } 92 }
90 93
91 /** 94 /**
@@ -94,22 +97,22 @@ export default class AuthMiddleware {
94 public async handle( 97 public async handle(
95 { request, auth, response }: HttpContext, 98 { request, auth, response }: HttpContext,
96 next: () => Promise<void>, 99 next: () => Promise<void>,
97 customGuards: (keyof GuardsList)[] 100 customGuards: (keyof GuardsList)[],
98 ) { 101 ) {
99 /** 102 /**
100 * Uses the user defined guards or the default guard mentioned in 103 * Uses the user defined guards or the default guard mentioned in
101 * the config file 104 * the config file
102 */ 105 */
103 const guards = customGuards.length > 0 ? customGuards : [auth.name] 106 const guards = customGuards.length > 0 ? customGuards : [auth.name];
104 try { 107 try {
105 await this.authenticate(auth, guards, request) 108 await this.authenticate(auth, guards, request);
106 } catch (error) { 109 } catch (error) {
107 // If the user is not authenticated and it is a web endpoint, redirect to the login page 110 // If the user is not authenticated and it is a web endpoint, redirect to the login page
108 if (guards.includes('web')) { 111 if (guards.includes('web')) {
109 return response.redirect(error.redirectTo) 112 return response.redirect(error.redirectTo);
110 } 113 }
111 throw error 114 throw error;
112 } 115 }
113 await next() 116 await next();
114 } 117 }
115} 118}