- renamings to the new naming convetion for adonisjs version 6
Some checks failed
CI Pipeline / japa-tests (push) Failing after 58s
Some checks failed
CI Pipeline / japa-tests (push) Failing after 58s
- npm updates
This commit is contained in:
parent
bee76f8d5b
commit
a29865b781
53 changed files with 701 additions and 731 deletions
64
app/middleware/Is.ts
Normal file
64
app/middleware/Is.ts
Normal file
|
@ -0,0 +1,64 @@
|
|||
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');
|
||||
|
||||
/**
|
||||
* Role authentication to check if user has any of the specified roles
|
||||
*
|
||||
* Should be called after auth middleware
|
||||
*/
|
||||
export default class Is {
|
||||
/**
|
||||
* Handle request
|
||||
*/
|
||||
public async handle({ auth, response }: HttpContext, next: () => Promise<void>, roleNames: string[]) {
|
||||
/**
|
||||
* Check if user is logged-in or not.
|
||||
*/
|
||||
let user = await auth.user;
|
||||
if (!user) {
|
||||
return response.unauthorized({ error: 'Must be logged in' });
|
||||
}
|
||||
let hasRole = await this.checkHasRoles(user, roleNames);
|
||||
if (!hasRole) {
|
||||
return response.unauthorized({
|
||||
error: `Doesn't have required role(s): ${roleNames.join(',')}`,
|
||||
});
|
||||
// return new Exception(`Doesn't have required role(s): ${roleNames.join(',')}`,
|
||||
// 401,
|
||||
// "E_INVALID_AUTH_UID");
|
||||
}
|
||||
// await next();
|
||||
return next()
|
||||
}
|
||||
|
||||
private async checkHasRoles(user: User, roleNames: Array<string>): Promise<boolean> {
|
||||
let rolePlaceHolder = '(';
|
||||
let placeholders = new Array(roleNames.length).fill('?');
|
||||
rolePlaceHolder += placeholders.join(',');
|
||||
rolePlaceHolder += ')';
|
||||
|
||||
let {
|
||||
0: {
|
||||
0: { roleCount },
|
||||
},
|
||||
} = await db.rawQuery(
|
||||
'SELECT count(`ur`.`id`) as roleCount FROM ' +
|
||||
userRoleTable +
|
||||
' ur INNER JOIN ' +
|
||||
roleTable +
|
||||
' r ON ur.role_id=r.id WHERE `ur`.`user_id`=? AND `r`.`name` in ' +
|
||||
rolePlaceHolder +
|
||||
' LIMIT 1',
|
||||
[user.id, ...roleNames],
|
||||
);
|
||||
|
||||
return roleCount > 0;
|
||||
}
|
||||
}
|
21
app/middleware/SilentAuth.ts
Normal file
21
app/middleware/SilentAuth.ts
Normal file
|
@ -0,0 +1,21 @@
|
|||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
|
||||
/**
|
||||
* Silent auth middleware can be used as a global middleware to silent check
|
||||
* if the user is logged-in or not.
|
||||
*
|
||||
* The request continues as usual, even when the user is not logged-in.
|
||||
*/
|
||||
export default class SilentAuthMiddleware {
|
||||
/**
|
||||
* Handle request
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
await auth.check();
|
||||
await next();
|
||||
}
|
||||
}
|
25
app/middleware/auth_middleware.ts
Normal file
25
app/middleware/auth_middleware.ts
Normal 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()
|
||||
}
|
||||
}
|
90
app/middleware/can_middleware.ts
Normal file
90
app/middleware/can_middleware.ts
Normal file
|
@ -0,0 +1,90 @@
|
|||
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');
|
||||
|
||||
/**
|
||||
* Permission authentication to check if user has any of the specified permissions
|
||||
*
|
||||
* Should be called after auth middleware
|
||||
*/
|
||||
export default class Can {
|
||||
/**
|
||||
* Handle request
|
||||
*/
|
||||
public async handle({ auth, response }: HttpContext, next: () => Promise<void>, permissionNames: string[]) {
|
||||
/**
|
||||
* Check if user is logged-in
|
||||
*/
|
||||
let user = await auth.user;
|
||||
if (!user) {
|
||||
return response.unauthorized({ error: 'Must be logged in' });
|
||||
}
|
||||
let hasPermission = await this.checkHasPermissions(user, permissionNames);
|
||||
if (!hasPermission) {
|
||||
// return response.unauthorized({
|
||||
// error: `Doesn't have required role(s): ${permissionNames.join(',')}`,
|
||||
// });
|
||||
throw new Exception(`Doesn't have required permission(s): ${permissionNames.join(',')}`, { status: 401 });
|
||||
}
|
||||
// await next();
|
||||
return next();
|
||||
}
|
||||
|
||||
private async checkHasPermissions(user: User, permissionNames: Array<string>): Promise<boolean> {
|
||||
let rolePlaceHolder = '(';
|
||||
let placeholders = new Array(permissionNames.length).fill('?');
|
||||
rolePlaceHolder += placeholders.join(',');
|
||||
rolePlaceHolder += ')';
|
||||
|
||||
// let test = user
|
||||
// .related('roles')
|
||||
// .query()
|
||||
// .count('permissions.name')
|
||||
// .innerJoin('gba.role_has_permissions', function () {
|
||||
// this.on('gba.role_has_permissions.role_id', 'roles.id');
|
||||
// })
|
||||
// .innerJoin('gba.permissions', function () {
|
||||
// this.on('role_has_permissions.permission_id', 'permissions.id');
|
||||
// })
|
||||
// .andWhereIn('permissions.name', permissionNames);
|
||||
|
||||
// select "permissions"."name"
|
||||
// from "gba"."roles"
|
||||
// inner join "gba"."link_accounts_roles" on "roles"."id" = "link_accounts_roles"."role_id"
|
||||
// inner join "gba"."role_has_permissions" on "gba"."role_has_permissions"."role_id" = "roles"."id"
|
||||
// inner join "gba"."permissions" on "role_has_permissions"."permission_id" = "permissions"."id"
|
||||
// where ("permissions"."name" in ('dataset-list', 'dataset-publish'))
|
||||
// and ("link_accounts_roles"."account_id" = 1)
|
||||
|
||||
let {
|
||||
rows: {
|
||||
0: { permissioncount },
|
||||
},
|
||||
} = await db.rawQuery(
|
||||
'SELECT count("p"."name") as permissionCount FROM ' +
|
||||
roleTable +
|
||||
' r INNER JOIN ' +
|
||||
userRoleTable +
|
||||
' ur ON ur.role_id=r.id AND "ur"."account_id"=? ' +
|
||||
' INNER JOIN ' +
|
||||
rolePermissionTable +
|
||||
' rp ON rp.role_id=r.id ' +
|
||||
' INNER JOIN ' +
|
||||
permissionTable +
|
||||
' p ON rp.permission_id=p.id AND "p"."name" in ' +
|
||||
rolePlaceHolder +
|
||||
' LIMIT 1',
|
||||
[user.id, ...permissionNames],
|
||||
);
|
||||
|
||||
return permissioncount > 0;
|
||||
}
|
||||
}
|
19
app/middleware/container_bindings_middleware.ts
Normal file
19
app/middleware/container_bindings_middleware.ts
Normal 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();
|
||||
}
|
||||
}
|
27
app/middleware/guest_middleware.ts
Normal file
27
app/middleware/guest_middleware.ts
Normal 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();
|
||||
}
|
||||
}
|
80
app/middleware/role_middleware.ts
Normal file
80
app/middleware/role_middleware.ts
Normal file
|
@ -0,0 +1,80 @@
|
|||
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 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 }: 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 = auth.user as User;
|
||||
if (!user) {
|
||||
return response.unauthorized({ error: 'Must be logged in' });
|
||||
}
|
||||
|
||||
let hasRole = await this.checkHasRoles(user, userRoles);
|
||||
if (!hasRole) {
|
||||
// return response.unauthorized({
|
||||
// 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(',')}`, { status: 401 });
|
||||
}
|
||||
|
||||
// code for middleware goes here. ABOVE THE NEXT CALL
|
||||
await next();
|
||||
}
|
||||
|
||||
private async checkHasRoles(user: User, userRoles: string[]): Promise<boolean> {
|
||||
// await user.load("roles");
|
||||
// const ok = user.roles.map((role) => role.name);
|
||||
// const roles = await user.getRoles();
|
||||
|
||||
let rolePlaceHolder = '(';
|
||||
let placeholders = new Array(userRoles.length).fill('?');
|
||||
rolePlaceHolder += placeholders.join(',');
|
||||
rolePlaceHolder += ')';
|
||||
|
||||
// const roles = await user
|
||||
// .related('roles')
|
||||
// .query()
|
||||
// .count('*') // .select('name')
|
||||
// .whereIn('name', userRoles);
|
||||
// // .groupBy('name');
|
||||
|
||||
// select count(*) as roleCount
|
||||
// from gba.roles
|
||||
// inner join gba.link_accounts_roles
|
||||
// on "roles"."id" = "link_accounts_roles"."role_id"
|
||||
// where ("name" in ('administrator', 'editor')) and ("link_accounts_roles"."account_id" = 1)
|
||||
|
||||
let {
|
||||
rows: {
|
||||
0: { rolecount },
|
||||
},
|
||||
} = await db.rawQuery(
|
||||
'SELECT count("r"."id") as roleCount FROM ' +
|
||||
roleTable +
|
||||
' r INNER JOIN ' +
|
||||
userRoleTable +
|
||||
' ur ON r.id=ur.role_id WHERE "ur"."account_id"=? AND "r"."name" in ' +
|
||||
rolePlaceHolder +
|
||||
' LIMIT 1',
|
||||
[user.id, ...userRoles],
|
||||
);
|
||||
|
||||
return rolecount > 0;
|
||||
}
|
||||
}
|
47
app/middleware/stardust_middleware.ts
Normal file
47
app/middleware/stardust_middleware.ts
Normal file
|
@ -0,0 +1,47 @@
|
|||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
import type { NextFn } from '@adonisjs/core/types/http';
|
||||
|
||||
|
||||
declare global {
|
||||
function myFunction(): boolean;
|
||||
var myVariable: number;
|
||||
|
||||
interface StardustData {
|
||||
pathname?: string;
|
||||
namedRoutes?: Record<string, string>;
|
||||
}
|
||||
var stardust: StardustData;
|
||||
}
|
||||
|
||||
declare global {}
|
||||
export default class StardustMiddleware {
|
||||
async handle(ctx: HttpContext, next: NextFn): Promise<void> {
|
||||
/**
|
||||
* Middleware logic goes here (before the next call)
|
||||
*/
|
||||
|
||||
// Check if the request is an API request
|
||||
if (!ctx.request.url().startsWith('/api')) {
|
||||
// Middleware logic for non-API requests
|
||||
const { pathname } = new URL(ctx.request.completeUrl()); // '/', '/app/login'
|
||||
globalThis.myFunction = () => {
|
||||
return true;
|
||||
};
|
||||
globalThis.myVariable = 1;
|
||||
|
||||
globalThis.stardust = {
|
||||
...globalThis.stardust,
|
||||
pathname,
|
||||
};
|
||||
|
||||
/**
|
||||
* Call next method in the pipeline and return its output
|
||||
*/
|
||||
await next();
|
||||
} else {
|
||||
// Skip middleware for API requests
|
||||
await next();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Add table
editor.link_modal.header
Reference in a new issue