Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions backend/src/authorization/auth-with-api.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,20 @@ export class AuthWithApiMiddleware implements NestMiddleware {
const jwtSecret = process.env.JWT_SECRET;
const data = jwt.verify(tokenFromCookie, jwtSecret) as jwt.JwtPayload;
const userId = data.id;

if (!userId) {
throw new UnauthorizedException('JWT verification failed');
}

const userExists = await this.userRepository.findOne({ where: { id: userId } });
if (!userExists) {
throw new UnauthorizedException('JWT verification failed');
}

if (userExists.suspended) {
throw new UnauthorizedException(Messages.ACCOUNT_SUSPENDED);
}

const addedScope: Array<JwtScopesEnum> = data.scope;
if (addedScope && addedScope.length > 0) {
if (addedScope.includes(JwtScopesEnum.TWO_FA_ENABLE)) {
Expand Down Expand Up @@ -104,13 +115,14 @@ export class AuthWithApiMiddleware implements NestMiddleware {
.where('api_key.hash = :hash', { hash: apiKeyHash })
.getOne();

if (!foundUserByApiKey) {
throw new NotFoundException(Messages.NO_AUTH_KEYS_FOUND);
}

if (foundUserByApiKey.suspended) {
throw new UnauthorizedException(Messages.API_KEY_SUSPENDED);
}

if (!foundUserByApiKey) {
throw new NotFoundException(Messages.NO_AUTH_KEYS_FOUND);
}
req.decoded = {
sub: foundUserByApiKey.id,
email: foundUserByApiKey.email,
Expand Down
130 changes: 71 additions & 59 deletions backend/src/authorization/auth.middleware.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import {
BadRequestException,
HttpException,
Injectable,
InternalServerErrorException,
NestMiddleware,
UnauthorizedException,
BadRequestException,
HttpException,
Injectable,
InternalServerErrorException,
NestMiddleware,
UnauthorizedException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Response } from 'express';
Expand All @@ -21,61 +21,73 @@ import { IRequestWithCognitoInfo } from './cognito-decoded.interface.js';

@Injectable()
export class AuthMiddleware implements NestMiddleware {
public constructor(
@InjectRepository(UserEntity)readonly _userRepository: Repository<UserEntity>,
@InjectRepository(LogOutEntity)
private readonly logOutRepository: Repository<LogOutEntity>,
) {}
async use(req: IRequestWithCognitoInfo, _res: Response, next: (err?: any, res?: any) => void): Promise<void> {
let token: string;
try {
token = req.cookies[Constants.JWT_COOKIE_KEY_NAME];
} catch (_e) {
if (process.env.NODE_ENV !== 'test') {
throw new UnauthorizedException('JWT verification failed');
}
}
public constructor(
@InjectRepository(UserEntity)
private readonly userRepository: Repository<UserEntity>,
@InjectRepository(LogOutEntity)
private readonly logOutRepository: Repository<LogOutEntity>,
) {}
async use(req: IRequestWithCognitoInfo, _res: Response, next: (err?: any, res?: any) => void): Promise<void> {
let token: string;
try {
token = req.cookies[Constants.JWT_COOKIE_KEY_NAME];
} catch (_e) {
if (process.env.NODE_ENV !== 'test') {
throw new UnauthorizedException('JWT verification failed');
}
}

if (!token) {
throw new UnauthorizedException('Token is missing');
}
if (!token) {
throw new UnauthorizedException('Token is missing');
}

const isLoggedOut = !!(await this.logOutRepository.findOne({ where: { jwtToken: token } }));
if (isLoggedOut) {
throw new UnauthorizedException('Token is invalid');
}
const isLoggedOut = !!(await this.logOutRepository.findOne({ where: { jwtToken: token } }));
if (isLoggedOut) {
throw new UnauthorizedException('Token is invalid');
}

try {
const jwtSecret = process.env.JWT_SECRET;
const data = jwt.verify(token, jwtSecret) as jwt.JwtPayload;
const userId = data.id;
if (!userId) {
throw new UnauthorizedException('JWT verification failed');
}
const addedScope: Array<JwtScopesEnum> = data.scope;
if (addedScope && addedScope.length > 0) {
if (addedScope.includes(JwtScopesEnum.TWO_FA_ENABLE)) {
throw new BadRequestException(Messages.TWO_FA_REQUIRED);
}
}
try {
const jwtSecret = process.env.JWT_SECRET;
const data = jwt.verify(token, jwtSecret) as jwt.JwtPayload;
const userId = data.id;

const payload = {
sub: userId,
email: data.email,
exp: data.exp,
iat: data.iat,
};
if (!payload || isObjectEmpty(payload)) {
throw new UnauthorizedException('JWT verification failed');
}
req.decoded = payload;
next();
} catch (e) {
Sentry.captureException(e);
if (e instanceof HttpException || e instanceof UnauthorizedException) {
throw e;
}
throw new InternalServerErrorException(Messages.AUTHORIZATION_REJECTED);
}
}
if (!userId) {
throw new UnauthorizedException('JWT verification failed');
}

const userExists = await this.userRepository.findOne({ where: { id: userId } });
if (!userExists) {
throw new UnauthorizedException('JWT verification failed');
}

if (userExists.suspended) {
throw new UnauthorizedException(Messages.ACCOUNT_SUSPENDED);
}

const addedScope: Array<JwtScopesEnum> = data.scope;
if (addedScope && addedScope.length > 0) {
if (addedScope.includes(JwtScopesEnum.TWO_FA_ENABLE)) {
throw new BadRequestException(Messages.TWO_FA_REQUIRED);
}
}

const payload = {
sub: userId,
email: data.email,
exp: data.exp,
iat: data.iat,
};
if (!payload || isObjectEmpty(payload)) {
throw new UnauthorizedException('JWT verification failed');
}
req.decoded = payload;
next();
} catch (e) {
Sentry.captureException(e);
if (e instanceof HttpException || e instanceof UnauthorizedException) {
throw e;
}
throw new InternalServerErrorException(Messages.AUTHORIZATION_REJECTED);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -658,5 +658,5 @@ test.serial(`${currentTest} should delete company`, async (t) => {
.set('Cookie', adminUserToken)
.set('Accept', 'application/json');

t.is(foundCompanyInfoAfterDelete.status, 403);
t.is(foundCompanyInfoAfterDelete.status, 401);
});
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ test.serial(`${currentTest} should return user deletion result`, async (t) => {
.set('Cookie', token)
.set('Content-Type', 'application/json')
.set('Accept', 'application/json');
t.is(getUserResult.status, 404);
t.is(getUserResult.status, 401);
t.pass();
});

Expand Down
4 changes: 2 additions & 2 deletions backend/test/ava-tests/saas-tests/company-info-e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -726,7 +726,7 @@ test.serial(`${currentTest} should delete company`, async (t) => {
.set('Cookie', adminUserToken)
.set('Accept', 'application/json');

t.is(foundCompanyInfoAfterDelete.status, 403);
t.is(foundCompanyInfoAfterDelete.status, 401);
});

currentTest = `PUT company/2fa/:companyId`;
Expand Down Expand Up @@ -905,7 +905,7 @@ test.serial(
.set('Accept', 'application/json');

const findAllConnectionsResponseRO = JSON.parse(findAllConnectionsResponse.text);
t.is(findAllConnectionsResponse.status, 403);
t.is(findAllConnectionsResponse.status, 401);
t.is(findAllConnectionsResponseRO.message, Messages.ACCOUNT_SUSPENDED);
},
);
Expand Down
2 changes: 1 addition & 1 deletion backend/test/ava-tests/saas-tests/user-e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ test.serial(`${currentTest} should return user deletion result`, async (t) => {
.set('Cookie', token)
.set('Content-Type', 'application/json')
.set('Accept', 'application/json');
t.is(getUserResult.status, 404);
t.is(getUserResult.status, 401);
t.pass();
});

Expand Down
Loading