Created
September 5, 2021 09:25
-
-
Save ambrizals/92e3d8c9ac5caf0d24ca0c9956bb3e70 to your computer and use it in GitHub Desktop.
CheckRole Decoration on Adonis 5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { HttpContext } from '@adonisjs/http-server/build/standalone' | |
import UnAuthorized from 'App/Exceptions/UnAuthorizedException' | |
const message = 'You are not authorized' | |
const status = 403 | |
const errorCode = 'E_UNAUTHORIZED' | |
function CheckRole(permitted: string[]) { | |
return function (target: Object, propertyKey: string, descriptor: PropertyDescriptor) { | |
const current = descriptor.value | |
descriptor.value = function (...args: any[]) { | |
const ctx: HttpContext = args[0] | |
const filtered = permitted.filter((item) => ctx.request.role === item) | |
if (filtered.length === 1) { | |
current(ctx) | |
} else { | |
throw new UnAuthorized(message, status, errorCode) | |
} | |
} | |
} | |
} | |
export { CheckRole } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext' | |
import { CheckRole } from 'App/Services/auth/RoleCheckService' | |
export default class AuthTestsController { | |
@CheckRole(['satpam']) | |
public async index(ctx: HttpContextContract) { | |
return ctx.response.send('siap') | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment