Merge pull request #1762 from gradido/define-context-object

refactor: Define Context Interface
This commit is contained in:
Moriz Wahl 2022-04-12 19:54:24 +02:00 committed by GitHub
commit a9f64d2fd6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 61 additions and 58 deletions

View File

@ -1,6 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */ import { Context, getUser } from '@/server/context'
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { Resolver, Query, Arg, Args, Authorized, Mutation, Ctx, Int } from 'type-graphql' import { Resolver, Query, Arg, Args, Authorized, Mutation, Ctx, Int } from 'type-graphql'
import { import {
getCustomRepository, getCustomRepository,
@ -137,7 +135,7 @@ export class AdminResolver {
@Mutation(() => Date, { nullable: true }) @Mutation(() => Date, { nullable: true })
async deleteUser( async deleteUser(
@Arg('userId', () => Int) userId: number, @Arg('userId', () => Int) userId: number,
@Ctx() context: any, @Ctx() context: Context,
): Promise<Date | null> { ): Promise<Date | null> {
const user = await dbUser.findOne({ id: userId }) const user = await dbUser.findOne({ id: userId })
// user exists ? // user exists ?
@ -145,7 +143,7 @@ export class AdminResolver {
throw new Error(`Could not find user with userId: ${userId}`) throw new Error(`Could not find user with userId: ${userId}`)
} }
// moderator user disabled own account? // moderator user disabled own account?
const moderatorUser = context.user const moderatorUser = getUser(context)
if (moderatorUser.id === userId) { if (moderatorUser.id === userId) {
throw new Error('Moderator can not delete his own account!') throw new Error('Moderator can not delete his own account!')
} }
@ -309,10 +307,10 @@ export class AdminResolver {
@Mutation(() => Boolean) @Mutation(() => Boolean)
async confirmPendingCreation( async confirmPendingCreation(
@Arg('id', () => Int) id: number, @Arg('id', () => Int) id: number,
@Ctx() context: any, @Ctx() context: Context,
): Promise<boolean> { ): Promise<boolean> {
const pendingCreation = await AdminPendingCreation.findOneOrFail(id) const pendingCreation = await AdminPendingCreation.findOneOrFail(id)
const moderatorUser = context.user const moderatorUser = getUser(context)
if (moderatorUser.id === pendingCreation.userId) if (moderatorUser.id === pendingCreation.userId)
throw new Error('Moderator can not confirm own pending creation') throw new Error('Moderator can not confirm own pending creation')

View File

@ -1,6 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */ import { Context, getUser } from '@/server/context'
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { Resolver, Query, Ctx, Authorized } from 'type-graphql' import { Resolver, Query, Ctx, Authorized } from 'type-graphql'
import { Balance } from '@model/Balance' import { Balance } from '@model/Balance'
import { calculateDecay } from '@/util/decay' import { calculateDecay } from '@/util/decay'
@ -16,8 +14,8 @@ import { TransactionLinkRepository } from '@repository/TransactionLink'
export class BalanceResolver { export class BalanceResolver {
@Authorized([RIGHTS.BALANCE]) @Authorized([RIGHTS.BALANCE])
@Query(() => Balance) @Query(() => Balance)
async balance(@Ctx() context: any): Promise<Balance> { async balance(@Ctx() context: Context): Promise<Balance> {
const { user } = context const user = getUser(context)
const now = new Date() const now = new Date()
const gdtResolver = new GdtResolver() const gdtResolver = new GdtResolver()

View File

@ -1,6 +1,3 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { Resolver, Query, Authorized } from 'type-graphql' import { Resolver, Query, Authorized } from 'type-graphql'
import { RIGHTS } from '@/auth/RIGHTS' import { RIGHTS } from '@/auth/RIGHTS'
import CONFIG from '@/config' import CONFIG from '@/config'

View File

@ -1,6 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */ import { Context, getUser } from '@/server/context'
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { Resolver, Query, Args, Ctx, Authorized, Arg } from 'type-graphql' import { Resolver, Query, Args, Ctx, Authorized, Arg } from 'type-graphql'
import CONFIG from '@/config' import CONFIG from '@/config'
import { GdtEntryList } from '@model/GdtEntryList' import { GdtEntryList } from '@model/GdtEntryList'
@ -16,9 +14,9 @@ export class GdtResolver {
async listGDTEntries( async listGDTEntries(
@Args() @Args()
{ currentPage = 1, pageSize = 5, order = Order.DESC }: Paginated, { currentPage = 1, pageSize = 5, order = Order.DESC }: Paginated,
@Ctx() context: any, @Ctx() context: Context,
): Promise<GdtEntryList> { ): Promise<GdtEntryList> {
const userEntity = context.user const userEntity = getUser(context)
try { try {
const resultGDT = await apiGet( const resultGDT = await apiGet(
@ -28,15 +26,15 @@ export class GdtResolver {
throw new Error(resultGDT.data) throw new Error(resultGDT.data)
} }
return new GdtEntryList(resultGDT.data) return new GdtEntryList(resultGDT.data)
} catch (err: any) { } catch (err) {
throw new Error('GDT Server is not reachable.') throw new Error('GDT Server is not reachable.')
} }
} }
@Authorized([RIGHTS.GDT_BALANCE]) @Authorized([RIGHTS.GDT_BALANCE])
@Query(() => Number) @Query(() => Number)
async gdtBalance(@Ctx() context: any): Promise<number | null> { async gdtBalance(@Ctx() context: Context): Promise<number | null> {
const { user } = context const user = getUser(context)
try { try {
const resultGDTSum = await apiPost(`${CONFIG.GDT_API_URL}/GdtEntries/sumPerEmailApi`, { const resultGDTSum = await apiPost(`${CONFIG.GDT_API_URL}/GdtEntries/sumPerEmailApi`, {
email: user.email, email: user.email,
@ -45,9 +43,9 @@ export class GdtResolver {
throw new Error('Call not successful') throw new Error('Call not successful')
} }
return Number(resultGDTSum.data.sum) || 0 return Number(resultGDTSum.data.sum) || 0
} catch (err: any) { } catch (err) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
console.log('Could not query GDT Server', err) console.log('Could not query GDT Server')
return null return null
} }
} }

View File

@ -1,6 +1,3 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { Resolver, Query, Authorized, Arg, Mutation, Args } from 'type-graphql' import { Resolver, Query, Authorized, Arg, Mutation, Args } from 'type-graphql'
import { import {
getKlickTippUser, getKlickTippUser,

View File

@ -1,6 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */ import { Context, getUser } from '@/server/context'
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { Resolver, Args, Arg, Authorized, Ctx, Mutation, Query, Int } from 'type-graphql' import { Resolver, Args, Arg, Authorized, Ctx, Mutation, Query, Int } from 'type-graphql'
import { TransactionLink } from '@model/TransactionLink' import { TransactionLink } from '@model/TransactionLink'
import { TransactionLink as dbTransactionLink } from '@entity/TransactionLink' import { TransactionLink as dbTransactionLink } from '@entity/TransactionLink'
@ -38,9 +36,9 @@ export class TransactionLinkResolver {
@Mutation(() => TransactionLink) @Mutation(() => TransactionLink)
async createTransactionLink( async createTransactionLink(
@Args() { amount, memo }: TransactionLinkArgs, @Args() { amount, memo }: TransactionLinkArgs,
@Ctx() context: any, @Ctx() context: Context,
): Promise<TransactionLink> { ): Promise<TransactionLink> {
const { user } = context const user = getUser(context)
const createdDate = new Date() const createdDate = new Date()
const validUntil = transactionLinkExpireDate(createdDate) const validUntil = transactionLinkExpireDate(createdDate)
@ -72,9 +70,9 @@ export class TransactionLinkResolver {
@Mutation(() => Boolean) @Mutation(() => Boolean)
async deleteTransactionLink( async deleteTransactionLink(
@Arg('id', () => Int) id: number, @Arg('id', () => Int) id: number,
@Ctx() context: any, @Ctx() context: Context,
): Promise<boolean> { ): Promise<boolean> {
const { user } = context const user = getUser(context)
const transactionLink = await dbTransactionLink.findOne({ id }) const transactionLink = await dbTransactionLink.findOne({ id })
if (!transactionLink) { if (!transactionLink) {
@ -113,9 +111,9 @@ export class TransactionLinkResolver {
async listTransactionLinks( async listTransactionLinks(
@Args() @Args()
{ currentPage = 1, pageSize = 5, order = Order.DESC }: Paginated, { currentPage = 1, pageSize = 5, order = Order.DESC }: Paginated,
@Ctx() context: any, @Ctx() context: Context,
): Promise<TransactionLink[]> { ): Promise<TransactionLink[]> {
const { user } = context const user = getUser(context)
// const now = new Date() // const now = new Date()
const transactionLinks = await dbTransactionLink.find({ const transactionLinks = await dbTransactionLink.find({
where: { where: {
@ -136,9 +134,9 @@ export class TransactionLinkResolver {
@Mutation(() => Boolean) @Mutation(() => Boolean)
async redeemTransactionLink( async redeemTransactionLink(
@Arg('code', () => String) code: string, @Arg('code', () => String) code: string,
@Ctx() context: any, @Ctx() context: Context,
): Promise<boolean> { ): Promise<boolean> {
const { user } = context const user = getUser(context)
const transactionLink = await dbTransactionLink.findOneOrFail({ code }) const transactionLink = await dbTransactionLink.findOneOrFail({ code })
const linkedUser = await dbUser.findOneOrFail({ id: transactionLink.userId }) const linkedUser = await dbUser.findOneOrFail({ id: transactionLink.userId })

View File

@ -1,8 +1,7 @@
/* eslint-disable new-cap */ /* eslint-disable new-cap */
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
/* eslint-disable @typescript-eslint/no-non-null-assertion */ /* eslint-disable @typescript-eslint/no-non-null-assertion */
import { Context, getUser } from '@/server/context'
import { Resolver, Query, Args, Authorized, Ctx, Mutation } from 'type-graphql' import { Resolver, Query, Args, Authorized, Ctx, Mutation } from 'type-graphql'
import { getCustomRepository, getConnection } from '@dbTools/typeorm' import { getCustomRepository, getConnection } from '@dbTools/typeorm'
@ -147,10 +146,10 @@ export class TransactionResolver {
async transactionList( async transactionList(
@Args() @Args()
{ currentPage = 1, pageSize = 25, order = Order.DESC }: Paginated, { currentPage = 1, pageSize = 25, order = Order.DESC }: Paginated,
@Ctx() context: any, @Ctx() context: Context,
): Promise<TransactionList> { ): Promise<TransactionList> {
const now = new Date() const now = new Date()
const user = context.user const user = getUser(context)
// find current balance // find current balance
const lastTransaction = await dbTransaction.findOne( const lastTransaction = await dbTransaction.findOne(
@ -247,10 +246,10 @@ export class TransactionResolver {
@Mutation(() => String) @Mutation(() => String)
async sendCoins( async sendCoins(
@Args() { email, amount, memo }: TransactionSendArgs, @Args() { email, amount, memo }: TransactionSendArgs,
@Ctx() context: any, @Ctx() context: Context,
): Promise<boolean> { ): Promise<boolean> {
// TODO this is subject to replay attacks // TODO this is subject to replay attacks
const senderUser = context.user const senderUser = getUser(context)
if (senderUser.pubKey.length !== 32) { if (senderUser.pubKey.length !== 32) {
throw new Error('invalid sender public key') throw new Error('invalid sender public key')
} }

View File

@ -1,7 +1,5 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import fs from 'fs' import fs from 'fs'
import { Context, getUser } from '@/server/context'
import { Resolver, Query, Args, Arg, Authorized, Ctx, UseMiddleware, Mutation } from 'type-graphql' import { Resolver, Query, Args, Arg, Authorized, Ctx, UseMiddleware, Mutation } from 'type-graphql'
import { getConnection, getCustomRepository } from '@dbTools/typeorm' import { getConnection, getCustomRepository } from '@dbTools/typeorm'
import CONFIG from '@/config' import CONFIG from '@/config'
@ -192,9 +190,9 @@ export class UserResolver {
@Authorized([RIGHTS.VERIFY_LOGIN]) @Authorized([RIGHTS.VERIFY_LOGIN])
@Query(() => User) @Query(() => User)
@UseMiddleware(klicktippNewsletterStateMiddleware) @UseMiddleware(klicktippNewsletterStateMiddleware)
async verifyLogin(@Ctx() context: any): Promise<User> { async verifyLogin(@Ctx() context: Context): Promise<User> {
// TODO refactor and do not have duplicate code with login(see below) // TODO refactor and do not have duplicate code with login(see below)
const userEntity = context.user const userEntity = getUser(context)
const user = new User(userEntity) const user = new User(userEntity)
// user.pubkey = userEntity.pubKey.toString('hex') // user.pubkey = userEntity.pubKey.toString('hex')
// Elopage Status & Stored PublisherId // Elopage Status & Stored PublisherId
@ -218,7 +216,7 @@ export class UserResolver {
@UseMiddleware(klicktippNewsletterStateMiddleware) @UseMiddleware(klicktippNewsletterStateMiddleware)
async login( async login(
@Args() { email, password, publisherId }: UnsecureLoginArgs, @Args() { email, password, publisherId }: UnsecureLoginArgs,
@Ctx() context: any, @Ctx() context: Context,
): Promise<User> { ): Promise<User> {
email = email.trim().toLowerCase() email = email.trim().toLowerCase()
const dbUser = await DbUser.findOneOrFail({ email }, { withDeleted: true }).catch(() => { const dbUser = await DbUser.findOneOrFail({ email }, { withDeleted: true }).catch(() => {
@ -540,9 +538,9 @@ export class UserResolver {
passwordNew, passwordNew,
coinanimation, coinanimation,
}: UpdateUserInfosArgs, }: UpdateUserInfosArgs,
@Ctx() context: any, @Ctx() context: Context,
): Promise<boolean> { ): Promise<boolean> {
const userEntity = context.user const userEntity = getUser(context)
if (firstName) { if (firstName) {
userEntity.firstName = firstName userEntity.firstName = firstName
@ -619,7 +617,7 @@ export class UserResolver {
@Authorized([RIGHTS.HAS_ELOPAGE]) @Authorized([RIGHTS.HAS_ELOPAGE])
@Query(() => Boolean) @Query(() => Boolean)
async hasElopage(@Ctx() context: any): Promise<boolean> { async hasElopage(@Ctx() context: Context): Promise<boolean> {
const userEntity = context.user const userEntity = context.user
if (!userEntity) { if (!userEntity) {
return false return false

View File

@ -1,9 +1,24 @@
/* eslint-disable @typescript-eslint/no-explicit-any */ import { Role } from '@/auth/Role'
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ 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'
const context = (args: any) => { export interface Context {
token: string | null
setHeaders: { key: string; value: string }[]
role?: Role
user?: dbUser
// hack to use less DB calls for Balance Resolver
lastTransaction?: dbTransaction
transactionCount?: number
linkCount?: number
sumHoldAvailableAmount?: Decimal
}
const context = (args: ExpressContext): Context => {
const authorization = args.req.headers.authorization const authorization = args.req.headers.authorization
let token = null let token: string | null = null
if (authorization) { if (authorization) {
token = authorization.replace(/^Bearer /, '') token = authorization.replace(/^Bearer /, '')
} }
@ -14,4 +29,9 @@ const context = (args: any) => {
return context return context
} }
export const getUser = (context: Context): dbUser => {
if (context.user) return context.user
throw new Error('No user given in context!')
}
export default context export default context