Skip to content

Commit

Permalink
Merge branch 'stage'
Browse files Browse the repository at this point in the history
  • Loading branch information
August Andersen committed Aug 28, 2024
2 parents c43e461 + ee442fe commit 32c582d
Show file tree
Hide file tree
Showing 372 changed files with 15,616 additions and 16,560 deletions.
2 changes: 1 addition & 1 deletion .jest/setEnvVars.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
process.env.KAFKAJS_LOG_LEVEL='ERROR'
process.env.KAFKAJS_LOG_LEVEL = "ERROR";
11 changes: 0 additions & 11 deletions .prettierrc.js

This file was deleted.

11 changes: 11 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"trailingComma": "es5",
"tabWidth": 2,
"printWidth": 120,
"semi": true,
"singleQuote": false,
"useTabs": false,
"bracketSpacing": true,
"arrowParens": "avoid",
"endOfLine": "auto"
}
952 changes: 540 additions & 412 deletions package-lock.json

Large diffs are not rendered by default.

65 changes: 27 additions & 38 deletions src/auth/api-key.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,47 +10,36 @@ import { ApiKeyHeader, ApiKeyStrategyName, HeaderApiVerifiedCallback } from "./c
const passReqToCallback = false;

@Injectable()
export class ApiKeyStrategy extends PassportStrategy(
HeaderAPIKeyStrategy,
ApiKeyStrategyName
) {
constructor(
private authService: AuthService,
private permissionService: PermissionService
) {
super(
{
header: ApiKeyHeader,
prefix: "",
},
passReqToCallback
);
}
export class ApiKeyStrategy extends PassportStrategy(HeaderAPIKeyStrategy, ApiKeyStrategyName) {
constructor(private authService: AuthService, private permissionService: PermissionService) {
super(
{
header: ApiKeyHeader,
prefix: "",
},
passReqToCallback
);
}

async validate(
apiKey: string,
_done: HeaderApiVerifiedCallback
): Promise<AuthenticatedUser> {
const apiKeyDb = await this.authService.validateApiKey(apiKey);
if (!apiKeyDb) {
throw new UnauthorizedException(ErrorCodes.ApiKeyAuthFailed);
}
async validate(apiKey: string, _done: HeaderApiVerifiedCallback): Promise<AuthenticatedUser> {
const apiKeyDb = await this.authService.validateApiKey(apiKey);
if (!apiKeyDb) {
throw new UnauthorizedException(ErrorCodes.ApiKeyAuthFailed);
}

// Get the permissions and the UserID from the API Key instead of the user
const permissions = await this.permissionService.findPermissionGroupedByLevelForApiKey(
apiKeyDb.id
);
// Get the permissions and the UserID from the API Key instead of the user
const permissions = await this.permissionService.findPermissionGroupedByLevelForApiKey(apiKeyDb.id);

// const permissions = dbApiKey.permissions as Permission[];
const userId = apiKeyDb.systemUser.id;
// const permissions = dbApiKey.permissions as Permission[];
const userId = apiKeyDb.systemUser.id;

// Set the permissions and the userId on the returned user
const user: AuthenticatedUser = {
userId,
username: apiKeyDb.systemUser.name,
permissions,
};
// Set the permissions and the userId on the returned user
const user: AuthenticatedUser = {
userId,
username: apiKeyDb.systemUser.name,
permissions,
};

return user;
}
return user;
}
}
6 changes: 3 additions & 3 deletions src/auth/constants.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { AuthenticatedUser } from "@dto/internal/authenticated-user";

export type HeaderApiVerifiedCallback = (
err: Error | null,
user?: AuthenticatedUser,
info?: Record<string, unknown>
err: Error | null,
user?: AuthenticatedUser,
info?: Record<string, unknown>
) => void;

export const ApiKeyStrategyName = "api-key";
Expand Down
30 changes: 15 additions & 15 deletions src/auth/custom-exception-filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,21 @@ import { RedirectingException } from "./redirecting-exception";

@Catch(HttpException)
export class CustomExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost): void {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status = exception.getStatus();
catch(exception: HttpException, host: ArgumentsHost): void {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status = exception.getStatus();

if (status == 302) {
const asRedirectingException = exception as RedirectingException;
return response.redirect(asRedirectingException.url);
}

response.status(status).json({
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
});
if (status == 302) {
const asRedirectingException = exception as RedirectingException;
return response.redirect(asRedirectingException.url);
}

response.status(status).json({
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
});
}
}
24 changes: 12 additions & 12 deletions src/auth/handle-redirect-url-parameter.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,18 @@ import { Request, Response } from "express";

