Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor/eslint #41

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
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
30 changes: 0 additions & 30 deletions .eslintrc.js

This file was deleted.

13 changes: 13 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { eslintConfig as common } from '@gewis/eslint-config-typescript';
import { eslintConfig as prettier } from '@gewis/prettier-config';

export default [
...common,
// TODO should move to eslint-config-typescript
{
rules: {
'import/no-named-as-default-member': 'off',
},
},
prettier,
];
8 changes: 3 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"gen-client": "nswag openapi2tsclient /input:src/public/swagger.json /output:../parelpracht-client/src/clients/server.generated.ts /ServiceHost:.",
"db:diagram": "typeorm-uml ormconfig.json",
"db:validate": "ts-node src/dbvalidator/validate.ts",
"lint": "eslint src",
"lint": "yarn tsoa && eslint src",
"lint:fix": "eslint . --fix",
"format": "prettier --ignore-path .gitignore --check .",
"format:fix": "prettier --ignore-path .gitignore --write ."
Expand Down Expand Up @@ -52,6 +52,7 @@
"validator": "^13.12.0"
},
"devDependencies": {
"@gewis/eslint-config-typescript": "^2.2.3",
"@gewis/prettier-config": "^2.2.2",
"@types/axios": "^0.14.4",
"@types/express": "5.0.0",
Expand All @@ -70,11 +71,8 @@
"@types/swagger-ui-express": "^4.1.8",
"@types/uuid": "^10.0.0",
"@types/validator": "^13.12.2",
"@typescript-eslint/eslint-plugin": "^8.25.0",
"@typescript-eslint/parser": "^8.25.0",
"concurrently": "^9.1.2",
"eslint": "^8.57.1",
"eslint-plugin-import": "^2.31.0",
"eslint": "^9.21.0",
"nodemon": "^3.1.9",
"ts-node": "^10.9.2",
"typescript": "^5.7.3"
Expand Down
35 changes: 25 additions & 10 deletions src/auth/LDAPStrategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,23 @@ import { Role } from '../entity/Role';
import UserService from '../services/UserService';
import { Roles } from '../entity/enums/Roles';
import AppDataSource from '../database';
import { ExpressRequest } from '../types';

const isDefined = (i: string | undefined) => i !== undefined && i !== '';

export interface LDAPUser {
sAMAccountName: string;
memberOfFlattened: string[];
memberOf: string[];
mail: string;
givenName: string;
sn: string;
}

interface AuthInfo {
message: string;
}

export const ldapEnabled = () =>
isDefined(process.env.LDAP_URL) &&
isDefined(process.env.LDAP_BINDDN) &&
Expand All @@ -28,7 +42,7 @@ export const LDAPStrategy = new Strategy({
},
});

