mirror of
https://github.com/ershisan99/flashcards-api.git
synced 2025-12-16 20:59:26 +00:00
add remember me functionality
This commit is contained in:
@@ -12,14 +12,17 @@ import { UsersRepository } from '../users/infrastructure/users.repository'
|
||||
export class AuthService {
|
||||
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 refreshSecretKey = process.env.REFRESH_JWT_SECRET_KEY
|
||||
|
||||
const accessExpiresIn = rememberMe ? '1d' : '10m'
|
||||
|
||||
const payload: { userId: string; date: Date } = {
|
||||
userId,
|
||||
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, {
|
||||
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)
|
||||
|
||||
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 {
|
||||
resultCode: 0,
|
||||
|
||||
@@ -9,11 +9,13 @@ export class LocalStrategy extends PassportStrategy(Strategy) {
|
||||
constructor(private readonly authService: AuthService) {
|
||||
super({
|
||||
usernameField: 'email',
|
||||
passReqToCallback: true,
|
||||
})
|
||||
}
|
||||
|
||||
async validate(email: string, password: string): Promise<any> {
|
||||
const newCredentials = await this.authService.checkCredentials(email, password)
|
||||
async validate(req: any, email: string, password: string): Promise<any> {
|
||||
const rememberMe = req?.body?.rememberMe || false
|
||||
const newCredentials = await this.authService.checkCredentials(email, password, rememberMe)
|
||||
|
||||
if (newCredentials.resultCode === 1) {
|
||||
throw new UnauthorizedException('Invalid credentials')
|
||||
|
||||
Reference in New Issue
Block a user