typestack / routing-controllers

Create structured, declarative and beautifully organized class-based controllers with heavy decorators usage in Express / Koa using TypeScript and Routing Controllers Framework.
MIT License
4.4k stars 394 forks source link

In Middleware how to use CurrentUser()? #529

Open Q00 opened 4 years ago

Q00 commented 4 years ago

@sh3d2 one issue is that the service being injected can change for each request (i.e. depends on currentUser). How would you handle that in routing-controller?

Originally posted by @tonyxiao in https://github.com/typestack/routing-controllers/issues/327#issuecomment-433586208

Hi. Thanks for making this good library. It is very interesting using this library. I wanna ask something. How can the middleware access currentUser? Now I try to make a logic about logging middleware and if jwt token exists, I will save user id to reference in database, what can I do?

Q00 commented 4 years ago

I use request.query in currentUserCheck.ts

    const userService = Container.get(UserService);
    const user = await userService.getById(
      Authentication.getUserIdByToken(token).userId
    );

    action.request.query.user = user;

In middleware, I just call req.query.user

jiang000jie commented 10 months ago

any solution? Here is my problem:

@JsonController("/project")
@Service()
export class ProjectController {

    @Post("/getProject")
    async getDetail(@CurrentUser() user: User, @BodyParam("project_id") project_id: number) {
        // to check if currentUser has the access to the project
        if (!user.relatedProjectIds?.includes(project_id + "")) {
            return "don't have the access to the project";
        }
        ......
        return {}
    }

    @Post("/add")
    async add(@Body() p: Project) {
        const res = await this.dataSource.manager.insert(Project, p);
        return true;
    }

    @Post("/modify")
    async modify(@CurrentUser() user: User, @Body() p: Project) {       
        // to check if currentUser has the access to the project
        if (!user.relatedProjectIds?.includes(project_id + "")) {
            return "don't have the access to the project";
        }
        ......
        return {}
    }
        @Post("/remove")
    async delete(@CurrentUser() user: User, @BodyParam("project_id") project_id: number) {
        // to check if currentUser has the access to the project
        if (!user.relatedProjectIds?.includes(project_id + "")) {
            return "don't have the access to the project";
        }
        ......
        return {}
    }

I wanna build a middleware to handle most of routes with @CurrentUser so that code is more clean

jiang000jie commented 10 months ago

I get one solution. You can use Container.set() in a middleware such as AuthMiddleware.ts. Then, in the middleware above, you can get currentUserwith Container.get().

It works well !