Answer the question
In order to leave comments, you need to log in
How to use cookies in NestJS?
There is such an endpoint for getting a list of books, only for an authorized user.
@Get()
@Roles(Role.Admin, Role.User)
@UseGuards(JwtAuthGuard, RolesGuard)
getAllBooks(): Promise<Book[]> {
return this.bookService.getAllBooks();
}
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}
@Injectable()
export class RolesGuard implements CanActivate {
constructor(
@Inject(forwardRef(() => UserService))
private userService: UserService,
private reflector: Reflector,
) {}
canActivate(context: ExecutionContext): Promise<boolean> | boolean {
const request = context.switchToHttp().getRequest();
console.log(request);
const { userId } = request.user;
const requiredRoles = this.reflector.getAllAndOverride<Role[]>('roles', [
context.getHandler(),
context.getClass(),
]);
const hasRole = async (userId: number, requiredRoles: Role[]) => {
const { role } = await this.userService.getById(userId);
return requiredRoles.includes(role) || !requiredRoles;
};
return hasRole(userId, requiredRoles);
}
}
@Get()
// @Roles(Role.Admin, Role.User)
// @UseGuards(JwtAuthGuard, RolesGuard)
getAllBooks(@Cookies() cookies: string): Promise<Book[]> | string {
return cookies;
}
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { TokenPayload } from '../token-payload.interface';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.JWT_SECRET,
});
}
async validate(payload: TokenPayload) {
return { userId: payload.userId };
}
}
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question