The library Inversify-Express-Utils is very good library that unions the functionality of both libraries: ExpresJs and InversifyJs. It provides a lot of functionality for extension. It also provides an authentication provider integration. But it is handled in an imperative way. There were not pre-configured possibilities.
I wanted to define rules in a declarative way by decorators. It was logical. But they were absent. I investigated a way how to implement decorators for, and covered the authentication provider by decorators.This is a decorator for my application. It checks if an user has a permission.
export function permission (permission: string): any {
return function (target: any, key: string | symbol, descriptor: TypedPropertyDescriptor) {
const fn = descriptor.value as Handler
descriptor.value = async function (request: Request, response: Response, next: NextFunction) {
const context: HttpContext = Reflect.getMetadata(
'inversify-express-utils:httpcontext',
request
)
const hasAccess = await context.user.isResourceOwner(permission)
if (hasAccess) {
return fn.call(this, request, response)
} else {
response
.status(403)
.send({ error: 'The authenticated user does not have an access to the resource.' })
return response
}
}
return descriptor
}
}
Because it is a custom implementation we need handle it with InversifyJS. The MetaData - httpContext is attached to the incoming request. We retrieve it in a following way:const context: HttpContext = Reflect.getMetadata( 'inversify-express-utils:httpcontext', request )I've created a Pull Request where I created decorators for the authentication provider and covered everything by tests. I would be glad if somebody review, comment and vote for.
Reagards, Viktor.
Комментариев нет:
Отправить комментарий