summaryrefslogtreecommitdiffstats
path: root/app/Middleware/Auth.ts
diff options
context:
space:
mode:
authorLibravatar MCMXC <16797721+mcmxcdev@users.noreply.github.com>2024-02-10 18:19:14 -0700
committerLibravatar Vijay A <vraravam@users.noreply.github.com>2024-02-13 06:59:44 +0530
commit7584d2d7a7110aef0331ebfa178b2295842c59fa (patch)
tree900cd71237e6231b57936fcce77ff229cd459041 /app/Middleware/Auth.ts
parentupgrade recipes submodule (diff)
downloadferdium-server-7584d2d7a7110aef0331ebfa178b2295842c59fa.tar.gz
ferdium-server-7584d2d7a7110aef0331ebfa178b2295842c59fa.tar.zst
ferdium-server-7584d2d7a7110aef0331ebfa178b2295842c59fa.zip
refactor: project maintenance
- work in progress
Diffstat (limited to 'app/Middleware/Auth.ts')
-rw-r--r--app/Middleware/Auth.ts61
1 files changed, 29 insertions, 32 deletions
diff --git a/app/Middleware/Auth.ts b/app/Middleware/Auth.ts
index d0b212c..29620bb 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 { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; 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
@@ -27,9 +27,9 @@ export default class AuthMiddleware {
27 * during the current request. 27 * during the current request.
28 */ 28 */
29 protected async authenticate( 29 protected async authenticate(
30 auth: HttpContextContract['auth'], 30 auth: HttpContext['auth'],
31 guards: (keyof GuardsList)[], 31 guards: (keyof GuardsList)[],
32 request: HttpContextContract['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,25 +56,22 @@ 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( 69 const jwt = await jose.jwtVerify(authToken, new TextEncoder().encode(appKey))
70 authToken, 70 const { uid } = jwt.payload
71 new TextEncoder().encode(appKey),
72 );
73 const { uid } = jwt.payload;
74 71
75 // @ts-expect-error 72 // @ts-expect-error
76 request.user = await User.findOrFail(uid); 73 request.user = await User.findOrFail(uid)
77 return; 74 return
78 } catch { 75 } catch {
79 // Silent fail to allow the rest of the code to handle the error 76 // Silent fail to allow the rest of the code to handle the error
80 } 77 }
@@ -87,32 +84,32 @@ export default class AuthMiddleware {
87 'Unauthorized access', 84 'Unauthorized access',
88 'E_UNAUTHORIZED_ACCESS', 85 'E_UNAUTHORIZED_ACCESS',
89 guardLastAttempted, 86 guardLastAttempted,
90 this.redirectTo, 87 this.redirectTo
91 ); 88 )
92 } 89 }
93 90
94 /** 91 /**
95 * Handle request 92 * Handle request
96 */ 93 */
97 public async handle( 94 public async handle(
98 { request, auth, response }: HttpContextContract, 95 { request, auth, response }: HttpContext,
99 next: () => Promise<void>, 96 next: () => Promise<void>,
100 customGuards: (keyof GuardsList)[], 97 customGuards: (keyof GuardsList)[]
101 ) { 98 ) {
102 /** 99 /**
103 * Uses the user defined guards or the default guard mentioned in 100 * Uses the user defined guards or the default guard mentioned in
104 * the config file 101 * the config file
105 */ 102 */
106 const guards = customGuards.length > 0 ? customGuards : [auth.name]; 103 const guards = customGuards.length > 0 ? customGuards : [auth.name]
107 try { 104 try {
108 await this.authenticate(auth, guards, request); 105 await this.authenticate(auth, guards, request)
109 } catch (error) { 106 } catch (error) {
110 // If the user is not authenticated and it is a web endpoint, redirect to the login page 107 // If the user is not authenticated and it is a web endpoint, redirect to the login page
111 if (guards.includes('web')) { 108 if (guards.includes('web')) {
112 return response.redirect(error.redirectTo); 109 return response.redirect(error.redirectTo)
113 } 110 }
114 throw error; 111 throw error
115 } 112 }
116 await next(); 113 await next()
117 } 114 }
118} 115}