Merge pull request #3592 from gradido/fix_biome

fix(other): fix biome config
This commit is contained in:
einhornimmond 2025-12-04 13:10:53 +01:00 committed by GitHub
commit 5a6cb94bb3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
264 changed files with 2465 additions and 1939 deletions

View File

@ -1,8 +1,7 @@
import axios from 'axios' import axios from 'axios'
import { getLogger } from 'log4js'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { LogError } from '@/server/LogError' import { LogError } from '@/server/LogError'
import { getLogger } from 'log4js'
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.apis.HttpRequest`) const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.apis.HttpRequest`)

View File

@ -1,7 +1,7 @@
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { CONFIG } from '@/config'
import KlicktippConnector from 'klicktipp-api' import KlicktippConnector from 'klicktipp-api'
import { getLogger } from 'log4js' import { getLogger } from 'log4js'
import { CONFIG } from '@/config'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
const klicktippConnector = new KlicktippConnector() const klicktippConnector = new KlicktippConnector()
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.apis.KlicktippController`) const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.apis.KlicktippController`)

View File

@ -18,5 +18,3 @@ describe('undefined DltConnectorClient', () => {
CONFIG.DLT_ACTIVE = true CONFIG.DLT_ACTIVE = true
}) })
}) })

View File

@ -1,9 +1,8 @@
import { getLogger } from 'log4js'
import { IRestResponse, RestClient } from 'typed-rest-client'
import { CONFIG } from '@/config' import { CONFIG } from '@/config'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { getLogger } from 'log4js'
import { TransactionDraft } from './model/TransactionDraft' import { TransactionDraft } from './model/TransactionDraft'
import { IRestResponse, RestClient } from 'typed-rest-client'
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.apis.dltConnector`) const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.apis.dltConnector`)
@ -44,7 +43,7 @@ export class DltConnectorClient {
'gradido-backend', 'gradido-backend',
CONFIG.DLT_CONNECTOR_URL, CONFIG.DLT_CONNECTOR_URL,
undefined, undefined,
{ keepAlive: true } { keepAlive: true },
) )
} catch (e) { } catch (e) {
logger.error("couldn't connect to dlt-connector: ", e) logger.error("couldn't connect to dlt-connector: ", e)
@ -58,11 +57,10 @@ export class DltConnectorClient {
* transmit transaction via dlt-connector to hiero * transmit transaction via dlt-connector to hiero
* and update dltTransactionId of transaction in db with hiero transaction id * and update dltTransactionId of transaction in db with hiero transaction id
*/ */
public async sendTransaction(input: TransactionDraft): Promise<IRestResponse<{ transactionId: string }>> { public async sendTransaction(
input: TransactionDraft,
): Promise<IRestResponse<{ transactionId: string }>> {
logger.debug('transmit transaction or user to dlt connector', input) logger.debug('transmit transaction or user to dlt connector', input)
return await this.client.create<{ transactionId: string }>( return await this.client.create<{ transactionId: string }>('/sendTransaction', input)
'/sendTransaction',
input
)
} }
} }

View File

@ -1,9 +1,8 @@
import { getLogger } from 'log4js'
import { IRestResponse } from 'typed-rest-client'
import { TransactionDraft } from '@/apis/dltConnector/model/TransactionDraft'
import { CONFIG } from '@/config' import { CONFIG } from '@/config'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { getLogger } from 'log4js'
import { TransactionDraft } from '@/apis/dltConnector/model/TransactionDraft'
import { IRestResponse } from 'typed-rest-client'
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.apis.dltConnector`) const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.apis.dltConnector`)

View File

