routing-controllers icon indicating copy to clipboard operation
routing-controllers copied to clipboard

In Middleware how to use CurrentUser()?

Open Q00 opened this issue 6 years ago • 3 comments

@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 avatar Jan 14 '20 01:01 Q00

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

Q00 avatar Jan 14 '20 02:01 Q00

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 avatar Dec 22 '23 08:12 jiang000jie

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

It works well !

jiang000jie avatar Dec 22 '23 09:12 jiang000jie