routing-controllers
routing-controllers copied to clipboard
How to get current user in @UseBefore?
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)
Would also love to know if there is a way to use currentUser in UseBefore!
@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
+1 for this. Would be a great feature.
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)