I'm trying to implement the remember me feature using NestJS framework, I already have the Jwt and local strategy implemented and working like this:
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private configService: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: configService.get('JWT_SECRET'),
});
}
async validate(payload: any) {
return { userId: payload.sub, username: payload.email };
}
}
Local strategy:
import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthService } from '../services/auth.service';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super({ usernameField: 'email' });
}
async validate(email: string, password: string): Promise<any> {
const user = await this.authService.validateUser(email, password);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
I thought of a way to solve it via the ignoreExpiration flag, do you guys know a way to implement this with the NestJS framework? Tried searching on the docs, but it appears that they don't have that there.
For future references, I found a solution.
In the jwtService I'm generating a token using the this.jwtService.sign(payload)
method, on this method I have access to a flag called expiresIn
(safer than ignoreExpiration flag) so i'm passing a boolean variable to the api to check wheter it has the remember checked or not and setting this flag accordingly. It looks like this
remember
? (token = this.jwtService.sign(payload, { expiresIn: '60d' }))
: (token = this.jwtService.sign(payload, { expiresIn: '1d' }));