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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
2 changes: 1 addition & 1 deletion autoadmin-ws-server/src/constants/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const CONSTANTS = Object.freeze({

RES_CACHE_OPTIONS: {
max: 5000,
dispose: function(key, n) {
dispose: (_key, n) => {
n?.send('Connection was closed by timeout');
},
maxAge: 600000,
Expand Down
8 changes: 4 additions & 4 deletions autoadmin-ws-server/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ import axios from 'axios';
const app = express();
import { createServer } from 'http';
const httpServer = createServer(app);
const wsServer = createServer((req, res) => {
const wsServer = createServer((_req, res) => {
res.writeHead(200);
res.end();
});
import WebSocket, { WebSocketServer } from 'ws';
const router = Router();
const _router = Router();
import commandRoute from './routes/command.js';
import {
getCacheWsConnection,
Expand All @@ -29,7 +29,7 @@ const tokenCacheResult = new LRUCache(CONSTANTS.TOKEN_RESULT_CACHE_OPTIONS);

app.use(json());

app.get('/', (req, res) => {
app.get('/', (_req, res) => {
res.json({ status: CONSTANTS.API_IS_RUNNING });
});

Expand All @@ -42,7 +42,7 @@ wsServer.listen(wsPort, () => {
const ws = new WebSocketServer({ server: wsServer });

ws.on('connection', (connection, req) => {
const ip = req.socket.remoteAddress;
const _ip = req.socket.remoteAddress;
// console.log(`Connected ${ip}`);

connection.on('message', async (message) => {
Expand Down
2 changes: 0 additions & 2 deletions backend/src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
import { ScheduleModule } from '@nestjs/schedule';
import { DataSource } from 'typeorm';
import { AppController } from './app.controller.js';
import { GlobalDatabaseContext } from './common/application/global-database-context.js';
import { BaseType, UseCaseType } from './common/data-injection.tokens.js';
Expand Down Expand Up @@ -107,7 +106,6 @@ import { SignInAuditModule } from './entities/user-sign-in-audit/sign-in-audit.m
],
})
export class ApplicationModule implements NestModule {
constructor(private dataSource: DataSource) {}
configure(consumer: MiddlewareConsumer): void {
consumer.apply(AppLoggerMiddleware).forRoutes('*');
}
Expand Down
25 changes: 13 additions & 12 deletions backend/src/authorization/auth-with-api.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import jwt from 'jsonwebtoken';
import Sentry from '@sentry/minimal';
import { Encryptor } from '../helpers/encryption/encryptor.js';
import { EncryptionAlgorithmEnum } from '../enums/encryption-algorithm.enum.js';
import { IRequestWithCognitoInfo } from './cognito-decoded.interface.js';

@Injectable()
export class AuthWithApiMiddleware implements NestMiddleware {
Expand All @@ -27,7 +28,7 @@ export class AuthWithApiMiddleware implements NestMiddleware {
private readonly userRepository: Repository<UserEntity>,
) {}

async use(req: Request, res: Response, next: (err?: any, res?: any) => void): Promise<void> {
async use(req: IRequestWithCognitoInfo, _res: Response, next: (err?: any, res?: any) => void): Promise<void> {
try {
await this.authenticateRequest(req);
next();
Expand All @@ -37,7 +38,7 @@ export class AuthWithApiMiddleware implements NestMiddleware {
}
}

private async authenticateRequest(req: Request): Promise<void> {
private async authenticateRequest(req: IRequestWithCognitoInfo): Promise<void> {
const tokenFromCookie = this.getTokenFromCookie(req);
if (tokenFromCookie) {
await this.authenticateWithToken(tokenFromCookie, req);
Expand All @@ -57,15 +58,15 @@ export class AuthWithApiMiddleware implements NestMiddleware {
throw new InternalServerErrorException(Messages.AUTHORIZATION_REJECTED);
}

private async authenticateWithToken(tokenFromCookie: string, req: Request): Promise<void> {
private async authenticateWithToken(tokenFromCookie: string, req: IRequestWithCognitoInfo): Promise<void> {
try {
const jwtSecret = process.env.JWT_SECRET;
const data = jwt.verify(tokenFromCookie, jwtSecret);
const userId = data['id'];
const data = jwt.verify(tokenFromCookie, jwtSecret) as jwt.JwtPayload;
const userId = data.id;
if (!userId) {
throw new UnauthorizedException('JWT verification failed');
}
const addedScope: Array<JwtScopesEnum> = data['scope'];
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);
Expand All @@ -74,21 +75,21 @@ export class AuthWithApiMiddleware implements NestMiddleware {

const payload = {
sub: userId,
email: data['email'],
exp: data['exp'],
iat: data['iat'],
email: data.email,
exp: data.exp,
iat: data.iat,
};
if (!payload || isObjectEmpty(payload)) {
throw new UnauthorizedException('JWT verification failed');
}
req['decoded'] = payload;
req.decoded = payload;
} catch (error) {
Sentry.captureException(error);
throw error;
}
}

private async authenticateWithApiKey(req: Request): Promise<void> {
private async authenticateWithApiKey(req: IRequestWithCognitoInfo): Promise<void> {
let apiKey = req.headers?.['x-api-key'];
if (Array.isArray(apiKey)) {
apiKey = apiKey[0];
Expand All @@ -106,7 +107,7 @@ export class AuthWithApiMiddleware implements NestMiddleware {
if (!foundUserByApiKey) {
throw new NotFoundException(Messages.NO_AUTH_KEYS_FOUND);
}
req['decoded'] = {
req.decoded = {
sub: foundUserByApiKey.id,
email: foundUserByApiKey.email,
};
Expand Down
22 changes: 11 additions & 11 deletions backend/src/authorization/auth.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
UnauthorizedException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Request, Response } from 'express';
import { Response } from 'express';
import jwt from 'jsonwebtoken';
import { Repository } from 'typeorm';
import { LogOutEntity } from '../entities/log-out/log-out.entity.js';
Expand All @@ -17,16 +17,16 @@ import { isObjectEmpty } from '../helpers/index.js';
import { Constants } from '../helpers/constants/constants.js';
import Sentry from '@sentry/minimal';
import { JwtScopesEnum } from '../entities/user/enums/jwt-scopes.enum.js';
import { IRequestWithCognitoInfo } from './cognito-decoded.interface.js';

@Injectable()
export class AuthMiddleware implements NestMiddleware {
public constructor(
@InjectRepository(UserEntity)
private readonly userRepository: Repository<UserEntity>,
@InjectRepository(UserEntity)readonly _userRepository: Repository<UserEntity>,
@InjectRepository(LogOutEntity)
private readonly logOutRepository: Repository<LogOutEntity>,
) {}
async use(req: Request, res: Response, next: (err?: any, res?: any) => void): Promise<void> {
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];
Expand All @@ -47,12 +47,12 @@ export class AuthMiddleware implements NestMiddleware {

try {
const jwtSecret = process.env.JWT_SECRET;
const data = jwt.verify(token, jwtSecret);
const userId = data['id'];
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'];
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);
Expand All @@ -61,14 +61,14 @@ export class AuthMiddleware implements NestMiddleware {

const payload = {
sub: userId,
email: data['email'],
exp: data['exp'],
iat: data['iat'],
email: data.email,
exp: data.exp,
iat: data.iat,
};
if (!payload || isObjectEmpty(payload)) {
throw new UnauthorizedException('JWT verification failed');
}
req['decoded'] = payload;
req.decoded = payload;
next();
} catch (e) {
Sentry.captureException(e);
Expand Down
2 changes: 1 addition & 1 deletion backend/src/authorization/basic-auth.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Messages } from '../exceptions/text/messages.js';

@Injectable()
export class BasicAuthMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: (err?: any, res?: any) => void): void {
use(req: Request, _res: Response, next: (err?: any, res?: any) => void): void {
const basicAuthLogin = process.env.BASIC_AUTH_LOGIN;
const basicAuthPassword = process.env.BASIC_AUTH_PWD;
const userCredentials = auth(req);
Expand Down
5 changes: 3 additions & 2 deletions backend/src/authorization/cognito-decoded.interface.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import type { Request } from 'express';
export interface ICognitoDecodedData {
at_hash: string;
sub: string;
aud: string;
aud: string | string[];
email_verified: boolean;
event_id: string;
token_use: string;
Expand All @@ -15,6 +16,6 @@ export interface ICognitoDecodedData {

export interface IRequestWithCognitoInfo extends Request {
query: any;
decoded: ICognitoDecodedData;
decoded: Partial<ICognitoDecodedData>;
params: any;
}
17 changes: 9 additions & 8 deletions backend/src/authorization/non-scoped-auth.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,23 @@ import {
UnauthorizedException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Request, Response } from 'express';
import { Response } from 'express';
import jwt from 'jsonwebtoken';
import { Repository } from 'typeorm';
import { LogOutEntity } from '../entities/log-out/log-out.entity.js';
import { Messages } from '../exceptions/text/messages.js';
import { isObjectEmpty } from '../helpers/index.js';
import { Constants } from '../helpers/constants/constants.js';
import Sentry from '@sentry/minimal';
import { IRequestWithCognitoInfo } from './cognito-decoded.interface.js';

@Injectable()
export class NonScopedAuthMiddleware implements NestMiddleware {
public constructor(
@InjectRepository(LogOutEntity)
private readonly logOutRepository: Repository<LogOutEntity>,
) {}
async use(req: Request, res: Response, next: (err?: any, res?: any) => void): Promise<void> {
async use(req: IRequestWithCognitoInfo, _res: Response, next: (err?: any, res?: any) => void): Promise<void> {
console.log(`auth middleware triggered ->: ${new Date().toISOString()}`);
let token: string;
try {
Expand All @@ -43,22 +44,22 @@ export class NonScopedAuthMiddleware implements NestMiddleware {

try {
const jwtSecret = process.env.JWT_SECRET;
const data = jwt.verify(token, jwtSecret);
const userId = data['id'];
const data = jwt.verify(token, jwtSecret) as jwt.JwtPayload;
const userId = data.id;
if (!userId) {
throw new UnauthorizedException('JWT verification failed');
}

const payload = {
sub: userId,
email: data['email'],
exp: data['exp'],
iat: data['iat'],
email: data.email,
exp: data.exp,
iat: data.iat,
};
if (!payload || isObjectEmpty(payload)) {
throw new UnauthorizedException('JWT verification failed');
}
req['decoded'] = payload;
req.decoded = payload;
next();
} catch (e) {
Sentry.captureException(e);
Expand Down
11 changes: 6 additions & 5 deletions backend/src/authorization/saas-auth.middleware.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
import { Injectable, NestMiddleware, UnauthorizedException } from '@nestjs/common';
import { Request, Response } from 'express';
import { Response } from 'express';
import jwt from 'jsonwebtoken';
import { Messages } from '../exceptions/text/messages.js';
import { extractTokenFromHeader } from './utils/extract-token-from-header.js';
import { IRequestWithCognitoInfo } from './cognito-decoded.interface.js';

@Injectable()
export class SaaSAuthMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: (err?: any, res?: any) => void): void {
use(req: IRequestWithCognitoInfo, _res: Response, next: (err?: any, res?: any) => void): void {
console.log(`saas auth middleware triggered ->: ${new Date().toISOString()}`);
const token = extractTokenFromHeader(req);
if (!token) {
throw new UnauthorizedException('Token is missing');
}
try {
const jwtSecret = process.env.MICROSERVICE_JWT_SECRET;
const data = jwt.verify(token, jwtSecret);
const requestId = data['request_id'];
const data = jwt.verify(token, jwtSecret) as jwt.JwtPayload;
const requestId = data.request_id;

if (!requestId) {
throw new UnauthorizedException(Messages.AUTHORIZATION_REJECTED);
}

req['decoded'] = data;
req.decoded = data;
next();
} catch (_e) {
throw new UnauthorizedException(Messages.AUTHORIZATION_REJECTED);
Expand Down
20 changes: 10 additions & 10 deletions backend/src/authorization/temporary-auth.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
UnauthorizedException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Request, Response } from 'express';
import { Response } from 'express';
import jwt from 'jsonwebtoken';
import { Repository } from 'typeorm';
import { LogOutEntity } from '../entities/log-out/log-out.entity.js';
Expand All @@ -15,16 +15,16 @@ import { Messages } from '../exceptions/text/messages.js';
import { isObjectEmpty } from '../helpers/index.js';
import Sentry from '@sentry/minimal';
import { Constants } from '../helpers/constants/constants.js';
import { IRequestWithCognitoInfo } from './cognito-decoded.interface.js';

@Injectable()
export class TemporaryAuthMiddleware implements NestMiddleware {
public constructor(
@InjectRepository(UserEntity)
private readonly userRepository: Repository<UserEntity>,
@InjectRepository(UserEntity)readonly _userRepository: Repository<UserEntity>,
@InjectRepository(LogOutEntity)
private readonly logOutRepository: Repository<LogOutEntity>,
) {}
async use(req: Request, res: Response, next: (err?: any, res?: any) => void): Promise<void> {
async use(req: IRequestWithCognitoInfo, _res: Response, next: (err?: any, res?: any) => void): Promise<void> {
console.log(`temporary auth middleware triggered ->: ${new Date().toISOString()}`);
let token: string;
try {
Expand All @@ -46,21 +46,21 @@ export class TemporaryAuthMiddleware implements NestMiddleware {

try {
const jwtSecret = process.env.TEMPORARY_JWT_SECRET;
const data = jwt.verify(token, jwtSecret);
const userId = data['id'];
const data = jwt.verify(token, jwtSecret) as jwt.JwtPayload;
const userId = data.id;
if (!userId) {
throw new UnauthorizedException('JWT verification failed');
}
const payload = {
sub: userId,
email: data['email'],
exp: data['exp'],
iat: data['iat'],
email: data.email,
exp: data.exp,
iat: data.iat,
};
if (!payload || isObjectEmpty(payload)) {
throw new UnauthorizedException('JWT verification failed');
}
req['decoded'] = payload;
req.decoded = payload;
next();
} catch (e) {
Sentry.captureException(e);
Expand Down
4 changes: 0 additions & 4 deletions backend/src/common/application/global-database-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -391,11 +391,7 @@ export class GlobalDatabaseContext implements IGlobalDatabaseContext {

public async commitTransaction(): Promise<void> {
if (!this._queryRunner) return;
try {
await this._queryRunner.commitTransaction();
} catch (e) {
throw e;
}
}

public async rollbackTransaction(): Promise<void> {
Expand Down
Loading
Loading