- update to AdonisJS 6
Some checks failed
CI Pipeline / japa-tests (push) Failing after 1m15s

This commit is contained in:
Kaimbacher 2024-03-14 20:25:27 +01:00
parent f828ca4491
commit cb51a4136f
167 changed files with 21485 additions and 21212 deletions

View file

@ -1,67 +0,0 @@
import { AuthenticationException } from '@adonisjs/auth/build/standalone';
import type { GuardsList } from '@ioc:Adonis/Addons/Auth';
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
/**
* Auth middleware is meant to restrict un-authenticated access to a given route
* or a group of routes.
*
* You must register this middleware inside `start/kernel.ts` file under the list
* of named middleware.
*/
export default class AuthMiddleware {
/**
* The URL to redirect to when request is Unauthorized
*/
protected redirectTo = '/app/login';
/**
* Authenticates the current HTTP request against a custom set of defined
* guards.
*
* The authentication loop stops as soon as the user is authenticated using any
* of the mentioned guards and that guard will be used by the rest of the code
* during the current request.
*/
protected async authenticate(auth: HttpContextContract['auth'], guards: (keyof GuardsList)[]) {
/**
* Hold reference to the guard last attempted within the for loop. We pass
* the reference of the guard to the "AuthenticationException", so that
* it can decide the correct response behavior based upon the guard
* driver
*/
let guardLastAttempted: string | undefined;
for (let guard of guards) {
guardLastAttempted = guard;
if (await auth.use(guard).check()) {
/**
* Instruct auth to use the given guard as the default guard for
* the rest of the request, since the user authenticated
* succeeded here
*/
auth.defaultGuard = guard;
return true;
}
}
/**
* Unable to authenticate using any guard
*/
throw new AuthenticationException('Unauthorized access', 'E_UNAUTHORIZED_ACCESS', guardLastAttempted, this.redirectTo);
}
/**
* Handle request
*/
public async handle({ auth }: HttpContextContract, next: () => Promise<void>, customGuards: (keyof GuardsList)[]) {
/**
* Uses the user defined guards or the default guard mentioned in
* the config file
*/
const guards = customGuards.length ? customGuards : [auth.name];
await this.authenticate(auth, guards);
await next();
}
}

View file

