Skip to content

Commit

Permalink
add error reporting
Browse files Browse the repository at this point in the history
  • Loading branch information
Szotkowski committed Sep 29, 2023
1 parent 38c2b38 commit 9bd05f8
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 38 deletions.
8 changes: 6 additions & 2 deletions src/controllers/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ export class UserController {
const {refreshToken} = requestBody;
if (!refreshToken) {
throw new HttpErrors.Unauthorized(
`Error verifying token: 'refresh token' is null`,
'Error verifying token: refresh token is null',
);
}
const userRefreshData = await this.jwtService.verifyToken(refreshToken);
Expand All @@ -165,8 +165,9 @@ export class UserController {
accessToken: token,
};
} catch (error) {
await this.emailService.sendError('Error verifying token: ' + error);
throw new HttpErrors.Unauthorized(
`Error verifying token: ${error.message}`,
'Error verifying token',
);
}
}
Expand Down Expand Up @@ -316,6 +317,7 @@ export class UserController {
});
return true;
} catch (error) {
await this.emailService.sendError('Failed to update user email verification status: ' + error);
if (error.name === 'TokenExpiredError') {
throw new HttpErrors.UnprocessableEntity(
'Verification token has expired',
Expand Down Expand Up @@ -379,6 +381,7 @@ export class UserController {
await this.userRepository.updateById(user.id, {emailVerified: true});
return true;
} catch (error) {
await this.emailService.sendError('Failed to update user email verification status: ' + error);
if (error.name === 'TokenExpiredError') {
throw new HttpErrors.UnprocessableEntity(
'Verification token has expired',
Expand Down Expand Up @@ -499,6 +502,7 @@ export class UserController {
});
return true;
} catch (error) {
await this.emailService.sendError('Failed to update user email verification status: ' + error);
if (error.name === 'TokenExpiredError') {
throw new HttpErrors.UnprocessableEntity(
'Verification token has expired',
Expand Down
3 changes: 2 additions & 1 deletion src/services/email.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ dotenv.config();
export class EmailService {
constructor() { }

public generateVerificationToken(userId: string): string {
private generateVerificationToken(userId: string): string {
const secret = process.env.JWT_SECRET_EMAIL ?? '';
console.log(secret);
const token = jwt.sign({userId}, secret, {
expiresIn: '1h',
algorithm: 'HS256',
Expand Down
28 changes: 19 additions & 9 deletions src/services/imgur-service.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import {Request, Response} from '@loopback/rest';
import {inject} from '@loopback/core';
import {HttpErrors, Request, Response} from '@loopback/rest';
import fetch from 'cross-fetch';
import * as dotenv from 'dotenv';
import multer from 'multer';
import {EmailService} from '.';
dotenv.config();

export class ImgurService {
private readonly clientId = process.env.IMGUR_CLIENT_ID ?? '';

constructor() {}
constructor(
@inject('services.email')
public emailService: EmailService,
) { }

async savePicture(
request: Request,
Expand All @@ -24,11 +29,13 @@ export class ImgurService {
});
const imgurData = await imgurResponse.json();
if (!imgurData.success) {
throw new Error(`Error in save`);
await this.emailService.sendError('Error in save picture: ' + JSON.stringify(imgurData, null, 2));
throw new HttpErrors.InternalServerError('Error in save picture');
}
return {link: imgurData.data.link, deletehash: imgurData.data.deletehash};
} catch (error) {
throw new Error(`Save error: ${error.message}`);
await this.emailService.sendError('Error in save picture: ' + error);
throw new HttpErrors.InternalServerError('Error in save picture');
}
}

Expand All @@ -45,11 +52,13 @@ export class ImgurService {
);
const imgurData = await imgurResponse.json();
if (!imgurData.success) {
throw new Error(`Error in save`);
await this.emailService.sendError('Error in delete picture: ' + JSON.stringify(imgurData, null, 2));
throw new HttpErrors.InternalServerError('Error in delete picture');
}
return true;
} catch (error) {
throw new Error(`Write error: ${error.message}`);
await this.emailService.sendError('Error in delete picture: ' + error);
throw new HttpErrors.InternalServerError('Error in delete picture');
}
}

Expand All @@ -67,7 +76,7 @@ export class ImgurService {
if (file.mimetype.startsWith('image/')) {
cb(null, true);
} else {
cb(new Error('Only image files are allowed'));
cb(new HttpErrors.UnprocessableEntity('Only image files are allowed'));
}
},
}).single('image');
Expand All @@ -84,10 +93,11 @@ export class ImgurService {
if (request.file) {
return request.file;
} else {
throw new Error(`No file uploaded.`);
throw new HttpErrors.UnprocessableEntity('No file uploaded.');
}
} catch (error) {
throw new Error(`Upload error: ${error.message}`);
await this.emailService.sendError('Error in upload picture: ' + error);
throw new HttpErrors.InternalServerError('Error in upload picture');
}
}
}
12 changes: 9 additions & 3 deletions src/services/jwt-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {repository} from '@loopback/repository';
import {HttpErrors} from '@loopback/rest';
import {UserProfile, securityId} from '@loopback/security';
import {promisify} from 'util';
import {EmailService} from '.';
import {
UserRepository
} from '../repositories';
Expand All @@ -25,6 +26,8 @@ export class JWTService implements TokenService {
private jwtSecret: string,
@inject('authentication.jwt.expiresIn')
private jwtExpiresIn: string,
@inject('services.email')
public emailService: EmailService,
@inject('services.user.service')
public userService: MyUserService,
@repository(UserRepository) protected userRepository: UserRepository,
Expand All @@ -50,8 +53,9 @@ export class JWTService implements TokenService {
},
);
} catch (error) {
await this.emailService.sendError('Error verifying token:' + error);
throw new HttpErrors.Unauthorized(
`Error verifying token : ${error.message}`,
`Error verifying token`,
);
}
return userProfile;
Expand All @@ -75,7 +79,8 @@ export class JWTService implements TokenService {
expiresIn: this.jwtExpiresIn,
});
} catch (error) {
throw new HttpErrors.Unauthorized(`Error encoding token : ${error}`);
await this.emailService.sendError('Error encoding token:' + error);
throw new HttpErrors.Unauthorized(`Error encoding token`);
}
return token;
}
Expand All @@ -99,8 +104,9 @@ export class JWTService implements TokenService {
accessToken: token,
};
} catch (error) {
await this.emailService.sendError(`Error verifying token: ` + error);
throw new HttpErrors.Unauthorized(
`Error verifying token : ${error.message}`,
`Error verifying token`,
);
}
}
Expand Down
73 changes: 50 additions & 23 deletions src/services/vault-service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import {inject} from '@loopback/core';
import {HttpErrors} from '@loopback/rest';
import fetch from 'cross-fetch';
import * as dotenv from 'dotenv';
import * as fs from 'fs';
import {EmailService} from '.';
dotenv.config();

