From 3563aef346a8863f13921dce0c5a2b4c99d1aec7 Mon Sep 17 00:00:00 2001 From: Ulf Gebhardt Date: Tue, 7 Feb 2023 17:14:44 +0100 Subject: [PATCH 1/2] use LogError instead of Error where applicable --- backend/src/apis/KlicktippController.ts | 2 +- backend/src/auth/JWT.ts | 2 +- backend/src/graphql/directive/isAuthorized.ts | 9 +++---- .../resolver/ContributionMessageResolver.ts | 8 +++++-- backend/src/graphql/resolver/GdtResolver.ts | 9 +++---- .../resolver/TransactionLinkResolver.ts | 24 +++++++++++-------- .../src/graphql/resolver/util/creations.ts | 2 +- backend/src/server/context.ts | 5 ++-- backend/src/util/decay.ts | 2 +- backend/src/util/klicktipp.ts | 2 +- 10 files changed, 38 insertions(+), 27 deletions(-) diff --git a/backend/src/apis/KlicktippController.ts b/backend/src/apis/KlicktippController.ts index 824d40af2..ca64f4b2e 100644 --- a/backend/src/apis/KlicktippController.ts +++ b/backend/src/apis/KlicktippController.ts @@ -31,7 +31,7 @@ export const unsubscribe = async (email: string): Promise => { if (isLogin) { return await klicktippConnector.unsubscribe(email) } - throw new Error(`Could not unsubscribe ${email}`) + throw new LogError('Could not unsubscribe', email) } export const getKlickTippUser = async (email: string): Promise => { diff --git a/backend/src/auth/JWT.ts b/backend/src/auth/JWT.ts index 8399c881b..301d2ddad 100644 --- a/backend/src/auth/JWT.ts +++ b/backend/src/auth/JWT.ts @@ -3,7 +3,7 @@ import CONFIG from '@/config/' import { CustomJwtPayload } from './CustomJwtPayload' export const decode = (token: string): CustomJwtPayload | null => { - if (!token) throw new Error('401 Unauthorized') + if (!token) throw new LogError('401 Unauthorized') try { return jwt.verify(token, CONFIG.JWT_SECRET) } catch (err) { diff --git a/backend/src/graphql/directive/isAuthorized.ts b/backend/src/graphql/directive/isAuthorized.ts index 2843225ae..59daa89f1 100644 --- a/backend/src/graphql/directive/isAuthorized.ts +++ b/backend/src/graphql/directive/isAuthorized.ts @@ -7,6 +7,7 @@ import { ROLE_UNAUTHORIZED, ROLE_USER, ROLE_ADMIN } from '@/auth/ROLES' import { RIGHTS } from '@/auth/RIGHTS' import { INALIENABLE_RIGHTS } from '@/auth/INALIENABLE_RIGHTS' import { User } from '@entity/User' +import LogError from '@/server/LogError' const isAuthorized: AuthChecker = async ({ context }, rights) => { context.role = ROLE_UNAUTHORIZED // unauthorized user @@ -17,13 +18,13 @@ const isAuthorized: AuthChecker = async ({ context }, rights) => { // Do we have a token? if (!context.token) { - throw new Error('401 Unauthorized') + throw new LogError('401 Unauthorized') } // Decode the token const decoded = decode(context.token) if (!decoded) { - throw new Error('403.13 - Client certificate revoked') + throw new LogError('403.13 - Client certificate revoked') } // Set context gradidoID context.gradidoID = decoded.gradidoID @@ -39,13 +40,13 @@ const isAuthorized: AuthChecker = async ({ context }, rights) => { context.role = user.isAdmin ? ROLE_ADMIN : ROLE_USER } catch { // in case the database query fails (user deleted) - throw new Error('401 Unauthorized') + throw new LogError('401 Unauthorized') } // check for correct rights const missingRights = (rights).filter((right) => !context.role.hasRight(right)) if (missingRights.length !== 0) { - throw new Error('401 Unauthorized') + throw new LogError('401 Unauthorized') } // set new header token diff --git a/backend/src/graphql/resolver/ContributionMessageResolver.ts b/backend/src/graphql/resolver/ContributionMessageResolver.ts index 3e6f86e53..fe6d0dd7e 100644 --- a/backend/src/graphql/resolver/ContributionMessageResolver.ts +++ b/backend/src/graphql/resolver/ContributionMessageResolver.ts @@ -33,10 +33,14 @@ export class ContributionMessageResolver { try { const contribution = await DbContribution.findOne({ id: contributionId }) if (!contribution) { - throw new Error('Contribution not found') + throw new LogError('Contribution not found', contributionId) } if (contribution.userId !== user.id) { - throw new Error('Can not send message to contribution of another user') + throw new LogError( + 'Can not send message to contribution of another user', + contribution.userId, + user.id, + ) } contributionMessage.contributionId = contributionId diff --git a/backend/src/graphql/resolver/GdtResolver.ts b/backend/src/graphql/resolver/GdtResolver.ts index 6f9691cd9..1745e7bbd 100644 --- a/backend/src/graphql/resolver/GdtResolver.ts +++ b/backend/src/graphql/resolver/GdtResolver.ts @@ -8,6 +8,7 @@ import { Context, getUser } from '@/server/context' import CONFIG from '@/config' import { apiGet, apiPost } from '@/apis/HttpRequest' import { RIGHTS } from '@/auth/RIGHTS' +import LogError from '@/server/LogError' @Resolver() export class GdtResolver { @@ -25,11 +26,11 @@ export class GdtResolver { `${CONFIG.GDT_API_URL}/GdtEntries/listPerEmailApi/${userEntity.emailContact.email}/${currentPage}/${pageSize}/${order}`, ) if (!resultGDT.success) { - throw new Error(resultGDT.data) + throw new LogError(resultGDT.data) } return new GdtEntryList(resultGDT.data) } catch (err) { - throw new Error('GDT Server is not reachable.') + throw new LogError('GDT Server is not reachable') } } @@ -42,7 +43,7 @@ export class GdtResolver { email: user.emailContact.email, }) if (!resultGDTSum.success) { - throw new Error('Call not successful') + throw new LogError('Call not successful') } return Number(resultGDTSum.data.sum) || 0 } catch (err) { @@ -59,7 +60,7 @@ export class GdtResolver { // load user const resultPID = await apiGet(`${CONFIG.GDT_API_URL}/publishers/checkPidApi/${pid}`) if (!resultPID.success) { - throw new Error(resultPID.data) + throw new LogError(resultPID.data) } return resultPID.data.pid } diff --git a/backend/src/graphql/resolver/TransactionLinkResolver.ts b/backend/src/graphql/resolver/TransactionLinkResolver.ts index 696c51d97..5ec18112c 100644 --- a/backend/src/graphql/resolver/TransactionLinkResolver.ts +++ b/backend/src/graphql/resolver/TransactionLinkResolver.ts @@ -84,8 +84,8 @@ export class TransactionLinkResolver { transactionLink.code = transactionLinkCode(createdDate) transactionLink.createdAt = createdDate transactionLink.validUntil = validUntil - await DbTransactionLink.save(transactionLink).catch(() => { - throw new Error('Unable to save transaction link') + await DbTransactionLink.save(transactionLink).catch((e) => { + throw new LogError('Unable to save transaction link', e) }) return new TransactionLink(transactionLink, new User(user)) @@ -101,19 +101,23 @@ export class TransactionLinkResolver { const transactionLink = await DbTransactionLink.findOne({ id }) if (!transactionLink) { - throw new Error('Transaction Link not found!') + throw new LogError('Transaction link not found', id) } if (transactionLink.userId !== user.id) { - throw new Error('Transaction Link cannot be deleted!') + throw new LogError( + 'Transaction link cannot be deleted by another user', + transactionLink.userId, + user.id, + ) } if (transactionLink.redeemedBy) { - throw new Error('Transaction Link already redeemed!') + throw new LogError('Transaction link already redeemed', transactionLink.redeemedBy) } - await transactionLink.softRemove().catch(() => { - throw new Error('Transaction Link could not be deleted!') + await transactionLink.softRemove().catch((e) => { + throw new LogError('Transaction link could not be deleted', e) }) return true @@ -316,18 +320,18 @@ export class TransactionLinkResolver { ) if (user.id === linkedUser.id) { - throw new Error('Cannot redeem own transaction link.') + throw new LogError('Cannot redeem own transaction link', user.id) } // TODO: The now check should be done within the semaphore lock, // since the program might wait a while till it is ready to proceed // writing the transaction. if (transactionLink.validUntil.getTime() < now.getTime()) { - throw new Error('Transaction Link is not valid anymore.') + throw new LogError('Transaction link is not valid anymore', transactionLink.validUntil) } if (transactionLink.redeemedBy) { - throw new Error('Transaction Link already redeemed.') + throw new LogError('Transaction link already redeemed', transactionLink.redeemedBy) } await executeTransaction( diff --git a/backend/src/graphql/resolver/util/creations.ts b/backend/src/graphql/resolver/util/creations.ts index 6a47915b1..b9ba2e69f 100644 --- a/backend/src/graphql/resolver/util/creations.ts +++ b/backend/src/graphql/resolver/util/creations.ts @@ -143,7 +143,7 @@ export const updateCreations = ( const index = getCreationIndex(contribution.contributionDate.getMonth(), timezoneOffset) if (index < 0) { - throw new Error('You cannot create GDD for a month older than the last three months.') + throw new LogError('You cannot create GDD for a month older than the last three months') } creations[index] = creations[index].plus(contribution.amount.toString()) return creations diff --git a/backend/src/server/context.ts b/backend/src/server/context.ts index 8ba590dd3..32a765777 100644 --- a/backend/src/server/context.ts +++ b/backend/src/server/context.ts @@ -3,6 +3,7 @@ import { User as dbUser } from '@entity/User' import { Transaction as dbTransaction } from '@entity/Transaction' import Decimal from 'decimal.js-light' import { ExpressContext } from 'apollo-server-express' +import LogError from './LogError' export interface Context { token: string | null @@ -35,7 +36,7 @@ const context = (args: ExpressContext): Context => { export const getUser = (context: Context): dbUser => { if (context.user) return context.user - throw new Error('No user given in context!') + throw new LogError('No user given in context') } export const getClientTimezoneOffset = (context: Context): number => { @@ -45,7 +46,7 @@ export const getClientTimezoneOffset = (context: Context): number => { ) { return context.clientTimezoneOffset } - throw new Error('No valid client time zone offset in context!') + throw new LogError('No valid client time zone offset in context') } export default context diff --git a/backend/src/util/decay.ts b/backend/src/util/decay.ts index 48674dc50..4c09d62a5 100644 --- a/backend/src/util/decay.ts +++ b/backend/src/util/decay.ts @@ -22,7 +22,7 @@ function calculateDecay( const startBlockMs = startBlock.getTime() if (toMs < fromMs) { - throw new Error('to < from, reverse decay calculation is invalid') + throw new LogError('calculateDecay: to < from, reverse decay calculation is invalid') } // Initialize with no decay diff --git a/backend/src/util/klicktipp.ts b/backend/src/util/klicktipp.ts index 0432f196e..7dfc2c98e 100644 --- a/backend/src/util/klicktipp.ts +++ b/backend/src/util/klicktipp.ts @@ -5,7 +5,7 @@ import { User } from '@entity/User' export async function retrieveNotRegisteredEmails(): Promise { const con = await connection() if (!con) { - throw new Error('No connection to database') + throw new LogError('No connection to database') } const users = await User.find({ relations: ['emailContact'] }) const notRegisteredUser = [] From 868566f716e423e88a6000f2daf3fec70afbd5c0 Mon Sep 17 00:00:00 2001 From: Ulf Gebhardt Date: Tue, 7 Feb 2023 17:25:27 +0100 Subject: [PATCH 2/2] missing changes --- backend/src/apis/KlicktippController.ts | 2 +- backend/src/auth/JWT.ts | 1 + backend/src/util/decay.ts | 1 + backend/src/util/klicktipp.ts | 1 + 4 files changed, 4 insertions(+), 1 deletion(-) diff --git a/backend/src/apis/KlicktippController.ts b/backend/src/apis/KlicktippController.ts index ca64f4b2e..824d40af2 100644 --- a/backend/src/apis/KlicktippController.ts +++ b/backend/src/apis/KlicktippController.ts @@ -31,7 +31,7 @@ export const unsubscribe = async (email: string): Promise => { if (isLogin) { return await klicktippConnector.unsubscribe(email) } - throw new LogError('Could not unsubscribe', email) + throw new Error(`Could not unsubscribe ${email}`) } export const getKlickTippUser = async (email: string): Promise => { diff --git a/backend/src/auth/JWT.ts b/backend/src/auth/JWT.ts index 301d2ddad..3f9c052f5 100644 --- a/backend/src/auth/JWT.ts +++ b/backend/src/auth/JWT.ts @@ -1,6 +1,7 @@ import jwt from 'jsonwebtoken' import CONFIG from '@/config/' import { CustomJwtPayload } from './CustomJwtPayload' +import LogError from '@/server/LogError' export const decode = (token: string): CustomJwtPayload | null => { if (!token) throw new LogError('401 Unauthorized') diff --git a/backend/src/util/decay.ts b/backend/src/util/decay.ts index 4c09d62a5..641654756 100644 --- a/backend/src/util/decay.ts +++ b/backend/src/util/decay.ts @@ -1,6 +1,7 @@ import Decimal from 'decimal.js-light' import CONFIG from '@/config' import { Decay } from '@model/Decay' +import LogError from '@/server/LogError' // TODO: externalize all those definitions and functions into an external decay library diff --git a/backend/src/util/klicktipp.ts b/backend/src/util/klicktipp.ts index 7dfc2c98e..02bdd853b 100644 --- a/backend/src/util/klicktipp.ts +++ b/backend/src/util/klicktipp.ts @@ -1,6 +1,7 @@ import connection from '@/typeorm/connection' import { getKlickTippUser } from '@/apis/KlicktippController' import { User } from '@entity/User' +import LogError from '@/server/LogError' export async function retrieveNotRegisteredEmails(): Promise { const con = await connection()