Removed renewing refresh tokens. Fixed error 500 when using expired tokens. Fixed log out response when user only has access token."
This commit is contained in:
@ -4,6 +4,7 @@ import { JwtService } from '@nestjs/jwt';
|
||||
import { UserEntity } from 'src/users/entities/users.entity';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { PinoLogger } from 'nestjs-pino';
|
||||
import { AccessTokenDto } from './dto/access-token.dto';
|
||||
|
||||
@Injectable()
|
||||
export class AuthAccessService {
|
||||
@ -13,7 +14,7 @@ export class AuthAccessService {
|
||||
private logger: PinoLogger,
|
||||
) { }
|
||||
|
||||
async generate(user: UserEntity) {
|
||||
async generate(user: UserEntity): Promise<AccessTokenDto> {
|
||||
const now = new Date();
|
||||
const limit = parseInt(this.config.getOrThrow<string>('AUTH_JWT_ACCESS_TOKEN_EXPIRATION_MS'));
|
||||
const expiration = moment(now).add(limit, 'ms').toDate();
|
||||
|
@ -8,10 +8,10 @@ import { OfflineGuard } from './guards/offline.guard';
|
||||
import { UserEntity } from 'src/users/entities/users.entity';
|
||||
import { QueryFailedError } from 'typeorm';
|
||||
import { PinoLogger } from 'nestjs-pino';
|
||||
import { JwtAccessGuard } from './guards/jwt-access.guard';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { AuthenticationDto } from './dto/authentication.dto';
|
||||
import { AppConfig } from 'src/asset/config/app-config';
|
||||
import { JwtMixedGuard } from './guards/jwt-mixed.guard';
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
@ -93,22 +93,23 @@ export class AuthController {
|
||||
};
|
||||
}
|
||||
|
||||
@UseGuards(JwtAccessGuard)
|
||||
@UseGuards(JwtMixedGuard)
|
||||
@Delete('login')
|
||||
async logout(
|
||||
@Request() req,
|
||||
@Res({ passthrough: true }) response: Response,
|
||||
) {
|
||||
const accessToken = req.cookies?.Authentication;
|
||||
const refreshToken = req.cookies?.Refresh;
|
||||
|
||||
response.clearCookie('Authentication');
|
||||
response.clearCookie('Refresh');
|
||||
|
||||
if (!refreshToken || !await this.auth.revoke(req.user.userId, refreshToken)) {
|
||||
if (!accessToken && !refreshToken && !await this.auth.revoke(req.user.userId, refreshToken)) {
|
||||
// User has already logged off.
|
||||
this.logger.info({
|
||||
class: AuthController.name,
|
||||
method: this.login.name,
|
||||
method: this.logout.name,
|
||||
user: req.user,
|
||||
msg: 'User has already logged off based on ' + (!refreshToken ? 'cookies' : 'database'),
|
||||
});
|
||||
@ -116,7 +117,7 @@ export class AuthController {
|
||||
response.statusCode = 400;
|
||||
return {
|
||||
success: false,
|
||||
error_message: 'User has already logged off.'
|
||||
error_message: 'User has already logged off.',
|
||||
};
|
||||
}
|
||||
|
||||
@ -140,12 +141,30 @@ export class AuthController {
|
||||
) {
|
||||
this.logger.info({
|
||||
class: AuthController.name,
|
||||
method: this.login.name,
|
||||
method: this.refresh.name,
|
||||
user: req.user,
|
||||
refresh_token: req.cookies.Refresh,
|
||||
msg: 'User logged in.',
|
||||
msg: 'Attempting to renew access token.',
|
||||
});
|
||||
|
||||
const results = await this.auth.verify(req.cookies.Authentication, req.cookies.Refresh);
|
||||
|
||||
if (results.validation === false) {
|
||||
this.logger.info({
|
||||
class: AuthController.name,
|
||||
method: this.refresh.name,
|
||||
user: req.user,
|
||||
refresh_token: req.cookies.Refresh,
|
||||
msg: 'Refresh token is invalid. Access token is not refreshing.',
|
||||
});
|
||||
|
||||
response.statusCode = 400;
|
||||
return {
|
||||
success: false,
|
||||
error_message: 'Refresh token is invalid.',
|
||||
};
|
||||
}
|
||||
|
||||
const data = await this.auth.renew(req.user);
|
||||
|
||||
response.cookie('Authentication', data.access_token, {
|
||||
@ -162,22 +181,6 @@ export class AuthController {
|
||||
msg: 'Updated Authentication cookie for access token.',
|
||||
});
|
||||
|
||||
if (data.refresh_token) {
|
||||
response.cookie('Refresh', data.refresh_token, {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
expires: new Date(data.refresh_exp),
|
||||
sameSite: 'strict',
|
||||
});
|
||||
this.logger.debug({
|
||||
class: AuthController.name,
|
||||
method: this.refresh.name,
|
||||
user: req.user,
|
||||
refresh_token: data.refresh_token,
|
||||
msg: 'Updated Refresh cookie for refresh token.',
|
||||
});
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
|
@ -6,6 +6,8 @@ import { AuthAccessService } from './auth.access.service';
|
||||
import { UUID } from 'crypto';
|
||||
import { AuthenticationDto } from './dto/authentication.dto';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { AccessTokenDto } from './dto/access-token.dto';
|
||||
import { TokenExpiredError } from '@nestjs/jwt';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
@ -18,35 +20,34 @@ export class AuthService {
|
||||
|
||||
async login(
|
||||
loginDetails: LoginDto
|
||||
): Promise<AuthenticationDto | null> {
|
||||
): Promise<AuthenticationDto> {
|
||||
const user = await this.users.findOne(loginDetails);
|
||||
if (!user) {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
|
||||
if (loginDetails.remember_me) {
|
||||
return this.renew(user);
|
||||
const access_token = await this.accessTokens.generate(user);
|
||||
|
||||
if (!loginDetails.remember_me) {
|
||||
return {
|
||||
...access_token,
|
||||
refresh_token: null,
|
||||
refresh_exp: null,
|
||||
}
|
||||
}
|
||||
|
||||
const access_token = await this.accessTokens.generate(user);
|
||||
const refresh_token = await this.refreshTokens.generate(user);
|
||||
return {
|
||||
...access_token,
|
||||
refresh_token: null,
|
||||
refresh_exp: null,
|
||||
refresh_token: refresh_token.refresh_token,
|
||||
refresh_exp: refresh_token.exp,
|
||||
}
|
||||
}
|
||||
|
||||
async renew(
|
||||
user: UserEntity,
|
||||
): Promise<AuthenticationDto | null> {
|
||||
const new_refresh_data = await this.refreshTokens.generate(user);
|
||||
const access_token = await this.accessTokens.generate(user);
|
||||
|
||||
return {
|
||||
...access_token,
|
||||
refresh_token: new_refresh_data.refresh_token,
|
||||
refresh_exp: new_refresh_data.exp,
|
||||
}
|
||||
): Promise<AccessTokenDto> {
|
||||
return await this.accessTokens.generate(user);
|
||||
}
|
||||
|
||||
async validate(
|
||||
@ -64,8 +65,18 @@ export class AuthService {
|
||||
let refresh: any = null;
|
||||
|
||||
if (accessToken) {
|
||||
access = await this.accessTokens.verify(accessToken);
|
||||
if (!access.username || !access.sub) {
|
||||
try {
|
||||
access = await this.accessTokens.verify(accessToken);
|
||||
} catch (err) {
|
||||
if (!(err instanceof TokenExpiredError)) {
|
||||
return {
|
||||
validation: false,
|
||||
userId: null,
|
||||
username: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
if (access && (!access.username || !access.sub)) {
|
||||
return {
|
||||
validation: false,
|
||||
userId: null,
|
||||
@ -75,7 +86,16 @@ export class AuthService {
|
||||
}
|
||||
|
||||
if (refreshToken) {
|
||||
refresh = await this.refreshTokens.verify(refreshToken);
|
||||
try {
|
||||
refresh = await this.refreshTokens.verify(refreshToken);
|
||||
} catch (err) {
|
||||
return {
|
||||
validation: false,
|
||||
userId: null,
|
||||
username: null,
|
||||
};
|
||||
}
|
||||
|
||||
if (!refresh.username || !refresh.sub) {
|
||||
return {
|
||||
validation: false,
|
||||
@ -85,7 +105,19 @@ export class AuthService {
|
||||
}
|
||||
}
|
||||
|
||||
if (accessToken && refreshToken) {
|
||||
if (!access && !refresh) {
|
||||
return {
|
||||
validation: false,
|
||||
userId: null,
|
||||
username: null,
|
||||
};
|
||||
} else if (!access && refresh) {
|
||||
return {
|
||||
validation: null,
|
||||
userId: null,
|
||||
username: null,
|
||||
};
|
||||
} else if (access && refresh) {
|
||||
if (access.username != refresh.username || access.sub != refresh.sub) {
|
||||
return {
|
||||
validation: false,
|
||||
@ -95,29 +127,10 @@ export class AuthService {
|
||||
}
|
||||
}
|
||||
|
||||
if (!accessToken || !access.exp || access.exp * 1000 <= new Date().getTime()) {
|
||||
if (!refreshToken || !refresh.exp || refresh.exp * 1000 <= new Date().getTime()) {
|
||||
// Both expired.
|
||||
return {
|
||||
validation: false,
|
||||
userId: null,
|
||||
username: null,
|
||||
};
|
||||
}
|
||||
|
||||
// Refresh token is still active.
|
||||
return {
|
||||
validation: null,
|
||||
userId: refresh.sub,
|
||||
username: refresh.username,
|
||||
};
|
||||
}
|
||||
|
||||
// Access still active, at least.
|
||||
return {
|
||||
validation: true,
|
||||
userId: access.sub,
|
||||
username: access.username,
|
||||
userId: (access ?? refresh).sub,
|
||||
username: (access ?? refresh).username,
|
||||
};
|
||||
}
|
||||
|
||||
|
@ -0,0 +1,4 @@
|
||||
export class AccessTokenDto {
|
||||
access_token: string;
|
||||
exp: number;
|
||||
}
|
12
backend/nestjs-seshat-api/src/auth/guards/jwt-mixed.guard.ts
Normal file
12
backend/nestjs-seshat-api/src/auth/guards/jwt-mixed.guard.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { ForbiddenException, Injectable } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
|
||||
@Injectable()
|
||||
export class JwtMixedGuard extends AuthGuard(['jwt-access', 'jwt-refresh']) {
|
||||
handleRequest(err, user, info) {
|
||||
if (err || !user) {
|
||||
throw err || new ForbiddenException();
|
||||
}
|
||||
return user;
|
||||
}
|
||||
}
|
@ -3,11 +3,11 @@ import { ForbiddenException, Injectable } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
|
||||
@Injectable()
|
||||
export class OfflineGuard extends AuthGuard('jwt-access') {
|
||||
export class OfflineGuard extends AuthGuard(['jwt-access', 'jwt-refresh']) {
|
||||
handleRequest(err, user, info) {
|
||||
if (err || user) {
|
||||
throw err || new ForbiddenException();
|
||||
}
|
||||
return null;
|
||||
return user;
|
||||
}
|
||||
}
|
||||
|
@ -18,7 +18,6 @@ export class SimplifiedSearchContext {
|
||||
if (provider == 'google') {
|
||||
return new GoogleSearchContext(search, valuesCopy)
|
||||
}
|
||||
console.log('abc4')
|
||||
return null;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user