I am using Angular+Nest to develop a website. I have created a service(Angular) so that client can get user's information from server when project start up(the same as fresh). Some actions don't need to login, so the login is optional.
What I want is if user has logined, then client should send a request to get user's information.
Server code as below:
export const RequestUser = createParamDecorator((data, req): RequestUserDTO => {
return req.user;
});
@Controller('auth')
export class AuthController {
@Get('getUserInfoByToken')
async getUserInfoByToken(@RequestUser() user: User): Promise<any> {
if (user) {
return {
nickname: user.nickname,
level: user.level
};
}
}
}
Howerver, I find there's nothing be return if I don't add @UseGuards(AuthGuard())
as decorator. But if I add it, when project start, this request return 401
as status code. Then the web will turn to login page.
What should I do to avoid this situation? Not every action need login.
If you got totally different approach in mind, let me know - will try to help.
Will try to serve a bit more detailed example, which includes
passport
under the hood. It assumes thatpassport
is used and thatAuthorization
token is being sent.const RegisteredPassportModule = PassportModule.register({ defaultStrategy: 'bearer' })
HttpStrategy
to someAuthModule
PassportModule.register({ defaultStrategy: 'bearer' })
to imports toAuthModule
Then:
AuthService
is a service (and a part ofAuthModule
) that allows to find given user via token sent via token passed viaAuthorization
header, directly from the database.Usage is after all quite simple (you can put the guard for either method of controller):
Where
RequestWithUser
is just:and the
/user
endpoint would be just returningrequest.user
I hope this helps!
If you really insist on this way (see comments), you can use Interceptors:
so AuthGuard is not needed.
Write a conditional logic in the AuthGuard to check if a user is provided in the request.