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

How to get current user in @UseBefore?

Open kkorus opened this issue 4 years ago • 4 comments

I'm using authorizationChecker with currentUserChecker

in authorizationChecker I store logged user in action.request.user = user.

Now I need to get user some info in one of my @UseBefore middlewares, but what I'm getting is undefined as @UseBefore middleware in run before authorization check

    UseBefore(async (req, res, next) => {
      console.log(req.user) // undefined
      return next()
    })(target, propertyKey, descriptor)

kkorus avatar Mar 27 '20 12:03 kkorus

Would also love to know if there is a way to use currentUser in UseBefore!

laurentsmohr avatar Apr 21 '20 08:04 laurentsmohr

@kkorus, @laurentsmohr, this probably goes back to what @MichalLytek called as "middlewares 2.0" in the discussions at #256. The idea never had a real implementation. Maybe it's time to resume that conversation and get it done.

Similar: #131, #489, #492, 529

jotamorais avatar May 01 '20 03:05 jotamorais

+1 for this. Would be a great feature.

abhi12299 avatar May 10 '22 15:05 abhi12299

I created a function for currentUserChecker using the CurrentUserChecker type like so:

export const currentUserChecker: CurrentUserChecker = async (action: Action):Promise<UserEntity|null> => {
    if (Env.isDev() && action.request.query['DEV_TOKEN']) {
        const id = Number(action.request.query['DEV_TOKEN']);
        return await UserEntity.findOneByOrFail({ id });
    }

    const token = action.request.headers['authorization'];

    if (!token) {
        return null;
    }

    const accessToken = token.split(' ')[1];
    return await SupabaseAuthService.getUserFromJwt(accessToken);
};

I pass this function to my RoutingControllersOptions like so:

const app = createExpressServer({
    authorizationChecker,
    currentUserChecker,
    controllers,
});

and now I can call the currentUserChecker from anywhere I have an Action or Request.

UseBefore(async (req, res, next) => {
    const user = currentUserChecker({request:req})
    console.log(user) // undefined
    return next()
})(target, propertyKey, descriptor)

angelxmoreno avatar Apr 15 '24 16:04 angelxmoreno