@Injectable()
export class HandleRedirectUrlParameterMiddleware implements NestMiddleware {
private readonly logger = new Logger(HandleRedirectUrlParameterMiddleware.name);
private readonly logger = new Logger(HandleRedirectUrlParameterMiddleware.name);

// eslint-disable-next-line @typescript-eslint/ban-types
use(req: Request, res: Response, next: Function): void {
const redirectParam = req.query["redirect"];
if (redirectParam) {
this.logger.debug(`Has 'redirect' param: ${redirectParam}`);
res.cookie("redirect", redirectParam, {
expires: new Date(Date.now() + 900000),
});
}

next();
// eslint-disable-next-line @typescript-eslint/ban-types
use(req: Request, res: Response, next: Function): void {
const redirectParam = req.query["redirect"];
if (redirectParam) {
this.logger.debug(`Has 'redirect' param: ${redirectParam}`);
res.cookie("redirect", redirectParam, {
expires: new Date(Date.now() + 900000),
});
}

next();
}
}
79 changes: 37 additions & 42 deletions src/auth/jwt.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,51 +10,46 @@ import { JwtStrategyName } from "./constants";

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, JwtStrategyName) {
constructor(
private permissionService: PermissionService,
private userService: UserService,
private configService: ConfigService
) {
super({
// Configure the strategy to look for the JWT token in the Authorization header
jwtFromRequest: ExtractJwt.fromExtractors([
ExtractJwt.fromAuthHeaderAsBearerToken(),
ExtractJwt.fromUrlQueryParameter("secret_token"),
]),
ignoreExpiration: false,
secretOrKey: configService.get<string>("jwt.secret"),
});
}
private readonly logger = new Logger(JwtStrategy.name);

private readonly NAME_ID_FORMAT =
"urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName";
constructor(
private permissionService: PermissionService,
private userService: UserService,
private configService: ConfigService
) {
super({
// Configure the strategy to look for the JWT token in the Authorization header
jwtFromRequest: ExtractJwt.fromExtractors([
ExtractJwt.fromAuthHeaderAsBearerToken(),
ExtractJwt.fromUrlQueryParameter("secret_token"),
]),
ignoreExpiration: false,
secretOrKey: configService.get<string>("jwt.secret"),
});
}
private readonly logger = new Logger(JwtStrategy.name);

async validate(payload: JwtPayloadDto): Promise<AuthenticatedUser> {
// Does the user still exist?
const exists = await this.userService.findOne(payload.sub);
if (!exists) {
this.logger.warn(
`Authorization for user with id: ${payload.sub} failed, since they no longer exists`
);
throw new UnauthorizedException();
}
private readonly NAME_ID_FORMAT = "urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName";

const result: AuthenticatedUser = {
userId: payload.sub,
username: payload.username,
};
async validate(payload: JwtPayloadDto): Promise<AuthenticatedUser> {
// Does the user still exist?
const exists = await this.userService.findOne(payload.sub);
if (!exists) {
this.logger.warn(`Authorization for user with id: ${payload.sub} failed, since they no longer exists`);
throw new UnauthorizedException();
}

if (exists.nameId) {
// Add SAML stuff
result.nameID = exists.nameId;
result.nameIDFormat = this.NAME_ID_FORMAT;
}
// This data is already validated
result.permissions = await this.permissionService.findPermissionGroupedByLevelForUser(
payload.sub
);
const result: AuthenticatedUser = {
userId: payload.sub,
username: payload.username,
};

return result;
if (exists.nameId) {
// Add SAML stuff
result.nameID = exists.nameId;
result.nameIDFormat = this.NAME_ID_FORMAT;
}
// This data is already validated
result.permissions = await this.permissionService.findPermissionGroupedByLevelForUser(payload.sub);

return result;
}
}
55 changes: 20 additions & 35 deletions src/auth/kombit-auth.guard.ts
Original file line number Diff line number Diff line change
@@ -1,47 +1,32 @@
import { ErrorCodes } from "@enum/error-codes.enum";
import {
ExecutionContext,
Injectable,
Logger,
UnauthorizedException,
} from "@nestjs/common";
import { ExecutionContext, Injectable, Logger, UnauthorizedException } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
import { Request as expressRequest, Response } from "express";
import { RedirectingException } from "./redirecting-exception";

@Injectable()
export class KombitAuthGuard extends AuthGuard("kombit") {
constructor() {
super();
}
constructor() {
super();
}

private readonly logger = new Logger(KombitAuthGuard.name);
private readonly logger = new Logger(KombitAuthGuard.name);

handleRequest(
err: any,
user: any,
info: any,
context: ExecutionContext,
status: any
) {
if (err || !user) {
const req: expressRequest = context.switchToHttp().getRequest();
const res: Response = context.switchToHttp().getResponse();
const redirectTarget = req.cookies["redirect"];
this.logger.error(`Login with KOMBIT failed, got error: ${err}`, err);
handleRequest(err: any, user: any, info: any, context: ExecutionContext, status: any) {
if (err || !user) {
const req: expressRequest = context.switchToHttp().getRequest();
const res: Response = context.switchToHttp().getResponse();
const redirectTarget = req.cookies["redirect"];
this.logger.error(`Login with KOMBIT failed, got error: ${err}`, err);

if (redirectTarget) {
const redirectError =
err?.message == ErrorCodes.UserInactive
? ErrorCodes.UserInactive
: ErrorCodes.KOMBITLoginFailed;
throw new RedirectingException(
`${redirectTarget}?error=${redirectError}`
);
} else {
throw new UnauthorizedException(ErrorCodes.MissingRole);
}
}
return user;
if (redirectTarget) {
const redirectError =
err?.message == ErrorCodes.UserInactive ? ErrorCodes.UserInactive : ErrorCodes.KOMBITLoginFailed;
throw new RedirectingException(`${redirectTarget}?error=${redirectError}`);
} else {
throw new UnauthorizedException(ErrorCodes.MissingRole);
}
}
return user;
}
}
Loading

0 comments on commit 32c582d

Please sign in to comment.