2024-03-14 19:25:27 +00:00
|
|
|
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';
|
2023-03-03 15:54:28 +00:00
|
|
|
// import { Exception } from '@adonisjs/core/build/standalone'
|
|
|
|
|
2024-03-14 19:25:27 +00:00
|
|
|
const roleTable = config.get('rolePermission.role_table', 'roles');
|
|
|
|
const userRoleTable = config.get('rolePermission.user_role_table', 'user_roles');
|
2023-03-03 15:54:28 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Role authentication to check if user has any of the specified roles
|
|
|
|
*
|
|
|
|
* Should be called after auth middleware
|
|
|
|
*/
|
|
|
|
export default class Is {
|
|
|
|
/**
|
2023-06-22 15:20:04 +00:00
|
|
|
* Handle request
|
2023-03-03 15:54:28 +00:00
|
|
|
*/
|
2024-03-14 19:25:27 +00:00
|
|
|
public async handle({ auth, response }: HttpContext, next: () => Promise<void>, roleNames: string[]) {
|
2023-06-22 15:20:04 +00:00
|
|
|
/**
|
|
|
|
* 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");
|
|
|
|
}
|
2024-03-14 19:25:27 +00:00
|
|
|
// await next();
|
|
|
|
return next()
|
2023-03-03 15:54:28 +00:00
|
|
|
}
|
|
|
|
|
2023-06-22 15:20:04 +00:00
|
|
|
private async checkHasRoles(user: User, roleNames: Array<string>): Promise<boolean> {
|
|
|
|
let rolePlaceHolder = '(';
|
|
|
|
let placeholders = new Array(roleNames.length).fill('?');
|
|
|
|
rolePlaceHolder += placeholders.join(',');
|
|
|
|
rolePlaceHolder += ')';
|
2023-03-03 15:54:28 +00:00
|
|
|
|
2023-06-22 15:20:04 +00:00
|
|
|
let {
|
|
|
|
0: {
|
|
|
|
0: { roleCount },
|
|
|
|
},
|
2024-03-14 19:25:27 +00:00
|
|
|
} = await db.rawQuery(
|
2023-06-22 15:20:04 +00:00
|
|
|
'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],
|
|
|
|
);
|
2023-03-03 15:54:28 +00:00
|
|
|
|
2023-06-22 15:20:04 +00:00
|
|
|
return roleCount > 0;
|
|
|
|
}
|
2023-03-03 15:54:28 +00:00
|
|
|
}
|