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 { UserEntity } from 'src/users/entities/users.entity';
|
||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { PinoLogger } from 'nestjs-pino';
|
import { PinoLogger } from 'nestjs-pino';
|
||||||
|
import { AccessTokenDto } from './dto/access-token.dto';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AuthAccessService {
|
export class AuthAccessService {
|
||||||
@@ -13,7 +14,7 @@ export class AuthAccessService {
|
|||||||
private logger: PinoLogger,
|
private logger: PinoLogger,
|
||||||
) { }
|
) { }
|
||||||
|
|
||||||
async generate(user: UserEntity) {
|
async generate(user: UserEntity): Promise<AccessTokenDto> {
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const limit = parseInt(this.config.getOrThrow<string>('AUTH_JWT_ACCESS_TOKEN_EXPIRATION_MS'));
|
const limit = parseInt(this.config.getOrThrow<string>('AUTH_JWT_ACCESS_TOKEN_EXPIRATION_MS'));
|
||||||
const expiration = moment(now).add(limit, 'ms').toDate();
|
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 { 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 { LoginDto } from './dto/login.dto';
|
import { LoginDto } from './dto/login.dto';
|
||||||
import { AuthenticationDto } from './dto/authentication.dto';
|
import { AuthenticationDto } from './dto/authentication.dto';
|
||||||
import { AppConfig } from 'src/asset/config/app-config';
|
import { AppConfig } from 'src/asset/config/app-config';
|
||||||
|
import { JwtMixedGuard } from './guards/jwt-mixed.guard';
|
||||||
|
|
||||||
@Controller('auth')
|
@Controller('auth')
|
||||||
export class AuthController {
|
export class AuthController {
|
||||||
@@ -93,22 +93,23 @@ export class AuthController {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@UseGuards(JwtAccessGuard)
|
@UseGuards(JwtMixedGuard)
|
||||||
@Delete('login')
|
@Delete('login')
|
||||||
async logout(
|
async logout(
|
||||||
@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');
|
||||||
response.clearCookie('Refresh');
|
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.
|
// User has already logged off.
|
||||||
this.logger.info({
|
this.logger.info({
|
||||||
class: AuthController.name,
|
class: AuthController.name,
|
||||||
method: this.login.name,
|
method: this.logout.name,
|
||||||
user: req.user,
|
user: req.user,
|
||||||
msg: 'User has already logged off based on ' + (!refreshToken ? 'cookies' : 'database'),
|
msg: 'User has already logged off based on ' + (!refreshToken ? 'cookies' : 'database'),
|
||||||
});
|
});
|
||||||
@@ -116,7 +117,7 @@ export class AuthController {
|
|||||||
response.statusCode = 400;
|
response.statusCode = 400;
|
||||||
return {
|
return {
|
||||||
success: false,
|
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({
|
this.logger.info({
|
||||||
class: AuthController.name,
|
class: AuthController.name,
|
||||||
method: this.login.name,
|
method: this.refresh.name,
|
||||||
user: req.user,
|
user: req.user,
|
||||||
refresh_token: req.cookies.Refresh,
|
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);
|
const data = await this.auth.renew(req.user);
|
||||||
|
|
||||||
response.cookie('Authentication', data.access_token, {
|
response.cookie('Authentication', data.access_token, {
|
||||||
@@ -162,22 +181,6 @@ export class AuthController {
|
|||||||
msg: 'Updated Authentication cookie for access token.',
|
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 };
|
return { success: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -6,6 +6,8 @@ import { AuthAccessService } from './auth.access.service';
|
|||||||
import { UUID } from 'crypto';
|
import { UUID } from 'crypto';
|
||||||
import { AuthenticationDto } from './dto/authentication.dto';
|
import { AuthenticationDto } from './dto/authentication.dto';
|
||||||
import { LoginDto } from './dto/login.dto';
|
import { LoginDto } from './dto/login.dto';
|
||||||
|
import { AccessTokenDto } from './dto/access-token.dto';
|
||||||
|
import { TokenExpiredError } from '@nestjs/jwt';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AuthService {
|
export class AuthService {
|
||||||
@@ -18,35 +20,34 @@ export class AuthService {
|
|||||||
|
|
||||||
async login(
|
async login(
|
||||||
loginDetails: LoginDto
|
loginDetails: LoginDto
|
||||||
): Promise<AuthenticationDto | null> {
|
): Promise<AuthenticationDto> {
|
||||||
const user = await this.users.findOne(loginDetails);
|
const user = await this.users.findOne(loginDetails);
|
||||||
if (!user) {
|
if (!user) {
|
||||||
throw new UnauthorizedException();
|
throw new UnauthorizedException();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (loginDetails.remember_me) {
|
const access_token = await this.accessTokens.generate(user);
|
||||||
return this.renew(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 {
|
return {
|
||||||
...access_token,
|
...access_token,
|
||||||
refresh_token: null,
|
refresh_token: refresh_token.refresh_token,
|
||||||
refresh_exp: null,
|
refresh_exp: refresh_token.exp,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async renew(
|
async renew(
|
||||||
user: UserEntity,
|
user: UserEntity,
|
||||||
): Promise<AuthenticationDto | null> {
|
): Promise<AccessTokenDto> {
|
||||||
const new_refresh_data = await this.refreshTokens.generate(user);
|
return await this.accessTokens.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,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async validate(
|
async validate(
|
||||||
@@ -64,8 +65,18 @@ export class AuthService {
|
|||||||
let refresh: any = null;
|
let refresh: any = null;
|
||||||
|
|
||||||
if (accessToken) {
|
if (accessToken) {
|
||||||
access = await this.accessTokens.verify(accessToken);
|
try {
|
||||||
if (!access.username || !access.sub) {
|
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 {
|
return {
|
||||||
validation: false,
|
validation: false,
|
||||||
userId: null,
|
userId: null,
|
||||||
@@ -75,7 +86,16 @@ export class AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (refreshToken) {
|
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) {
|
if (!refresh.username || !refresh.sub) {
|
||||||
return {
|
return {
|
||||||
validation: false,
|
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) {
|
if (access.username != refresh.username || access.sub != refresh.sub) {
|
||||||
return {
|
return {
|
||||||
validation: false,
|
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 {
|
return {
|
||||||
validation: true,
|
validation: true,
|
||||||
userId: access.sub,
|
userId: (access ?? refresh).sub,
|
||||||
username: access.username,
|
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';
|
import { AuthGuard } from '@nestjs/passport';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class OfflineGuard extends AuthGuard('jwt-access') {
|
export class OfflineGuard extends AuthGuard(['jwt-access', 'jwt-refresh']) {
|
||||||
handleRequest(err, user, info) {
|
handleRequest(err, user, info) {
|
||||||
if (err || user) {
|
if (err || user) {
|
||||||
throw err || new ForbiddenException();
|
throw err || new ForbiddenException();
|
||||||
}
|
}
|
||||||
return null;
|
return user;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -18,7 +18,6 @@ export class SimplifiedSearchContext {
|
|||||||
if (provider == 'google') {
|
if (provider == 'google') {
|
||||||
return new GoogleSearchContext(search, valuesCopy)
|
return new GoogleSearchContext(search, valuesCopy)
|
||||||
}
|
}
|
||||||
console.log('abc4')
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
Reference in New Issue
Block a user