|
1
|
|
|
import { AuthenticationException } from '@adonisjs/auth/build/standalone' |
|
2
|
|
|
import type { GuardsList } from '@ioc:Adonis/Addons/Auth' |
|
3
|
|
|
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext' |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* Auth middleware is meant to restrict un-authenticated access to a given route |
|
7
|
|
|
* or a group of routes. |
|
8
|
|
|
* |
|
9
|
|
|
* You must register this middleware inside `start/kernel.ts` file under the list |
|
10
|
|
|
* of named middleware. |
|
11
|
|
|
*/ |
|
12
|
|
|
export default class AuthMiddleware { |
|
13
|
|
|
/** |
|
14
|
|
|
* The URL to redirect to when request is Unauthorized |
|
15
|
|
|
*/ |
|
16
|
|
|
protected redirectTo = '/login' |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* Authenticates the current HTTP request against a custom set of defined |
|
20
|
|
|
* guards. |
|
21
|
|
|
* |
|
22
|
|
|
* The authentication loop stops as soon as the user is authenticated using any |
|
23
|
|
|
* of the mentioned guards and that guard will be used by the rest of the code |
|
24
|
|
|
* during the current request. |
|
25
|
|
|
*/ |
|
26
|
|
|
protected async authenticate(auth: HttpContextContract['auth'], guards: (keyof GuardsList)[]) { |
|
27
|
|
|
/** |
|
28
|
|
|
* Hold reference to the guard last attempted within the for loop. We pass |
|
29
|
|
|
* the reference of the guard to the "AuthenticationException", so that |
|
30
|
|
|
* it can decide the correct response behavior based upon the guard |
|
31
|
|
|
* driver |
|
32
|
|
|
*/ |
|
33
|
|
|
let guardLastAttempted: string | undefined |
|
34
|
|
|
|
|
35
|
|
|
for (let guard of guards) { |
|
36
|
|
|
guardLastAttempted = guard |
|
37
|
|
|
|
|
38
|
|
|
if (await auth.use(guard).check()) { |
|
39
|
|
|
/** |
|
40
|
|
|
* Instruct auth to use the given guard as the default guard for |
|
41
|
|
|
* the rest of the request, since the user authenticated |
|
42
|
|
|
* succeeded here |
|
43
|
|
|
*/ |
|
44
|
|
|
auth.defaultGuard = guard |
|
45
|
|
|
return true |
|
46
|
|
|
} |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* Unable to authenticate using any guard |
|
51
|
|
|
*/ |
|
52
|
|
|
throw new AuthenticationException( |
|
53
|
|
|
'Unauthorized access', |
|
54
|
|
|
'E_UNAUTHORIZED_ACCESS', |
|
55
|
|
|
guardLastAttempted, |
|
56
|
|
|
this.redirectTo, |
|
57
|
|
|
) |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** |
|
61
|
|
|
* Handle request |
|
62
|
|
|
*/ |
|
63
|
|
|
public async handle ( |
|
64
|
|
|
{ auth }: HttpContextContract, |
|
65
|
|
|
next: () => Promise<void>, |
|
66
|
|
|
customGuards: (keyof GuardsList)[] |
|
67
|
|
|
) { |
|
68
|
|
|
/** |
|
69
|
|
|
* Uses the user defined guards or the default guard mentioned in |
|
70
|
|
|
* the config file |
|
71
|
|
|
*/ |
|
72
|
|
|
const guards = customGuards.length ? customGuards : [auth.name] |
|
73
|
|
|
await this.authenticate(auth, guards) |
|
74
|
|
|
await next() |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|