add remember me functionality

This commit is contained in:
2023-08-04 13:21:18 +02:00
parent 582c2885ed
commit c4d344f07d
2 changed files with 11 additions and 6 deletions

View File

@@ -12,14 +12,17 @@ import { UsersRepository } from '../users/infrastructure/users.repository'
export class AuthService { export class AuthService {
constructor(private usersRepository: UsersRepository, private prisma: PrismaService) {} constructor(private usersRepository: UsersRepository, private prisma: PrismaService) {}
async createJwtTokensPair(userId: string) { async createJwtTokensPair(userId: string, rememberMe?: boolean) {
const accessSecretKey = process.env.ACCESS_JWT_SECRET_KEY const accessSecretKey = process.env.ACCESS_JWT_SECRET_KEY
const refreshSecretKey = process.env.REFRESH_JWT_SECRET_KEY const refreshSecretKey = process.env.REFRESH_JWT_SECRET_KEY
const accessExpiresIn = rememberMe ? '1d' : '10m'
const payload: { userId: string; date: Date } = { const payload: { userId: string; date: Date } = {
userId, userId,
date: new Date(), date: new Date(),
} }
const accessToken = jwt.sign(payload, accessSecretKey, { expiresIn: '10m' }) const accessToken = jwt.sign(payload, accessSecretKey, { expiresIn: accessExpiresIn })
const refreshToken = jwt.sign(payload, refreshSecretKey, { const refreshToken = jwt.sign(payload, refreshSecretKey, {
expiresIn: '30d', expiresIn: '30d',
}) })
@@ -39,7 +42,7 @@ export class AuthService {
} }
} }
async checkCredentials(email: string, password: string) { async checkCredentials(email: string, password: string, rememberMe?: boolean) {
const user = await this.usersRepository.findUserByEmail(email) const user = await this.usersRepository.findUserByEmail(email)
if (!user /*|| !user.emailConfirmation.isConfirmed*/) if (!user /*|| !user.emailConfirmation.isConfirmed*/)
@@ -63,7 +66,7 @@ export class AuthService {
}, },
} }
} }
const tokensPair = await this.createJwtTokensPair(user.id) const tokensPair = await this.createJwtTokensPair(user.id, rememberMe)
return { return {
resultCode: 0, resultCode: 0,

View File

@@ -9,11 +9,13 @@ export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) { constructor(private readonly authService: AuthService) {
super({ super({
usernameField: 'email', usernameField: 'email',
passReqToCallback: true,
}) })
} }
async validate(email: string, password: string): Promise<any> { async validate(req: any, email: string, password: string): Promise<any> {
const newCredentials = await this.authService.checkCredentials(email, password) const rememberMe = req?.body?.rememberMe || false
const newCredentials = await this.authService.checkCredentials(email, password, rememberMe)
if (newCredentials.resultCode === 1) { if (newCredentials.resultCode === 1) {
throw new UnauthorizedException('Invalid credentials') throw new UnauthorizedException('Invalid credentials')