aboutsummaryrefslogtreecommitdiffstats
path: root/app/Middleware
diff options
context:
space:
mode:
Diffstat (limited to 'app/Middleware')
-rw-r--r--app/Middleware/AllowGuestOnly.ts56
-rw-r--r--app/Middleware/Auth.ts118
-rw-r--r--app/Middleware/ConvertEmptyStringsToNull.js15
-rw-r--r--app/Middleware/Dashboard.ts17
-rw-r--r--app/Middleware/HandleDoubleSlash.js24
-rw-r--r--app/Middleware/SilentAuth.ts24
6 files changed, 215 insertions, 39 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}
diff --git a/app/Middleware/Auth.ts b/app/Middleware/Auth.ts
new file mode 100644
index 0000000..d0b212c
--- /dev/null
+++ b/app/Middleware/Auth.ts
@@ -0,0 +1,118 @@
1import { GuardsList } from '@ioc:Adonis/Addons/Auth';
2import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
3import { AuthenticationException } from '@adonisjs/auth/build/standalone';
4import * as jose from 'jose';
5import { appKey } from 'Config/app';
6import User from 'App/Models/User';
7
8/**
9 * Auth middleware is meant to restrict un-authenticated access to a given route
10 * or a group of routes.
11 *
12 * You must register this middleware inside `start/kernel.ts` file under the list
13 * of named middleware.
14 */
15export default class AuthMiddleware {
16 /**
17 * The URL to redirect to when request is Unauthorized
18 */
19 protected redirectTo = '/user/login';
20
21 /**
22 * Authenticates the current HTTP request against a custom set of defined
23 * guards.
24 *
25 * The authentication loop stops as soon as the user is authenticated using any
26 * of the mentioned guards and that guard will be used by the rest of the code
27 * during the current request.
28 */
29 protected async authenticate(
30 auth: HttpContextContract['auth'],
31 guards: (keyof GuardsList)[],
32 request: HttpContextContract['request'],
33 ) {
34 /**
35 * Hold reference to the guard last attempted within the for loop. We pass
36 * the reference of the guard to the "AuthenticationException", so that
37 * it can decide the correct response behavior based upon the guard
38 * driver
39 */
40 let guardLastAttempted: string | undefined;
41
42 for (const guard of guards) {
43 guardLastAttempted = guard;
44
45 let isLoggedIn = false;
46 try {
47 // eslint-disable-next-line no-await-in-loop
48 isLoggedIn = await auth.use(guard).check();
49 } catch {
50 // Silent fail to allow the rest of the code to handle the error
51 }
52
53 if (isLoggedIn) {
54 /**
55 * Instruct auth to use the given guard as the default guard for
56 * the rest of the request, since the user authenticated
57 * succeeded here
58 */
59 auth.defaultGuard = guard;
60 return;
61 }
62 }
63
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)
66 const authToken = request.headers().authorization?.split(' ')[1];
67 if (authToken) {
68 try {
69 const jwt = await jose.jwtVerify(
70 authToken,
71 new TextEncoder().encode(appKey),
72 );
73 const { uid } = jwt.payload;
74
75 // @ts-expect-error
76 request.user = await User.findOrFail(uid);
77 return;
78 } catch {
79 // Silent fail to allow the rest of the code to handle the error
80 }
81 }
82
83 /**
84 * Unable to authenticate using any guard
85 */
86 throw new AuthenticationException(
87 'Unauthorized access',
88 'E_UNAUTHORIZED_ACCESS',
89 guardLastAttempted,
90 this.redirectTo,
91 );
92 }
93
94 /**
95 * Handle request
96 */
97 public async handle(
98 { request, auth, response }: HttpContextContract,
99 next: () => Promise<void>,
100 customGuards: (keyof GuardsList)[],
101 ) {
102 /**
103 * Uses the user defined guards or the default guard mentioned in
104 * the config file
105 */
106 const guards = customGuards.length > 0 ? customGuards : [auth.name];
107 try {
108 await this.authenticate(auth, guards, request);
109 } catch (error) {
110 // If the user is not authenticated and it is a web endpoint, redirect to the login page
111 if (guards.includes('web')) {
112 return response.redirect(error.redirectTo);
113 }
114 throw error;
115 }
116 await next();
117 }
118}
diff --git a/app/Middleware/ConvertEmptyStringsToNull.js b/app/Middleware/ConvertEmptyStringsToNull.js
deleted file mode 100644
index af6379a..0000000
--- a/app/Middleware/ConvertEmptyStringsToNull.js
+++ /dev/null
@@ -1,15 +0,0 @@
1class ConvertEmptyStringsToNull {
2 async handle({ request }, next) {
3 if (Object.keys(request.body).length) {
4 request.body = Object.assign(
5 ...Object.keys(request.body).map((key) => ({
6 [key]: request.body[key] !== '' ? request.body[key] : null,
7 })),
8 );
9 }
10
11 await next();
12 }
13}
14
15module.exports = ConvertEmptyStringsToNull;
diff --git a/app/Middleware/Dashboard.ts b/app/Middleware/Dashboard.ts
new file mode 100644
index 0000000..62deea0
--- /dev/null
+++ b/app/Middleware/Dashboard.ts
@@ -0,0 +1,17 @@
1import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
2import Config from '@ioc:Adonis/Core/Config';
3
4export default class Dashboard {
5 public async handle(
6 { response }: HttpContextContract,
7 next: () => Promise<void>,
8 ) {
9 if (Config.get('dashboard.enabled') === false) {
10 response.send(
11 'The user dashboard is disabled on this server\n\nIf you are the server owner, please set IS_DASHBOARD_ENABLED to true to enable the dashboard.',
12 );
13 } else {
14 await next();
15 }
16 }
17}
diff --git a/app/Middleware/HandleDoubleSlash.js b/app/Middleware/HandleDoubleSlash.js
deleted file mode 100644
index c4bc053..0000000
--- a/app/Middleware/HandleDoubleSlash.js
+++ /dev/null
@@ -1,24 +0,0 @@
1/** @typedef {import('@adonisjs/framework/src/Request')} Request */
2/** @typedef {import('@adonisjs/framework/src/Response')} Response */
3/** @typedef {import('@adonisjs/framework/src/View')} View */
4
5class HandleDoubleSlash {
6 /**
7 * @param {object} ctx
8 * @param {Request} ctx.request
9 * @param {Function} next
10 */
11 // eslint-disable-next-line consistent-return
12 async handle({ request, response }, next) {
13 // Redirect requests that contain duplicate slashes to the right path
14 if (request.url().includes('//')) {
15 return response.redirect(
16 request.url().replace(/\/{2,}/g, '/'),
17 );
18 }
19
20 await next();
21 }
22}
23
24module.exports = HandleDoubleSlash;
diff --git a/app/Middleware/SilentAuth.ts b/app/Middleware/SilentAuth.ts
new file mode 100644
index 0000000..ee73ec4
--- /dev/null
+++ b/app/Middleware/SilentAuth.ts
@@ -0,0 +1,24 @@
1import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
2
3/**
4 * Silent auth middleware can be used as a global middleware to silent check
5 * if the user is logged-in or not.
6 *
7 * The request continues as usual, even when the user is not logged-in.
8 */
9export default class SilentAuthMiddleware {
10 /**
11 * Handle request
12 */
13 public async handle(
14 { auth }: HttpContextContract,
15 next: () => Promise<void>,
16 ) {
17 /**
18 * Check if user is logged-in or not. If yes, then `ctx.auth.user` will be
19 * set to the instance of the currently logged in user.
20 */
21 await auth.check();
22 await next();
23 }
24}