export class VaultService {
Expand All @@ -13,26 +16,33 @@ export class VaultService {
];
private readonly rootToken = process.env.ROOT_VAULT_TOKEN ?? '';

constructor() {
this.checkAndUnsealIfNeeded().catch(error => {
throw new Error('Error during initialization:' + error);
constructor(
@inject('services.email')
public emailService: EmailService,
) {
this.checkAndUnsealIfNeeded().catch(async error => {
await this.emailService.sendError('Error during initialization: ' + error);
throw new HttpErrors.InternalServerError('Error during initialization');
});
}

private async checkAndUnsealIfNeeded(): Promise<void> {
try {
const response = await fetch(`${this.vaultEndpoint}/v1/sys/seal-status`, {
const response = await fetch(`
${this.vaultEndpoint}/v1/sys/seal-status`, {
method: 'GET',
});
if (!response.ok) {
throw new Error(`Status check error: ${response.statusText}`);
await this.emailService.sendError(String('Status check error: ' + JSON.stringify(response, null, 2)));
throw new HttpErrors.InternalServerError('Status check error');
}
const responseData = await response.json();
if (responseData.sealed) {
await this.unseal();
}
} catch (error) {
throw new Error(`Status check error: ${error.message}`);
await this.emailService.sendError('Status check error: ' + error);
throw new HttpErrors.InternalServerError('Status check error');
}
}

Expand All @@ -44,7 +54,8 @@ export class VaultService {
this.unsealKeys[2],
];
for (const key of unsealKeys) {
const response = await fetch(`${this.vaultEndpoint}/v1/sys/unseal`, {
const response = await fetch(
`${this.vaultEndpoint}/v1/sys/unseal`, {
method: 'POST',
headers: {
'X-Vault-Token': this.rootToken,
Expand All @@ -55,11 +66,13 @@ export class VaultService {
}),
});
if (!response.ok) {
throw new Error(`Unseal error`);
await this.emailService.sendError(String('Unseal error: ' + JSON.stringify(response, null, 2)));
throw new HttpErrors.InternalServerError('Unseal error');
}
}
} catch (error) {
throw new Error(`Unseal error: ${error.message}`);
await this.emailService.sendError('Unseal error: ' + error);
throw new HttpErrors.InternalServerError('Unseal error');
}
}

Expand All @@ -80,10 +93,12 @@ export class VaultService {
},
);
if (!response.ok) {
throw new Error(`Unable to create user`);
await this.emailService.sendError(String('Unable to create user: ' + JSON.stringify(response, null, 2)));
throw new HttpErrors.InternalServerError('Unable to create user');
}
} catch (error) {
throw new Error(`Authentication error: ${error.message}`);
await this.emailService.sendError('Unable to create user: ' + error);
throw new HttpErrors.InternalServerError('Unable to create user');
}
}

Expand All @@ -105,10 +120,12 @@ export class VaultService {
},
);
if (!response.ok) {
throw new Error(`Unable to create policy`);
await this.emailService.sendError(String('Unable to create policy: ' + JSON.stringify(response, null, 2)));
throw new HttpErrors.InternalServerError('Unable to create policy');
}
} catch (error) {
throw new Error(`Authentication error: ${error.message}`);
await this.emailService.sendError('Unable to create policy' + error);
throw new HttpErrors.InternalServerError('Unable to create policy');
}
}

