Skip to content

Instantly share code, notes, and snippets.

@ambrizals
Created September 5, 2021 09:25
Show Gist options
  • Save ambrizals/92e3d8c9ac5caf0d24ca0c9956bb3e70 to your computer and use it in GitHub Desktop.
Save ambrizals/92e3d8c9ac5caf0d24ca0c9956bb3e70 to your computer and use it in GitHub Desktop.
CheckRole Decoration on Adonis 5
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 }
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