lukeautry / tsoa

Build OpenAPI-compliant REST APIs using TypeScript and Node
MIT License
3.42k stars 489 forks source link

Question: arguments-aware authorization possible? #1513

Closed ondrejpar closed 8 months ago

ondrejpar commented 9 months ago

Hi, I have a controller similar to this:

@Route('/api')
class PetshopController extends Controller {
  @Get('/{shopId}/pets')
  getPets(@Query() shopId: string) { ... }
  @Post('/{shopId}/pets')
  addPet(@Query() shopId: string) { ... }
  ...ten more methods that use shopId
}

I need to verify (authorize) that caller can access the shop identified by shopId. The authorization is quite complex and involves database.

I can add await authorizeShopAccess(shopId) to the beginning of every method, but is there a way to write this only once? As far as I can tell, the middlewares don't have access to path parameters (or arguments in general) and @Security only handles authentication, not authorization.

Sorting

github-actions[bot] commented 9 months ago

Hello there ondrejpar 👋

Thank you for opening your very first issue in this project.

We will try to get back to you as soon as we can.👀

WoH commented 9 months ago

the middlewares don't have access to path parameters (or arguments in general)

But the request object

ondrejpar commented 9 months ago

@WoH well, yes, but I would have to parse the path again and keep patterns in sync at two different places - not DRY.

WoH commented 9 months ago

Then you probably want your own Decorator. (Albeit lose the OpenAPI response docs)

ondrejpar commented 8 months ago

Did that and works perfectly. I created my own Authorizer (the code is a bit complex for Typescript 4, I think it could be simplified for Typescript 5) which uses Proxy to intercept all calls to the annotated class and performs authorization. In fact, it's all completely independent on TSOA. Thanks for help.