@ -1,8 +1,3 @@
import { IRestResponse } from 'typed-rest-client'
import { DltTransactionType } from './enum/DltTransactionType'
import { getLogger } from 'log4js'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { DltConnectorClient } from './DltConnectorClient'
import { import {
Community as DbCommunity, Community as DbCommunity,
Contribution as DbContribution, Contribution as DbContribution,
@ -14,15 +9,22 @@ import {
getUserById, getUserById,
UserLoggingView, UserLoggingView,
} from 'database' } from 'database'
import { TransactionDraft } from './model/TransactionDraft' import { getLogger } from 'log4js'
import { IRestResponse } from 'typed-rest-client'
import { CONFIG } from '@/config' import { CONFIG } from '@/config'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { DltConnectorClient } from './DltConnectorClient'
import { DltTransactionType } from './enum/DltTransactionType'
import { TransactionDraft } from './model/TransactionDraft'
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.dltConnector`) const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.dltConnector`)
// will be undefined if dlt connect is disabled // will be undefined if dlt connect is disabled
const dltConnectorClient = DltConnectorClient.getInstance() const dltConnectorClient = DltConnectorClient.getInstance()
async function checkDltConnectorResult(dltTransaction: DbDltTransaction, clientResponse: Promise<IRestResponse<{ transactionId: string }>>) async function checkDltConnectorResult(
: Promise<DbDltTransaction> { dltTransaction: DbDltTransaction,
clientResponse: Promise<IRestResponse<{ transactionId: string }>>,
): Promise<DbDltTransaction> {
// check result from dlt connector // check result from dlt connector
try { try {
const response = await clientResponse const response = await clientResponse
@ -47,7 +49,11 @@ async function checkDltConnectorResult(dltTransaction: DbDltTransaction, clientR
return dltTransaction return dltTransaction
} }
async function executeDltTransaction(draft: TransactionDraft | null, typeId: DltTransactionType, persist = true): Promise<DbDltTransaction | null> { async function executeDltTransaction(
draft: TransactionDraft | null,
typeId: DltTransactionType,
persist = true,
): Promise<DbDltTransaction | null> {
if (draft && dltConnectorClient) { if (draft && dltConnectorClient) {
const clientResponse = dltConnectorClient.sendTransaction(draft) const clientResponse = dltConnectorClient.sendTransaction(draft)
let dltTransaction = new DbDltTransaction() let dltTransaction = new DbDltTransaction()
@ -65,17 +71,26 @@ async function executeDltTransaction(draft: TransactionDraft | null, typeId: Dlt
* send register address transaction via dlt-connector to hiero * send register address transaction via dlt-connector to hiero
* and update dltTransactionId of transaction in db with hiero transaction id * and update dltTransactionId of transaction in db with hiero transaction id
*/ */
export async function registerAddressTransaction(user: DbUser, community: DbCommunity): Promise<DbDltTransaction | null> { export async function registerAddressTransaction(
user: DbUser,
community: DbCommunity,
): Promise<DbDltTransaction | null> {
if (!CONFIG.DLT_ACTIVE) { if (!CONFIG.DLT_ACTIVE) {
return Promise.resolve(null) return Promise.resolve(null)
} }
if (!user.id) { if (!user.id) {
logger.error(`missing id for user: ${user.gradidoID}, please call registerAddressTransaction after user.save()`) logger.error(
`missing id for user: ${user.gradidoID}, please call registerAddressTransaction after user.save()`,
)
return null return null
} }
// return null if some data where missing and log error // return null if some data where missing and log error
const draft = TransactionDraft.createRegisterAddress(user, community) const draft = TransactionDraft.createRegisterAddress(user, community)
const dltTransaction = await executeDltTransaction(draft, DltTransactionType.REGISTER_ADDRESS, false) const dltTransaction = await executeDltTransaction(
draft,
DltTransactionType.REGISTER_ADDRESS,
false,
)
if (dltTransaction) { if (dltTransaction) {
if (user.id) { if (user.id) {
dltTransaction.userId = user.id dltTransaction.userId = user.id
@ -98,7 +113,12 @@ export async function contributionTransaction(
logger.error('home community not found') logger.error('home community not found')
return null return null
} }
const draft = TransactionDraft.createContribution(contribution, createdAt, signingUser, homeCommunity) const draft = TransactionDraft.createContribution(
contribution,
createdAt,
signingUser,
homeCommunity,
)
return await executeDltTransaction(draft, DltTransactionType.CREATION) return await executeDltTransaction(draft, DltTransactionType.CREATION)
} }
@ -107,7 +127,7 @@ export async function transferTransaction(
recipientUser: DbUser, recipientUser: DbUser,
amount: string, amount: string,
memo: string, memo: string,
createdAt: Date createdAt: Date,
): Promise<DbDltTransaction | null> { ): Promise<DbDltTransaction | null> {
if (!CONFIG.DLT_ACTIVE) { if (!CONFIG.DLT_ACTIVE) {
return Promise.resolve(null) return Promise.resolve(null)
@ -125,8 +145,10 @@ export async function transferTransaction(
return await executeDltTransaction(draft, DltTransactionType.TRANSFER) return await executeDltTransaction(draft, DltTransactionType.TRANSFER)
} }
export async function deferredTransferTransaction(senderUser: DbUser, transactionLink: DbTransactionLink) export async function deferredTransferTransaction(
: Promise<DbDltTransaction | null> { senderUser: DbUser,
transactionLink: DbTransactionLink,
): Promise<DbDltTransaction | null> {
if (!CONFIG.DLT_ACTIVE) { if (!CONFIG.DLT_ACTIVE) {
return Promise.resolve(null) return Promise.resolve(null)
} }
@ -138,8 +160,12 @@ export async function deferredTransferTransaction(senderUser: DbUser, transactio
return await executeDltTransaction(draft, DltTransactionType.DEFERRED_TRANSFER) return await executeDltTransaction(draft, DltTransactionType.DEFERRED_TRANSFER)
} }
export async function redeemDeferredTransferTransaction(transactionLink: DbTransactionLink, amount: string, createdAt: Date, recipientUser: DbUser) export async function redeemDeferredTransferTransaction(
: Promise<DbDltTransaction | null> { transactionLink: DbTransactionLink,
amount: string,
createdAt: Date,
recipientUser: DbUser,
): Promise<DbDltTransaction | null> {
if (!CONFIG.DLT_ACTIVE) { if (!CONFIG.DLT_ACTIVE) {
return Promise.resolve(null) return Promise.resolve(null)
} }
@ -158,9 +184,11 @@ export async function redeemDeferredTransferTransaction(transactionLink: DbTrans
} }
logger.debug(`sender: ${new UserLoggingView(transactionLink.user)}`) logger.debug(`sender: ${new UserLoggingView(transactionLink.user)}`)
logger.debug(`recipient: ${new UserLoggingView(recipientUser)}`) logger.debug(`recipient: ${new UserLoggingView(recipientUser)}`)
const draft = TransactionDraft.redeemDeferredTransfer(transactionLink, amount, createdAt, recipientUser) const draft = TransactionDraft.redeemDeferredTransfer(
transactionLink,
amount,
createdAt,
recipientUser,
)
return await executeDltTransaction(draft, DltTransactionType.REDEEM_DEFERRED_TRANSFER) return await executeDltTransaction(draft, DltTransactionType.REDEEM_DEFERRED_TRANSFER)
} }

View File

@ -1,18 +1,17 @@
// https://www.npmjs.com/package/@apollo/protobufjs // https://www.npmjs.com/package/@apollo/protobufjs
import { AccountType } from '@dltConnector/enum/AccountType' import { AccountType } from '@dltConnector/enum/AccountType'
import { TransactionType } from '@dltConnector/enum/TransactionType' import { TransactionType } from '@dltConnector/enum/TransactionType'
import { AccountIdentifier } from './AccountIdentifier'
import { import {
Community as DbCommunity, Community as DbCommunity,
Contribution as DbContribution, Contribution as DbContribution,
TransactionLink as DbTransactionLink, TransactionLink as DbTransactionLink,
User as DbUser User as DbUser,
} from 'database' } from 'database'
import { CommunityAccountIdentifier } from './CommunityAccountIdentifier'
import { getLogger } from 'log4js' import { getLogger } from 'log4js'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { CODE_VALID_DAYS_DURATION } from '@/graphql/resolver/const/const' import { CODE_VALID_DAYS_DURATION } from '@/graphql/resolver/const/const'
import { AccountIdentifier } from './AccountIdentifier'
import { CommunityAccountIdentifier } from './CommunityAccountIdentifier'
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.dltConnector.model.TransactionDraft`) const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.dltConnector.model.TransactionDraft`)
@ -35,7 +34,10 @@ export class TransactionDraft {
static createRegisterAddress(user: DbUser, community: DbCommunity): TransactionDraft | null { static createRegisterAddress(user: DbUser, community: DbCommunity): TransactionDraft | null {
if (community.hieroTopicId) { if (community.hieroTopicId) {
const draft = new TransactionDraft() const draft = new TransactionDraft()
draft.user = new AccountIdentifier(community.hieroTopicId, new CommunityAccountIdentifier(user.gradidoID)) draft.user = new AccountIdentifier(
community.hieroTopicId,
new CommunityAccountIdentifier(user.gradidoID),
)
draft.type = TransactionType.REGISTER_ADDRESS draft.type = TransactionType.REGISTER_ADDRESS
draft.createdAt = user.createdAt.toISOString() draft.createdAt = user.createdAt.toISOString()
draft.accountType = AccountType.COMMUNITY_HUMAN draft.accountType = AccountType.COMMUNITY_HUMAN
@ -46,11 +48,22 @@ export class TransactionDraft {
return null return null
} }
static createContribution(contribution: DbContribution, createdAt: Date, signingUser: DbUser, community: DbCommunity): TransactionDraft | null { static createContribution(
contribution: DbContribution,
createdAt: Date,
signingUser: DbUser,
community: DbCommunity,
): TransactionDraft | null {
if (community.hieroTopicId) { if (community.hieroTopicId) {
const draft = new TransactionDraft() const draft = new TransactionDraft()
draft.user = new AccountIdentifier(community.hieroTopicId, new CommunityAccountIdentifier(contribution.user.gradidoID)) draft.user = new AccountIdentifier(
draft.linkedUser = new AccountIdentifier(community.hieroTopicId, new CommunityAccountIdentifier(signingUser.gradidoID)) community.hieroTopicId,
new CommunityAccountIdentifier(contribution.user.gradidoID),
)
draft.linkedUser = new AccountIdentifier(
community.hieroTopicId,
new CommunityAccountIdentifier(signingUser.gradidoID),
)
draft.type = TransactionType.GRADIDO_CREATION draft.type = TransactionType.GRADIDO_CREATION
draft.createdAt = createdAt.toISOString() draft.createdAt = createdAt.toISOString()
draft.amount = contribution.amount.toString() draft.amount = contribution.amount.toString()
@ -63,18 +76,32 @@ export class TransactionDraft {
return null return null
} }
static createTransfer(sendingUser: DbUser, receivingUser: DbUser, amount: string, memo: string, createdAt: Date): TransactionDraft | null { static createTransfer(
sendingUser: DbUser,
receivingUser: DbUser,
amount: string,
memo: string,
createdAt: Date,
): TransactionDraft | null {
if (!sendingUser.community || !receivingUser.community) { if (!sendingUser.community || !receivingUser.community) {
throw new Error(`missing community for user ${sendingUser.id} and/or ${receivingUser.id}`) throw new Error(`missing community for user ${sendingUser.id} and/or ${receivingUser.id}`)
} }
const senderUserTopic = sendingUser.community.hieroTopicId const senderUserTopic = sendingUser.community.hieroTopicId
const receiverUserTopic = receivingUser.community.hieroTopicId const receiverUserTopic = receivingUser.community.hieroTopicId
if (!senderUserTopic || !receiverUserTopic) { if (!senderUserTopic || !receiverUserTopic) {
throw new Error(`missing topicId for community ${sendingUser.community.id} and/or ${receivingUser.community.id}`) throw new Error(
`missing topicId for community ${sendingUser.community.id} and/or ${receivingUser.community.id}`,
)
} }
const draft = new TransactionDraft() const draft = new TransactionDraft()
draft.user = new AccountIdentifier(senderUserTopic, new CommunityAccountIdentifier(sendingUser.gradidoID)) draft.user = new AccountIdentifier(
draft.linkedUser = new AccountIdentifier(receiverUserTopic, new CommunityAccountIdentifier(receivingUser.gradidoID)) senderUserTopic,
new CommunityAccountIdentifier(sendingUser.gradidoID),
)
draft.linkedUser = new AccountIdentifier(
receiverUserTopic,
new CommunityAccountIdentifier(receivingUser.gradidoID),
)
draft.type = TransactionType.GRADIDO_TRANSFER draft.type = TransactionType.GRADIDO_TRANSFER
draft.createdAt = createdAt.toISOString() draft.createdAt = createdAt.toISOString()
draft.amount = amount draft.amount = amount
@ -82,8 +109,10 @@ export class TransactionDraft {
return draft return draft
} }
static createDeferredTransfer(sendingUser: DbUser, transactionLink: DbTransactionLink) static createDeferredTransfer(
: TransactionDraft | null { sendingUser: DbUser,
transactionLink: DbTransactionLink,
): TransactionDraft | null {
if (!sendingUser.community) { if (!sendingUser.community) {
throw new Error(`missing community for user ${sendingUser.id}`) throw new Error(`missing community for user ${sendingUser.id}`)
} }
@ -94,7 +123,10 @@ export class TransactionDraft {
const createdAtOnlySeconds = transactionLink.createdAt const createdAtOnlySeconds = transactionLink.createdAt
createdAtOnlySeconds.setMilliseconds(0) createdAtOnlySeconds.setMilliseconds(0)
const draft = new TransactionDraft() const draft = new TransactionDraft()
draft.user = new AccountIdentifier(senderUserTopic, new CommunityAccountIdentifier(sendingUser.gradidoID)) draft.user = new AccountIdentifier(
senderUserTopic,
new CommunityAccountIdentifier(sendingUser.gradidoID),
)
draft.linkedUser = new AccountIdentifier(senderUserTopic, transactionLink.code) draft.linkedUser = new AccountIdentifier(senderUserTopic, transactionLink.code)
draft.type = TransactionType.GRADIDO_DEFERRED_TRANSFER draft.type = TransactionType.GRADIDO_DEFERRED_TRANSFER
draft.createdAt = createdAtOnlySeconds.toISOString() draft.createdAt = createdAtOnlySeconds.toISOString()
@ -104,7 +136,12 @@ export class TransactionDraft {
return draft return draft
} }
static redeemDeferredTransfer(transactionLink: DbTransactionLink, amount: string, createdAt: Date, recipientUser: DbUser): TransactionDraft | null { static redeemDeferredTransfer(
transactionLink: DbTransactionLink,
amount: string,
createdAt: Date,
recipientUser: DbUser,
): TransactionDraft | null {
if (!transactionLink.user.community) { if (!transactionLink.user.community) {
throw new Error(`missing community for user ${transactionLink.user.id}`) throw new Error(`missing community for user ${transactionLink.user.id}`)
} }
@ -123,7 +160,10 @@ export class TransactionDraft {
createdAtOnlySeconds.setMilliseconds(0) createdAtOnlySeconds.setMilliseconds(0)
const draft = new TransactionDraft() const draft = new TransactionDraft()
draft.user = new AccountIdentifier(senderUserTopic, transactionLink.code) draft.user = new AccountIdentifier(senderUserTopic, transactionLink.code)
draft.linkedUser = new AccountIdentifier(recipientUserTopic, new CommunityAccountIdentifier(recipientUser.gradidoID)) draft.linkedUser = new AccountIdentifier(
recipientUserTopic,
new CommunityAccountIdentifier(recipientUser.gradidoID),
)
draft.type = TransactionType.GRADIDO_REDEEM_DEFERRED_TRANSFER draft.type = TransactionType.GRADIDO_REDEEM_DEFERRED_TRANSFER
draft.createdAt = createdAtOnlySeconds.toISOString() draft.createdAt = createdAtOnlySeconds.toISOString()
draft.amount = amount draft.amount = amount

View File

@ -1,15 +1,16 @@
import { User as DbUser } from 'database' import { User as DbUser } from 'database'
// import { createTestClient } from 'apollo-server-testing' // import { createTestClient } from 'apollo-server-testing'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
// import { createGmsUser } from '@/apis/gms/GmsClient' // import { createGmsUser } from '@/apis/gms/GmsClient'
// import { GmsUser } from '@/apis/gms/model/GmsUser' // import { GmsUser } from '@/apis/gms/model/GmsUser'
import { CONFIG as CORE_CONFIG } from 'core' import { CONFIG as CORE_CONFIG } from 'core'
import { AppDatabase, getHomeCommunity } from 'database'
import { getLogger } from 'log4js'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { sendUserToGms } from '@/graphql/resolver/util/sendUserToGms' import { sendUserToGms } from '@/graphql/resolver/util/sendUserToGms'
import { LogError } from '@/server/LogError' import { LogError } from '@/server/LogError'
import { initLogging } from '@/server/logger' import { initLogging } from '@/server/logger'
import { AppDatabase, getHomeCommunity } from 'database'
import { getLogger } from 'log4js'
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.apis.gms.ExportUsers`) const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.apis.gms.ExportUsers`)

View File

@ -1,11 +1,10 @@
import axios from 'axios' import axios from 'axios'
import { httpAgent, httpsAgent } from '@/apis/ConnectionAgents'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { CONFIG } from '@/config'
import { LogError } from '@/server/LogError'
import { ensureUrlEndsWithSlash } from 'core' import { ensureUrlEndsWithSlash } from 'core'
import { getLogger } from 'log4js' import { getLogger } from 'log4js'
import { httpAgent, httpsAgent } from '@/apis/ConnectionAgents'
import { CONFIG } from '@/config'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { LogError } from '@/server/LogError'
import { GmsUser } from './model/GmsUser' import { GmsUser } from './model/GmsUser'

View File

@ -1,9 +1,8 @@
import { AppDatabase, User } from 'database' import { AppDatabase, User } from 'database'
import { getLogger } from 'log4js'
import { IsNull, Not } from 'typeorm' import { IsNull, Not } from 'typeorm'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { initLogging } from '@/server/logger' import { initLogging } from '@/server/logger'
import { getLogger } from 'log4js'
import { HumHubClient } from './HumHubClient' import { HumHubClient } from './HumHubClient'
import { GetUser } from './model/GetUser' import { GetUser } from './model/GetUser'
import { UsersResponse } from './model/UsersResponse' import { UsersResponse } from './model/UsersResponse'

View File

@ -1,12 +1,11 @@
import { ProjectBranding } from 'database' import { ProjectBranding } from 'database'
import { SignJWT } from 'jose' import { SignJWT } from 'jose'
import { getLogger } from 'log4js'
import { IRequestOptions, IRestResponse, RestClient } from 'typed-rest-client' import { IRequestOptions, IRestResponse, RestClient } from 'typed-rest-client'
import { CONFIG } from '@/config' import { CONFIG } from '@/config'
import { LogError } from '@/server/LogError'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { getLogger } from 'log4js' import { LogError } from '@/server/LogError'
import { PostUserLoggingView } from './logging/PostUserLogging.view' import { PostUserLoggingView } from './logging/PostUserLogging.view'
import { GetUser } from './model/GetUser' import { GetUser } from './model/GetUser'
import { PostUser } from './model/PostUser' import { PostUser } from './model/PostUser'

View File

@ -1,11 +1,9 @@
import { User } from 'database' import { User } from 'database'
import { getLogger } from 'log4js'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { LogError } from '@/server/LogError' import { LogError } from '@/server/LogError'
import { getLogger } from 'log4js'
import { HumHubClient } from './HumHubClient'
import { isHumhubUserIdenticalToDbUser } from './compareHumhubUserDbUser' import { isHumhubUserIdenticalToDbUser } from './compareHumhubUserDbUser'
import { HumHubClient } from './HumHubClient'
import { GetUser } from './model/GetUser' import { GetUser } from './model/GetUser'
import { PostUser } from './model/PostUser' import { PostUser } from './model/PostUser'

View File

@ -1,14 +1,12 @@
import { OpenaiThreads, User } from 'database' import { OpenaiThreads, User } from 'database'
import { getLogger } from 'log4js'
import { OpenAI } from 'openai' import { OpenAI } from 'openai'
import { Message } from 'openai/resources/beta/threads/messages' import { Message } from 'openai/resources/beta/threads/messages'
import { httpsAgent } from '@/apis/ConnectionAgents' import { httpsAgent } from '@/apis/ConnectionAgents'
import { CONFIG } from '@/config' import { CONFIG } from '@/config'
import { Message as MessageModel } from './model/Message'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { getLogger } from 'log4js' import { Message as MessageModel } from './model/Message'
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.apis.openai.OpenaiClient`) const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.apis.openai.OpenaiClient`)
// this is the time after when openai is deleting an inactive thread // this is the time after when openai is deleting an inactive thread
@ -89,8 +87,13 @@ export class OpenaiClient {
logger.warn(`No openai thread found for user: ${user.id}`) logger.warn(`No openai thread found for user: ${user.id}`)
return [] return []
} }
if (openaiThreadEntity.updatedAt < new Date(Date.now() - OPENAI_AI_THREAD_DEFAULT_TIMEOUT_DAYS * 24 * 60 * 60 * 1000)) { if (
logger.info(`Openai thread for user: ${user.id} is older than ${OPENAI_AI_THREAD_DEFAULT_TIMEOUT_DAYS} days, deleting...`) openaiThreadEntity.updatedAt <
new Date(Date.now() - OPENAI_AI_THREAD_DEFAULT_TIMEOUT_DAYS * 24 * 60 * 60 * 1000)
) {
logger.info(
`Openai thread for user: ${user.id} is older than ${OPENAI_AI_THREAD_DEFAULT_TIMEOUT_DAYS} days, deleting...`,
)
// let run async, because it could need some time, but we don't need to wait, because we create a new one nevertheless // let run async, because it could need some time, but we don't need to wait, because we create a new one nevertheless
// biome-ignore lint/complexity/noVoid: start it intentionally async without waiting for result // biome-ignore lint/complexity/noVoid: start it intentionally async without waiting for result
void this.deleteThread(openaiThreadEntity.id) void this.deleteThread(openaiThreadEntity.id)
@ -113,7 +116,7 @@ export class OpenaiClient {
) )
.reverse() .reverse()
} catch (e) { } catch (e) {
if(e instanceof Error && e.toString().includes('No thread found with id')) { if (e instanceof Error && e.toString().includes('No thread found with id')) {
logger.info(`Thread not found: ${openaiThreadEntity.id}`) logger.info(`Thread not found: ${openaiThreadEntity.id}`)
return [] return []
} }
@ -141,7 +144,10 @@ export class OpenaiClient {
} }
public async runAndGetLastNewMessage(threadId: string): Promise<MessageModel> { public async runAndGetLastNewMessage(threadId: string): Promise<MessageModel> {
const updateOpenAiThreadResolver = OpenaiThreads.update({ id: threadId }, { updatedAt: new Date() }) const updateOpenAiThreadResolver = OpenaiThreads.update(
{ id: threadId },
{ updatedAt: new Date() },
)
const run = await this.openai.beta.threads.runs.createAndPoll(threadId, { const run = await this.openai.beta.threads.runs.createAndPoll(threadId, {
assistant_id: CONFIG.OPENAI_ASSISTANT_ID, assistant_id: CONFIG.OPENAI_ASSISTANT_ID,
}) })

View File

@ -1,4 +1,4 @@
import { SignJWT, jwtVerify } from 'jose' import { jwtVerify, SignJWT } from 'jose'
import { CONFIG } from '@/config/' import { CONFIG } from '@/config/'
import { LogError } from '@/server/LogError' import { LogError } from '@/server/LogError'

View File

@ -11,11 +11,11 @@ import {
GRAPHIQL, GRAPHIQL,
HUMHUB_ACTIVE, HUMHUB_ACTIVE,
HUMHUB_API_URL, HUMHUB_API_URL,
LOG_FILES_BASE_PATH,
LOG_LEVEL,
LOG4JS_CONFIG, LOG4JS_CONFIG,
LOGIN_APP_SECRET, LOGIN_APP_SECRET,
LOGIN_SERVER_KEY, LOGIN_SERVER_KEY,
LOG_FILES_BASE_PATH,
LOG_LEVEL,
NODE_ENV, NODE_ENV,
OPENAI_ACTIVE, OPENAI_ACTIVE,
PRODUCTION, PRODUCTION,

View File

@ -1,6 +1,5 @@
import { User, UserRole } from 'database'
import { RoleNames } from '@enum/RoleNames' import { RoleNames } from '@enum/RoleNames'
import { User, UserRole } from 'database'
export class UserLogic { export class UserLogic {
public constructor(private self: User) {} public constructor(private self: User) {}

View File

@ -1,35 +1,35 @@
export { EventType } from './EventType'
export { Event } from './Event'
export { EVENT_ADMIN_CONTRIBUTION_CONFIRM } from './EVENT_ADMIN_CONTRIBUTION_CONFIRM' export { EVENT_ADMIN_CONTRIBUTION_CONFIRM } from './EVENT_ADMIN_CONTRIBUTION_CONFIRM'
export { EVENT_ADMIN_CONTRIBUTION_CREATE } from './EVENT_ADMIN_CONTRIBUTION_CREATE' export { EVENT_ADMIN_CONTRIBUTION_CREATE } from './EVENT_ADMIN_CONTRIBUTION_CREATE'
export { EVENT_ADMIN_CONTRIBUTION_DELETE } from './EVENT_ADMIN_CONTRIBUTION_DELETE' export { EVENT_ADMIN_CONTRIBUTION_DELETE } from './EVENT_ADMIN_CONTRIBUTION_DELETE'
export { EVENT_ADMIN_CONTRIBUTION_DENY } from './EVENT_ADMIN_CONTRIBUTION_DENY' export { EVENT_ADMIN_CONTRIBUTION_DENY } from './EVENT_ADMIN_CONTRIBUTION_DENY'
export { EVENT_ADMIN_CONTRIBUTION_UPDATE } from './EVENT_ADMIN_CONTRIBUTION_UPDATE'
export { EVENT_ADMIN_CONTRIBUTION_LINK_CREATE } from './EVENT_ADMIN_CONTRIBUTION_LINK_CREATE' export { EVENT_ADMIN_CONTRIBUTION_LINK_CREATE } from './EVENT_ADMIN_CONTRIBUTION_LINK_CREATE'
export { EVENT_ADMIN_CONTRIBUTION_LINK_DELETE } from './EVENT_ADMIN_CONTRIBUTION_LINK_DELETE' export { EVENT_ADMIN_CONTRIBUTION_LINK_DELETE } from './EVENT_ADMIN_CONTRIBUTION_LINK_DELETE'
export { EVENT_ADMIN_CONTRIBUTION_LINK_UPDATE } from './EVENT_ADMIN_CONTRIBUTION_LINK_UPDATE' export { EVENT_ADMIN_CONTRIBUTION_LINK_UPDATE } from './EVENT_ADMIN_CONTRIBUTION_LINK_UPDATE'
export { EVENT_ADMIN_CONTRIBUTION_MESSAGE_CREATE } from './EVENT_ADMIN_CONTRIBUTION_MESSAGE_CREATE' export { EVENT_ADMIN_CONTRIBUTION_MESSAGE_CREATE } from './EVENT_ADMIN_CONTRIBUTION_MESSAGE_CREATE'
export { EVENT_ADMIN_CONTRIBUTION_UPDATE } from './EVENT_ADMIN_CONTRIBUTION_UPDATE'
export { EVENT_ADMIN_USER_DELETE } from './EVENT_ADMIN_USER_DELETE' export { EVENT_ADMIN_USER_DELETE } from './EVENT_ADMIN_USER_DELETE'
export { EVENT_ADMIN_USER_UNDELETE } from './EVENT_ADMIN_USER_UNDELETE'
export { EVENT_ADMIN_USER_ROLE_SET } from './EVENT_ADMIN_USER_ROLE_SET' export { EVENT_ADMIN_USER_ROLE_SET } from './EVENT_ADMIN_USER_ROLE_SET'
export { EVENT_ADMIN_USER_UNDELETE } from './EVENT_ADMIN_USER_UNDELETE'
export { EVENT_CONTRIBUTION_CREATE } from './EVENT_CONTRIBUTION_CREATE' export { EVENT_CONTRIBUTION_CREATE } from './EVENT_CONTRIBUTION_CREATE'
export { EVENT_CONTRIBUTION_DELETE } from './EVENT_CONTRIBUTION_DELETE' export { EVENT_CONTRIBUTION_DELETE } from './EVENT_CONTRIBUTION_DELETE'
export { EVENT_CONTRIBUTION_UPDATE } from './EVENT_CONTRIBUTION_UPDATE'
export { EVENT_CONTRIBUTION_MESSAGE_CREATE } from './EVENT_CONTRIBUTION_MESSAGE_CREATE'
export { EVENT_CONTRIBUTION_LINK_REDEEM } from './EVENT_CONTRIBUTION_LINK_REDEEM' export { EVENT_CONTRIBUTION_LINK_REDEEM } from './EVENT_CONTRIBUTION_LINK_REDEEM'
export { EVENT_CONTRIBUTION_MESSAGE_CREATE } from './EVENT_CONTRIBUTION_MESSAGE_CREATE'
export { EVENT_CONTRIBUTION_UPDATE } from './EVENT_CONTRIBUTION_UPDATE'
export { EVENT_EMAIL_ACCOUNT_MULTIREGISTRATION } from './EVENT_EMAIL_ACCOUNT_MULTIREGISTRATION' export { EVENT_EMAIL_ACCOUNT_MULTIREGISTRATION } from './EVENT_EMAIL_ACCOUNT_MULTIREGISTRATION'
export { EVENT_EMAIL_ADMIN_CONFIRMATION } from './EVENT_EMAIL_ADMIN_CONFIRMATION' export { EVENT_EMAIL_ADMIN_CONFIRMATION } from './EVENT_EMAIL_ADMIN_CONFIRMATION'
export { EVENT_EMAIL_CONFIRMATION } from './EVENT_EMAIL_CONFIRMATION' export { EVENT_EMAIL_CONFIRMATION } from './EVENT_EMAIL_CONFIRMATION'
export { EVENT_EMAIL_FORGOT_PASSWORD } from './EVENT_EMAIL_FORGOT_PASSWORD' export { EVENT_EMAIL_FORGOT_PASSWORD } from './EVENT_EMAIL_FORGOT_PASSWORD'
export { EVENT_NEWSLETTER_SUBSCRIBE } from './EVENT_NEWSLETTER_SUBSCRIBE' export { EVENT_NEWSLETTER_SUBSCRIBE } from './EVENT_NEWSLETTER_SUBSCRIBE'
export { EVENT_NEWSLETTER_UNSUBSCRIBE } from './EVENT_NEWSLETTER_UNSUBSCRIBE' export { EVENT_NEWSLETTER_UNSUBSCRIBE } from './EVENT_NEWSLETTER_UNSUBSCRIBE'
export { EVENT_TRANSACTION_SEND } from './EVENT_TRANSACTION_SEND'
export { EVENT_TRANSACTION_RECEIVE } from './EVENT_TRANSACTION_RECEIVE'
export { EVENT_TRANSACTION_LINK_CREATE } from './EVENT_TRANSACTION_LINK_CREATE' export { EVENT_TRANSACTION_LINK_CREATE } from './EVENT_TRANSACTION_LINK_CREATE'
export { EVENT_TRANSACTION_LINK_DELETE } from './EVENT_TRANSACTION_LINK_DELETE' export { EVENT_TRANSACTION_LINK_DELETE } from './EVENT_TRANSACTION_LINK_DELETE'
export { EVENT_TRANSACTION_LINK_REDEEM } from './EVENT_TRANSACTION_LINK_REDEEM' export { EVENT_TRANSACTION_LINK_REDEEM } from './EVENT_TRANSACTION_LINK_REDEEM'
export { EVENT_TRANSACTION_RECEIVE } from './EVENT_TRANSACTION_RECEIVE'
export { EVENT_TRANSACTION_SEND } from './EVENT_TRANSACTION_SEND'
export { EVENT_USER_ACTIVATE_ACCOUNT } from './EVENT_USER_ACTIVATE_ACCOUNT' export { EVENT_USER_ACTIVATE_ACCOUNT } from './EVENT_USER_ACTIVATE_ACCOUNT'
export { EVENT_USER_INFO_UPDATE } from './EVENT_USER_INFO_UPDATE' export { EVENT_USER_INFO_UPDATE } from './EVENT_USER_INFO_UPDATE'
export { EVENT_USER_LOGIN } from './EVENT_USER_LOGIN' export { EVENT_USER_LOGIN } from './EVENT_USER_LOGIN'
export { EVENT_USER_LOGOUT } from './EVENT_USER_LOGOUT' export { EVENT_USER_LOGOUT } from './EVENT_USER_LOGOUT'
export { EVENT_USER_REGISTER } from './EVENT_USER_REGISTER' export { EVENT_USER_REGISTER } from './EVENT_USER_REGISTER'
export { Event } from './Event'
export { EventType } from './EventType'

View File

@ -1,26 +1,32 @@
import { import {
CommunityHandshakeState as DbCommunityHandshakeState, CommunityHandshakeStateLogic,
EncryptedTransferArgs,
ensureUrlEndsWithSlash,
getFederatedCommunityWithApiOrFail,
} from 'core'
import {
CommunityHandshakeStateLoggingView, CommunityHandshakeStateLoggingView,
CommunityHandshakeStateType,
CommunityHandshakeState as DbCommunityHandshakeState,
FederatedCommunity as DbFederatedCommunity, FederatedCommunity as DbFederatedCommunity,
findPendingCommunityHandshake, findPendingCommunityHandshake,
getHomeCommunityWithFederatedCommunityOrFail,
CommunityHandshakeStateType,
getCommunityByPublicKeyOrFail, getCommunityByPublicKeyOrFail,
getHomeCommunityWithFederatedCommunityOrFail,
} from 'database' } from 'database'
import { randombytes_random } from 'sodium-native'
import { AuthenticationClient as V1_0_AuthenticationClient } from '@/federation/client/1_0/AuthenticationClient'
import { ensureUrlEndsWithSlash, getFederatedCommunityWithApiOrFail } from 'core'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { communityAuthenticatedSchema, encryptAndSign, OpenConnectionJwtPayloadType } from 'shared'
import { getLogger } from 'log4js' import { getLogger } from 'log4js'
import {
communityAuthenticatedSchema,
Ed25519PublicKey,
encryptAndSign,
OpenConnectionJwtPayloadType,
} from 'shared'
import { randombytes_random } from 'sodium-native'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { AuthenticationClient as V1_0_AuthenticationClient } from '@/federation/client/1_0/AuthenticationClient'
import { AuthenticationClientFactory } from './client/AuthenticationClientFactory' import { AuthenticationClientFactory } from './client/AuthenticationClientFactory'
import { EncryptedTransferArgs } from 'core'
import { CommunityHandshakeStateLogic } from 'core'
import { Ed25519PublicKey } from 'shared'
const createLogger = (functionName: string) => getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.federation.authenticateCommunities.${functionName}`) const createLogger = (functionName: string) =>
getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.federation.authenticateCommunities.${functionName}`)
export enum StartCommunityAuthenticationResult { export enum StartCommunityAuthenticationResult {
ALREADY_AUTHENTICATED = 'already authenticated', ALREADY_AUTHENTICATED = 'already authenticated',
@ -48,7 +54,9 @@ export async function startCommunityAuthentication(
// - if communityUuid is a valid v4Uuid and // - if communityUuid is a valid v4Uuid and
// - if authenticatedAt is a valid date // - if authenticatedAt is a valid date
if (communityAuthenticatedSchema.safeParse(comB).success) { if (communityAuthenticatedSchema.safeParse(comB).success) {
methodLogger.debug(`comB.communityUuid is already a valid v4Uuid ${ comB.communityUuid || 'null' } and was authenticated at ${ comB.authenticatedAt || 'null'}`) methodLogger.debug(
`comB.communityUuid is already a valid v4Uuid ${comB.communityUuid || 'null'} and was authenticated at ${comB.authenticatedAt || 'null'}`,
)
return StartCommunityAuthenticationResult.ALREADY_AUTHENTICATED return StartCommunityAuthenticationResult.ALREADY_AUTHENTICATED
} }
/*methodLogger.debug('comB.uuid is null or is a not valid v4Uuid...', /*methodLogger.debug('comB.uuid is null or is a not valid v4Uuid...',
@ -62,7 +70,10 @@ export async function startCommunityAuthentication(
// retry on timeout or failure // retry on timeout or failure
if (!(await stateLogic.isTimeoutUpdate())) { if (!(await stateLogic.isTimeoutUpdate())) {
// authentication with community and api version is still in progress and it is not timeout yet // authentication with community and api version is still in progress and it is not timeout yet
methodLogger.debug('existingState, so we exit here', new CommunityHandshakeStateLoggingView(existingState)) methodLogger.debug(
'existingState, so we exit here',
new CommunityHandshakeStateLoggingView(existingState),
)
return StartCommunityAuthenticationResult.ALREADY_IN_PROGRESS return StartCommunityAuthenticationResult.ALREADY_IN_PROGRESS
} }
} }
@ -82,7 +93,8 @@ export async function startCommunityAuthentication(
methodLogger.debug('[START_COMMUNITY_AUTHENTICATION] community handshake state created') methodLogger.debug('[START_COMMUNITY_AUTHENTICATION] community handshake state created')
//create JWT with url in payload encrypted by foreignCom.publicJwtKey and signed with homeCom.privateJwtKey //create JWT with url in payload encrypted by foreignCom.publicJwtKey and signed with homeCom.privateJwtKey
const payload = new OpenConnectionJwtPayloadType(handshakeID, const payload = new OpenConnectionJwtPayloadType(
handshakeID,
ensureUrlEndsWithSlash(homeFedComA.endPoint).concat(homeFedComA.apiVersion), ensureUrlEndsWithSlash(homeFedComA.endPoint).concat(homeFedComA.apiVersion),
) )
// methodLogger.debug('payload', payload) // methodLogger.debug('payload', payload)

View File

@ -1,11 +1,8 @@
import { EncryptedTransferArgs, ensureUrlEndsWithSlash } from 'core'
import { FederatedCommunity as DbFederatedCommunity } from 'database' import { FederatedCommunity as DbFederatedCommunity } from 'database'
import { GraphQLClient } from 'graphql-request' import { GraphQLClient } from 'graphql-request'
import { ensureUrlEndsWithSlash } from 'core'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { EncryptedTransferArgs } from 'core'
import { getLogger } from 'log4js' import { getLogger } from 'log4js'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { openConnection } from './query/openConnection' import { openConnection } from './query/openConnection'
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.federation.client.1_0.AuthenticationClient`) const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.federation.client.1_0.AuthenticationClient`)

View File

@ -1,11 +1,8 @@
import { EncryptedTransferArgs, ensureUrlEndsWithSlash } from 'core'
import { FederatedCommunity as DbFederatedCommunity } from 'database' import { FederatedCommunity as DbFederatedCommunity } from 'database'
import { GraphQLClient } from 'graphql-request' import { GraphQLClient } from 'graphql-request'
import { ensureUrlEndsWithSlash } from 'core'
import { getLogger } from 'log4js' import { getLogger } from 'log4js'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { EncryptedTransferArgs } from 'core'
import { processDisburseJwtOnSenderCommunity as processDisburseJwtOnSenderCommunityQuery } from './query/processDisburseJwtOnSenderCommunity' import { processDisburseJwtOnSenderCommunity as processDisburseJwtOnSenderCommunityQuery } from './query/processDisburseJwtOnSenderCommunity'
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.federation.client.1_0.DisbursementClient`) const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.federation.client.1_0.DisbursementClient`)
@ -30,7 +27,9 @@ export class DisbursementClient {
async sendDisburseJwtToSenderCommunity(args: EncryptedTransferArgs): Promise<string | null> { async sendDisburseJwtToSenderCommunity(args: EncryptedTransferArgs): Promise<string | null> {
logger.debug('sendDisburseJwtToSenderCommunity against endpoint=', this.endpoint) logger.debug('sendDisburseJwtToSenderCommunity against endpoint=', this.endpoint)
try { try {
const { data } = await this.client.rawRequest<{ processDisburseJwtOnSenderCommunity: string }>(processDisburseJwtOnSenderCommunityQuery, { args }) const { data } = await this.client.rawRequest<{
processDisburseJwtOnSenderCommunity: string
}>(processDisburseJwtOnSenderCommunityQuery, { args })
const response = data?.processDisburseJwtOnSenderCommunity const response = data?.processDisburseJwtOnSenderCommunity
if (response) { if (response) {
logger.debug('received response:', response) logger.debug('received response:', response)
@ -43,5 +42,4 @@ export class DisbursementClient {
} }
return null return null
} }
} }

View File

@ -1,11 +1,10 @@
import { ensureUrlEndsWithSlash } from 'core'
import { FederatedCommunity as DbFederatedCommunity } from 'database' import { FederatedCommunity as DbFederatedCommunity } from 'database'
import { GraphQLClient } from 'graphql-request' import { GraphQLClient } from 'graphql-request'
import { getLogger } from 'log4js'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { getPublicCommunityInfo } from '@/federation/client/1_0/query/getPublicCommunityInfo' import { getPublicCommunityInfo } from '@/federation/client/1_0/query/getPublicCommunityInfo'
import { getPublicKey } from '@/federation/client/1_0/query/getPublicKey' import { getPublicKey } from '@/federation/client/1_0/query/getPublicKey'
import { ensureUrlEndsWithSlash } from 'core'
import { getLogger } from 'log4js'
import { PublicCommunityInfoLoggingView } from './logging/PublicCommunityInfoLogging.view' import { PublicCommunityInfoLoggingView } from './logging/PublicCommunityInfoLogging.view'
import { GetPublicKeyResult } from './model/GetPublicKeyResult' import { GetPublicKeyResult } from './model/GetPublicKeyResult'

View File

@ -1,9 +1,7 @@
import { FederatedCommunity as DbFederatedCommunity } from 'database'
import { AuthenticationClient as V1_0_AuthenticationClient } from '@/federation/client/1_0/AuthenticationClient'
import { AuthenticationClient as V1_1_AuthenticationClient } from '@/federation/client/1_1/AuthenticationClient'
import { ApiVersionType } from 'core' import { ApiVersionType } from 'core'
import { FederatedCommunity as DbFederatedCommunity } from 'database'
import { AuthenticationClient as V1_0_AuthenticationClient } from '@/federation/client/1_0/AuthenticationClient'
import { AuthenticationClient as V1_1_AuthenticationClient } from '@/federation/client/1_1/AuthenticationClient'
type AuthenticationClient = V1_0_AuthenticationClient | V1_1_AuthenticationClient type AuthenticationClient = V1_0_AuthenticationClient | V1_1_AuthenticationClient

View File

@ -1,8 +1,7 @@
import { ApiVersionType } from 'core'
import { FederatedCommunity as DbFederatedCommunity } from 'database' import { FederatedCommunity as DbFederatedCommunity } from 'database'
import { DisbursementClient as V1_0_DisbursementClient } from '@/federation/client/1_0/DisbursementClient' import { DisbursementClient as V1_0_DisbursementClient } from '@/federation/client/1_0/DisbursementClient'
import { DisbursementClient as V1_1_DisbursementClient } from '@/federation/client/1_1/DisbursementClient' import { DisbursementClient as V1_1_DisbursementClient } from '@/federation/client/1_1/DisbursementClient'
import { ApiVersionType } from 'core'
type DisbursementClient = V1_0_DisbursementClient | V1_1_DisbursementClient type DisbursementClient = V1_0_DisbursementClient | V1_1_DisbursementClient

View File

@ -1,8 +1,7 @@
import { ApiVersionType, ensureUrlEndsWithSlash } from 'core'
import { FederatedCommunity as DbFederatedCommunity } from 'database' import { FederatedCommunity as DbFederatedCommunity } from 'database'
import { FederationClient as V1_0_FederationClient } from '@/federation/client/1_0/FederationClient' import { FederationClient as V1_0_FederationClient } from '@/federation/client/1_0/FederationClient'
import { FederationClient as V1_1_FederationClient } from '@/federation/client/1_1/FederationClient' import { FederationClient as V1_1_FederationClient } from '@/federation/client/1_1/FederationClient'
import { ApiVersionType, ensureUrlEndsWithSlash } from 'core'
type FederationClient = V1_0_FederationClient | V1_1_FederationClient type FederationClient = V1_0_FederationClient | V1_1_FederationClient

View File

@ -1,13 +1,11 @@
import { cleanDB, testEnvironment } from '@test/helpers'
import { ApolloServerTestClient } from 'apollo-server-testing' import { ApolloServerTestClient } from 'apollo-server-testing'
import { FederatedCommunity as DbFederatedCommunity } from 'database' import { getLogger } from 'config-schema/test/testSetup'
import { AppDatabase, FederatedCommunity as DbFederatedCommunity } from 'database'
import { GraphQLClient } from 'graphql-request' import { GraphQLClient } from 'graphql-request'
import { Response } from 'graphql-request/dist/types' import { Response } from 'graphql-request/dist/types'
import { DataSource, Not } from 'typeorm' import { DataSource, Not } from 'typeorm'
import { cleanDB, testEnvironment } from '@test/helpers'
import { getLogger } from 'config-schema/test/testSetup'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { AppDatabase } from 'database'
import { validateCommunities } from './validateCommunities' import { validateCommunities } from './validateCommunities'
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.federation.validateCommunities`) const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.federation.validateCommunities`)

View File

@ -1,20 +1,19 @@
import { ApiVersionType } from 'core'
import { import {
Community as DbCommunity, Community as DbCommunity,
FederatedCommunity as DbFederatedCommunity, FederatedCommunity as DbFederatedCommunity,
getHomeCommunity, getHomeCommunity,
} from 'database' } from 'database'
import { getLogger } from 'log4js'
import { createKeyPair, Ed25519PublicKey } from 'shared'
import { IsNull } from 'typeorm' import { IsNull } from 'typeorm'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { FederationClient as V1_0_FederationClient } from '@/federation/client/1_0/FederationClient' import { FederationClient as V1_0_FederationClient } from '@/federation/client/1_0/FederationClient'
import { PublicCommunityInfo } from '@/federation/client/1_0/model/PublicCommunityInfo' import { PublicCommunityInfo } from '@/federation/client/1_0/model/PublicCommunityInfo'
import { FederationClientFactory } from '@/federation/client/FederationClientFactory' import { FederationClientFactory } from '@/federation/client/FederationClientFactory'
import { LogError } from '@/server/LogError' import { LogError } from '@/server/LogError'
import { createKeyPair, Ed25519PublicKey } from 'shared'
import { getLogger } from 'log4js'
import { startCommunityAuthentication } from './authenticateCommunities' import { startCommunityAuthentication } from './authenticateCommunities'
import { PublicCommunityInfoLoggingView } from './client/1_0/logging/PublicCommunityInfoLogging.view' import { PublicCommunityInfoLoggingView } from './client/1_0/logging/PublicCommunityInfoLogging.view'
import { ApiVersionType } from 'core'
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.federation.validateCommunities`) const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.federation.validateCommunities`)
@ -47,7 +46,11 @@ export async function validateCommunities(): Promise<void> {
logger.debug(`verify federation community: ${dbFedComB.endPoint}${dbFedComB.apiVersion}`) logger.debug(`verify federation community: ${dbFedComB.endPoint}${dbFedComB.apiVersion}`)
const apiValueStrings: string[] = Object.values(ApiVersionType) const apiValueStrings: string[] = Object.values(ApiVersionType)
if (!apiValueStrings.includes(dbFedComB.apiVersion)) { if (!apiValueStrings.includes(dbFedComB.apiVersion)) {
logger.debug('dbFedComB with unsupported apiVersion', dbFedComB.endPoint, dbFedComB.apiVersion) logger.debug(
'dbFedComB with unsupported apiVersion',
dbFedComB.endPoint,
dbFedComB.apiVersion,
)
logger.debug(`supported ApiVersions=`, apiValueStrings) logger.debug(`supported ApiVersions=`, apiValueStrings)
continue continue
} }
@ -65,18 +68,29 @@ export async function validateCommunities(): Promise<void> {
const pubComInfo = await client.getPublicCommunityInfo() const pubComInfo = await client.getPublicCommunityInfo()
if (pubComInfo) { if (pubComInfo) {
await writeForeignCommunity(dbFedComB, pubComInfo) await writeForeignCommunity(dbFedComB, pubComInfo)
logger.debug(`wrote response of getPublicCommunityInfo in dbFedComB ${dbFedComB.endPoint}`) logger.debug(
`wrote response of getPublicCommunityInfo in dbFedComB ${dbFedComB.endPoint}`,
)
try { try {
const result = await startCommunityAuthentication(dbFedComB) const result = await startCommunityAuthentication(dbFedComB)
logger.info(`${dbFedComB.endPoint}${dbFedComB.apiVersion} verified, authentication state: ${result}`) logger.info(
`${dbFedComB.endPoint}${dbFedComB.apiVersion} verified, authentication state: ${result}`,
)
} catch (err) { } catch (err) {
logger.warn(`Warning: Authentication of community ${dbFedComB.endPoint} still ongoing:`, err) logger.warn(
`Warning: Authentication of community ${dbFedComB.endPoint} still ongoing:`,
err,
)
} }
} else { } else {
logger.debug('missing result of getPublicCommunityInfo') logger.debug('missing result of getPublicCommunityInfo')
} }
} else { } else {
logger.debug('received not matching publicKey:', clientPublicKey.asHex(), fedComBPublicKey.asHex()) logger.debug(
'received not matching publicKey:',
clientPublicKey.asHex(),
fedComBPublicKey.asHex(),
)
} }
} }
} catch (err) { } catch (err) {
@ -89,25 +103,36 @@ export async function writeJwtKeyPairInHomeCommunity(): Promise<DbCommunity> {
logger.debug(`Federation: writeJwtKeyPairInHomeCommunity`) logger.debug(`Federation: writeJwtKeyPairInHomeCommunity`)
try { try {
// check for existing homeCommunity entry // check for existing homeCommunity entry
let homeCom = await getHomeCommunity() const homeCom = await getHomeCommunity()
if (homeCom) { if (homeCom) {
if (!homeCom.publicJwtKey && !homeCom.privateJwtKey) { if (!homeCom.publicJwtKey && !homeCom.privateJwtKey) {
// Generate key pair using jose library // Generate key pair using jose library
const { publicKey, privateKey } = await createKeyPair(); const { publicKey, privateKey } = await createKeyPair()
logger.debug(`Federation: writeJwtKeyPairInHomeCommunity publicKey=`, publicKey); logger.debug(`Federation: writeJwtKeyPairInHomeCommunity publicKey=`, publicKey)
logger.debug(`Federation: writeJwtKeyPairInHomeCommunity privateKey=`, privateKey.slice(0, 20)); logger.debug(
`Federation: writeJwtKeyPairInHomeCommunity privateKey=`,
privateKey.slice(0, 20),
)
homeCom.publicJwtKey = publicKey; homeCom.publicJwtKey = publicKey
logger.debug(`Federation: writeJwtKeyPairInHomeCommunity publicJwtKey.length=`, homeCom.publicJwtKey.length); logger.debug(
homeCom.privateJwtKey = privateKey; `Federation: writeJwtKeyPairInHomeCommunity publicJwtKey.length=`,
logger.debug(`Federation: writeJwtKeyPairInHomeCommunity privateJwtKey.length=`, homeCom.privateJwtKey.length); homeCom.publicJwtKey.length,
)
homeCom.privateJwtKey = privateKey
logger.debug(
`Federation: writeJwtKeyPairInHomeCommunity privateJwtKey.length=`,
homeCom.privateJwtKey.length,
)
await DbCommunity.save(homeCom) await DbCommunity.save(homeCom)
logger.debug(`Federation: writeJwtKeyPairInHomeCommunity done`) logger.debug(`Federation: writeJwtKeyPairInHomeCommunity done`)
} else { } else {
logger.debug(`Federation: writeJwtKeyPairInHomeCommunity: keypair already exists`) logger.debug(`Federation: writeJwtKeyPairInHomeCommunity: keypair already exists`)
} }
} else { } else {
throw new Error(`Error! A HomeCommunity-Entry still not exist! Please start the DHT-Modul first.`) throw new Error(
`Error! A HomeCommunity-Entry still not exist! Please start the DHT-Modul first.`,
)
} }
return homeCom return homeCom
} catch (err) { } catch (err) {

View File

@ -1,8 +1,7 @@
import { ContributionMessageType } from '@enum/ContributionMessageType'
import { IsEnum, IsInt, IsString } from 'class-validator' import { IsEnum, IsInt, IsString } from 'class-validator'
import { ArgsType, Field, InputType, Int } from 'type-graphql' import { ArgsType, Field, InputType, Int } from 'type-graphql'
import { ContributionMessageType } from '@enum/ContributionMessageType'
import { isValidDateString } from '@/graphql/validator/DateString' import { isValidDateString } from '@/graphql/validator/DateString'
@InputType() @InputType()

View File

@ -1,8 +1,7 @@
import { Order } from '@enum/Order'
import { IsEnum, IsPositive } from 'class-validator' import { IsEnum, IsPositive } from 'class-validator'
import { ArgsType, Field, InputType, Int } from 'type-graphql' import { ArgsType, Field, InputType, Int } from 'type-graphql'
import { Order } from '@enum/Order'
@ArgsType() @ArgsType()
@InputType() @InputType()
export class Paginated { export class Paginated {

View File

@ -1,8 +1,7 @@
import { ContributionStatus } from '@enum/ContributionStatus'
import { IsBoolean, IsPositive, IsString } from 'class-validator' import { IsBoolean, IsPositive, IsString } from 'class-validator'
import { ArgsType, Field, InputType, Int } from 'type-graphql' import { ArgsType, Field, InputType, Int } from 'type-graphql'
import { ContributionStatus } from '@enum/ContributionStatus'
import { isContributionStatusArray } from '@/graphql/validator/ContributionStatusArray' import { isContributionStatusArray } from '@/graphql/validator/ContributionStatusArray'
@ArgsType() @ArgsType()

View File

@ -1,8 +1,7 @@
import { RoleNames } from '@enum/RoleNames'
import { IsEnum, IsPositive } from 'class-validator' import { IsEnum, IsPositive } from 'class-validator'
import { ArgsType, Field, InputType, Int } from 'type-graphql' import { ArgsType, Field, InputType, Int } from 'type-graphql'
import { RoleNames } from '@enum/RoleNames'
@InputType() @InputType()
@ArgsType() @ArgsType()
export class SetUserRoleArgs { export class SetUserRoleArgs {

View File

@ -1,9 +1,8 @@
import { IsBoolean, IsEnum, IsInt, IsString } from 'class-validator'
import { ArgsType, Field, InputType, Int } from 'type-graphql'
import { GmsPublishLocationType } from '@enum/GmsPublishLocationType' import { GmsPublishLocationType } from '@enum/GmsPublishLocationType'
import { PublishNameType } from '@enum/PublishNameType' import { PublishNameType } from '@enum/PublishNameType'
import { Location } from '@model/Location' import { Location } from '@model/Location'
import { IsBoolean, IsEnum, IsInt, IsString } from 'class-validator'
import { ArgsType, Field, InputType, Int } from 'type-graphql'
import { isValidLocation } from '@/graphql/validator/Location' import { isValidLocation } from '@/graphql/validator/Location'

View File

@ -1,8 +1,7 @@
import { RoleNames } from '@enum/RoleNames'
import { User } from 'database' import { User } from 'database'
import { AuthChecker } from 'type-graphql' import { AuthChecker } from 'type-graphql'
import { RoleNames } from '@enum/RoleNames'
import { INALIENABLE_RIGHTS } from '@/auth/INALIENABLE_RIGHTS' import { INALIENABLE_RIGHTS } from '@/auth/INALIENABLE_RIGHTS'
import { decode, encode } from '@/auth/JWT' import { decode, encode } from '@/auth/JWT'
import { RIGHTS } from '@/auth/RIGHTS' import { RIGHTS } from '@/auth/RIGHTS'
@ -14,8 +13,8 @@ import {
ROLE_UNAUTHORIZED, ROLE_UNAUTHORIZED,
ROLE_USER, ROLE_USER,
} from '@/auth/ROLES' } from '@/auth/ROLES'
import { LogError } from '@/server/LogError'
import { Context } from '@/server/context' import { Context } from '@/server/context'
import { LogError } from '@/server/LogError'
export const isAuthorized: AuthChecker<Context> = async ({ context }, rights) => { export const isAuthorized: AuthChecker<Context> = async ({ context }, rights) => {
context.role = ROLE_UNAUTHORIZED // unauthorized user context.role = ROLE_UNAUTHORIZED // unauthorized user

View File

@ -1,5 +1,5 @@
import { registerEnumType } from 'type-graphql'
import { ContributionCycleType } from 'database' import { ContributionCycleType } from 'database'
import { registerEnumType } from 'type-graphql'
export { ContributionCycleType } export { ContributionCycleType }

View File

@ -1,5 +1,5 @@
import { registerEnumType } from 'type-graphql'
import { ContributionStatus } from 'database' import { ContributionStatus } from 'database'
import { registerEnumType } from 'type-graphql'
export { ContributionStatus } export { ContributionStatus }

View File

@ -1,5 +1,5 @@
import { registerEnumType } from 'type-graphql'
import { ContributionType } from 'database' import { ContributionType } from 'database'
import { registerEnumType } from 'type-graphql'
export { ContributionType } export { ContributionType }

View File

@ -1,5 +1,5 @@
import { registerEnumType } from 'type-graphql'
import { PendingTransactionState } from 'shared' import { PendingTransactionState } from 'shared'
import { registerEnumType } from 'type-graphql'
export { PendingTransactionState } export { PendingTransactionState }

View File

@ -1,5 +1,5 @@
import { registerEnumType } from 'type-graphql'
import { RoleNames } from 'database' import { RoleNames } from 'database'
import { registerEnumType } from 'type-graphql'
export { RoleNames } export { RoleNames }

View File

@ -2,8 +2,8 @@ import { IsString, IsUUID } from 'class-validator'
import { ArgsType, Field, InputType } from 'type-graphql' import { ArgsType, Field, InputType } from 'type-graphql'
import { Location } from '@/graphql/model/Location' import { Location } from '@/graphql/model/Location'
import { isValidLocation } from '@/graphql/validator/Location'
import { isValidHieroId } from '@/graphql/validator/HieroId' import { isValidHieroId } from '@/graphql/validator/HieroId'
import { isValidLocation } from '@/graphql/validator/Location'
@ArgsType() @ArgsType()
@InputType() @InputType()

View File

@ -1,6 +1,5 @@
import { Field, Int, ObjectType } from 'type-graphql'
import { ContributionLink } from '@model/ContributionLink' import { ContributionLink } from '@model/ContributionLink'
import { Field, Int, ObjectType } from 'type-graphql'
@ObjectType() @ObjectType()
export class ContributionLinkList { export class ContributionLinkList {

View File

@ -1,8 +1,7 @@
import { ensureUrlEndsWithSlash } from 'core'
import { FederatedCommunity as DbFederatedCommunity } from 'database' import { FederatedCommunity as DbFederatedCommunity } from 'database'
import { Field, Int, ObjectType } from 'type-graphql' import { Field, Int, ObjectType } from 'type-graphql'
import { ensureUrlEndsWithSlash } from 'core'
@ObjectType() @ObjectType()
export class FederatedCommunity { export class FederatedCommunity {
constructor(dbCom: DbFederatedCommunity) { constructor(dbCom: DbFederatedCommunity) {

View File

@ -1,6 +1,5 @@
import { Field, Float, Int, ObjectType } from 'type-graphql'
import { GdtEntryType } from '@enum/GdtEntryType' import { GdtEntryType } from '@enum/GdtEntryType'
import { Field, Float, Int, ObjectType } from 'type-graphql'
@ObjectType() @ObjectType()
export class GdtEntry { export class GdtEntry {

View File

@ -1,7 +1,6 @@
import { Decimal } from 'decimal.js-light' import { Decimal } from 'decimal.js-light'
import { Field, ObjectType } from 'type-graphql'
import { RedeemJwtPayloadType } from 'shared' import { RedeemJwtPayloadType } from 'shared'
import { Field, ObjectType } from 'type-graphql'
import { Community } from './Community' import { Community } from './Community'
import { User } from './User' import { User } from './User'

View File

@ -1,9 +1,8 @@
import { Decay, TransactionTypeId } from 'core'
import { Transaction as dbTransaction } from 'database' import { Transaction as dbTransaction } from 'database'
import { Decimal } from 'decimal.js-light' import { Decimal } from 'decimal.js-light'
import { Field, Int, ObjectType } from 'type-graphql' import { Field, Int, ObjectType } from 'type-graphql'
import { Decay, TransactionTypeId } from 'core'
import { User } from './User' import { User } from './User'
@ObjectType() @ObjectType()

View File

@ -1,10 +1,9 @@
import { GmsPublishLocationType } from '@enum/GmsPublishLocationType'
import { PublishNameType } from '@enum/PublishNameType'
import { User as DbUser } from 'database' import { User as DbUser } from 'database'
import { Field, Int, ObjectType } from 'type-graphql' import { Field, Int, ObjectType } from 'type-graphql'
import { Point } from 'typeorm' import { Point } from 'typeorm'
import { GmsPublishLocationType } from '@enum/GmsPublishLocationType'
import { PublishNameType } from '@enum/PublishNameType'
import { PublishNameLogic } from '@/data/PublishName.logic' import { PublishNameLogic } from '@/data/PublishName.logic'
import { Point2Location } from '@/graphql/resolver/util/Location2Point' import { Point2Location } from '@/graphql/resolver/util/Location2Point'

View File

@ -1,10 +1,8 @@
import { Arg, Authorized, Ctx, Mutation, Query, Resolver } from 'type-graphql'
import { OpenaiMessage } from '@input/OpenaiMessage' import { OpenaiMessage } from '@input/OpenaiMessage'
import { ChatGptMessage } from '@model/ChatGptMessage' import { ChatGptMessage } from '@model/ChatGptMessage'
import { Arg, Authorized, Ctx, Mutation, Query, Resolver } from 'type-graphql'
import { OpenaiClient } from '@/apis/openai/OpenaiClient'
import { Message } from '@/apis/openai/model/Message' import { Message } from '@/apis/openai/model/Message'
import { OpenaiClient } from '@/apis/openai/OpenaiClient'
import { RIGHTS } from '@/auth/RIGHTS' import { RIGHTS } from '@/auth/RIGHTS'
import { Context } from '@/server/context' import { Context } from '@/server/context'
@ -15,10 +13,14 @@ export class AiChatResolver {
async resumeChat(@Ctx() context: Context): Promise<ChatGptMessage[]> { async resumeChat(@Ctx() context: Context): Promise<ChatGptMessage[]> {
const openaiClient = OpenaiClient.getInstance() const openaiClient = OpenaiClient.getInstance()
if (!openaiClient) { if (!openaiClient) {
return Promise.resolve([new ChatGptMessage({ content: 'OpenAI API is not enabled', role: 'assistant' }, true)]) return Promise.resolve([
new ChatGptMessage({ content: 'OpenAI API is not enabled', role: 'assistant' }, true),
])
} }
if (!context.user) { if (!context.user) {
return Promise.resolve([new ChatGptMessage({ content: 'User not found', role: 'assistant' }, true)]) return Promise.resolve([
new ChatGptMessage({ content: 'User not found', role: 'assistant' }, true),
])
} }
const messages = await openaiClient.resumeThread(context.user) const messages = await openaiClient.resumeThread(context.user)
return messages.map((message) => new ChatGptMessage(message)) return messages.map((message) => new ChatGptMessage(message))
@ -42,10 +44,14 @@ export class AiChatResolver {
): Promise<ChatGptMessage> { ): Promise<ChatGptMessage> {
const openaiClient = OpenaiClient.getInstance() const openaiClient = OpenaiClient.getInstance()
if (!openaiClient) { if (!openaiClient) {
return Promise.resolve(new ChatGptMessage({ content: 'OpenAI API is not enabled', role: 'assistant' }, true)) return Promise.resolve(
new ChatGptMessage({ content: 'OpenAI API is not enabled', role: 'assistant' }, true),
)
} }
if (!context.user) { if (!context.user) {
return Promise.resolve(new ChatGptMessage({ content: 'User not found', role: 'assistant' }, true)) return Promise.resolve(
new ChatGptMessage({ content: 'User not found', role: 'assistant' }, true),
)
} }
const messageObj = new Message(message) const messageObj = new Message(message)
if (!threadId || threadId.length === 0) { if (!threadId || threadId.length === 0) {

View File

@ -1,19 +1,20 @@
import { Transaction as dbTransaction, TransactionLink as dbTransactionLink } from 'database' import { Balance } from '@model/Balance'
import { DecayLoggingView } from 'core'
import {
Transaction as dbTransaction,
TransactionLink as dbTransactionLink,
getLastTransaction,
} from 'database'
import { Decimal } from 'decimal.js-light' import { Decimal } from 'decimal.js-light'
import { getLogger } from 'log4js'
import { calculateDecay } from 'shared'
import { Authorized, Ctx, Query, Resolver } from 'type-graphql' import { Authorized, Ctx, Query, Resolver } from 'type-graphql'
import { IsNull } from 'typeorm' import { IsNull } from 'typeorm'
import { Balance } from '@model/Balance'
import { RIGHTS } from '@/auth/RIGHTS' import { RIGHTS } from '@/auth/RIGHTS'
import { BalanceLoggingView } from '@/logging/BalanceLogging.view'
import { Context, getUser } from '@/server/context'
import { DecayLoggingView } from 'core'
import { calculateDecay } from 'shared'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { getLastTransaction } from 'database' import { BalanceLoggingView } from '@/logging/BalanceLogging.view'
import { getLogger } from 'log4js' import { Context, getUser } from '@/server/context'
import { GdtResolver } from './GdtResolver' import { GdtResolver } from './GdtResolver'
import { transactionLinkSummary } from './util/transactionLinkSummary' import { transactionLinkSummary } from './util/transactionLinkSummary'

View File

@ -1,11 +1,17 @@
import { cleanDB, testEnvironment } from '@test/helpers'
import { ApolloServerTestClient } from 'apollo-server-testing' import { ApolloServerTestClient } from 'apollo-server-testing'
import { Community as DbCommunity, FederatedCommunity as DbFederatedCommunity, getHomeCommunity } from 'database' import { getLogger } from 'config-schema/test/testSetup'
import {
AppDatabase,
Community as DbCommunity,
FederatedCommunity as DbFederatedCommunity,
getHomeCommunity,
} from 'database'
import { createCommunity, createVerifiedFederatedCommunity } from 'database/src/seeds/community'
import { GraphQLError } from 'graphql/error/GraphQLError' import { GraphQLError } from 'graphql/error/GraphQLError'
import { DataSource } from 'typeorm' import { DataSource } from 'typeorm'
import { v4 as uuidv4 } from 'uuid' import { v4 as uuidv4 } from 'uuid'
import { CONFIG } from '@/config'
import { cleanDB, testEnvironment } from '@test/helpers'
import { userFactory } from '@/seeds/factory/user' import { userFactory } from '@/seeds/factory/user'
import { login, updateHomeCommunityQuery } from '@/seeds/graphql/mutations' import { login, updateHomeCommunityQuery } from '@/seeds/graphql/mutations'
import { import {
@ -15,11 +21,6 @@ import {
reachableCommunities, reachableCommunities,
} from '@/seeds/graphql/queries' } from '@/seeds/graphql/queries'
import { peterLustig } from '@/seeds/users/peter-lustig' import { peterLustig } from '@/seeds/users/peter-lustig'
import { createCommunity, createVerifiedFederatedCommunity } from 'database/src/seeds/community'
import { getLogger } from 'config-schema/test/testSetup'
import { CONFIG } from '@/config'
import { AppDatabase } from 'database'
jest.mock('@/password/EncryptorUtils') jest.mock('@/password/EncryptorUtils')
@ -498,7 +499,7 @@ describe('CommunityResolver', () => {
DbCommunity.insert(foreignCom2), DbCommunity.insert(foreignCom2),
DbFederatedCommunity.insert(com1FedCom), DbFederatedCommunity.insert(com1FedCom),
DbFederatedCommunity.insert(com1FedCom2), DbFederatedCommunity.insert(com1FedCom2),
DbFederatedCommunity.insert(com2FedCom) DbFederatedCommunity.insert(com2FedCom),
]) ])
}) })
@ -512,13 +513,14 @@ describe('CommunityResolver', () => {
description: homeCom1.description, description: homeCom1.description,
url: homeCom1.url, url: homeCom1.url,
uuid: homeCom1.communityUuid, uuid: homeCom1.communityUuid,
}, { },
{
foreign: foreignCom1.foreign, foreign: foreignCom1.foreign,
name: foreignCom1.name, name: foreignCom1.name,
description: foreignCom1.description, description: foreignCom1.description,
url: foreignCom1.url, url: foreignCom1.url,
uuid: foreignCom1.communityUuid, uuid: foreignCom1.communityUuid,
} },
]) ])
}) })
}) })
@ -574,7 +576,7 @@ describe('CommunityResolver', () => {
description: homeCom?.description, description: homeCom?.description,
url: homeCom?.url, url: homeCom?.url,
creationDate: homeCom?.creationDate?.toISOString(), creationDate: homeCom?.creationDate?.toISOString(),
uuid: homeCom?.communityUuid uuid: homeCom?.communityUuid,
}, },
}, },
}) })
@ -599,7 +601,7 @@ describe('CommunityResolver', () => {
await Promise.all([ await Promise.all([
DbCommunity.insert(foreignCom1), DbCommunity.insert(foreignCom1),
DbCommunity.insert(foreignCom2), DbCommunity.insert(foreignCom2),
mutate({ mutation: login, variables: peterLoginData }) mutate({ mutation: login, variables: peterLoginData }),
]) ])
}) })

View File

@ -1,26 +1,15 @@
import {
Community as DbCommunity,
getReachableCommunities,
getHomeCommunity
} from 'database'
import { Arg, Args, Authorized, Mutation, Query, Resolver } from 'type-graphql'
import { Paginated } from '@arg/Paginated' import { Paginated } from '@arg/Paginated'
import { EditCommunityInput } from '@input/EditCommunityInput' import { EditCommunityInput } from '@input/EditCommunityInput'
import { AdminCommunityView } from '@model/AdminCommunityView' import { AdminCommunityView } from '@model/AdminCommunityView'
import { Community } from '@model/Community' import { Community } from '@model/Community'
import { Community as DbCommunity, getHomeCommunity, getReachableCommunities } from 'database'
import { RIGHTS } from '@/auth/RIGHTS'
import { LogError } from '@/server/LogError'
import { Location2Point } from './util/Location2Point'
import {
getAllCommunities,
getCommunityByIdentifier,
getCommunityByUuid,
} from './util/communities'
import { updateAllDefinedAndChanged } from 'shared' import { updateAllDefinedAndChanged } from 'shared'
import { Arg, Args, Authorized, Mutation, Query, Resolver } from 'type-graphql'
import { RIGHTS } from '@/auth/RIGHTS'
import { CONFIG } from '@/config' import { CONFIG } from '@/config'
import { LogError } from '@/server/LogError'
import { getAllCommunities, getCommunityByIdentifier, getCommunityByUuid } from './util/communities'
import { Location2Point } from './util/Location2Point'
@Resolver() @Resolver()
export class CommunityResolver { export class CommunityResolver {
@ -35,11 +24,13 @@ export class CommunityResolver {
@Query(() => [Community]) @Query(() => [Community])
async reachableCommunities(): Promise<Community[]> { async reachableCommunities(): Promise<Community[]> {
const dbCommunities: DbCommunity[] = await getReachableCommunities( const dbCommunities: DbCommunity[] = await getReachableCommunities(
CONFIG.FEDERATION_VALIDATE_COMMUNITY_TIMER * 2, { CONFIG.FEDERATION_VALIDATE_COMMUNITY_TIMER * 2,
{
// order by // order by
foreign: 'ASC', // home community first foreign: 'ASC', // home community first
name: 'ASC', // sort foreign communities by name name: 'ASC', // sort foreign communities by name
}) },
)
return dbCommunities.map((dbCom: DbCommunity) => new Community(dbCom)) return dbCommunities.map((dbCom: DbCommunity) => new Community(dbCom))
} }

View File

@ -1,11 +1,10 @@
import { cleanDB, resetToken, testEnvironment } from '@test/helpers'
import { ApolloServerTestClient } from 'apollo-server-testing' import { ApolloServerTestClient } from 'apollo-server-testing'
import { ContributionLink as DbContributionLink, Event as DbEvent } from 'database' import { getLogger } from 'config-schema/test/testSetup'
import { AppDatabase, ContributionLink as DbContributionLink, Event as DbEvent } from 'database'
import { Decimal } from 'decimal.js-light' import { Decimal } from 'decimal.js-light'
import { GraphQLError } from 'graphql' import { GraphQLError } from 'graphql'
import { DataSource } from 'typeorm' import { DataSource } from 'typeorm'
import { cleanDB, resetToken, testEnvironment } from '@test/helpers'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { EventType } from '@/event/Events' import { EventType } from '@/event/Events'
import { userFactory } from '@/seeds/factory/user' import { userFactory } from '@/seeds/factory/user'
@ -18,8 +17,6 @@ import {
import { listContributionLinks } from '@/seeds/graphql/queries' import { listContributionLinks } from '@/seeds/graphql/queries'
import { bibiBloxberg } from '@/seeds/users/bibi-bloxberg' import { bibiBloxberg } from '@/seeds/users/bibi-bloxberg'
import { peterLustig } from '@/seeds/users/peter-lustig' import { peterLustig } from '@/seeds/users/peter-lustig'
import { getLogger } from 'config-schema/test/testSetup'
import { AppDatabase } from 'database'
jest.mock('@/password/EncryptorUtils') jest.mock('@/password/EncryptorUtils')

View File

@ -1,12 +1,11 @@
import { ContributionLink as DbContributionLink } from 'database'
import { Arg, Args, Authorized, Ctx, Int, Mutation, Query, Resolver } from 'type-graphql'
import { IsNull, MoreThan } from 'typeorm'
import { ContributionLinkArgs } from '@arg/ContributionLinkArgs' import { ContributionLinkArgs } from '@arg/ContributionLinkArgs'
import { Paginated } from '@arg/Paginated' import { Paginated } from '@arg/Paginated'
import { Order } from '@enum/Order' import { Order } from '@enum/Order'
import { ContributionLink } from '@model/ContributionLink' import { ContributionLink } from '@model/ContributionLink'
import { ContributionLinkList } from '@model/ContributionLinkList' import { ContributionLinkList } from '@model/ContributionLinkList'
import { ContributionLink as DbContributionLink } from 'database'
import { Arg, Args, Authorized, Ctx, Int, Mutation, Query, Resolver } from 'type-graphql'
import { IsNull, MoreThan } from 'typeorm'
import { RIGHTS } from '@/auth/RIGHTS' import { RIGHTS } from '@/auth/RIGHTS'
import { import {
@ -14,8 +13,8 @@ import {
EVENT_ADMIN_CONTRIBUTION_LINK_DELETE, EVENT_ADMIN_CONTRIBUTION_LINK_DELETE,
EVENT_ADMIN_CONTRIBUTION_LINK_UPDATE, EVENT_ADMIN_CONTRIBUTION_LINK_UPDATE,
} from '@/event/Events' } from '@/event/Events'
import { LogError } from '@/server/LogError'
import { Context, getUser } from '@/server/context' import { Context, getUser } from '@/server/context'
import { LogError } from '@/server/LogError'
import { transactionLinkCode as contributionLinkCode } from './TransactionLinkResolver' import { transactionLinkCode as contributionLinkCode } from './TransactionLinkResolver'
import { isStartEndDateValid } from './util/creations' import { isStartEndDateValid } from './util/creations'

View File

@ -1,13 +1,12 @@
import { ApolloServerTestClient } from 'apollo-server-testing'
import { Contribution as DbContribution, Event as DbEvent } from 'database'
import { GraphQLError } from 'graphql'
import { DataSource } from 'typeorm'
import { ContributionStatus } from '@enum/ContributionStatus' import { ContributionStatus } from '@enum/ContributionStatus'
import { cleanDB, resetToken, testEnvironment } from '@test/helpers' import { cleanDB, resetToken, testEnvironment } from '@test/helpers'
import { ApolloServerTestClient } from 'apollo-server-testing'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { getLogger } from 'config-schema/test/testSetup'
import { sendAddedContributionMessageEmail } from 'core' import { sendAddedContributionMessageEmail } from 'core'
import { AppDatabase, Contribution as DbContribution, Event as DbEvent } from 'database'
import { GraphQLError } from 'graphql'
import { DataSource } from 'typeorm'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { EventType } from '@/event/Events' import { EventType } from '@/event/Events'
import { userFactory } from '@/seeds/factory/user' import { userFactory } from '@/seeds/factory/user'
import { import {
@ -20,10 +19,10 @@ import { adminListContributionMessages, listContributionMessages } from '@/seeds
import { bibiBloxberg } from '@/seeds/users/bibi-bloxberg' import { bibiBloxberg } from '@/seeds/users/bibi-bloxberg'
import { bobBaumeister } from '@/seeds/users/bob-baumeister' import { bobBaumeister } from '@/seeds/users/bob-baumeister'
import { peterLustig } from '@/seeds/users/peter-lustig' import { peterLustig } from '@/seeds/users/peter-lustig'
import { getLogger} from 'config-schema/test/testSetup'
import { AppDatabase } from 'database'
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.ContributionMessageResolver`) const logger = getLogger(
`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.ContributionMessageResolver`,
)
const logErrorLogger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.server.LogError`) const logErrorLogger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.server.LogError`)
const interactionLogger = getLogger( const interactionLogger = getLogger(
`${LOG4JS_BASE_CATEGORY_NAME}.interactions.updateUnconfirmedContribution`, `${LOG4JS_BASE_CATEGORY_NAME}.interactions.updateUnconfirmedContribution`,

View File

@ -1,35 +1,34 @@
import { ContributionMessageArgs } from '@arg/ContributionMessageArgs'
import { Paginated } from '@arg/Paginated'
import { ContributionMessageType } from '@enum/ContributionMessageType'
import { Order } from '@enum/Order'
import { ContributionMessage, ContributionMessageListResult } from '@model/ContributionMessage'
import { sendAddedContributionMessageEmail } from 'core'
import { import {
AppDatabase, AppDatabase,
Contribution as DbContribution, Contribution as DbContribution,
ContributionMessage as DbContributionMessage, ContributionMessage as DbContributionMessage,
User as DbUser, User as DbUser,
} from 'database' } from 'database'
import { getLogger } from 'log4js'
import { Arg, Args, Authorized, Ctx, Int, Mutation, Query, Resolver } from 'type-graphql' import { Arg, Args, Authorized, Ctx, Int, Mutation, Query, Resolver } from 'type-graphql'
import { EntityManager, FindOptionsRelations } from 'typeorm' import { EntityManager, FindOptionsRelations } from 'typeorm'
import { ContributionMessageArgs } from '@arg/ContributionMessageArgs'
import { Paginated } from '@arg/Paginated'
import { ContributionMessageType } from '@enum/ContributionMessageType'
import { Order } from '@enum/Order'
import { ContributionMessage, ContributionMessageListResult } from '@model/ContributionMessage'
import { RIGHTS } from '@/auth/RIGHTS' import { RIGHTS } from '@/auth/RIGHTS'
import { sendAddedContributionMessageEmail } from 'core' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { import {
EVENT_ADMIN_CONTRIBUTION_MESSAGE_CREATE, EVENT_ADMIN_CONTRIBUTION_MESSAGE_CREATE,
EVENT_CONTRIBUTION_MESSAGE_CREATE, EVENT_CONTRIBUTION_MESSAGE_CREATE,
} from '@/event/Events' } from '@/event/Events'
import { UpdateUnconfirmedContributionContext } from '@/interactions/updateUnconfirmedContribution/UpdateUnconfirmedContribution.context' import { UpdateUnconfirmedContributionContext } from '@/interactions/updateUnconfirmedContribution/UpdateUnconfirmedContribution.context'
import { LogError } from '@/server/LogError'
import { Context, getUser } from '@/server/context' import { Context, getUser } from '@/server/context'
import { getLogger } from 'log4js' import { LogError } from '@/server/LogError'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { contributionFrontendLink } from './util/contributions' import { contributionFrontendLink } from './util/contributions'
import { findContributionMessages } from './util/findContributionMessages' import { findContributionMessages } from './util/findContributionMessages'
const db = AppDatabase.getInstance() const db = AppDatabase.getInstance()
const createLogger = () => getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.ContributionMessageResolver`) const createLogger = () =>
getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.ContributionMessageResolver`)
@Resolver() @Resolver()
export class ContributionMessageResolver { export class ContributionMessageResolver {

View File

@ -1,9 +1,3 @@
import { ApolloServerTestClient } from 'apollo-server-testing'
import { Contribution, Event as DbEvent, Transaction as DbTransaction, User } from 'database'
import { Decimal } from 'decimal.js-light'
import { GraphQLError } from 'graphql'
import { DataSource, Equal } from 'typeorm'
import { ContributionMessageType } from '@enum/ContributionMessageType' import { ContributionMessageType } from '@enum/ContributionMessageType'
import { ContributionStatus } from '@enum/ContributionStatus' import { ContributionStatus } from '@enum/ContributionStatus'
import { Order } from '@enum/Order' import { Order } from '@enum/Order'
@ -14,13 +8,26 @@ import {
resetToken, resetToken,
testEnvironment, testEnvironment,
} from '@test/helpers' } from '@test/helpers'
import { ApolloServerTestClient } from 'apollo-server-testing'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { getLogger } from 'config-schema/test/testSetup'
import { import {
getFirstDayOfPreviousNMonth,
sendContributionConfirmedEmail, sendContributionConfirmedEmail,
sendContributionDeletedEmail, sendContributionDeletedEmail,
sendContributionDeniedEmail, sendContributionDeniedEmail,
} from 'core' } from 'core'
import {
AppDatabase,
Contribution,
Event as DbEvent,
Transaction as DbTransaction,
User,
} from 'database'
import { Decimal } from 'decimal.js-light'
import { GraphQLError } from 'graphql'
import { getLogger as originalGetLogger } from 'log4js'
import { DataSource, Equal } from 'typeorm'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { EventType } from '@/event/Events' import { EventType } from '@/event/Events'
import { creations } from '@/seeds/creation/index' import { creations } from '@/seeds/creation/index'
import { creationFactory } from '@/seeds/factory/creation' import { creationFactory } from '@/seeds/factory/creation'
@ -49,10 +56,6 @@ import { garrickOllivander } from '@/seeds/users/garrick-ollivander'
import { peterLustig } from '@/seeds/users/peter-lustig' import { peterLustig } from '@/seeds/users/peter-lustig'
import { raeuberHotzenplotz } from '@/seeds/users/raeuber-hotzenplotz' import { raeuberHotzenplotz } from '@/seeds/users/raeuber-hotzenplotz'
import { stephenHawking } from '@/seeds/users/stephen-hawking' import { stephenHawking } from '@/seeds/users/stephen-hawking'
import { getFirstDayOfPreviousNMonth } from 'core'
import { getLogger } from 'config-schema/test/testSetup'
import { getLogger as originalGetLogger } from 'log4js'
import { AppDatabase } from 'database'
jest.mock('core', () => { jest.mock('core', () => {
const originalModule = jest.requireActual('core') const originalModule = jest.requireActual('core')

View File

@ -1,35 +1,9 @@
import {
AppDatabase,
Contribution as DbContribution,
Transaction as DbTransaction,
User as DbUser,
getLastTransaction,
UserContact,
} from 'database'
import { Decimal } from 'decimal.js-light'
import { GraphQLResolveInfo } from 'graphql'
import { Arg, Args, Authorized, Ctx, Info, Int, Mutation, Query, Resolver } from 'type-graphql'
import { EntityManager, IsNull } from 'typeorm'
import { RIGHTS } from '@/auth/RIGHTS'
import {
EVENT_ADMIN_CONTRIBUTION_CONFIRM,
EVENT_ADMIN_CONTRIBUTION_CREATE,
EVENT_ADMIN_CONTRIBUTION_DELETE,
EVENT_ADMIN_CONTRIBUTION_DENY,
EVENT_ADMIN_CONTRIBUTION_UPDATE,
EVENT_CONTRIBUTION_CREATE,
EVENT_CONTRIBUTION_DELETE,
EVENT_CONTRIBUTION_UPDATE,
} from '@/event/Events'
import { UpdateUnconfirmedContributionContext } from '@/interactions/updateUnconfirmedContribution/UpdateUnconfirmedContribution.context'
import { LogError } from '@/server/LogError'
import { Context, getClientTimezoneOffset, getUser } from '@/server/context'
import { AdminCreateContributionArgs } from '@arg/AdminCreateContributionArgs' import { AdminCreateContributionArgs } from '@arg/AdminCreateContributionArgs'
import { AdminUpdateContributionArgs } from '@arg/AdminUpdateContributionArgs' import { AdminUpdateContributionArgs } from '@arg/AdminUpdateContributionArgs'
import { ContributionArgs } from '@arg/ContributionArgs' import { ContributionArgs } from '@arg/ContributionArgs'
import { Paginated } from '@arg/Paginated' import { Paginated } from '@arg/Paginated'
import { SearchContributionsFilterArgs } from '@arg/SearchContributionsFilterArgs' import { SearchContributionsFilterArgs } from '@arg/SearchContributionsFilterArgs'
import { ContributionMessageType } from '@enum/ContributionMessageType'
import { ContributionStatus } from '@enum/ContributionStatus' import { ContributionStatus } from '@enum/ContributionStatus'
import { ContributionType } from '@enum/ContributionType' import { ContributionType } from '@enum/ContributionType'
import { AdminUpdateContribution } from '@model/AdminUpdateContribution' import { AdminUpdateContribution } from '@model/AdminUpdateContribution'
@ -42,15 +16,39 @@ import {
sendContributionConfirmedEmail, sendContributionConfirmedEmail,
sendContributionDeletedEmail, sendContributionDeletedEmail,
sendContributionDeniedEmail, sendContributionDeniedEmail,
TransactionTypeId TransactionTypeId,
} from 'core' } from 'core'
import { calculateDecay, Decay } from 'shared' import {
AppDatabase,
import { contributionTransaction } from '@/apis/dltConnector' Contribution as DbContribution,
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' Transaction as DbTransaction,
import { ContributionMessageType } from '@enum/ContributionMessageType' User as DbUser,
getLastTransaction,
UserContact,
} from 'database'
import { Decimal } from 'decimal.js-light'
import { GraphQLResolveInfo } from 'graphql'
import { getLogger } from 'log4js' import { getLogger } from 'log4js'
import { Mutex } from 'redis-semaphore' import { Mutex } from 'redis-semaphore'
import { calculateDecay, Decay } from 'shared'
import { Arg, Args, Authorized, Ctx, Info, Int, Mutation, Query, Resolver } from 'type-graphql'
import { EntityManager, IsNull } from 'typeorm'
import { contributionTransaction } from '@/apis/dltConnector'
import { RIGHTS } from '@/auth/RIGHTS'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import {
EVENT_ADMIN_CONTRIBUTION_CONFIRM,
EVENT_ADMIN_CONTRIBUTION_CREATE,
EVENT_ADMIN_CONTRIBUTION_DELETE,
EVENT_ADMIN_CONTRIBUTION_DENY,
EVENT_ADMIN_CONTRIBUTION_UPDATE,
EVENT_CONTRIBUTION_CREATE,
EVENT_CONTRIBUTION_DELETE,
EVENT_CONTRIBUTION_UPDATE,
} from '@/event/Events'
import { UpdateUnconfirmedContributionContext } from '@/interactions/updateUnconfirmedContribution/UpdateUnconfirmedContribution.context'
import { Context, getClientTimezoneOffset, getUser } from '@/server/context'
import { LogError } from '@/server/LogError'
import { import {
contributionFrontendLink, contributionFrontendLink,
loadAllContributions, loadAllContributions,
@ -61,7 +59,8 @@ import { extractGraphQLFields } from './util/extractGraphQLFields'
import { findContributions } from './util/findContributions' import { findContributions } from './util/findContributions'
const db = AppDatabase.getInstance() const db = AppDatabase.getInstance()
const createLogger = () => getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.ContributionResolver`) const createLogger = () =>
getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.ContributionResolver`)
@Resolver(() => Contribution) @Resolver(() => Contribution)
export class ContributionResolver { export class ContributionResolver {
@ -435,12 +434,15 @@ export class ContributionResolver {
const logger = createLogger() const logger = createLogger()
logger.addContext('contribution', id) logger.addContext('contribution', id)
// acquire lock // acquire lock
const mutex = new Mutex (db.getRedisClient(), 'TRANSACTIONS_LOCK') const mutex = new Mutex(db.getRedisClient(), 'TRANSACTIONS_LOCK')
await mutex.acquire() await mutex.acquire()
try { try {
const clientTimezoneOffset = getClientTimezoneOffset(context) const clientTimezoneOffset = getClientTimezoneOffset(context)
const contribution = await DbContribution.findOne({ where: { id }, relations: {user: {emailContact: true}} }) const contribution = await DbContribution.findOne({
where: { id },
relations: { user: { emailContact: true } },
})
if (!contribution) { if (!contribution) {
throw new LogError('Contribution not found', id) throw new LogError('Contribution not found', id)
} }
@ -460,7 +462,11 @@ export class ContributionResolver {
throw new LogError('Can not confirm contribution since the user was deleted') throw new LogError('Can not confirm contribution since the user was deleted')
} }
const receivedCallDate = new Date() const receivedCallDate = new Date()
const dltTransactionPromise = contributionTransaction(contribution, moderatorUser, receivedCallDate) const dltTransactionPromise = contributionTransaction(
contribution,
moderatorUser,
receivedCallDate,
)
const creations = await getUserCreation(contribution.userId, clientTimezoneOffset, false) const creations = await getUserCreation(contribution.userId, clientTimezoneOffset, false)
validateContribution( validateContribution(
creations, creations,
@ -536,12 +542,14 @@ export class ContributionResolver {
// wait for finishing transaction by dlt-connector/hiero // wait for finishing transaction by dlt-connector/hiero
const dltStartTime = new Date() const dltStartTime = new Date()
const dltTransaction = await dltTransactionPromise const dltTransaction = await dltTransactionPromise
if(dltTransaction) { if (dltTransaction) {
dltTransaction.transactionId = transaction.id dltTransaction.transactionId = transaction.id
await dltTransaction.save() await dltTransaction.save()
} }
const dltEndTime = new Date() const dltEndTime = new Date()
logger.debug(`dlt-connector contribution finished in ${dltEndTime.getTime() - dltStartTime.getTime()} ms`) logger.debug(
`dlt-connector contribution finished in ${dltEndTime.getTime() - dltStartTime.getTime()} ms`,
)
} catch (e) { } catch (e) {
await queryRunner.rollbackTransaction() await queryRunner.rollbackTransaction()
throw new LogError('Creation was not successful', e) throw new LogError('Creation was not successful', e)

View File

@ -1,16 +1,13 @@
import { cleanDB, testEnvironment } from '@test/helpers'
import { ApolloServerTestClient } from 'apollo-server-testing' import { ApolloServerTestClient } from 'apollo-server-testing'
import { User as DbUser } from 'database' import { CONFIG as CORE_CONFIG } from 'core'
import { AppDatabase, User as DbUser } from 'database'
import { GraphQLError } from 'graphql' import { GraphQLError } from 'graphql'
import { DataSource } from 'typeorm' import { DataSource } from 'typeorm'
import { cleanDB, testEnvironment } from '@test/helpers'
import { CONFIG as CORE_CONFIG } from 'core'
import { CONFIG } from '@/config' import { CONFIG } from '@/config'
import { writeHomeCommunityEntry } from '@/seeds/community' import { writeHomeCommunityEntry } from '@/seeds/community'
import { createUser, forgotPassword, setPassword } from '@/seeds/graphql/mutations' import { createUser, forgotPassword, setPassword } from '@/seeds/graphql/mutations'
import { queryOptIn } from '@/seeds/graphql/queries' import { queryOptIn } from '@/seeds/graphql/queries'
import { AppDatabase } from 'database'
let mutate: ApolloServerTestClient['mutate'] let mutate: ApolloServerTestClient['mutate']
let query: ApolloServerTestClient['query'] let query: ApolloServerTestClient['query']

View File

@ -1,17 +1,15 @@
import { Arg, Args, Authorized, Ctx, Float, Int, Query, Resolver } from 'type-graphql'
import { Paginated } from '@arg/Paginated' import { Paginated } from '@arg/Paginated'
import { Order } from '@enum/Order' import { Order } from '@enum/Order'
import { GdtEntry } from '@model/GdtEntry' import { GdtEntry } from '@model/GdtEntry'
import { GdtEntryList } from '@model/GdtEntryList' import { GdtEntryList } from '@model/GdtEntryList'
import { getLogger } from 'log4js'
import { Arg, Args, Authorized, Ctx, Float, Int, Query, Resolver } from 'type-graphql'
import { apiGet, apiPost } from '@/apis/HttpRequest' import { apiGet, apiPost } from '@/apis/HttpRequest'
import { RIGHTS } from '@/auth/RIGHTS' import { RIGHTS } from '@/auth/RIGHTS'
import { CONFIG } from '@/config' import { CONFIG } from '@/config'
import { LogError } from '@/server/LogError'
import { Context, getUser } from '@/server/context'
import { getLogger } from 'log4js'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { Context, getUser } from '@/server/context'
import { LogError } from '@/server/LogError'
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.GdtResolver`) const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.GdtResolver`)

View File

@ -1,15 +1,12 @@
import { Event as DbEvent, UserContact } from 'database'
import { GraphQLError } from 'graphql'
import { cleanDB, resetToken, testEnvironment } from '@test/helpers' import { cleanDB, resetToken, testEnvironment } from '@test/helpers'
import { getLogger } from 'config-schema/test/testSetup' import { getLogger } from 'config-schema/test/testSetup'
import { AppDatabase, Event as DbEvent, UserContact } from 'database'
import { GraphQLError } from 'graphql'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { EventType } from '@/event/Events' import { EventType } from '@/event/Events'
import { userFactory } from '@/seeds/factory/user' import { userFactory } from '@/seeds/factory/user'
import { login, subscribeNewsletter, unsubscribeNewsletter } from '@/seeds/graphql/mutations' import { login, subscribeNewsletter, unsubscribeNewsletter } from '@/seeds/graphql/mutations'
import { bibiBloxberg } from '@/seeds/users/bibi-bloxberg' import { bibiBloxberg } from '@/seeds/users/bibi-bloxberg'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { AppDatabase } from 'database'
jest.mock('@/password/EncryptorUtils') jest.mock('@/password/EncryptorUtils')

View File

@ -1,16 +1,14 @@
import { ProjectBranding as DbProjectBranding } from 'database'
import { Arg, Authorized, ID, Int, Mutation, Query, Resolver } from 'type-graphql'
import { ProjectBrandingInput } from '@input/ProjectBrandingInput' import { ProjectBrandingInput } from '@input/ProjectBrandingInput'
import { ProjectBranding } from '@model/ProjectBranding' import { ProjectBranding } from '@model/ProjectBranding'
import { Space } from '@model/Space' import { Space } from '@model/Space'
import { SpaceList } from '@model/SpaceList' import { SpaceList } from '@model/SpaceList'
import { ProjectBranding as DbProjectBranding } from 'database'
import { getLogger } from 'log4js'
import { Arg, Authorized, ID, Int, Mutation, Query, Resolver } from 'type-graphql'
import { HumHubClient } from '@/apis/humhub/HumHubClient' import { HumHubClient } from '@/apis/humhub/HumHubClient'
import { RIGHTS } from '@/auth/RIGHTS' import { RIGHTS } from '@/auth/RIGHTS'
import { LogError } from '@/server/LogError'
import { getLogger } from 'log4js'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { LogError } from '@/server/LogError'
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.ProjectBrandingResolver`) const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.ProjectBrandingResolver`)

View File

@ -1,11 +1,9 @@
import { CommunityStatistics, DynamicStatisticsFields } from '@model/CommunityStatistics'
import { AppDatabase, Transaction as DbTransaction, User as DbUser } from 'database' import { AppDatabase, Transaction as DbTransaction, User as DbUser } from 'database'
import { Decimal } from 'decimal.js-light' import { Decimal } from 'decimal.js-light'
import { Authorized, FieldResolver, Query, Resolver } from 'type-graphql'
import { CommunityStatistics, DynamicStatisticsFields } from '@model/CommunityStatistics'
import { RIGHTS } from '@/auth/RIGHTS'
import { calculateDecay } from 'shared' import { calculateDecay } from 'shared'
import { Authorized, FieldResolver, Query, Resolver } from 'type-graphql'
import { RIGHTS } from '@/auth/RIGHTS'
const db = AppDatabase.getInstance() const db = AppDatabase.getInstance()

View File

@ -1,5 +1,9 @@
import { UnconfirmedContribution } from '@model/UnconfirmedContribution'
import { cleanDB, resetEntity, resetToken, testEnvironment } from '@test/helpers'
import { ApolloServerTestClient } from 'apollo-server-testing' import { ApolloServerTestClient } from 'apollo-server-testing'
import { getLogger } from 'config-schema/test/testSetup'
import { import {
AppDatabase,
ContributionLink as DbContributionLink, ContributionLink as DbContributionLink,
Event as DbEvent, Event as DbEvent,
Transaction, Transaction,
@ -9,10 +13,8 @@ import {
import { Decimal } from 'decimal.js-light' import { Decimal } from 'decimal.js-light'
import { GraphQLError } from 'graphql' import { GraphQLError } from 'graphql'
import { DataSource } from 'typeorm' import { DataSource } from 'typeorm'
import { CONFIG } from '@/config'
import { UnconfirmedContribution } from '@model/UnconfirmedContribution' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { cleanDB, resetEntity, resetToken, testEnvironment } from '@test/helpers'
import { EventType } from '@/event/Events' import { EventType } from '@/event/Events'
import { creations } from '@/seeds/creation/index' import { creations } from '@/seeds/creation/index'
import { creationFactory } from '@/seeds/factory/creation' import { creationFactory } from '@/seeds/factory/creation'
@ -32,11 +34,7 @@ import { listTransactionLinksAdmin } from '@/seeds/graphql/queries'
import { transactionLinks } from '@/seeds/transactionLink/index' import { transactionLinks } from '@/seeds/transactionLink/index'
import { bibiBloxberg } from '@/seeds/users/bibi-bloxberg' import { bibiBloxberg } from '@/seeds/users/bibi-bloxberg'
import { peterLustig } from '@/seeds/users/peter-lustig' import { peterLustig } from '@/seeds/users/peter-lustig'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { getLogger } from 'config-schema/test/testSetup'
import { transactionLinkCode } from './TransactionLinkResolver' import { transactionLinkCode } from './TransactionLinkResolver'
import { CONFIG } from '@/config'
import { AppDatabase } from 'database'
const logErrorLogger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.server.LogError`) const logErrorLogger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.server.LogError`)
@ -967,7 +965,7 @@ describe('TransactionLinkResolver', () => {
createdAt: expect.any(String), createdAt: expect.any(String),
}), }),
expect.objectContaining({ expect.objectContaining({
memo: "Kein Trick, keine Zauberrei,\n bei Gradidio sei dabei!", memo: 'Kein Trick, keine Zauberrei,\n bei Gradidio sei dabei!',
deletedAt: expect.any(String), deletedAt: expect.any(String),
}), }),
]), ]),

View File

@ -1,5 +1,3 @@
import { randomBytes } from 'crypto'
import { Paginated } from '@arg/Paginated' import { Paginated } from '@arg/Paginated'
import { TransactionLinkArgs } from '@arg/TransactionLinkArgs' import { TransactionLinkArgs } from '@arg/TransactionLinkArgs'
import { TransactionLinkFilters } from '@arg/TransactionLinkFilters' import { TransactionLinkFilters } from '@arg/TransactionLinkFilters'
@ -12,51 +10,65 @@ import { RedeemJwtLink } from '@model/RedeemJwtLink'
import { TransactionLink, TransactionLinkResult } from '@model/TransactionLink' import { TransactionLink, TransactionLinkResult } from '@model/TransactionLink'
import { User } from '@model/User' import { User } from '@model/User'
import { QueryLinkResult } from '@union/QueryLinkResult' import { QueryLinkResult } from '@union/QueryLinkResult'
import { Decay, interpretEncryptedTransferArgs, TransactionTypeId } from 'core'
import { import {
AppDatabase, Contribution as DbContribution, Decay,
EncryptedTransferArgs,
fullName,
interpretEncryptedTransferArgs,
TransactionTypeId,
} from 'core'
import { randomBytes } from 'crypto'
import {
AppDatabase,
Contribution as DbContribution,
ContributionLink as DbContributionLink, ContributionLink as DbContributionLink,
FederatedCommunity as DbFederatedCommunity,
DltTransaction as DbDltTransaction, DltTransaction as DbDltTransaction,
FederatedCommunity as DbFederatedCommunity,
Transaction as DbTransaction, Transaction as DbTransaction,
TransactionLink as DbTransactionLink, TransactionLink as DbTransactionLink,
User as DbUser, User as DbUser,
findModeratorCreatingContributionLink, findModeratorCreatingContributionLink,
findTransactionLinkByCode, findTransactionLinkByCode,
getHomeCommunity getHomeCommunity,
getLastTransaction,
} from 'database' } from 'database'
import { Decimal } from 'decimal.js-light' import { Decimal } from 'decimal.js-light'
import { Redis } from 'ioredis'
import { getLogger, Logger } from 'log4js'
import { Mutex } from 'redis-semaphore'
// import { TRANSACTION_LINK_LOCK, TRANSACTIONS_LOCK } from 'database'
import {
calculateDecay,
compoundInterest,
DisburseJwtPayloadType,
decode,
encode,
encryptAndSign,
RedeemJwtPayloadType,
SignedTransferPayloadType,
verify,
} from 'shared'
import { randombytes_random } from 'sodium-native'
import { Arg, Args, Authorized, Ctx, Int, Mutation, Query, Resolver } from 'type-graphql' import { Arg, Args, Authorized, Ctx, Int, Mutation, Query, Resolver } from 'type-graphql'
import {
contributionTransaction,
deferredTransferTransaction,
redeemDeferredTransferTransaction,
} from '@/apis/dltConnector'
import { RIGHTS } from '@/auth/RIGHTS' import { RIGHTS } from '@/auth/RIGHTS'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { import {
EVENT_CONTRIBUTION_LINK_REDEEM, EVENT_CONTRIBUTION_LINK_REDEEM,
EVENT_TRANSACTION_LINK_CREATE, EVENT_TRANSACTION_LINK_CREATE,
EVENT_TRANSACTION_LINK_DELETE, EVENT_TRANSACTION_LINK_DELETE,
EVENT_TRANSACTION_LINK_REDEEM, EVENT_TRANSACTION_LINK_REDEEM,
} from '@/event/Events' } from '@/event/Events'
import { LogError } from '@/server/LogError'
import { Context, getClientTimezoneOffset, getUser } from '@/server/context'
import { calculateBalance } from '@/util/validate'
import { fullName } from 'core'
// import { TRANSACTION_LINK_LOCK, TRANSACTIONS_LOCK } from 'database'
import {
calculateDecay,
compoundInterest,
decode,
DisburseJwtPayloadType,
encode,
encryptAndSign,
RedeemJwtPayloadType,
verify
} from 'shared'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { DisbursementClient as V1_0_DisbursementClient } from '@/federation/client/1_0/DisbursementClient' import { DisbursementClient as V1_0_DisbursementClient } from '@/federation/client/1_0/DisbursementClient'
import { DisbursementClientFactory } from '@/federation/client/DisbursementClientFactory' import { DisbursementClientFactory } from '@/federation/client/DisbursementClientFactory'
import { EncryptedTransferArgs } from 'core' import { Context, getClientTimezoneOffset, getUser } from '@/server/context'
import { getLastTransaction } from 'database' import { LogError } from '@/server/LogError'
import { getLogger, Logger } from 'log4js' import { calculateBalance } from '@/util/validate'
import { randombytes_random } from 'sodium-native' import { CODE_VALID_DAYS_DURATION } from './const/const'
import { executeTransaction } from './TransactionResolver' import { executeTransaction } from './TransactionResolver'
import { import {
getAuthenticatedCommunities, getAuthenticatedCommunities,
@ -65,13 +77,9 @@ import {
} from './util/communities' } from './util/communities'
import { getUserCreation, validateContribution } from './util/creations' import { getUserCreation, validateContribution } from './util/creations'
import { transactionLinkList } from './util/transactionLinkList' import { transactionLinkList } from './util/transactionLinkList'
import { SignedTransferPayloadType } from 'shared'
import { contributionTransaction, deferredTransferTransaction, redeemDeferredTransferTransaction } from '@/apis/dltConnector'
import { CODE_VALID_DAYS_DURATION } from './const/const'
import { Redis } from 'ioredis'
import { Mutex } from 'redis-semaphore'
const createLogger = (method: string) => getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.TransactionLinkResolver.${method}`) const createLogger = (method: string) =>
getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.TransactionLinkResolver.${method}`)
// TODO: do not export, test it inside the resolver // TODO: do not export, test it inside the resolver
export const transactionLinkCode = (date: Date): string => { export const transactionLinkCode = (date: Date): string => {
@ -83,7 +91,6 @@ export const transactionLinkCode = (date: Date): string => {
) )
} }
const db = AppDatabase.getInstance() const db = AppDatabase.getInstance()
export const transactionLinkExpireDate = (date: Date): Date => { export const transactionLinkExpireDate = (date: Date): Date => {
@ -130,7 +137,9 @@ export class TransactionLinkResolver {
const startTime = Date.now() const startTime = Date.now()
const dltTransaction = await dltTransactionPromise const dltTransaction = await dltTransactionPromise
const endTime = Date.now() const endTime = Date.now()
createLogger('createTransactionLink').debug(`dlt transaction created in ${endTime - startTime} ms`) createLogger('createTransactionLink').debug(
`dlt transaction created in ${endTime - startTime} ms`,
)
if (dltTransaction) { if (dltTransaction) {
dltTransaction.transactionLinkId = transactionLink.id dltTransaction.transactionLinkId = transactionLink.id
await DbDltTransaction.save(dltTransaction) await DbDltTransaction.save(dltTransaction)
@ -167,14 +176,21 @@ export class TransactionLinkResolver {
}) })
transactionLink.user = user transactionLink.user = user
const dltTransactionPromise = redeemDeferredTransferTransaction(transactionLink, transactionLink.amount.toString(), transactionLink.deletedAt!, user) const dltTransactionPromise = redeemDeferredTransferTransaction(
transactionLink,
transactionLink.amount.toString(),
transactionLink.deletedAt!,
user,
)
await EVENT_TRANSACTION_LINK_DELETE(user, transactionLink) await EVENT_TRANSACTION_LINK_DELETE(user, transactionLink)
// wait for dlt transaction to be created // wait for dlt transaction to be created
const startTime = Date.now() const startTime = Date.now()
const dltTransaction = await dltTransactionPromise const dltTransaction = await dltTransactionPromise
const endTime = Date.now() const endTime = Date.now()
createLogger('deleteTransactionLink').debug(`dlt transaction created in ${endTime - startTime} ms`) createLogger('deleteTransactionLink').debug(
`dlt transaction created in ${endTime - startTime} ms`,
)
if (dltTransaction) { if (dltTransaction) {
dltTransaction.transactionLinkId = transactionLink.id dltTransaction.transactionLinkId = transactionLink.id
await DbDltTransaction.save(dltTransaction) await DbDltTransaction.save(dltTransaction)
@ -382,12 +398,13 @@ export class TransactionLinkResolver {
const startTime = new Date() const startTime = new Date()
const dltTransaction = await dltTransactionPromise const dltTransaction = await dltTransactionPromise
const endTime = new Date() const endTime = new Date()
methodLogger.info(`dlt-connector transaction finished in ${endTime.getTime() - startTime.getTime()} ms`) methodLogger.info(
`dlt-connector transaction finished in ${endTime.getTime() - startTime.getTime()} ms`,
)
if (dltTransaction) { if (dltTransaction) {
dltTransaction.transactionId = transaction.id dltTransaction.transactionId = transaction.id
await dltTransaction.save() await dltTransaction.save()
} }
} }
} catch (e) { } catch (e) {
await queryRunner.rollbackTransaction() await queryRunner.rollbackTransaction()
@ -508,7 +525,11 @@ export class TransactionLinkResolver {
if (!recipientCom.publicJwtKey) { if (!recipientCom.publicJwtKey) {
throw new LogError('Recipient community publicJwtKey is not set') throw new LogError('Recipient community publicJwtKey is not set')
} }
const redeemJwt = await encryptAndSign(redeemJwtPayloadType, senderCom.privateJwtKey!, recipientCom.publicJwtKey!) const redeemJwt = await encryptAndSign(
redeemJwtPayloadType,
senderCom.privateJwtKey!,
recipientCom.publicJwtKey!,
)
if (!redeemJwt) { if (!redeemJwt) {
throw new LogError('Redeem JWT was not created successfully') throw new LogError('Redeem JWT was not created successfully')
} }
@ -517,7 +538,7 @@ export class TransactionLinkResolver {
args.publicKey = senderCom.publicKey.toString('hex') args.publicKey = senderCom.publicKey.toString('hex')
args.jwt = redeemJwt args.jwt = redeemJwt
args.handshakeID = randombytes_random().toString() args.handshakeID = randombytes_random().toString()
if(methodLogger.isDebugEnabled()) { if (methodLogger.isDebugEnabled()) {
methodLogger.debug('successfully created RedeemJWT-Response with args:', args) methodLogger.debug('successfully created RedeemJWT-Response with args:', args)
} }
const signedTransferPayload = new SignedTransferPayloadType( const signedTransferPayload = new SignedTransferPayloadType(
@ -525,15 +546,21 @@ export class TransactionLinkResolver {
args.jwt, args.jwt,
args.handshakeID, args.handshakeID,
) )
if(methodLogger.isDebugEnabled()) { if (methodLogger.isDebugEnabled()) {
methodLogger.debug('successfully created RedeemJWT-Response with signedTransferPayload:', signedTransferPayload) methodLogger.debug(
'successfully created RedeemJWT-Response with signedTransferPayload:',
signedTransferPayload,
)
} }
const signedTransferJwt = await encode(signedTransferPayload, senderCom.privateJwtKey!) const signedTransferJwt = await encode(signedTransferPayload, senderCom.privateJwtKey!)
if (!signedTransferJwt) { if (!signedTransferJwt) {
throw new LogError('SignedTransfer JWT was not created successfully') throw new LogError('SignedTransfer JWT was not created successfully')
} }
if(methodLogger.isDebugEnabled()) { if (methodLogger.isDebugEnabled()) {
methodLogger.debug('successfully created RedeemJWT-Response with signedTransferJwt:', signedTransferJwt) methodLogger.debug(
'successfully created RedeemJWT-Response with signedTransferJwt:',
signedTransferJwt,
)
} }
return signedTransferJwt return signedTransferJwt
@ -563,7 +590,7 @@ export class TransactionLinkResolver {
const handshakeID = randombytes_random().toString() const handshakeID = randombytes_random().toString()
const methodLogger = createLogger(`disburseTransactionLink`) const methodLogger = createLogger(`disburseTransactionLink`)
methodLogger.addContext('handshakeID', handshakeID) methodLogger.addContext('handshakeID', handshakeID)
if(methodLogger.isDebugEnabled()) { if (methodLogger.isDebugEnabled()) {
methodLogger.debug('args=', { methodLogger.debug('args=', {
senderGradidoId, senderGradidoId,
senderCommunityUuid, senderCommunityUuid,
@ -612,11 +639,15 @@ export class TransactionLinkResolver {
validUntil!, validUntil!,
recipientAlias!, recipientAlias!,
) )
if(methodLogger.isDebugEnabled()) { if (methodLogger.isDebugEnabled()) {
methodLogger.debug('disburseJwtPayload=', disburseJwtPayload) methodLogger.debug('disburseJwtPayload=', disburseJwtPayload)
} }
const jws = await encryptAndSign(disburseJwtPayload, recipientCom.privateJwtKey!, senderCom.publicJwtKey!) const jws = await encryptAndSign(
if(methodLogger.isDebugEnabled()) { disburseJwtPayload,
recipientCom.privateJwtKey!,
senderCom.publicJwtKey!,
)
if (methodLogger.isDebugEnabled()) {
methodLogger.debug('jws=', jws) methodLogger.debug('jws=', jws)
} }
const args = new EncryptedTransferArgs() const args = new EncryptedTransferArgs()
@ -626,7 +657,7 @@ export class TransactionLinkResolver {
try { try {
// now send the disburseJwt to the sender community to invoke a x-community-tx to disbures the redeemLink // now send the disburseJwt to the sender community to invoke a x-community-tx to disbures the redeemLink
const result = await client.sendDisburseJwtToSenderCommunity(args) const result = await client.sendDisburseJwtToSenderCommunity(args)
if(methodLogger.isDebugEnabled()) { if (methodLogger.isDebugEnabled()) {
methodLogger.debug('Disburse JWT was sent successfully with result=', result) methodLogger.debug('Disburse JWT was sent successfully with result=', result)
} }
} catch (e) { } catch (e) {
@ -679,22 +710,34 @@ export class TransactionLinkResolver {
// decode token first to get the EncryptedTransferArgs with the senderCommunity.publicKey as input to verify token // decode token first to get the EncryptedTransferArgs with the senderCommunity.publicKey as input to verify token
const decodedPayload = decode(code) as SignedTransferPayloadType const decodedPayload = decode(code) as SignedTransferPayloadType
logger.debug('queryRedeemJwtLink... decodedPayload=', decodedPayload) logger.debug('queryRedeemJwtLink... decodedPayload=', decodedPayload)
logger.debug('switch logger-context to received token-handshakeID:' + decodedPayload.handshakeID) logger.debug(
'switch logger-context to received token-handshakeID:' + decodedPayload.handshakeID,
)
logger.addContext('handshakeID', decodedPayload.handshakeID) logger.addContext('handshakeID', decodedPayload.handshakeID)
if(decodedPayload !== null && decodedPayload.tokentype === SignedTransferPayloadType.SIGNED_TRANSFER_TYPE) { if (
decodedPayload !== null &&
decodedPayload.tokentype === SignedTransferPayloadType.SIGNED_TRANSFER_TYPE
) {
const signedTransferPayload = new SignedTransferPayloadType( const signedTransferPayload = new SignedTransferPayloadType(
decodedPayload.publicKey, decodedPayload.publicKey,
decodedPayload.jwt, decodedPayload.jwt,
decodedPayload.handshakeID) decodedPayload.handshakeID,
)
logger.debug('queryRedeemJwtLink... signedTransferPayload=', signedTransferPayload) logger.debug('queryRedeemJwtLink... signedTransferPayload=', signedTransferPayload)
const senderCom = await getCommunityByPublicKey(Buffer.from(signedTransferPayload.publicKey, 'hex')) const senderCom = await getCommunityByPublicKey(
Buffer.from(signedTransferPayload.publicKey, 'hex'),
)
if (!senderCom) { if (!senderCom) {
const errmsg = `Sender community not found with publicKey=${signedTransferPayload.publicKey}` const errmsg = `Sender community not found with publicKey=${signedTransferPayload.publicKey}`
logger.error(errmsg) logger.error(errmsg)
throw new Error(errmsg) throw new Error(errmsg)
} }
logger.debug('queryRedeemJwtLink... senderCom=', senderCom) logger.debug('queryRedeemJwtLink... senderCom=', senderCom)
const jweVerifyResult = await verify(signedTransferPayload.handshakeID, signedTransferPayload.jwt, senderCom.publicJwtKey!) const jweVerifyResult = await verify(
signedTransferPayload.handshakeID,
signedTransferPayload.jwt,
senderCom.publicJwtKey!,
)
logger.debug('queryRedeemJwtLink... jweVerifyResult=', jweVerifyResult) logger.debug('queryRedeemJwtLink... jweVerifyResult=', jweVerifyResult)
let verifiedRedeemJwtPayload: RedeemJwtPayloadType | null = null let verifiedRedeemJwtPayload: RedeemJwtPayloadType | null = null
if (jweVerifyResult === null) { if (jweVerifyResult === null) {
@ -707,22 +750,34 @@ export class TransactionLinkResolver {
encryptedTransferArgs.jwt = signedTransferPayload.jwt encryptedTransferArgs.jwt = signedTransferPayload.jwt
encryptedTransferArgs.handshakeID = signedTransferPayload.handshakeID encryptedTransferArgs.handshakeID = signedTransferPayload.handshakeID
verifiedRedeemJwtPayload = await interpretEncryptedTransferArgs(encryptedTransferArgs) as RedeemJwtPayloadType verifiedRedeemJwtPayload = (await interpretEncryptedTransferArgs(
if(logger.isDebugEnabled()) { encryptedTransferArgs,
)) as RedeemJwtPayloadType
if (logger.isDebugEnabled()) {
logger.debug(`queryRedeemJwtLink() ...`, verifiedRedeemJwtPayload) logger.debug(`queryRedeemJwtLink() ...`, verifiedRedeemJwtPayload)
} }
if (!verifiedRedeemJwtPayload) { if (!verifiedRedeemJwtPayload) {
const errmsg = `invalid authentication payload of requesting community with publicKey` + signedTransferPayload.publicKey const errmsg =
`invalid authentication payload of requesting community with publicKey` +
signedTransferPayload.publicKey
logger.error(errmsg) logger.error(errmsg)
throw new Error(errmsg) throw new Error(errmsg)
} }
if (verifiedRedeemJwtPayload.tokentype !== RedeemJwtPayloadType.REDEEM_ACTIVATION_TYPE) { if (verifiedRedeemJwtPayload.tokentype !== RedeemJwtPayloadType.REDEEM_ACTIVATION_TYPE) {
const errmsg = `Wrong tokentype in redeem JWT: type=` + verifiedRedeemJwtPayload.tokentype + ' vs expected ' + RedeemJwtPayloadType.REDEEM_ACTIVATION_TYPE const errmsg =
`Wrong tokentype in redeem JWT: type=` +
verifiedRedeemJwtPayload.tokentype +
' vs expected ' +
RedeemJwtPayloadType.REDEEM_ACTIVATION_TYPE
logger.error(errmsg) logger.error(errmsg)
throw new Error(errmsg) throw new Error(errmsg)
} }
if(senderCom?.communityUuid !== verifiedRedeemJwtPayload.sendercommunityuuid) { if (senderCom?.communityUuid !== verifiedRedeemJwtPayload.sendercommunityuuid) {
const errmsg = `Mismatch of sender community UUID in redeem JWT against transfer JWT: uuid=` + senderCom.communityUuid + ' vs ' + verifiedRedeemJwtPayload.sendercommunityuuid const errmsg =
`Mismatch of sender community UUID in redeem JWT against transfer JWT: uuid=` +
senderCom.communityUuid +
' vs ' +
verifiedRedeemJwtPayload.sendercommunityuuid
logger.error(errmsg) logger.error(errmsg)
throw new Error(errmsg) throw new Error(errmsg)
} }

View File

@ -1,5 +1,9 @@
import { cleanDB, testEnvironment } from '@test/helpers'
import { ApolloServerTestClient } from 'apollo-server-testing' import { ApolloServerTestClient } from 'apollo-server-testing'
import { getLogger } from 'config-schema/test/testSetup'
import { CONFIG as CORE_CONFIG } from 'core'
import { import {
AppDatabase,
Community as DbCommunity, Community as DbCommunity,
Event as DbEvent, Event as DbEvent,
FederatedCommunity as DbFederatedCommunity, FederatedCommunity as DbFederatedCommunity,
@ -10,9 +14,7 @@ import {
import { GraphQLError } from 'graphql' import { GraphQLError } from 'graphql'
import { DataSource, In } from 'typeorm' import { DataSource, In } from 'typeorm'
import { v4 as uuidv4 } from 'uuid' import { v4 as uuidv4 } from 'uuid'
import { CONFIG } from '@/config'
import { cleanDB, testEnvironment } from '@test/helpers'
// import { CONFIG } from '@/config' // import { CONFIG } from '@/config'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { EventType } from '@/event/Events' import { EventType } from '@/event/Events'
@ -32,10 +34,6 @@ import { bobBaumeister } from '@/seeds/users/bob-baumeister'
import { garrickOllivander } from '@/seeds/users/garrick-ollivander' import { garrickOllivander } from '@/seeds/users/garrick-ollivander'
import { peterLustig } from '@/seeds/users/peter-lustig' import { peterLustig } from '@/seeds/users/peter-lustig'
import { stephenHawking } from '@/seeds/users/stephen-hawking' import { stephenHawking } from '@/seeds/users/stephen-hawking'
import { getLogger } from 'config-schema/test/testSetup'
import { CONFIG } from '@/config'
import { CONFIG as CORE_CONFIG} from 'core'
import { AppDatabase } from 'database'
jest.mock('@/password/EncryptorUtils') jest.mock('@/password/EncryptorUtils')
@ -552,7 +550,7 @@ describe('send coins', () => {
}) })
}) })
}) })
/* /*
describe.skip('X-Com send coins via gradido ID', () => { describe.skip('X-Com send coins via gradido ID', () => {
beforeAll(async () => { beforeAll(async () => {
CONFIG.FEDERATION_XCOM_SENDCOINS_ENABLED = true CONFIG.FEDERATION_XCOM_SENDCOINS_ENABLED = true

View File

@ -1,3 +1,16 @@
import { Paginated } from '@arg/Paginated'
import { TransactionSendArgs } from '@arg/TransactionSendArgs'
import { Order } from '@enum/Order'
import { Transaction } from '@model/Transaction'
import { TransactionList } from '@model/TransactionList'
import { User } from '@model/User'
import {
fullName,
processXComCompleteTransaction,
sendTransactionLinkRedeemedEmail,
sendTransactionReceivedEmail,
TransactionTypeId,
} from 'core'
import { import {
AppDatabase, AppDatabase,
countOpenPendingTransactions, countOpenPendingTransactions,
@ -10,45 +23,32 @@ import {
import { Decimal } from 'decimal.js-light' import { Decimal } from 'decimal.js-light'
import { Args, Authorized, Ctx, Mutation, Query, Resolver } from 'type-graphql' import { Args, Authorized, Ctx, Mutation, Query, Resolver } from 'type-graphql'
import { In, IsNull } from 'typeorm' import { In, IsNull } from 'typeorm'
import { Paginated } from '@arg/Paginated'
import { TransactionSendArgs } from '@arg/TransactionSendArgs'
import { Order } from '@enum/Order'
import { Transaction } from '@model/Transaction'
import { TransactionList } from '@model/TransactionList'
import { User } from '@model/User'
import {
fullName,
processXComCompleteTransaction,
sendTransactionLinkRedeemedEmail,
sendTransactionReceivedEmail,
TransactionTypeId
} from 'core'
import { RIGHTS } from '@/auth/RIGHTS' import { RIGHTS } from '@/auth/RIGHTS'
import { CONFIG } from '@/config' import { CONFIG } from '@/config'
import { import { EVENT_TRANSACTION_RECEIVE, EVENT_TRANSACTION_SEND } from '@/event/Events'
EVENT_TRANSACTION_RECEIVE, EVENT_TRANSACTION_SEND } from '@/event/Events'
import { LogError } from '@/server/LogError'
import { Context, getUser } from '@/server/context' import { Context, getUser } from '@/server/context'
import { LogError } from '@/server/LogError'
import { communityUser } from '@/util/communityUser' import { communityUser } from '@/util/communityUser'
import { calculateBalance } from '@/util/validate' import { calculateBalance } from '@/util/validate'
import { virtualDecayTransaction, virtualLinkTransaction } from '@/util/virtualTransactions' import { virtualDecayTransaction, virtualLinkTransaction } from '@/util/virtualTransactions'
// import { TRANSACTIONS_LOCK } from 'database' // import { TRANSACTIONS_LOCK } from 'database'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { getLastTransaction } from 'database' import { getLastTransaction } from 'database'
import { Redis } from 'ioredis'
import { getLogger, Logger } from 'log4js' import { getLogger, Logger } from 'log4js'
import { Mutex } from 'redis-semaphore'
import { redeemDeferredTransferTransaction, transferTransaction } from '@/apis/dltConnector'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { BalanceResolver } from './BalanceResolver' import { BalanceResolver } from './BalanceResolver'
import { GdtResolver } from './GdtResolver' import { GdtResolver } from './GdtResolver'
import { getCommunityName, isHomeCommunity } from './util/communities' import { getCommunityName, isHomeCommunity } from './util/communities'
import { getTransactionList } from './util/getTransactionList' import { getTransactionList } from './util/getTransactionList'
import { transactionLinkSummary } from './util/transactionLinkSummary' import { transactionLinkSummary } from './util/transactionLinkSummary'
import { transferTransaction, redeemDeferredTransferTransaction } from '@/apis/dltConnector'
import { Redis } from 'ioredis'
import { Mutex } from 'redis-semaphore'
const db = AppDatabase.getInstance() const db = AppDatabase.getInstance()
const createLogger = () => getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.TransactionResolver`) const createLogger = () =>
getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.TransactionResolver`)
export const executeTransaction = async ( export const executeTransaction = async (
amount: Decimal, amount: Decimal,
@ -66,15 +66,26 @@ export const executeTransaction = async (
const receivedCallDate = new Date() const receivedCallDate = new Date()
let dltTransactionPromise: Promise<DbDltTransaction | null> = Promise.resolve(null) let dltTransactionPromise: Promise<DbDltTransaction | null> = Promise.resolve(null)
if (!transactionLink) { if (!transactionLink) {
dltTransactionPromise = transferTransaction(sender, recipient, amount.toString(), memo, receivedCallDate) dltTransactionPromise = transferTransaction(
sender,
recipient,
amount.toString(),
memo,
receivedCallDate,
)
} else { } else {
dltTransactionPromise = redeemDeferredTransferTransaction(transactionLink, amount.toString(), receivedCallDate, recipient) dltTransactionPromise = redeemDeferredTransferTransaction(
transactionLink,
amount.toString(),
receivedCallDate,
recipient,
)
} }
try { try {
logger.info('executeTransaction', amount, memo, sender, recipient) logger.info('executeTransaction', amount, memo, sender, recipient)
if (await countOpenPendingTransactions([sender.gradidoID, recipient.gradidoID]) > 0) { if ((await countOpenPendingTransactions([sender.gradidoID, recipient.gradidoID])) > 0) {
throw new LogError( throw new LogError(
`There exist still ongoing 'Pending-Transactions' for the involved users on sender-side!`, `There exist still ongoing 'Pending-Transactions' for the involved users on sender-side!`,
) )
@ -178,7 +189,9 @@ export const executeTransaction = async (
const startTime = new Date() const startTime = new Date()
const dltTransaction = await dltTransactionPromise const dltTransaction = await dltTransactionPromise
const endTime = new Date() const endTime = new Date()
logger.debug(`dlt-connector transaction finished in ${endTime.getTime() - startTime.getTime()} ms`) logger.debug(
`dlt-connector transaction finished in ${endTime.getTime() - startTime.getTime()} ms`,
)
if (dltTransaction) { if (dltTransaction) {
dltTransaction.transactionId = transactionSend.id dltTransaction.transactionId = transactionSend.id
await dltTransaction.save() await dltTransaction.save()

View File

@ -1,5 +1,20 @@
import { GmsPublishLocationType } from '@enum/GmsPublishLocationType'
import { OptInType } from '@enum/OptInType'
import { PasswordEncryptionType } from '@enum/PasswordEncryptionType'
import { RoleNames } from '@enum/RoleNames'
import { UserContactType } from '@enum/UserContactType'
import { ContributionLink } from '@model/ContributionLink'
import { Location } from '@model/Location'
import { cleanDB, headerPushMock, resetToken, testEnvironment } from '@test/helpers'
import { UserInputError } from 'apollo-server-express' import { UserInputError } from 'apollo-server-express'
import { ApolloServerTestClient } from 'apollo-server-testing' import { ApolloServerTestClient } from 'apollo-server-testing'
import { getLogger } from 'config-schema/test/testSetup'
import {
objectValuesToArray,
sendAccountActivationEmail,
sendAccountMultiRegistrationEmail,
sendResetPasswordEmail,
} from 'core'
import { import {
AppDatabase, AppDatabase,
Community as DbCommunity, Community as DbCommunity,
@ -12,23 +27,9 @@ import {
import { GraphQLError } from 'graphql' import { GraphQLError } from 'graphql'
import { DataSource } from 'typeorm' import { DataSource } from 'typeorm'
import { v4 as uuidv4, validate as validateUUID, version as versionUUID } from 'uuid' import { v4 as uuidv4, validate as validateUUID, version as versionUUID } from 'uuid'
import { GmsPublishLocationType } from '@enum/GmsPublishLocationType'
import { OptInType } from '@enum/OptInType'
import { PasswordEncryptionType } from '@enum/PasswordEncryptionType'
import { RoleNames } from '@enum/RoleNames'
import { UserContactType } from '@enum/UserContactType'
import { ContributionLink } from '@model/ContributionLink'
import { Location } from '@model/Location'
import { cleanDB, headerPushMock, resetToken, testEnvironment } from '@test/helpers'
import { subscribe } from '@/apis/KlicktippController' import { subscribe } from '@/apis/KlicktippController'
import { CONFIG } from '@/config' import { CONFIG } from '@/config'
import { import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
sendAccountActivationEmail,
sendAccountMultiRegistrationEmail,
sendResetPasswordEmail,
} from 'core'
import { EventType } from '@/event/Events' import { EventType } from '@/event/Events'
import { PublishNameType } from '@/graphql/enum/PublishNameType' import { PublishNameType } from '@/graphql/enum/PublishNameType'
import { SecretKeyCryptographyCreateKey } from '@/password/EncryptorUtils' import { SecretKeyCryptographyCreateKey } from '@/password/EncryptorUtils'
@ -65,10 +66,6 @@ import { garrickOllivander } from '@/seeds/users/garrick-ollivander'
import { peterLustig } from '@/seeds/users/peter-lustig' import { peterLustig } from '@/seeds/users/peter-lustig'
import { stephenHawking } from '@/seeds/users/stephen-hawking' import { stephenHawking } from '@/seeds/users/stephen-hawking'
import { printTimeDuration } from '@/util/time' import { printTimeDuration } from '@/util/time'
import { objectValuesToArray } from 'core'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { getLogger } from 'config-schema/test/testSetup'
import { Location2Point } from './util/Location2Point' import { Location2Point } from './util/Location2Point'
jest.mock('@/apis/humhub/HumHubClient') jest.mock('@/apis/humhub/HumHubClient')
@ -158,7 +155,6 @@ describe('UserResolver', () => {
expect(result).toEqual( expect(result).toEqual(
expect.objectContaining({ data: { createUser: { id: expect.any(Number) } } }), expect.objectContaining({ data: { createUser: { id: expect.any(Number) } } }),
) )
}) })
describe('valid input data', () => { describe('valid input data', () => {
@ -1054,7 +1050,9 @@ describe('UserResolver', () => {
describe('duration not expired', () => { describe('duration not expired', () => {
it('throws an error', async () => { it('throws an error', async () => {
await expect(mutate({ mutation: forgotPassword, variables: { email: 'bob@baumeister.de' } })).resolves.toEqual( await expect(
mutate({ mutation: forgotPassword, variables: { email: 'bob@baumeister.de' } }),
).resolves.toEqual(
expect.objectContaining({ expect.objectContaining({
errors: [ errors: [
new GraphQLError( new GraphQLError(
@ -1071,7 +1069,9 @@ describe('UserResolver', () => {
describe('duration reset to 0', () => { describe('duration reset to 0', () => {
it('returns true', async () => { it('returns true', async () => {
CONFIG.EMAIL_CODE_REQUEST_TIME = 0 CONFIG.EMAIL_CODE_REQUEST_TIME = 0
await expect(mutate({ mutation: forgotPassword, variables: { email: 'bob@baumeister.de' } })).resolves.toEqual( await expect(
mutate({ mutation: forgotPassword, variables: { email: 'bob@baumeister.de' } }),
).resolves.toEqual(
expect.objectContaining({ expect.objectContaining({
data: { data: {
forgotPassword: true, forgotPassword: true,
@ -1112,7 +1112,9 @@ describe('UserResolver', () => {
describe('request reset password again', () => { describe('request reset password again', () => {
it('throws an error', async () => { it('throws an error', async () => {
CONFIG.EMAIL_CODE_REQUEST_TIME = emailCodeRequestTime CONFIG.EMAIL_CODE_REQUEST_TIME = emailCodeRequestTime
await expect(mutate({ mutation: forgotPassword, variables: { email: 'bob@baumeister.de' } })).resolves.toEqual( await expect(
mutate({ mutation: forgotPassword, variables: { email: 'bob@baumeister.de' } }),
).resolves.toEqual(
expect.objectContaining({ expect.objectContaining({
errors: [new GraphQLError('Email already sent less than 10 minutes ago')], errors: [new GraphQLError('Email already sent less than 10 minutes ago')],
}), }),
@ -1144,7 +1146,10 @@ describe('UserResolver', () => {
it('throws an error', async () => { it('throws an error', async () => {
jest.clearAllMocks() jest.clearAllMocks()
await expect( await expect(
query({ query: queryOptIn, variables: { email: 'bob@baumeister.de', optIn: 'not-valid' } }), query({
query: queryOptIn,
variables: { email: 'bob@baumeister.de', optIn: 'not-valid' },
}),
).resolves.toEqual( ).resolves.toEqual(
expect.objectContaining({ expect.objectContaining({
errors: [ errors: [
@ -1165,7 +1170,10 @@ describe('UserResolver', () => {
await expect( await expect(
query({ query({
query: queryOptIn, query: queryOptIn,
variables: { email: 'bob@baumeister.de', optIn: emailContact.emailVerificationCode.toString() }, variables: {
email: 'bob@baumeister.de',
optIn: emailContact.emailVerificationCode.toString(),
},
}), }),
).resolves.toEqual( ).resolves.toEqual(
expect.objectContaining({ expect.objectContaining({

View File

@ -1,32 +1,3 @@
import {
AppDatabase,
ContributionLink as DbContributionLink,
TransactionLink as DbTransactionLink,
User as DbUser,
UserContact as DbUserContact,
ProjectBranding,
UserLoggingView,
getHomeCommunity,
findUserByIdentifier
} from 'database'
import { GraphQLResolveInfo } from 'graphql'
import {
Arg,
Args,
Authorized,
Ctx,
FieldResolver,
Info,
Int,
Mutation,
Query,
Resolver,
Root,
} from 'type-graphql'
import { IRestResponse } from 'typed-rest-client'
import { EntityManager, EntityNotFoundError, In, Point } from 'typeorm'
import { v4 as uuidv4 } from 'uuid'
import { UserArgs } from '@arg//UserArgs' import { UserArgs } from '@arg//UserArgs'
import { CreateUserArgs } from '@arg/CreateUserArgs' import { CreateUserArgs } from '@arg/CreateUserArgs'
import { Paginated } from '@arg/Paginated' import { Paginated } from '@arg/Paginated'
@ -46,15 +17,55 @@ import { User } from '@model/User'
import { SearchUsersResult, UserAdmin } from '@model/UserAdmin' import { SearchUsersResult, UserAdmin } from '@model/UserAdmin'
import { UserContact } from '@model/UserContact' import { UserContact } from '@model/UserContact'
import { UserLocationResult } from '@model/UserLocationResult' import { UserLocationResult } from '@model/UserLocationResult'
import {
import { subscribe } from '@/apis/KlicktippController' delay,
sendAccountActivationEmail,
sendAccountMultiRegistrationEmail,
sendResetPasswordEmail,
validateAlias,
} from 'core'
import {
AppDatabase,
ContributionLink as DbContributionLink,
TransactionLink as DbTransactionLink,
User as DbUser,
UserContact as DbUserContact,
findUserByIdentifier,
getHomeCommunity,
ProjectBranding,
UserLoggingView,
} from 'database'
import { GraphQLResolveInfo } from 'graphql'
import { getLogger, Logger } from 'log4js'
import random from 'random-bigint'
import { updateAllDefinedAndChanged } from 'shared'
import { randombytes_random } from 'sodium-native'
import {
Arg,
Args,
Authorized,
Ctx,
FieldResolver,
Info,
Int,
Mutation,
Query,
Resolver,
Root,
} from 'type-graphql'
import { IRestResponse } from 'typed-rest-client'
import { EntityManager, EntityNotFoundError, In, Point } from 'typeorm'
import { v4 as uuidv4 } from 'uuid'
import { registerAddressTransaction } from '@/apis/dltConnector'
import { HumHubClient } from '@/apis/humhub/HumHubClient' import { HumHubClient } from '@/apis/humhub/HumHubClient'
import { Account as HumhubAccount } from '@/apis/humhub/model/Account' import { Account as HumhubAccount } from '@/apis/humhub/model/Account'
import { GetUser } from '@/apis/humhub/model/GetUser' import { GetUser } from '@/apis/humhub/model/GetUser'
import { PostUser } from '@/apis/humhub/model/PostUser' import { PostUser } from '@/apis/humhub/model/PostUser'
import { subscribe } from '@/apis/KlicktippController'
import { encode } from '@/auth/JWT' import { encode } from '@/auth/JWT'
import { RIGHTS } from '@/auth/RIGHTS' import { RIGHTS } from '@/auth/RIGHTS'
import { CONFIG } from '@/config' import { CONFIG } from '@/config'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { PublishNameLogic } from '@/data/PublishName.logic' import { PublishNameLogic } from '@/data/PublishName.logic'
import { import {
EVENT_ADMIN_USER_DELETE, EVENT_ADMIN_USER_DELETE,
@ -74,36 +85,22 @@ import {
} from '@/event/Events' } from '@/event/Events'
import { isValidPassword } from '@/password/EncryptorUtils' import { isValidPassword } from '@/password/EncryptorUtils'
import { encryptPassword, verifyPassword } from '@/password/PasswordEncryptor' import { encryptPassword, verifyPassword } from '@/password/PasswordEncryptor'
import { LogError } from '@/server/LogError'
import { Context, getClientTimezoneOffset, getUser } from '@/server/context' import { Context, getClientTimezoneOffset, getUser } from '@/server/context'
import { LogError } from '@/server/LogError'
import { communityDbUser } from '@/util/communityUser' import { communityDbUser } from '@/util/communityUser'
import { hasElopageBuys } from '@/util/hasElopageBuys' import { hasElopageBuys } from '@/util/hasElopageBuys'
import { durationInMinutesFromDates, getTimeDurationObject, printTimeDuration } from '@/util/time' import { durationInMinutesFromDates, getTimeDurationObject, printTimeDuration } from '@/util/time'
import {
delay,
sendAccountActivationEmail,
sendAccountMultiRegistrationEmail,
sendResetPasswordEmail,
} from 'core'
import random from 'random-bigint'
import { randombytes_random } from 'sodium-native'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { Logger, getLogger } from 'log4js'
import { FULL_CREATION_AVAILABLE } from './const/const' import { FULL_CREATION_AVAILABLE } from './const/const'
import { Location2Point, Point2Location } from './util/Location2Point'
import { authenticateGmsUserPlayground } from './util/authenticateGmsUserPlayground' import { authenticateGmsUserPlayground } from './util/authenticateGmsUserPlayground'
import { compareGmsRelevantUserSettings } from './util/compareGmsRelevantUserSettings' import { compareGmsRelevantUserSettings } from './util/compareGmsRelevantUserSettings'
import { getUserCreations } from './util/creations' import { getUserCreations } from './util/creations'
import { extractGraphQLFieldsForSelect } from './util/extractGraphQLFields' import { extractGraphQLFieldsForSelect } from './util/extractGraphQLFields'
import { findUsers } from './util/findUsers' import { findUsers } from './util/findUsers'
import { getKlicktippState } from './util/getKlicktippState' import { getKlicktippState } from './util/getKlicktippState'
import { Location2Point, Point2Location } from './util/Location2Point'
import { deleteUserRole, setUserRole } from './util/modifyUserRole' import { deleteUserRole, setUserRole } from './util/modifyUserRole'
import { sendUserToGms } from './util/sendUserToGms' import { sendUserToGms } from './util/sendUserToGms'
import { syncHumhub } from './util/syncHumhub' import { syncHumhub } from './util/syncHumhub'
import { validateAlias } from 'core'
import { registerAddressTransaction } from '@/apis/dltConnector'
import { updateAllDefinedAndChanged } from 'shared'
const LANGUAGES = ['de', 'en', 'es', 'fr', 'nl'] const LANGUAGES = ['de', 'en', 'es', 'fr', 'nl']
const DEFAULT_LANGUAGE = 'de' const DEFAULT_LANGUAGE = 'de'
@ -380,7 +377,9 @@ export class UserResolver {
const homeCom = await getHomeCommunity() const homeCom = await getHomeCommunity()
if (!homeCom) { if (!homeCom) {
logger.error('no home community found, please start the dht-node first') logger.error('no home community found, please start the dht-node first')
throw new Error(`Error creating user, please write the support team: ${CONFIG.COMMUNITY_SUPPORT_MAIL}`) throw new Error(
`Error creating user, please write the support team: ${CONFIG.COMMUNITY_SUPPORT_MAIL}`,
)
} }
if (homeCom.communityUuid) { if (homeCom.communityUuid) {
dbUser.communityUuid = homeCom.communityUuid dbUser.communityUuid = homeCom.communityUuid
@ -398,7 +397,7 @@ export class UserResolver {
dbUser.publisherId = publisherId ?? 0 dbUser.publisherId = publisherId ?? 0
dbUser.passwordEncryptionType = PasswordEncryptionType.NO_PASSWORD dbUser.passwordEncryptionType = PasswordEncryptionType.NO_PASSWORD
if(logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug('new dbUser', new UserLoggingView(dbUser)) logger.debug('new dbUser', new UserLoggingView(dbUser))
} }
if (redeemCode) { if (redeemCode) {
@ -510,7 +509,9 @@ export class UserResolver {
const startTime = new Date() const startTime = new Date()
await dltTransactionPromise await dltTransactionPromise
const endTime = new Date() const endTime = new Date()
logger.info(`dlt-connector register address finished in ${endTime.getTime() - startTime.getTime()} ms`) logger.info(
`dlt-connector register address finished in ${endTime.getTime() - startTime.getTime()} ms`,
)
return new User(dbUser) return new User(dbUser)
} }
@ -813,7 +814,7 @@ export class UserResolver {
if (!homeCom) { if (!homeCom) {
logger.error('no home community found, please start the dht-node first') logger.error('no home community found, please start the dht-node first')
throw new Error( throw new Error(
`Error updating user, please write the support team: ${CONFIG.COMMUNITY_SUPPORT_MAIL}` `Error updating user, please write the support team: ${CONFIG.COMMUNITY_SUPPORT_MAIL}`,
) )
} }
if (homeCom.gmsApiKey !== null) { if (homeCom.gmsApiKey !== null) {
@ -859,9 +860,11 @@ export class UserResolver {
if (context.token) { if (context.token) {
const homeCom = await getHomeCommunity() const homeCom = await getHomeCommunity()
if (!homeCom) { if (!homeCom) {
logger.error("couldn't authenticate for gms, no home community found, please start the dht-node first") logger.error(
"couldn't authenticate for gms, no home community found, please start the dht-node first",
)
throw new Error( throw new Error(
`Error authenticating for gms, please write the support team: ${CONFIG.COMMUNITY_SUPPORT_MAIL}` `Error authenticating for gms, please write the support team: ${CONFIG.COMMUNITY_SUPPORT_MAIL}`,
) )
} }
if (!homeCom.gmsApiKey) { if (!homeCom.gmsApiKey) {
@ -888,9 +891,11 @@ export class UserResolver {
if (context.token) { if (context.token) {
const homeCom = await getHomeCommunity() const homeCom = await getHomeCommunity()
if (!homeCom) { if (!homeCom) {
logger.error("couldn't load home community location, no home community found, please start the dht-node first") logger.error(
"couldn't load home community location, no home community found, please start the dht-node first",
)
throw new Error( throw new Error(
`Error loading user location, please write the support team: ${CONFIG.COMMUNITY_SUPPORT_MAIL}` `Error loading user location, please write the support team: ${CONFIG.COMMUNITY_SUPPORT_MAIL}`,
) )
} }
result.communityLocation = Point2Location(homeCom.location as Point) result.communityLocation = Point2Location(homeCom.location as Point)
@ -976,7 +981,15 @@ export class UserResolver {
@Ctx() context: Context, @Ctx() context: Context,
): Promise<SearchUsersResult> { ): Promise<SearchUsersResult> {
const clientTimezoneOffset = getClientTimezoneOffset(context) const clientTimezoneOffset = getClientTimezoneOffset(context)
const userFields = ['id', 'firstName', 'lastName', 'emailId', 'emailContact', 'deletedAt', 'createdAt'] const userFields = [
'id',
'firstName',
'lastName',
'emailId',
'emailContact',
'deletedAt',
'createdAt',
]
const [users, count] = await findUsers( const [users, count] = await findUsers(
userFields, userFields,
query, query,

View File

@ -1,12 +1,14 @@
import { cleanDB, contributionDateFormatter, testEnvironment } from '@test/helpers'
import { ApolloServerTestClient } from 'apollo-server-testing' import { ApolloServerTestClient } from 'apollo-server-testing'
import { Community as DbCommunity } from 'database' import { CONFIG as CORE_CONFIG } from 'core'
import { AppDatabase, Community as DbCommunity } from 'database'
import { Decimal } from 'decimal.js-light' import { Decimal } from 'decimal.js-light'
import { GraphQLError } from 'graphql' import { GraphQLError } from 'graphql'
// import { TRANSACTIONS_LOCK } from 'database'
import { Mutex } from 'redis-semaphore'
import { DataSource } from 'typeorm' import { DataSource } from 'typeorm'
import { v4 as uuidv4 } from 'uuid' import { v4 as uuidv4 } from 'uuid'
import { CONFIG } from '@/config'
import { cleanDB, contributionDateFormatter, testEnvironment } from '@test/helpers'
import { creationFactory, nMonthsBefore } from '@/seeds/factory/creation' import { creationFactory, nMonthsBefore } from '@/seeds/factory/creation'
import { userFactory } from '@/seeds/factory/user' import { userFactory } from '@/seeds/factory/user'
import { import {
@ -21,11 +23,6 @@ import {
import { bibiBloxberg } from '@/seeds/users/bibi-bloxberg' import { bibiBloxberg } from '@/seeds/users/bibi-bloxberg'
import { bobBaumeister } from '@/seeds/users/bob-baumeister' import { bobBaumeister } from '@/seeds/users/bob-baumeister'
import { peterLustig } from '@/seeds/users/peter-lustig' import { peterLustig } from '@/seeds/users/peter-lustig'
import { CONFIG } from '@/config'
import { CONFIG as CORE_CONFIG } from 'core'
// import { TRANSACTIONS_LOCK } from 'database'
import { Mutex } from 'redis-semaphore'
import { AppDatabase } from 'database'
jest.mock('@/password/EncryptorUtils') jest.mock('@/password/EncryptorUtils')
@ -53,7 +50,7 @@ afterAll(async () => {
await testEnv.db.getRedisClient().quit() await testEnv.db.getRedisClient().quit()
}) })
type WorkData = { start: number, end: number } type WorkData = { start: number; end: number }
async function fakeWork(workData: WorkData[], index: number) { async function fakeWork(workData: WorkData[], index: number) {
// const releaseLock = await TRANSACTIONS_LOCK.acquire() // const releaseLock = await TRANSACTIONS_LOCK.acquire()
// create a new mutex for every function call, like in production code // create a new mutex for every function call, like in production code
@ -73,14 +70,14 @@ describe('semaphore', () => {
const workData: WorkData[] = [] const workData: WorkData[] = []
const promises: Promise<void>[] = [] const promises: Promise<void>[] = []
for(let i = 0; i < 20; i++) { for (let i = 0; i < 20; i++) {
promises.push(fakeWork(workData, i)) promises.push(fakeWork(workData, i))
} }
await Promise.all(promises) await Promise.all(promises)
workData.sort((a, b) => a.start - b.start) workData.sort((a, b) => a.start - b.start)
workData.forEach((work, index) => { workData.forEach((work, index) => {
expect(work.start).toBeLessThan(work.end) expect(work.start).toBeLessThan(work.end)
if(index < workData.length - 1) { if (index < workData.length - 1) {
expect(work.start).toBeLessThan(workData[index + 1].start) expect(work.start).toBeLessThan(workData[index + 1].start)
expect(work.end).toBeLessThanOrEqual(workData[index + 1].start) expect(work.end).toBeLessThanOrEqual(workData[index + 1].start)
} }

View File

@ -1,6 +1,5 @@
import { Point } from 'typeorm'
import { Location } from '@model/Location' import { Location } from '@model/Location'
import { Point } from 'typeorm'
export function Location2Point(location: Location): Point { export function Location2Point(location: Location): Point {
let pointStr: string let pointStr: string

View File

@ -1,11 +1,10 @@
import { ensureUrlEndsWithSlash } from 'core'
import { User as DbUser } from 'database' import { User as DbUser } from 'database'
import { getLogger } from 'log4js'
import { verifyAuthToken } from '@/apis/gms/GmsClient' import { verifyAuthToken } from '@/apis/gms/GmsClient'
import { CONFIG } from '@/config' import { CONFIG } from '@/config'
import { GmsUserAuthenticationResult } from '@/graphql/model/GmsUserAuthenticationResult'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { ensureUrlEndsWithSlash } from 'core' import { GmsUserAuthenticationResult } from '@/graphql/model/GmsUserAuthenticationResult'
import { getLogger } from 'log4js'
const logger = getLogger( const logger = getLogger(
`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.util.authenticateGmsUserPlayground`, `${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.util.authenticateGmsUserPlayground`,

View File

@ -1,3 +1,4 @@
import { Paginated } from '@arg/Paginated'
import { import {
AppDatabase, AppDatabase,
Community as DbCommunity, Community as DbCommunity,
@ -5,8 +6,6 @@ import {
} from 'database' } from 'database'
import { FindOneOptions, IsNull, Not } from 'typeorm' import { FindOneOptions, IsNull, Not } from 'typeorm'
import { Paginated } from '@arg/Paginated'
import { LogError } from '@/server/LogError' import { LogError } from '@/server/LogError'
function findWithCommunityIdentifier(communityIdentifier: string): FindOneOptions<DbCommunity> { function findWithCommunityIdentifier(communityIdentifier: string): FindOneOptions<DbCommunity> {

View File

@ -1,13 +1,11 @@
import { User as DbUser, UserLoggingView } from 'database' import { User as DbUser, UserLoggingView } from 'database'
import { getLogger } from 'log4js'
import { Point } from 'typeorm' import { Point } from 'typeorm'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { UpdateUserInfosArgs } from '@/graphql/arg/UpdateUserInfosArgs' import { UpdateUserInfosArgs } from '@/graphql/arg/UpdateUserInfosArgs'
import { GmsPublishLocationType } from '@/graphql/enum/GmsPublishLocationType' import { GmsPublishLocationType } from '@/graphql/enum/GmsPublishLocationType'
import { PublishNameType } from '@/graphql/enum/PublishNameType' import { PublishNameType } from '@/graphql/enum/PublishNameType'
import { LogError } from '@/server/LogError' import { LogError } from '@/server/LogError'
import { getLogger } from 'log4js'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { Point2Location } from './Location2Point' import { Point2Location } from './Location2Point'
const logger = getLogger( const logger = getLogger(

View File

@ -1,12 +1,12 @@
import { Paginated } from '@arg/Paginated'
import { Contribution as DbContribution } from 'database'
import { FindManyOptions, In, MoreThan } from 'typeorm'
import { CONFIG } from '@/config' import { CONFIG } from '@/config'
import { Order } from '@/graphql/enum/Order' import { Order } from '@/graphql/enum/Order'
import { import {
DEFAULT_PAGINATION_PAGE_SIZE, DEFAULT_PAGINATION_PAGE_SIZE,
FRONTEND_CONTRIBUTIONS_ITEM_ANCHOR_PREFIX, FRONTEND_CONTRIBUTIONS_ITEM_ANCHOR_PREFIX,
} from '@/graphql/resolver/const/const' } from '@/graphql/resolver/const/const'
import { Paginated } from '@arg/Paginated'
import { Contribution as DbContribution } from 'database'
import { FindManyOptions, In, MoreThan } from 'typeorm'
// TODO: combine with Pagination class for all queries to use // TODO: combine with Pagination class for all queries to use
function buildPaginationOptions(paginated: Paginated): FindManyOptions<DbContribution> { function buildPaginationOptions(paginated: Paginated): FindManyOptions<DbContribution> {

View File

@ -1,9 +1,7 @@
import { ApolloServerTestClient } from 'apollo-server-testing'
import { Contribution, User } from 'database'
import { DataSource } from 'typeorm'
import { AppDatabase } from 'database'
import { cleanDB, contributionDateFormatter, testEnvironment } from '@test/helpers' import { cleanDB, contributionDateFormatter, testEnvironment } from '@test/helpers'
import { ApolloServerTestClient } from 'apollo-server-testing'
import { AppDatabase, Contribution, User } from 'database'
import { DataSource } from 'typeorm'
import { CONFIG } from '@/config' import { CONFIG } from '@/config'
import { userFactory } from '@/seeds/factory/user' import { userFactory } from '@/seeds/factory/user'

View File

@ -1,14 +1,11 @@
import { Contribution } from 'database'
import { Decimal } from 'decimal.js-light'
import { OpenCreation } from '@model/OpenCreation' import { OpenCreation } from '@model/OpenCreation'
import { FULL_CREATION_AVAILABLE, MAX_CREATION_AMOUNT } from '@/graphql/resolver/const/const'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { LogError } from '@/server/LogError'
import { getFirstDayOfPreviousNMonth } from 'core' import { getFirstDayOfPreviousNMonth } from 'core'
import { AppDatabase } from 'database' import { AppDatabase, Contribution } from 'database'
import { Decimal } from 'decimal.js-light'
import { getLogger } from 'log4js' import { getLogger } from 'log4js'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { FULL_CREATION_AVAILABLE, MAX_CREATION_AMOUNT } from '@/graphql/resolver/const/const'
import { LogError } from '@/server/LogError'
const db = AppDatabase.getInstance() const db = AppDatabase.getInstance()
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.util.creations`) const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.util.creations`)

View File

@ -1,7 +1,7 @@
import { GraphQLResolveInfo } from 'graphql' import { GraphQLResolveInfo } from 'graphql'
import { import {
ResolveTree,
parseResolveInfo, parseResolveInfo,
ResolveTree,
simplifyParsedResolveInfoFragmentWithType, simplifyParsedResolveInfoFragmentWithType,
} from 'graphql-parse-resolve-info' } from 'graphql-parse-resolve-info'
import { ObjectLiteral, SelectQueryBuilder } from 'typeorm' import { ObjectLiteral, SelectQueryBuilder } from 'typeorm'

View File

@ -1,8 +1,7 @@
import { ContributionMessage as DbContributionMessage } from 'database'
import { In } from 'typeorm'
import { Paginated } from '@arg/Paginated' import { Paginated } from '@arg/Paginated'
import { ContributionMessageType } from '@enum/ContributionMessageType' import { ContributionMessageType } from '@enum/ContributionMessageType'
import { ContributionMessage as DbContributionMessage } from 'database'
import { In } from 'typeorm'
interface FindContributionMessagesOptions { interface FindContributionMessagesOptions {
contributionId: number contributionId: number

View File

@ -1,8 +1,7 @@
import { AppDatabase, Contribution as DbContribution } from 'database'
import { Brackets, In, IsNull, LessThanOrEqual, Like, Not, SelectQueryBuilder } from 'typeorm'
import { Paginated } from '@arg/Paginated' import { Paginated } from '@arg/Paginated'
import { SearchContributionsFilterArgs } from '@arg/SearchContributionsFilterArgs' import { SearchContributionsFilterArgs } from '@arg/SearchContributionsFilterArgs'
import { AppDatabase, Contribution as DbContribution } from 'database'
import { Brackets, In, IsNull, LessThanOrEqual, Like, Not, SelectQueryBuilder } from 'typeorm'
import { LogError } from '@/server/LogError' import { LogError } from '@/server/LogError'

View File

@ -1,8 +1,7 @@
import { User as DbUser } from 'database'
import { IsNull, Like, Not } from 'typeorm'
import { SearchUsersFilters } from '@arg/SearchUsersFilters' import { SearchUsersFilters } from '@arg/SearchUsersFilters'
import { Order } from '@enum/Order' import { Order } from '@enum/Order'
import { User as DbUser } from 'database'
import { IsNull, Like, Not } from 'typeorm'
function likeQuery(searchCriteria: string) { function likeQuery(searchCriteria: string) {
return Like(`%${searchCriteria}%`) return Like(`%${searchCriteria}%`)

View File

@ -1,8 +1,7 @@
import { KlickTipp } from '@model/KlickTipp' import { KlickTipp } from '@model/KlickTipp'
import { getLogger } from 'log4js'
import { getKlickTippUser } from '@/apis/KlicktippController' import { getKlickTippUser } from '@/apis/KlicktippController'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { getLogger } from 'log4js'
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.util.getKlicktippState`) const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.util.getKlicktippState`)

View File

@ -1,6 +1,5 @@
import { Transaction as DbTransaction } from 'database'
import { Order } from '@enum/Order' import { Order } from '@enum/Order'
import { Transaction as DbTransaction } from 'database'
export const getTransactionList = async ( export const getTransactionList = async (
userId: number, userId: number,

View File

@ -1,11 +1,10 @@
import { Community as DbCommunity, User as DbUser } from 'database' import { Community as DbCommunity, User as DbUser } from 'database'
import { getLogger } from 'log4js'
import { createGmsUser, updateGmsUser } from '@/apis/gms/GmsClient' import { createGmsUser, updateGmsUser } from '@/apis/gms/GmsClient'
import { GmsUser } from '@/apis/gms/model/GmsUser' import { GmsUser } from '@/apis/gms/model/GmsUser'
import { CONFIG } from '@/config' import { CONFIG } from '@/config'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { LogError } from '@/server/LogError' import { LogError } from '@/server/LogError'
import { getLogger } from 'log4js'
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.util.sendUserToGms`) const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.util.sendUserToGms`)

View File

@ -1,12 +1,10 @@
import { getLogger } from 'config-schema/test/testSetup'
import { User, UserContact } from 'database' import { User, UserContact } from 'database'
import { HumHubClient } from '@/apis/humhub/HumHubClient' import { HumHubClient } from '@/apis/humhub/HumHubClient'
import { GetUser } from '@/apis/humhub/model/GetUser' import { GetUser } from '@/apis/humhub/model/GetUser'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { UpdateUserInfosArgs } from '@/graphql/arg/UpdateUserInfosArgs' import { UpdateUserInfosArgs } from '@/graphql/arg/UpdateUserInfosArgs'
import { PublishNameType } from '@/graphql/enum/PublishNameType' import { PublishNameType } from '@/graphql/enum/PublishNameType'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { getLogger } from 'config-schema/test/testSetup'
import { syncHumhub } from './syncHumhub' import { syncHumhub } from './syncHumhub'
jest.mock('@/apis/humhub/HumHubClient') jest.mock('@/apis/humhub/HumHubClient')

View File

@ -1,16 +1,16 @@
import { User } from 'database' import { User } from 'database'
import { getLogger } from 'log4js'
import { HumHubClient } from '@/apis/humhub/HumHubClient' import { HumHubClient } from '@/apis/humhub/HumHubClient'
import { GetUser } from '@/apis/humhub/model/GetUser' import { GetUser } from '@/apis/humhub/model/GetUser'
import { PostUser } from '@/apis/humhub/model/PostUser' import { PostUser } from '@/apis/humhub/model/PostUser'
import { ExecutedHumhubAction, syncUser } from '@/apis/humhub/syncUser' import { ExecutedHumhubAction, syncUser } from '@/apis/humhub/syncUser'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { PublishNameLogic } from '@/data/PublishName.logic' import { PublishNameLogic } from '@/data/PublishName.logic'
import { UpdateUserInfosArgs } from '@/graphql/arg/UpdateUserInfosArgs' import { UpdateUserInfosArgs } from '@/graphql/arg/UpdateUserInfosArgs'
import { PublishNameType } from '@/graphql/enum/PublishNameType' import { PublishNameType } from '@/graphql/enum/PublishNameType'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { getLogger } from 'log4js'
const createLogger = () => getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.util.syncHumhub`) const createLogger = () =>
getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.util.syncHumhub`)
/** /**
* Syncs the user with humhub * Syncs the user with humhub

View File

@ -1,10 +1,9 @@
import { TransactionLink as DbTransactionLink, User as DbUser } from 'database'
import { IsNull, MoreThan } from 'typeorm'
import { Paginated } from '@arg/Paginated' import { Paginated } from '@arg/Paginated'
import { TransactionLinkFilters } from '@arg/TransactionLinkFilters' import { TransactionLinkFilters } from '@arg/TransactionLinkFilters'
import { Order } from '@enum/Order' import { Order } from '@enum/Order'
import { TransactionLink, TransactionLinkResult } from '@model/TransactionLink' import { TransactionLink, TransactionLinkResult } from '@model/TransactionLink'
import { TransactionLink as DbTransactionLink, User as DbUser } from 'database'
import { IsNull, MoreThan } from 'typeorm'
import { User } from '@/graphql/model/User' import { User } from '@/graphql/model/User'

View File

@ -1,6 +1,5 @@
import { GraphQLScalarType, Kind } from 'graphql'
import { Location } from '@model/Location' import { Location } from '@model/Location'
import { GraphQLScalarType, Kind } from 'graphql'
import { LogError } from '@/server/LogError' import { LogError } from '@/server/LogError'

View File

@ -1,9 +1,8 @@
import { Location } from '@model/Location'
import { Decimal } from 'decimal.js-light' import { Decimal } from 'decimal.js-light'
import { GraphQLSchema } from 'graphql' import { GraphQLSchema } from 'graphql'
import { buildSchema } from 'type-graphql' import { buildSchema } from 'type-graphql'
import { Location } from '@model/Location'
import { isAuthorized } from './directive/isAuthorized' import { isAuthorized } from './directive/isAuthorized'
import { AiChatResolver } from './resolver/AiChatResolver' import { AiChatResolver } from './resolver/AiChatResolver'
import { BalanceResolver } from './resolver/BalanceResolver' import { BalanceResolver } from './resolver/BalanceResolver'

View File

@ -1,8 +1,7 @@
import { createUnionType } from 'type-graphql'
import { ContributionLink } from '@model/ContributionLink' import { ContributionLink } from '@model/ContributionLink'
import { RedeemJwtLink } from '@model/RedeemJwtLink' import { RedeemJwtLink } from '@model/RedeemJwtLink'
import { TransactionLink } from '@model/TransactionLink' import { TransactionLink } from '@model/TransactionLink'
import { createUnionType } from 'type-graphql'
export const QueryLinkResult = createUnionType({ export const QueryLinkResult = createUnionType({
name: 'QueryLinkResult', // the name of the GraphQL union name: 'QueryLinkResult', // the name of the GraphQL union

View File

@ -1,6 +1,5 @@
import { ValidationOptions, registerDecorator } from 'class-validator'
import { ContributionStatus } from '@enum/ContributionStatus' import { ContributionStatus } from '@enum/ContributionStatus'
import { registerDecorator, ValidationOptions } from 'class-validator'
export function isContributionStatusArray(validationOptions?: ValidationOptions) { export function isContributionStatusArray(validationOptions?: ValidationOptions) {
return function (object: Object, propertyName: string) { return function (object: Object, propertyName: string) {

View File

@ -1,4 +1,4 @@
import { ValidationArguments, ValidationOptions, registerDecorator } from 'class-validator' import { registerDecorator, ValidationArguments, ValidationOptions } from 'class-validator'
export function isValidDateString(validationOptions?: ValidationOptions) { export function isValidDateString(validationOptions?: ValidationOptions) {
return function (object: Object, propertyName: string) { return function (object: Object, propertyName: string) {

View File

@ -1,4 +1,4 @@
import { ValidationArguments, ValidationOptions, registerDecorator } from 'class-validator' import { registerDecorator, ValidationArguments, ValidationOptions } from 'class-validator'
import { Decimal } from 'decimal.js-light' import { Decimal } from 'decimal.js-light'
export function IsPositiveDecimal(validationOptions?: ValidationOptions) { export function IsPositiveDecimal(validationOptions?: ValidationOptions) {

View File

@ -1,4 +1,4 @@
import { ValidationArguments, ValidationOptions, registerDecorator } from 'class-validator' import { registerDecorator, ValidationArguments, ValidationOptions } from 'class-validator'
export function isValidHieroId(validationOptions?: ValidationOptions) { export function isValidHieroId(validationOptions?: ValidationOptions) {
return function (object: Object, propertyName: string) { return function (object: Object, propertyName: string) {

View File

@ -1,6 +1,5 @@
import { ValidationArguments, ValidationOptions, registerDecorator } from 'class-validator'
import { Location } from '@model/Location' import { Location } from '@model/Location'
import { registerDecorator, ValidationArguments, ValidationOptions } from 'class-validator'
import { Location2Point } from '@/graphql/resolver/util/Location2Point' import { Location2Point } from '@/graphql/resolver/util/Location2Point'

View File

@ -2,9 +2,11 @@ import 'reflect-metadata'
import 'source-map-support/register' import 'source-map-support/register'
import { getLogger } from 'log4js' import { getLogger } from 'log4js'
import { CONFIG } from './config' import { CONFIG } from './config'
import { startValidateCommunities } from './federation/validateCommunities' import {
startValidateCommunities,
writeJwtKeyPairInHomeCommunity,
} from './federation/validateCommunities'
import { createServer } from './server/createServer' import { createServer } from './server/createServer'
import { writeJwtKeyPairInHomeCommunity } from './federation/validateCommunities'
import { initLogging } from './server/logger' import { initLogging } from './server/logger'
async function main() { async function main() {

View File

@ -1,14 +1,13 @@
import { Contribution, User } from 'database' import { Contribution, User } from 'database'
import { Decimal } from 'decimal.js-light' import { Decimal } from 'decimal.js-light'
import { getLogger, Logger } from 'log4js'
import { Role } from '@/auth/Role' import { Role } from '@/auth/Role'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { ContributionLogic } from '@/data/Contribution.logic' import { ContributionLogic } from '@/data/Contribution.logic'
import { ContributionMessageBuilder } from '@/data/ContributionMessage.builder' import { ContributionMessageBuilder } from '@/data/ContributionMessage.builder'
import { ContributionStatus } from '@/graphql/enum/ContributionStatus' import { ContributionStatus } from '@/graphql/enum/ContributionStatus'
import { LogError } from '@/server/LogError'
import { Context, getClientTimezoneOffset } from '@/server/context' import { Context, getClientTimezoneOffset } from '@/server/context'
import { Logger, getLogger } from 'log4js' import { LogError } from '@/server/LogError'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
export abstract class AbstractUnconfirmedContributionRole { export abstract class AbstractUnconfirmedContributionRole {
private availableCreationSums?: Decimal[] private availableCreationSums?: Decimal[]
@ -24,7 +23,9 @@ export abstract class AbstractUnconfirmedContributionRole {
if (self.confirmedAt || self.deniedAt) { if (self.confirmedAt || self.deniedAt) {
throw new LogError("this contribution isn't unconfirmed!") throw new LogError("this contribution isn't unconfirmed!")
} }
this.logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.interactions.updateUnconfirmedContribution`) this.logger = getLogger(
`${LOG4JS_BASE_CATEGORY_NAME}.interactions.updateUnconfirmedContribution`,
)
this.logger.addContext('contribution', this.self.id) this.logger.addContext('contribution', this.self.id)
} }

View File

@ -1,13 +1,12 @@
import { AdminUpdateContributionArgs } from '@arg/AdminUpdateContributionArgs'
import { ContributionArgs } from '@arg/ContributionArgs'
import { Contribution, ContributionMessage } from 'database' import { Contribution, ContributionMessage } from 'database'
import { Decimal } from 'decimal.js-light' import { Decimal } from 'decimal.js-light'
import { EntityManager, FindOneOptions, FindOptionsRelations } from 'typeorm' import { EntityManager, FindOneOptions, FindOptionsRelations } from 'typeorm'
import { AdminUpdateContributionArgs } from '@arg/AdminUpdateContributionArgs'
import { ContributionArgs } from '@arg/ContributionArgs'
import { ContributionMessageArgs } from '@/graphql/arg/ContributionMessageArgs' import { ContributionMessageArgs } from '@/graphql/arg/ContributionMessageArgs'
import { LogError } from '@/server/LogError'
import { Context } from '@/server/context' import { Context } from '@/server/context'
import { LogError } from '@/server/LogError'
import { AbstractUnconfirmedContributionRole } from './AbstractUnconfirmedContribution.role' import { AbstractUnconfirmedContributionRole } from './AbstractUnconfirmedContribution.role'
import { UnconfirmedContributionAdminRole } from './UnconfirmedContributionAdmin.role' import { UnconfirmedContributionAdminRole } from './UnconfirmedContributionAdmin.role'

View File

@ -1,9 +1,9 @@
import { createHash } from 'crypto'
import { getHomeCommunity } from 'database'
import { exportJWK, importSPKI } from 'jose'
import { getLogger } from 'log4js'
import { CONFIG } from '@/config' import { CONFIG } from '@/config'
import { FRONTEND_LOGIN_ROUTE, GRADIDO_REALM, LOG4JS_BASE_CATEGORY_NAME } from '@/config/const' import { FRONTEND_LOGIN_ROUTE, GRADIDO_REALM, LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { getHomeCommunity } from 'database'
import { importSPKI, exportJWK } from 'jose'
import { createHash } from 'crypto'
import { getLogger } from 'log4js'
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.openIDConnect`) const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.openIDConnect`)
const defaultErrorForCaller = 'Internal Server Error' const defaultErrorForCaller = 'Internal Server Error'
@ -12,7 +12,10 @@ export const openidConfiguration = async (req: any, res: any): Promise<void> =>
res.setHeader('Content-Type', 'application/json') res.setHeader('Content-Type', 'application/json')
res.status(200).json({ res.status(200).json({
issuer: new URL(FRONTEND_LOGIN_ROUTE, CONFIG.COMMUNITY_URL).toString(), issuer: new URL(FRONTEND_LOGIN_ROUTE, CONFIG.COMMUNITY_URL).toString(),
jwks_uri: new URL(`/realms/${GRADIDO_REALM}/protocol/openid-connect/certs`, CONFIG.COMMUNITY_URL).toString(), jwks_uri: new URL(
`/realms/${GRADIDO_REALM}/protocol/openid-connect/certs`,
CONFIG.COMMUNITY_URL,
).toString(),
}) })
} }
@ -33,9 +36,7 @@ export const jwks = async (req: any, res: any): Promise<void> => {
const jwkRsa = await exportJWK(rsaKey) const jwkRsa = await exportJWK(rsaKey)
// Optional: calculate Key ID (z.B. SHA-256 Fingerprint) // Optional: calculate Key ID (z.B. SHA-256 Fingerprint)
const kid = createHash('sha256') const kid = createHash('sha256').update(homeCommunity.publicJwtKey).digest('base64url')
.update(homeCommunity.publicJwtKey)
.digest('base64url')
const jwks = { const jwks = {
keys: [ keys: [

View File

@ -1,16 +1,12 @@
import { cpus } from 'node:os' import { cpus } from 'node:os'
import path from 'node:path' import path from 'node:path'
import { User } from 'database'
import { Pool, pool } from 'workerpool'
import { PasswordEncryptionType } from '@enum/PasswordEncryptionType' import { PasswordEncryptionType } from '@enum/PasswordEncryptionType'
import { User } from 'database'
import { crypto_shorthash_KEYBYTES } from 'sodium-native'
import { Pool, pool } from 'workerpool'
import { CONFIG } from '@/config' import { CONFIG } from '@/config'
import { LogError } from '@/server/LogError' import { LogError } from '@/server/LogError'
import { crypto_shorthash_KEYBYTES } from 'sodium-native'
import { SecretKeyCryptographyCreateKeyFunc } from './EncryptionWorker.js' import { SecretKeyCryptographyCreateKeyFunc } from './EncryptionWorker.js'
const configLoginAppSecret = Buffer.from(CONFIG.LOGIN_APP_SECRET, 'hex') const configLoginAppSecret = Buffer.from(CONFIG.LOGIN_APP_SECRET, 'hex')

View File

@ -1,6 +1,6 @@
import { User } from 'database' import { User } from 'database'
import { SecretKeyCryptographyCreateKey, getUserCryptographicSalt } from './EncryptorUtils' import { getUserCryptographicSalt, SecretKeyCryptographyCreateKey } from './EncryptorUtils'
export const encryptPassword = async (dbUser: User, password: string): Promise<bigint> => { export const encryptPassword = async (dbUser: User, password: string): Promise<bigint> => {
const salt = getUserCryptographicSalt(dbUser) const salt = getUserCryptographicSalt(dbUser)

View File

@ -1,18 +1,12 @@
import { User } from 'database'
import { PasswordEncryptionType } from '@enum/PasswordEncryptionType' import { PasswordEncryptionType } from '@enum/PasswordEncryptionType'
import { User } from 'database'
import { CONFIG } from '@/config'
import { LogError } from '@/server/LogError'
import { getLogger } from 'log4js' import { getLogger } from 'log4js'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { import {
crypto_box_SEEDBYTES, crypto_box_SEEDBYTES,
crypto_hash_sha512_BYTES, crypto_hash_sha512_BYTES,
crypto_hash_sha512_STATEBYTES,
crypto_hash_sha512_final, crypto_hash_sha512_final,
crypto_hash_sha512_init, crypto_hash_sha512_init,
crypto_hash_sha512_STATEBYTES,
crypto_hash_sha512_update, crypto_hash_sha512_update,
crypto_pwhash, crypto_pwhash,
crypto_pwhash_MEMLIMIT_MIN, crypto_pwhash_MEMLIMIT_MIN,
@ -22,6 +16,10 @@ import {
crypto_shorthash_BYTES, crypto_shorthash_BYTES,
crypto_shorthash_KEYBYTES, crypto_shorthash_KEYBYTES,
} from 'sodium-native' } from 'sodium-native'
import { CONFIG } from '@/config'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { LogError } from '@/server/LogError'
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.password.EncryptorUtils`) const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.password.EncryptorUtils`)

View File

@ -1,4 +1,3 @@
export { creations } from 'database' export { creations } from 'database'
/* /*

View File

@ -1,13 +1,12 @@
import {
contributionLinkFactory as contributionLinkFactoryDb,
ContributionLinkInterface
} from 'database'
import { ContributionLink } from '@model/ContributionLink' import { ContributionLink } from '@model/ContributionLink'
import {
ContributionLinkInterface,
contributionLinkFactory as contributionLinkFactoryDb,
} from 'database'
export { ContributionLinkInterface } export { ContributionLinkInterface }
export async function contributionLinkFactory ( export async function contributionLinkFactory(
_client: any, _client: any,
contributionLink: ContributionLinkInterface, contributionLink: ContributionLinkInterface,
): Promise<ContributionLink> { ): Promise<ContributionLink> {

Some files were not shown because too many files have changed in this diff Show More