Expand All @@ -124,10 +141,12 @@ export class VaultService {
},
);
if (!response.ok) {
throw new Error(`Unable to create key`);
await this.emailService.sendError(String('Unable to create key: ' + JSON.stringify(response, null, 2)));
throw new HttpErrors.InternalServerError('Unable to create key');
}
} catch (error) {
throw new Error(`Authentication error: ${error.message}`);
await this.emailService.sendError('Unable to create key: ' + error);
throw new HttpErrors.InternalServerError('Unable to create key');
}
}

Expand All @@ -147,10 +166,12 @@ export class VaultService {
},
);
if (!response.ok) {
throw new Error(`Unable to update password`);
await this.emailService.sendError(String('Unable to update password: ' + JSON.stringify(response, null, 2)));
throw new HttpErrors.InternalServerError('Unable to update password');
}
} catch (error) {
throw new Error(`Authentication error: ${error.message}`);
await this.emailService.sendError('Unable to update password: ' + error);
throw new HttpErrors.InternalServerError('Unable to update password');
}
}

Expand All @@ -166,10 +187,12 @@ export class VaultService {
},
);
if (!response.ok) {
throw new Error(`Unable to delete user`);
await this.emailService.sendError(String('Unable to delete user: ' + JSON.stringify(response, null, 2)));
throw new HttpErrors.InternalServerError('Unable to delete user');
}
} catch (error) {
throw new Error(`Authentication error: ${error.message}`);
await this.emailService.sendError('Unable to delete user: ' + error);
throw new HttpErrors.InternalServerError('Unable to delete user');
}
}

Expand All @@ -185,10 +208,12 @@ export class VaultService {
},
);
if (!response.ok) {
throw new Error(`Unable to delete policy`);
await this.emailService.sendError(String('Unable to delete policy: ' + JSON.stringify(response, null, 2)));
throw new HttpErrors.InternalServerError('Unable to delete policy');
}
} catch (error) {
throw new Error(`Authentication error: ${error.message}`);
await this.emailService.sendError('Unable to delete policy: ' + error);
throw new HttpErrors.InternalServerError('Unable to delete policy');
}
}

Expand All @@ -204,10 +229,12 @@ export class VaultService {
},
);
if (!response.ok) {
throw new Error(`Unable to delete key`);
await this.emailService.sendError(String('Unable to delete key: ' + JSON.stringify(response, null, 2)));
throw new HttpErrors.InternalServerError('Unable to delete key');
}
} catch (error) {
throw new Error(`Authentication error: ${error.message}`);
await this.emailService.sendError('Unable to delete key: ' + error);
throw new HttpErrors.InternalServerError('Unable to delete key');
}
}
}

0 comments on commit 9bd05f8

Please sign in to comment.