const checkAllowedRoles = async (ldapUser: any): Promise<Roles[]> => {
const checkAllowedRoles = async (ldapUser: LDAPUser): Promise<Roles[]> => {
const roles = await AppDataSource.getRepository(Role).find();
const userRoles: Roles[] = [];
roles.forEach((role) => {
Expand All @@ -39,22 +53,23 @@ const checkAllowedRoles = async (ldapUser: any): Promise<Roles[]> => {
return userRoles;
};

export const updateUserInformation = async (user: User, ldapUser: any): Promise<User> => {
export const updateUserInformation = async (user: User, ldapUser: LDAPUser): Promise<User> => {
const userRoles = await checkAllowedRoles(ldapUser);
await new UserService().assignRoles(user, userRoles);

const identity = user.identityLdap;
// eslint-disable-next-line no-param-reassign

if (identity && !identity.overrideEmail) user.email = ldapUser.mail;
// eslint-disable-next-line no-param-reassign

user.firstName = ldapUser.givenName;
// eslint-disable-next-line no-param-reassign

user.lastName = ldapUser.sn;
return user.save();
};

export const ldapLogin = (req: express.Request, res: express.Response, next: express.NextFunction) => {
passport.authenticate('ldapauth', async (err: any, ldapUser: any, info: any) => {
export const ldapLogin = (req: ExpressRequest, res: express.Response, next: express.NextFunction) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call -- this seems to be correct
passport.authenticate('ldapauth', async (err: Error, ldapUser: LDAPUser, info: AuthInfo) => {
if (err) {
return next(err);
}
Expand Down Expand Up @@ -84,13 +99,13 @@ export const ldapLogin = (req: express.Request, res: express.Response, next: exp
lastName: ldapUser.sn,
email: ldapUser.mail,
function: '',
} as any as User;
} as User;
user = await userRepo.save(user);

identity = {
id: user.id,
username: ldapUser.sAMAccountName,
} as any as IdentityLDAP;
} as IdentityLDAP;
identity = await identityRepo.save(identity);
identity = await identityRepo.findOne({
where: { id: identity.id },
Expand All @@ -104,7 +119,7 @@ export const ldapLogin = (req: express.Request, res: express.Response, next: exp

await updateUserInformation(identity.user, ldapUser);

return req.logIn(identity.user, (e: any) => {
return req.logIn(identity.user, (e: Error) => {
// When the user enabled "remember me", we give the session cookie an
// expiration date of 30 days
if (req.body.rememberMe === true) {
Expand Down
11 changes: 7 additions & 4 deletions src/auth/LocalStrategy.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { Strategy as LocalStrategy } from 'passport-local';
import crypto from 'crypto';
import { Strategy as LocalStrategy } from 'passport-local';
import passport from 'passport';
import express from 'express';
import validator from 'validator';
import { IdentityLocal } from '../entity/IdentityLocal';
import { User } from '../entity/User';
import { ApiError, HTTPStatus } from '../helpers/error';
import AppDataSource from '../database';
import { ExpressRequest } from '../types';

const INVALID_LOGIN = 'Invalid email or password.';
const VERIFY_ACCOUNT = 'Please verify your account and set your password with the link received by email.';
Expand All @@ -32,6 +33,7 @@ export default new LocalStrategy(
usernameField: 'email',
passwordField: 'password',
},
// eslint-disable-next-line @typescript-eslint/no-misused-promises -- async is allowed here
async (email, password, done) => {
const userRepo = AppDataSource.getRepository(User);
const identityRepo = AppDataSource.getRepository(IdentityLocal);
Expand Down Expand Up @@ -67,15 +69,16 @@ export default new LocalStrategy(
},
);

export const localLogin = (req: express.Request, res: express.Response, next: express.NextFunction) => {
passport.authenticate('local', (err: any, user: any) => {
export const localLogin = (req: ExpressRequest, res: express.Response, next: express.NextFunction) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call -- this seems to be correct
passport.authenticate('local', (err: Error, user: User) => {
if (err) {
return next(err);
}
if (!user) {
return next(new ApiError(HTTPStatus.BadRequest, INVALID_LOGIN));
}
return req.logIn(user, (e: any) => {
return req.logIn(user, (e: Error) => {
// When the user enabled "remember me", we give the session cookie an
// expiration date of 30 days
if (req.body.rememberMe === true) {
Expand Down
6 changes: 3 additions & 3 deletions src/auth/authentication.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import express from 'express';
import { IdentityApiKey } from '../entity/IdentityApiKey';
import { User } from '../entity/User';
import { ApiError, HTTPStatus } from '../helpers/error';
import AppDataSource from '../database';
import { ExpressRequest } from '../types';

async function authWithApiKey(apiKey: string) {
const split = apiKey.split(' ');
Expand All @@ -22,10 +22,10 @@ async function authWithApiKey(apiKey: string) {
}

export async function expressAuthentication(
request: express.Request,
request: ExpressRequest,
securityName: string,
scopes?: string[],
): Promise<any> {
): Promise<unknown> {
switch (securityName) {
case 'local': {
const auth = request.header('Authentication');
Expand Down
28 changes: 14 additions & 14 deletions src/controllers/CompanyController.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Body, Tags, Controller, Post, Route, Put, Get, Security, Response, Delete, Request } from 'tsoa';
import express from 'express';
import { Readable } from 'stream';
import { body } from 'express-validator';
import { Company } from '../entity/Company';
import { Invoice } from '../entity/Invoice';
Expand All @@ -11,7 +10,6 @@ import CompanyService, {
CompanySummary,
ETCompanyListResponse,
} from '../services/CompanyService';
import { ListParams } from './ListParams';
import ActivityService, { ActivityParams, FullActivityParams } from '../services/ActivityService';
import BaseActivity from '../entity/activity/BaseActivity';
import { CompanyActivity } from '../entity/activity/CompanyActivity';
Expand All @@ -26,11 +24,14 @@ import BaseFile from '../entity/file/BaseFile';
import { CompanyFile } from '../entity/file/CompanyFile';
import StatisticsService, { ContractedProductsAnalysis } from '../services/StatisticsService';
import { Roles } from '../entity/enums/Roles';
import { ExpressRequest } from '../types';
import { ListParams } from './ListParams';
import { Body, Tags, Controller, Post, Route, Put, Get, Security, Response, Delete, Request } from 'tsoa';

@Route('company')
@Tags('Company')
export class CompanyController extends Controller {
private async validateCompanyParams(req: express.Request): Promise<void> {
private async validateCompanyParams(req: ExpressRequest): Promise<void> {
await validate(
[
body('name').notEmpty().trim(),
Expand Down Expand Up @@ -103,7 +104,7 @@ export class CompanyController extends Controller {
@Post()
@Security('local', ['ADMIN'])
@Response<WrappedApiError>(401)
public async createCompany(@Body() params: CompanyParams, @Request() req: express.Request): Promise<Company> {
public async createCompany(@Body() params: CompanyParams, @Request() req: ExpressRequest): Promise<Company> {
await this.validateCompanyParams(req);
return new CompanyService().createCompany(params);
}
Expand All @@ -120,7 +121,7 @@ export class CompanyController extends Controller {
public async updateCompany(
id: number,
@Body() params: Partial<CompanyParams>,
@Request() req: express.Request,
@Request() req: ExpressRequest,
): Promise<Company> {
await this.validateCompanyParams(req);
return new CompanyService({ actor: req.user as User }).updateCompany(id, params);
Expand All @@ -129,7 +130,6 @@ export class CompanyController extends Controller {
/**
* Delete company
* @param id ID of the company to delete
* @param req Express.js request object
*/
@Delete('{id}')
@Security('local', ['ADMIN'])
Expand All @@ -146,7 +146,7 @@ export class CompanyController extends Controller {
@Put('{id}/logo')
@Security('local', ['GENERAL', 'ADMIN'])
@Response<WrappedApiError>(401)
public async uploadCompanyLogo(@Request() req: express.Request, id: number) {
public async uploadCompanyLogo(@Request() req: ExpressRequest, id: number) {
await FileService.uploadCompanyLogo(req, id);
}

Expand Down Expand Up @@ -198,7 +198,7 @@ export class CompanyController extends Controller {
@Post('{id}/file/upload')
@Security('local', ['GENERAL', 'ADMIN'])
@Response<WrappedApiError>(401)
public async uploadCompanyFile(id: number, @Request() req: express.Request): Promise<CompanyFile> {
public async uploadCompanyFile(id: number, @Request() req: ExpressRequest): Promise<CompanyFile> {
const actor = req.user as User;
if (req.body.createdAt !== undefined && !actor.hasRole(Roles.ADMIN)) {
throw new ApiError(
Expand All @@ -207,7 +207,7 @@ export class CompanyController extends Controller {
);
}

return new FileService(CompanyFile, { actor: req.user as User }).uploadFile(req, id);
return (await new FileService(CompanyFile, { actor: req.user as User }).uploadFile(req, id)) as CompanyFile;
}

/**
Expand All @@ -219,7 +219,7 @@ export class CompanyController extends Controller {
@Get('{id}/file/{fileId}')
@Security('local', ['GENERAL', 'ADMIN'])
@Response<WrappedApiError>(401)
public async getCompanyFile(id: number, fileId: number): Promise<any> {
public async getCompanyFile(id: number, fileId: number): Promise<Readable> {
const file = <CompanyFile>await new FileService(CompanyFile).getFile(id, fileId);

return FileHelper.putFileInResponse(this, file);
Expand All @@ -239,7 +239,7 @@ export class CompanyController extends Controller {
id: number,
fileId: number,
@Body() params: Partial<FileParams>,
@Request() req: express.Request,
@Request() req: ExpressRequest,
): Promise<BaseFile> {
await validateFileParams(req);
return new FileService(CompanyFile).updateFile(id, fileId, params);
Expand Down Expand Up @@ -269,7 +269,7 @@ export class CompanyController extends Controller {
public async addCompanyComment(
id: number,
@Body() params: ActivityParams,
@Request() req: express.Request,
@Request() req: ExpressRequest,
): Promise<BaseActivity> {
await validateCommentParams(req);
const p: FullActivityParams = {
Expand All @@ -294,7 +294,7 @@ export class CompanyController extends Controller {
id: number,
activityId: number,
@Body() params: Partial<ActivityParams>,
@Request() req: express.Request,
@Request() req: ExpressRequest,
): Promise<BaseActivity> {
await validateActivityParams(req);
const p: Partial<FullActivityParams> = {
Expand Down
14 changes: 7 additions & 7 deletions src/controllers/ContactController.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import { Body, Controller, Post, Route, Put, Tags, Get, Security, Response, Request, Delete } from 'tsoa';
import { body } from 'express-validator';
import express from 'express';
import { Contact } from '../entity/Contact';
import { WrappedApiError } from '../helpers/error';
import ContactService, { ContactListResponse, ContactParams, ContactSummary } from '../services/ContactService';
import { ListParams } from './ListParams';
import { validate } from '../helpers/validation';
import { Gender } from '../entity/enums/Gender';
import { ContactFunction } from '../entity/enums/ContactFunction';
import { ExpressRequest } from '../types';
import { ListParams } from './ListParams';
import { Body, Controller, Post, Route, Put, Tags, Get, Security, Response, Request, Delete } from 'tsoa';

@Route('contact')
@Tags('Contact')
export class ContactController extends Controller {
private async validateContactParams(req: express.Request) {
private async validateContactParams(req: ExpressRequest) {
const emailOptionalFunctions = [
ContactFunction.SIGNATORY_AUTHORIZED,
ContactFunction.ASSISTING,
Expand Down Expand Up @@ -80,7 +80,7 @@ export class ContactController extends Controller {
@Post()
@Security('local', ['GENERAL', 'ADMIN'])
@Response<WrappedApiError>(401)
public async createContact(@Body() params: ContactParams, @Request() req: express.Request): Promise<Contact> {
public async createContact(@Body() params: ContactParams, @Request() req: ExpressRequest): Promise<Contact> {
await this.validateContactParams(req);
return new ContactService().createContact(params);
}
Expand All @@ -89,15 +89,15 @@ export class ContactController extends Controller {
* updateContact() - update contact
* @param id ID of contact to update
* @param params Update subset of parameter of contact
* @param req: express.Request
* @param req: ExpressRequest
*/
@Put('{id}')
@Security('local', ['GENERAL', 'ADMIN'])
@Response<WrappedApiError>(401)
public async updateContact(
id: number,
@Body() params: Partial<ContactParams>,
@Request() req: express.Request,
@Request() req: ExpressRequest,
): Promise<Contact> {
await this.validateContactParams(req);
return new ContactService().updateContact(id, params);
Expand Down
Loading