Removed renewing refresh token. Added validate endpoint for tokens. Refresh token is given only if 'remember me' option is enabled on login.

This commit is contained in:
Tom
2025-06-17 16:38:51 +00:00
parent c7ece75e7a
commit 6b010f66ba
7 changed files with 195 additions and 114 deletions

View File

@ -45,4 +45,12 @@ export class AuthAccessService {
exp: expiration.getTime(), exp: expiration.getTime(),
} }
} }
async verify(token: string) {
return await this.jwts.verifyAsync(token,
{
secret: this.config.getOrThrow<string>('AUTH_JWT_ACCESS_TOKEN_SECRET')
}
);
}
} }

View File

@ -10,6 +10,8 @@ import { UserEntity } from 'src/users/entities/users.entity';
import { QueryFailedError } from 'typeorm'; import { QueryFailedError } from 'typeorm';
import { PinoLogger } from 'nestjs-pino'; import { PinoLogger } from 'nestjs-pino';
import { JwtAccessGuard } from './guards/jwt-access.guard'; import { JwtAccessGuard } from './guards/jwt-access.guard';
import { LoginDto } from './dto/login.dto';
import { AuthenticationDto } from './dto/authentication.dto';
@Controller('auth') @Controller('auth')
export class AuthController { export class AuthController {
@ -24,11 +26,12 @@ export class AuthController {
async login( async login(
@Request() req, @Request() req,
@Res({ passthrough: true }) response: Response, @Res({ passthrough: true }) response: Response,
@Body() body: LoginDto,
) { ) {
let data: AuthenticationDto | null; let data: AuthenticationDto | null;
try { try {
data = await this.auth.login(req.user); data = await this.auth.login(req.user, body.remember_me);
if (!data.access_token || !data.refresh_token || !data.refresh_exp) { if (!data.access_token || body.remember_me && (!data.refresh_token || !data.refresh_exp)) {
response.statusCode = 500; response.statusCode = 500;
return { return {
success: false, success: false,
@ -58,12 +61,14 @@ export class AuthController {
sameSite: 'strict', sameSite: 'strict',
}); });
if (body.remember_me) {
response.cookie('Refresh', data.refresh_token, { response.cookie('Refresh', data.refresh_token, {
httpOnly: true, httpOnly: true,
secure: true, secure: true,
expires: new Date(data.refresh_exp), expires: new Date(data.refresh_exp),
sameSite: 'strict', sameSite: 'strict',
}); });
}
this.logger.info({ this.logger.info({
class: AuthController.name, class: AuthController.name,
@ -71,6 +76,7 @@ export class AuthController {
user: req.user, user: req.user,
access_token: data.access_token, access_token: data.access_token,
refresh_token: data.refresh_token, refresh_token: data.refresh_token,
remember_me: body.remember_me,
msg: 'User logged in.', msg: 'User logged in.',
}); });
@ -85,7 +91,6 @@ export class AuthController {
@Request() req, @Request() req,
@Res({ passthrough: true }) response: Response, @Res({ passthrough: true }) response: Response,
) { ) {
const accessToken = req.cookies?.Authentication;
const refreshToken = req.cookies?.Refresh; const refreshToken = req.cookies?.Refresh;
response.clearCookie('Authentication'); response.clearCookie('Authentication');
@ -97,7 +102,7 @@ export class AuthController {
class: AuthController.name, class: AuthController.name,
method: this.login.name, method: this.login.name,
user: req.user, user: req.user,
msg: 'User has already logged off via ' + (!refreshToken ? 'cookies' : 'database'), msg: 'User has already logged off based on ' + (!refreshToken ? 'cookies' : 'database'),
}); });
response.statusCode = 400; response.statusCode = 400;
@ -133,8 +138,7 @@ export class AuthController {
msg: 'User logged in.', msg: 'User logged in.',
}); });
const refreshToken = req.cookies.Refresh; const data = await this.auth.renew(req.user);
const data = await this.auth.renew(req.user, refreshToken);
response.cookie('Authentication', data.access_token, { response.cookie('Authentication', data.access_token, {
httpOnly: true, httpOnly: true,
@ -150,7 +154,7 @@ export class AuthController {
msg: 'Updated Authentication cookie for access token.', msg: 'Updated Authentication cookie for access token.',
}); });
if (data.refresh_token != refreshToken) { if (data.refresh_token) {
response.cookie('Refresh', data.refresh_token, { response.cookie('Refresh', data.refresh_token, {
httpOnly: true, httpOnly: true,
secure: true, secure: true,
@ -220,8 +224,8 @@ export class AuthController {
} }
try { try {
data = await this.auth.login(user); data = await this.auth.login(user, false);
if (!data.access_token || !data.refresh_token || !data.refresh_exp) { if (!data.access_token) {
this.logger.error({ this.logger.error({
class: AuthController.name, class: AuthController.name,
method: this.register.name, method: this.register.name,
@ -271,4 +275,27 @@ export class AuthController {
success: true, success: true,
}; };
} }
@Post('validate')
async validate(
@Request() req,
@Res({ passthrough: true }) response: Response,
) {
try {
const accessToken = req.cookies['Authentication'];
const refreshToken = req.cookies['Refresh'];
const verification = await this.auth.verify(accessToken, refreshToken);
return {
success: true,
...verification,
};
} catch (err) {
response.statusCode = 500;
return {
success: false,
error_message: err,
};
}
}
} }

View File

@ -1,6 +1,6 @@
import * as crypto from 'crypto'; import * as crypto from 'crypto';
import * as moment from "moment"; import * as moment from "moment";
import { Injectable, UnauthorizedException } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt'; import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm'; import { InjectRepository } from '@nestjs/typeorm';
@ -20,59 +20,11 @@ export class AuthRefreshService {
private logger: PinoLogger, private logger: PinoLogger,
) { } ) { }
async generate(user: UserEntity, refreshToken?: string) { async generate(user: UserEntity) {
let expiration: Date | null = null;
if (refreshToken) {
const token = await this.get(refreshToken, user.userId);
if (!token) {
this.logger.warn({
class: AuthRefreshService.name,
method: this.generate.name,
user,
refresh_token: refreshToken,
msg: 'Refresh token given is invalid.',
});
throw new UnauthorizedException('Invalid refresh token.');
}
if (token.exp.getTime() < new Date().getTime()) {
this.logger.warn({
class: AuthRefreshService.name,
method: this.generate.name,
user,
refresh_token: refreshToken,
exp: expiration,
msg: 'Refresh token given has expired.',
});
throw new UnauthorizedException('Invalid refresh token.');
}
expiration = token.exp;
}
// Generate new refresh token if either:
// - no previous token exists;
// - token has reached expiration threshold;
// - token has expired.
const now = new Date(); const now = new Date();
const expirationTime = parseInt(this.config.getOrThrow<string>('AUTH_JWT_REFRESH_TOKEN_EXPIRATION_MS')); const expirationTime = parseInt(this.config.getOrThrow<string>('AUTH_JWT_REFRESH_TOKEN_EXPIRATION_MS'));
const threshhold = parseInt(this.config.getOrThrow<string>('AUTH_JWT_REFRESH_TOKEN_EXPIRATION_THRESHHOLD_MS')); const expiration = moment(now).add(expirationTime, 'ms').toDate();
if (!refreshToken || expirationTime - (expiration.getTime() - now.getTime()) > threshhold) { const refreshToken = await this.jwts.signAsync(
let deletionTask = null;
if (refreshToken) {
deletionTask = this.revoke(user.userId, refreshToken);
this.logger.debug({
class: AuthRefreshService.name,
method: this.generate.name,
user,
refresh_token: refreshToken,
exp: expiration,
msg: 'Deleted previous refresh token.',
});
}
expiration = moment(now).add(expirationTime, 'ms').toDate();
refreshToken = await this.jwts.signAsync(
{ {
username: user.userLogin, username: user.userLogin,
sub: user.userId, sub: user.userId,
@ -109,9 +61,6 @@ export class AuthRefreshService {
msg: 'Inserted the new refresh token into the database.', msg: 'Inserted the new refresh token into the database.',
}); });
await deletionTask;
}
return { return {
refresh_token: refreshToken, refresh_token: refreshToken,
exp: expiration.getTime(), exp: expiration.getTime(),
@ -155,4 +104,14 @@ export class AuthRefreshService {
const refresh = await this.get(refreshToken, userId); const refresh = await this.get(refreshToken, userId);
return refresh && refresh.exp.getTime() > new Date().getTime(); return refresh && refresh.exp.getTime() > new Date().getTime();
} }
async verify(
refreshToken: string
): Promise<any> {
return await this.jwts.verifyAsync(refreshToken,
{
secret: this.config.getOrThrow<string>('AUTH_JWT_REFRESH_TOKEN_SECRET'),
}
);
}
} }

View File

@ -14,22 +14,26 @@ export class AuthService {
) { } ) { }
async login(user: UserEntity): Promise<AuthenticationDto> { async login(
return this.renew(user, null); user: UserEntity,
withRefresh: boolean
): Promise<AuthenticationDto> {
if (withRefresh) {
return this.renew(user);
} }
async validate( const access_token = await this.accessTokens.generate(user);
username: string, return {
password: string, ...access_token,
): Promise<UserEntity | null> { refresh_token: null,
return await this.users.findOne({ username, password }); refresh_exp: null,
}
} }
async renew( async renew(
user: UserEntity, user: UserEntity,
refresh_token: string | null
): Promise<AuthenticationDto | null> { ): Promise<AuthenticationDto | null> {
const new_refresh_data = await this.refreshTokens.generate(user, refresh_token); const new_refresh_data = await this.refreshTokens.generate(user);
const access_token = await this.accessTokens.generate(user); const access_token = await this.accessTokens.generate(user);
return { return {
@ -39,8 +43,83 @@ export class AuthService {
} }
} }
async revoke(userId: UUID, refreshToken: string): Promise<boolean> { async validate(
username: string,
password: string,
): Promise<UserEntity | null> {
return await this.users.findOne({ username, password });
}
async verify(
accessToken: string,
refreshToken: string
): Promise<{ validation: boolean, userId: UUID | null, username: string | null }> {
if (!accessToken) {
if (!refreshToken) {
return {
validation: false,
userId: null,
username: null,
}
}
const refresh = await this.refreshTokens.verify(refreshToken);
if (refresh.message || !refresh.exp || refresh.exp * 1000 <= new Date().getTime()) {
return {
validation: false,
userId: null,
username: null,
};
}
return {
validation: null,
userId: refresh.sub,
username: refresh.username,
};
}
const access = await this.accessTokens.verify(accessToken);
const refresh = await this.refreshTokens.verify(refreshToken);
if (!access.username || !refresh.username || access.username != refresh.username) {
return {
validation: false,
userId: null,
username: null,
};
}
if (!access.sub || !refresh.sub || access.sub != refresh.sub) {
return {
validation: false,
userId: null,
username: null,
};
}
if (access.message || !access.exp || access.exp * 1000 <= new Date().getTime()) {
if (refresh.message || !refresh.exp || refresh.exp * 1000 <= new Date().getTime()) {
return {
validation: false,
userId: null,
username: null,
};
}
return {
validation: null,
userId: access.sub,
username: access.username,
};
}
return {
validation: true,
userId: access.sub,
username: access.username,
};
}
async revoke(
userId: UUID,
refreshToken: string
): Promise<boolean> {
const res = await this.refreshTokens.revoke(userId, refreshToken); const res = await this.refreshTokens.revoke(userId, refreshToken);
return res?.affected === 1 return res?.affected === 1;
} }
} }

View File

@ -1,4 +1,4 @@
class AuthenticationDto { export class AuthenticationDto {
access_token: string; access_token: string;
exp: number; exp: number;
refresh_token: string | null; refresh_token: string | null;

View File

@ -0,0 +1,7 @@
import { IsBoolean, IsOptional } from 'class-validator';
export class LoginDto {
@IsBoolean()
@IsOptional()
readonly remember_me: boolean;
}

View File

@ -21,6 +21,7 @@ export function serialize_user_long(value: UserEntity) {
} }
export function serialize_token(value: string) { export function serialize_token(value: string) {
if (!value) return null;
return '...' + value.substring(Math.max(value.length - 12, value.length / 2) | 0); return '...' + value.substring(Math.max(value.length - 12, value.length / 2) | 0);
} }