@ -1,13 +1,14 @@
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
import Config from '@ioc:Adonis/Core/Config';
import Database from '@ioc:Adonis/Lucid/Database';
import User from 'App/Models/User';
import { Exception } from '@adonisjs/core/build/standalone';
import { HttpContext } from '@adonisjs/core/http';
// import Config from '@ioc:Adonis/Core/Config';
import config from '@adonisjs/core/services/config';
import db from '@adonisjs/lucid/services/db';
import User from '#app/Models/User';
import { Exception } from '@adonisjs/core/exceptions';
const permissionTable = Config.get('rolePermission.permission_table', 'permissions');
const rolePermissionTable = Config.get('rolePermission.role_permission_table', 'role_has_permissions');
const roleTable = Config.get('rolePermission.role_table', 'roles');
const userRoleTable = Config.get('rolePermission.user_role_table', 'link_accounts_roles');
const permissionTable = config.get('rolePermission.permission_table', 'permissions');
const rolePermissionTable = config.get('rolePermission.role_permission_table', 'role_has_permissions');
const roleTable = config.get('rolePermission.role_table', 'roles');
const userRoleTable = config.get('rolePermission.user_role_table', 'link_accounts_roles');
/**
* Permission authentication to check if user has any of the specified permissions
@ -18,7 +19,7 @@ export default class Can {
/**
* Handle request
*/
public async handle({ auth, response }: HttpContextContract, next: () => Promise<void>, permissionNames: string[]) {
public async handle({ auth, response }: HttpContext, next: () => Promise<void>, permissionNames: string[]) {
/**
* Check if user is logged-in
*/
@ -31,9 +32,10 @@ export default class Can {
// return response.unauthorized({
// error: `Doesn't have required role(s): ${permissionNames.join(',')}`,
// });
throw new Exception(`Doesn't have required permission(s): ${permissionNames.join(',')}`, 401);
throw new Exception(`Doesn't have required permission(s): ${permissionNames.join(',')}`, { status: 401 });
}
await next();
// await next();
return next();
}
private async checkHasPermissions(user: User, permissionNames: Array<string>): Promise<boolean> {
@ -66,7 +68,7 @@ export default class Can {
rows: {
0: { permissioncount },
},
} = await Database.rawQuery(
} = await db.rawQuery(
'SELECT count("p"."name") as permissionCount FROM ' +
roleTable +
' r INNER JOIN ' +

View file

@ -1,11 +1,12 @@
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
import Config from '@ioc:Adonis/Core/Config';
import Database from '@ioc:Adonis/Lucid/Database';
import User from 'App/Models/User';
import { HttpContext } from '@adonisjs/core/http';
// import Config from '@ioc:Adonis/Core/Config';
import config from '@adonisjs/core/services/config'
import db from '@adonisjs/lucid/services/db';
import User from '#app/Models/User';
// import { Exception } from '@adonisjs/core/build/standalone'
const roleTable = Config.get('rolePermission.role_table', 'roles');
const userRoleTable = Config.get('rolePermission.user_role_table', 'user_roles');
const roleTable = config.get('rolePermission.role_table', 'roles');
const userRoleTable = config.get('rolePermission.user_role_table', 'user_roles');
/**
* Role authentication to check if user has any of the specified roles
@ -16,7 +17,7 @@ export default class Is {
/**
* Handle request
*/
public async handle({ auth, response }: HttpContextContract, next: () => Promise<void>, roleNames: string[]) {
public async handle({ auth, response }: HttpContext, next: () => Promise<void>, roleNames: string[]) {
/**
* Check if user is logged-in or not.
*/
@ -33,7 +34,8 @@ export default class Is {
// 401,
// "E_INVALID_AUTH_UID");
}
await next();
// await next();
return next()
}
private async checkHasRoles(user: User, roleNames: Array<string>): Promise<boolean> {
@ -46,7 +48,7 @@ export default class Is {
0: {
0: { roleCount },
},
} = await Database.rawQuery(
} = await db.rawQuery(
'SELECT count(`ur`.`id`) as roleCount FROM ' +
userRoleTable +
' ur INNER JOIN ' +

View file

@ -1,23 +1,25 @@
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
import Database from '@ioc:Adonis/Lucid/Database';
import Config from '@ioc:Adonis/Core/Config';
import User from 'app/Models/User';
import { Exception } from '@adonisjs/core/build/standalone';
import type { HttpContext } from '@adonisjs/core/http';
import db from '@adonisjs/lucid/services/db';
import config from '@adonisjs/core/services/config';
import User from '#app/Models/User';
import { Exception } from '@adonisjs/core/exceptions';
const roleTable = Config.get('rolePermission.role_table', 'roles');
const userRoleTable = Config.get('rolePermission.user_role_table', 'link_accounts_roles');
// const roleTable = Config.get('rolePermission.role_table', 'roles');
const roleTable = config.get('rolePermission.role_table', 'roles');
// const userRoleTable = Config.get('rolePermission.user_role_table', 'link_accounts_roles');
const userRoleTable = config.get('rolePermission.user_role_table', 'user_roles');
// node ace make:middleware role
export default class Role {
// .middleware(['auth', 'role:admin,moderator'])
public async handle({ auth, response }: HttpContextContract, next: () => Promise<void>, userRoles: string[]) {
public async handle({ auth, response }: HttpContext, next: () => Promise<void>, userRoles: string[]) {
// Check if user is logged-in or not.
// let expression = "";
// if (Array.isArray(args)) {
// expression = args.join(" || ");
// }
let user = await auth.user;
let user = auth.user as User;
if (!user) {
return response.unauthorized({ error: 'Must be logged in' });
}
@ -28,7 +30,7 @@ export default class Role {
// error: `Doesn't have required role(s): ${userRoles.join(',')}`,
// // error: `Doesn't have required role(s)`,
// });
throw new Exception(`Doesn't have required role(s): ${userRoles.join(',')}`, 401);
throw new Exception(`Doesn't have required role(s): ${userRoles.join(',')}`, { status: 401 });
}
// code for middleware goes here. ABOVE THE NEXT CALL
@ -62,7 +64,7 @@ export default class Role {
rows: {
0: { rolecount },
},
} = await Database.rawQuery(
} = await db.rawQuery(
'SELECT count("r"."id") as roleCount FROM ' +
roleTable +
' r INNER JOIN ' +

View file

@ -1,4 +1,4 @@
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
import type { HttpContext } from '@adonisjs/core/http';
/**
* Silent auth middleware can be used as a global middleware to silent check
@ -10,7 +10,7 @@ export default class SilentAuthMiddleware {
/**
* Handle request
*/
public async handle({ auth }: HttpContextContract, next: () => Promise<void>) {
public async handle({ auth }: HttpContext, next: () => Promise<void>) {
/**
* Check if user is logged-in or not. If yes, then `ctx.auth.user` will be
* set to the instance of the currently logged in user.

View file

@ -0,0 +1,25 @@
import type { HttpContext } from '@adonisjs/core/http'
import type { NextFn } from '@adonisjs/core/types/http'
import type { Authenticators } from '@adonisjs/auth/types'
/**
* Auth middleware is used authenticate HTTP requests and deny
* access to unauthenticated users.
*/
export default class AuthMiddleware {
/**
* The URL to redirect to, when authentication fails
*/
redirectTo = '/app/login'
async handle(
ctx: HttpContext,
next: NextFn,
options: {
guards?: (keyof Authenticators)[]
} = {}
) {
await ctx.auth.authenticateUsing(options.guards, { loginRoute: this.redirectTo })
return next()
}
}

View file

@ -0,0 +1,19 @@
import { Logger } from '@adonisjs/core/logger';
import { HttpContext } from '@adonisjs/core/http';
import { NextFn } from '@adonisjs/core/types/http';
/**
* The container bindings middleware binds classes to their request
* specific value using the container resolver.
*
* - We bind "HttpContext" class to the "ctx" object
* - And bind "Logger" class to the "ctx.logger" object
*/
export default class ContainerBindingsMiddleware {
handle(ctx: HttpContext, next: NextFn) {
ctx.containerResolver.bindValue(HttpContext, ctx);
ctx.containerResolver.bindValue(Logger, ctx.logger);
return next();
}
}

View file

@ -0,0 +1,27 @@
import type { HttpContext } from '@adonisjs/core/http';
import type { NextFn } from '@adonisjs/core/types/http';
import type { Authenticators } from '@adonisjs/auth/types';
/**
* Guest middleware is used to deny access to routes that should
* be accessed by unauthenticated users.
*
* For example, the login page should not be accessible if the user
* is already logged-in
*/
export default class GuestMiddleware {
/**
* The URL to redirect to when user is logged-in
*/
redirectTo = '/';
async handle(ctx: HttpContext, next: NextFn, options: { guards?: (keyof Authenticators)[] } = {}) {
for (let guard of options.guards || [ctx.auth.defaultGuard]) {
if (await ctx.auth.use(guard).check()) {
return ctx.response.redirect(this.redirectTo, true);
}
}
return next();
}
}

View file

@ -0,0 +1,27 @@
import type { HttpContext } from '@adonisjs/core/http';
import type { NextFn } from '@adonisjs/core/types/http';
export default class StardustMiddleware {
async handle(ctx: HttpContext, next: NextFn): Promise<void> {
/**
* Middleware logic goes here (before the next call)
*/
// console.log(ctx);
const { pathname } = new URL(ctx.request.completeUrl());
globalThis.stardust = {
...globalThis.stardust,
pathname,
};
/**
* Call next method in the pipeline and return its output
*/
const output = await next();
return output;
}
}
// import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
// export default class StardustMiddleware {
// handle({ request }: HttpContextContract, next: () => Promise<void>): Promise<void>;
// }