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 { getLogger } from 'log4js'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { LogError } from '@/server/LogError'
import { getLogger } from 'log4js'
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 { getLogger } from 'log4js'
import { CONFIG } from '@/config'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
const klicktippConnector = new KlicktippConnector()
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.apis.KlicktippController`)

View File

@ -18,5 +18,3 @@ describe('undefined DltConnectorClient', () => {
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 { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { getLogger } from 'log4js'
import { TransactionDraft } from './model/TransactionDraft'
import { IRestResponse, RestClient } from 'typed-rest-client'
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.apis.dltConnector`)
@ -44,7 +43,7 @@ export class DltConnectorClient {
'gradido-backend',
CONFIG.DLT_CONNECTOR_URL,
undefined,
{ keepAlive: true }
{ keepAlive: true },
)
} catch (e) {
logger.error("couldn't connect to dlt-connector: ", e)
@ -58,11 +57,10 @@ export class DltConnectorClient {
* transmit transaction via dlt-connector to hiero
* 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)
return await this.client.create<{ transactionId: string }>(
'/sendTransaction',
input
)
return await this.client.create<{ transactionId: string }>('/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 { 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`)

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 {
Community as DbCommunity,
Contribution as DbContribution,
@ -14,15 +9,22 @@ import {
getUserById,
UserLoggingView,
} from 'database'
import { TransactionDraft } from './model/TransactionDraft'
import { getLogger } from 'log4js'
import { IRestResponse } from 'typed-rest-client'
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`)
// will be undefined if dlt connect is disabled
const dltConnectorClient = DltConnectorClient.getInstance()
async function checkDltConnectorResult(dltTransaction: DbDltTransaction, clientResponse: Promise<IRestResponse<{ transactionId: string }>>)
: Promise<DbDltTransaction> {
async function checkDltConnectorResult(
dltTransaction: DbDltTransaction,
clientResponse: Promise<IRestResponse<{ transactionId: string }>>,
): Promise<DbDltTransaction> {
// check result from dlt connector
try {
const response = await clientResponse
@ -47,7 +49,11 @@ async function checkDltConnectorResult(dltTransaction: DbDltTransaction, clientR
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) {
const clientResponse = dltConnectorClient.sendTransaction(draft)
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
* 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) {
return Promise.resolve(null)
}
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 if some data where missing and log error
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 (user.id) {
dltTransaction.userId = user.id
@ -98,7 +113,12 @@ export async function contributionTransaction(
logger.error('home community not found')
return null
}
const draft = TransactionDraft.createContribution(contribution, createdAt, signingUser, homeCommunity)
const draft = TransactionDraft.createContribution(
contribution,
createdAt,
signingUser,
homeCommunity,
)
return await executeDltTransaction(draft, DltTransactionType.CREATION)
}
@ -107,7 +127,7 @@ export async function transferTransaction(
recipientUser: DbUser,
amount: string,
memo: string,
createdAt: Date
createdAt: Date,
): Promise<DbDltTransaction | null> {
if (!CONFIG.DLT_ACTIVE) {
return Promise.resolve(null)
@ -125,8 +145,10 @@ export async function transferTransaction(
return await executeDltTransaction(draft, DltTransactionType.TRANSFER)
}
export async function deferredTransferTransaction(senderUser: DbUser, transactionLink: DbTransactionLink)
: Promise<DbDltTransaction | null> {
export async function deferredTransferTransaction(
senderUser: DbUser,
transactionLink: DbTransactionLink,
): Promise<DbDltTransaction | null> {
if (!CONFIG.DLT_ACTIVE) {
return Promise.resolve(null)
}
@ -138,8 +160,12 @@ export async function deferredTransferTransaction(senderUser: DbUser, transactio
return await executeDltTransaction(draft, DltTransactionType.DEFERRED_TRANSFER)
}
export async function redeemDeferredTransferTransaction(transactionLink: DbTransactionLink, amount: string, createdAt: Date, recipientUser: DbUser)
: Promise<DbDltTransaction | null> {
export async function redeemDeferredTransferTransaction(
transactionLink: DbTransactionLink,
amount: string,
createdAt: Date,
recipientUser: DbUser,
): Promise<DbDltTransaction | null> {
if (!CONFIG.DLT_ACTIVE) {
return Promise.resolve(null)
}
@ -158,9 +184,11 @@ export async function redeemDeferredTransferTransaction(transactionLink: DbTrans
}
logger.debug(`sender: ${new UserLoggingView(transactionLink.user)}`)
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)
}

View File

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

View File

@ -1,15 +1,16 @@
import { User as DbUser } from 'database'
// import { createTestClient } from 'apollo-server-testing'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
// import { createGmsUser } from '@/apis/gms/GmsClient'
// import { GmsUser } from '@/apis/gms/model/GmsUser'
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 { LogError } from '@/server/LogError'
import { initLogging } from '@/server/logger'
import { AppDatabase, getHomeCommunity } from 'database'
import { getLogger } from 'log4js'
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.apis.gms.ExportUsers`)

View File

@ -1,11 +1,10 @@
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 { 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'

View File

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

View File

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

View File

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

View File

@ -1,14 +1,12 @@
import { OpenaiThreads, User } from 'database'
import { getLogger } from 'log4js'
import { OpenAI } from 'openai'
import { Message } from 'openai/resources/beta/threads/messages'
import { httpsAgent } from '@/apis/ConnectionAgents'
import { CONFIG } from '@/config'
import { Message as MessageModel } from './model/Message'
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`)
// 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}`)
return []
}
if (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...`)
if (
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
// biome-ignore lint/complexity/noVoid: start it intentionally async without waiting for result
void this.deleteThread(openaiThreadEntity.id)
@ -141,7 +144,10 @@ export class OpenaiClient {
}
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, {
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 { LogError } from '@/server/LogError'

View File

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

View File

@ -1,6 +1,5 @@
import { User, UserRole } from 'database'
import { RoleNames } from '@enum/RoleNames'
import { User, UserRole } from 'database'
export class UserLogic {
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_CREATE } from './EVENT_ADMIN_CONTRIBUTION_CREATE'
export { EVENT_ADMIN_CONTRIBUTION_DELETE } from './EVENT_ADMIN_CONTRIBUTION_DELETE'
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_DELETE } from './EVENT_ADMIN_CONTRIBUTION_LINK_DELETE'
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_UPDATE } from './EVENT_ADMIN_CONTRIBUTION_UPDATE'
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_UNDELETE } from './EVENT_ADMIN_USER_UNDELETE'
export { EVENT_CONTRIBUTION_CREATE } from './EVENT_CONTRIBUTION_CREATE'
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_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_ADMIN_CONFIRMATION } from './EVENT_EMAIL_ADMIN_CONFIRMATION'
export { EVENT_EMAIL_CONFIRMATION } from './EVENT_EMAIL_CONFIRMATION'
export { EVENT_EMAIL_FORGOT_PASSWORD } from './EVENT_EMAIL_FORGOT_PASSWORD'
export { EVENT_NEWSLETTER_SUBSCRIBE } from './EVENT_NEWSLETTER_SUBSCRIBE'
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_DELETE } from './EVENT_TRANSACTION_LINK_DELETE'
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_INFO_UPDATE } from './EVENT_USER_INFO_UPDATE'
export { EVENT_USER_LOGIN } from './EVENT_USER_LOGIN'
export { EVENT_USER_LOGOUT } from './EVENT_USER_LOGOUT'
export { EVENT_USER_REGISTER } from './EVENT_USER_REGISTER'
export { Event } from './Event'
export { EventType } from './EventType'

View File

@ -1,26 +1,32 @@
import {
CommunityHandshakeState as DbCommunityHandshakeState,
CommunityHandshakeStateLogic,
EncryptedTransferArgs,
ensureUrlEndsWithSlash,
getFederatedCommunityWithApiOrFail,
} from 'core'
import {
CommunityHandshakeStateLoggingView,
CommunityHandshakeStateType,
CommunityHandshakeState as DbCommunityHandshakeState,
FederatedCommunity as DbFederatedCommunity,
findPendingCommunityHandshake,
getHomeCommunityWithFederatedCommunityOrFail,
CommunityHandshakeStateType,
getCommunityByPublicKeyOrFail,
getHomeCommunityWithFederatedCommunityOrFail,
} 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 {
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 { 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 {
ALREADY_AUTHENTICATED = 'already authenticated',
@ -48,7 +54,9 @@ export async function startCommunityAuthentication(
// - if communityUuid is a valid v4Uuid and
// - if authenticatedAt is a valid date
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
}
/*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
if (!(await stateLogic.isTimeoutUpdate())) {
// 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
}
}
@ -82,7 +93,8 @@ export async function startCommunityAuthentication(
methodLogger.debug('[START_COMMUNITY_AUTHENTICATION] community handshake state created')
//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),
)
// methodLogger.debug('payload', payload)

View File

@ -1,11 +1,8 @@
import { EncryptedTransferArgs, ensureUrlEndsWithSlash } from 'core'
import { FederatedCommunity as DbFederatedCommunity } from 'database'
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 { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { openConnection } from './query/openConnection'
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 { GraphQLClient } from 'graphql-request'
import { ensureUrlEndsWithSlash } from 'core'
import { getLogger } from 'log4js'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { EncryptedTransferArgs } from 'core'
import { processDisburseJwtOnSenderCommunity as processDisburseJwtOnSenderCommunityQuery } from './query/processDisburseJwtOnSenderCommunity'
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> {
logger.debug('sendDisburseJwtToSenderCommunity against endpoint=', this.endpoint)
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
if (response) {
logger.debug('received response:', response)
@ -43,5 +42,4 @@ export class DisbursementClient {
}
return null
}
}

View File

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

View File

@ -1,8 +1,7 @@
import { ApiVersionType } from 'core'
import { FederatedCommunity as DbFederatedCommunity } from 'database'
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 { ApiVersionType } from 'core'
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 { FederationClient as V1_0_FederationClient } from '@/federation/client/1_0/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

View File

@ -1,13 +1,11 @@
import { cleanDB, testEnvironment } from '@test/helpers'
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 { Response } from 'graphql-request/dist/types'
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 { AppDatabase } from 'database'
import { validateCommunities } from './validateCommunities'
const logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.federation.validateCommunities`)

View File

@ -1,20 +1,19 @@
import { ApiVersionType } from 'core'
import {
Community as DbCommunity,
FederatedCommunity as DbFederatedCommunity,
getHomeCommunity,
} from 'database'
import { getLogger } from 'log4js'
import { createKeyPair, Ed25519PublicKey } from 'shared'
import { IsNull } from 'typeorm'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { FederationClient as V1_0_FederationClient } from '@/federation/client/1_0/FederationClient'
import { PublicCommunityInfo } from '@/federation/client/1_0/model/PublicCommunityInfo'
import { FederationClientFactory } from '@/federation/client/FederationClientFactory'
import { LogError } from '@/server/LogError'
import { createKeyPair, Ed25519PublicKey } from 'shared'
import { getLogger } from 'log4js'
import { startCommunityAuthentication } from './authenticateCommunities'
import { PublicCommunityInfoLoggingView } from './client/1_0/logging/PublicCommunityInfoLogging.view'
import { ApiVersionType } from 'core'
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}`)
const apiValueStrings: string[] = Object.values(ApiVersionType)
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)
continue
}
@ -65,18 +68,29 @@ export async function validateCommunities(): Promise<void> {
const pubComInfo = await client.getPublicCommunityInfo()
if (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 {
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) {
logger.warn(`Warning: Authentication of community ${dbFedComB.endPoint} still ongoing:`, err)
logger.warn(
`Warning: Authentication of community ${dbFedComB.endPoint} still ongoing:`,
err,
)
}
} else {
logger.debug('missing result of getPublicCommunityInfo')
}
} else {
logger.debug('received not matching publicKey:', clientPublicKey.asHex(), fedComBPublicKey.asHex())
logger.debug(
'received not matching publicKey:',
clientPublicKey.asHex(),
fedComBPublicKey.asHex(),
)
}
}
} catch (err) {
@ -89,25 +103,36 @@ export async function writeJwtKeyPairInHomeCommunity(): Promise<DbCommunity> {
logger.debug(`Federation: writeJwtKeyPairInHomeCommunity`)
try {
// check for existing homeCommunity entry
let homeCom = await getHomeCommunity()
const homeCom = await getHomeCommunity()
if (homeCom) {
if (!homeCom.publicJwtKey && !homeCom.privateJwtKey) {
// Generate key pair using jose library
const { publicKey, privateKey } = await createKeyPair();
logger.debug(`Federation: writeJwtKeyPairInHomeCommunity publicKey=`, publicKey);
logger.debug(`Federation: writeJwtKeyPairInHomeCommunity privateKey=`, privateKey.slice(0, 20));
const { publicKey, privateKey } = await createKeyPair()
logger.debug(`Federation: writeJwtKeyPairInHomeCommunity publicKey=`, publicKey)
logger.debug(
`Federation: writeJwtKeyPairInHomeCommunity privateKey=`,
privateKey.slice(0, 20),
)
homeCom.publicJwtKey = publicKey;
logger.debug(`Federation: writeJwtKeyPairInHomeCommunity publicJwtKey.length=`, homeCom.publicJwtKey.length);
homeCom.privateJwtKey = privateKey;
logger.debug(`Federation: writeJwtKeyPairInHomeCommunity privateJwtKey.length=`, homeCom.privateJwtKey.length);
homeCom.publicJwtKey = publicKey
logger.debug(
`Federation: writeJwtKeyPairInHomeCommunity publicJwtKey.length=`,
homeCom.publicJwtKey.length,
)
homeCom.privateJwtKey = privateKey
logger.debug(
`Federation: writeJwtKeyPairInHomeCommunity privateJwtKey.length=`,
homeCom.privateJwtKey.length,
)
await DbCommunity.save(homeCom)
logger.debug(`Federation: writeJwtKeyPairInHomeCommunity done`)
} else {
logger.debug(`Federation: writeJwtKeyPairInHomeCommunity: keypair already exists`)
}
} 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
} catch (err) {

View File

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

View File

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

View File

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

View File

@ -1,8 +1,7 @@
import { RoleNames } from '@enum/RoleNames'
import { IsEnum, IsPositive } from 'class-validator'
import { ArgsType, Field, InputType, Int } from 'type-graphql'
import { RoleNames } from '@enum/RoleNames'
@InputType()
@ArgsType()
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 { PublishNameType } from '@enum/PublishNameType'
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'

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,10 +1,9 @@
import { GmsPublishLocationType } from '@enum/GmsPublishLocationType'
import { PublishNameType } from '@enum/PublishNameType'
import { User as DbUser } from 'database'
import { Field, Int, ObjectType } from 'type-graphql'
import { Point } from 'typeorm'
import { GmsPublishLocationType } from '@enum/GmsPublishLocationType'
import { PublishNameType } from '@enum/PublishNameType'
import { PublishNameLogic } from '@/data/PublishName.logic'
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 { ChatGptMessage } from '@model/ChatGptMessage'
import { OpenaiClient } from '@/apis/openai/OpenaiClient'
import { Arg, Authorized, Ctx, Mutation, Query, Resolver } from 'type-graphql'
import { Message } from '@/apis/openai/model/Message'
import { OpenaiClient } from '@/apis/openai/OpenaiClient'
import { RIGHTS } from '@/auth/RIGHTS'
import { Context } from '@/server/context'
@ -15,10 +13,14 @@ export class AiChatResolver {
async resumeChat(@Ctx() context: Context): Promise<ChatGptMessage[]> {
const openaiClient = OpenaiClient.getInstance()
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) {
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)
return messages.map((message) => new ChatGptMessage(message))
@ -42,10 +44,14 @@ export class AiChatResolver {
): Promise<ChatGptMessage> {
const openaiClient = OpenaiClient.getInstance()
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) {
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)
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 { getLogger } from 'log4js'
import { calculateDecay } from 'shared'
import { Authorized, Ctx, Query, Resolver } from 'type-graphql'
import { IsNull } from 'typeorm'
import { Balance } from '@model/Balance'
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 { getLastTransaction } from 'database'
import { getLogger } from 'log4js'
import { BalanceLoggingView } from '@/logging/BalanceLogging.view'
import { Context, getUser } from '@/server/context'
import { GdtResolver } from './GdtResolver'
import { transactionLinkSummary } from './util/transactionLinkSummary'

View File

@ -1,11 +1,17 @@
import { cleanDB, testEnvironment } from '@test/helpers'
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 { DataSource } from 'typeorm'
import { v4 as uuidv4 } from 'uuid'
import { cleanDB, testEnvironment } from '@test/helpers'
import { CONFIG } from '@/config'
import { userFactory } from '@/seeds/factory/user'
import { login, updateHomeCommunityQuery } from '@/seeds/graphql/mutations'
import {
@ -15,11 +21,6 @@ import {
reachableCommunities,
} from '@/seeds/graphql/queries'
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')
@ -498,7 +499,7 @@ describe('CommunityResolver', () => {
DbCommunity.insert(foreignCom2),
DbFederatedCommunity.insert(com1FedCom),
DbFederatedCommunity.insert(com1FedCom2),
DbFederatedCommunity.insert(com2FedCom)
DbFederatedCommunity.insert(com2FedCom),
])
})
@ -512,13 +513,14 @@ describe('CommunityResolver', () => {
description: homeCom1.description,
url: homeCom1.url,
uuid: homeCom1.communityUuid,
}, {
},
{
foreign: foreignCom1.foreign,
name: foreignCom1.name,
description: foreignCom1.description,
url: foreignCom1.url,
uuid: foreignCom1.communityUuid,
}
},
])
})
})
@ -574,7 +576,7 @@ describe('CommunityResolver', () => {
description: homeCom?.description,
url: homeCom?.url,
creationDate: homeCom?.creationDate?.toISOString(),
uuid: homeCom?.communityUuid
uuid: homeCom?.communityUuid,
},
},
})
@ -599,7 +601,7 @@ describe('CommunityResolver', () => {
await Promise.all([
DbCommunity.insert(foreignCom1),
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 { EditCommunityInput } from '@input/EditCommunityInput'
import { AdminCommunityView } from '@model/AdminCommunityView'
import { Community } from '@model/Community'
import { RIGHTS } from '@/auth/RIGHTS'
import { LogError } from '@/server/LogError'
import { Location2Point } from './util/Location2Point'
import {
getAllCommunities,
getCommunityByIdentifier,
getCommunityByUuid,
} from './util/communities'
import { Community as DbCommunity, getHomeCommunity, getReachableCommunities } from 'database'
import { updateAllDefinedAndChanged } from 'shared'
import { Arg, Args, Authorized, Mutation, Query, Resolver } from 'type-graphql'
import { RIGHTS } from '@/auth/RIGHTS'
import { CONFIG } from '@/config'
import { LogError } from '@/server/LogError'
import { getAllCommunities, getCommunityByIdentifier, getCommunityByUuid } from './util/communities'
import { Location2Point } from './util/Location2Point'
@Resolver()
export class CommunityResolver {
@ -35,11 +24,13 @@ export class CommunityResolver {
@Query(() => [Community])
async reachableCommunities(): Promise<Community[]> {
const dbCommunities: DbCommunity[] = await getReachableCommunities(
CONFIG.FEDERATION_VALIDATE_COMMUNITY_TIMER * 2, {
CONFIG.FEDERATION_VALIDATE_COMMUNITY_TIMER * 2,
{
// order by
foreign: 'ASC', // home community first
name: 'ASC', // sort foreign communities by name
})
},
)
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 { 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 { GraphQLError } from 'graphql'
import { DataSource } from 'typeorm'
import { cleanDB, resetToken, testEnvironment } from '@test/helpers'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { EventType } from '@/event/Events'
import { userFactory } from '@/seeds/factory/user'
@ -18,8 +17,6 @@ import {
import { listContributionLinks } from '@/seeds/graphql/queries'
import { bibiBloxberg } from '@/seeds/users/bibi-bloxberg'
import { peterLustig } from '@/seeds/users/peter-lustig'
import { getLogger } from 'config-schema/test/testSetup'
import { AppDatabase } from 'database'
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 { Paginated } from '@arg/Paginated'
import { Order } from '@enum/Order'
import { ContributionLink } from '@model/ContributionLink'
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 {
@ -14,8 +13,8 @@ import {
EVENT_ADMIN_CONTRIBUTION_LINK_DELETE,
EVENT_ADMIN_CONTRIBUTION_LINK_UPDATE,
} from '@/event/Events'
import { LogError } from '@/server/LogError'
import { Context, getUser } from '@/server/context'
import { LogError } from '@/server/LogError'
import { transactionLinkCode as contributionLinkCode } from './TransactionLinkResolver'
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 { cleanDB, resetToken, testEnvironment } from '@test/helpers'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { ApolloServerTestClient } from 'apollo-server-testing'
import { getLogger } from 'config-schema/test/testSetup'
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 { userFactory } from '@/seeds/factory/user'
import {
@ -20,10 +19,10 @@ import { adminListContributionMessages, listContributionMessages } from '@/seeds
import { bibiBloxberg } from '@/seeds/users/bibi-bloxberg'
import { bobBaumeister } from '@/seeds/users/bob-baumeister'
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 interactionLogger = getLogger(
`${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 {
AppDatabase,
Contribution as DbContribution,
ContributionMessage as DbContributionMessage,
User as DbUser,
} from 'database'
import { getLogger } from 'log4js'
import { Arg, Args, Authorized, Ctx, Int, Mutation, Query, Resolver } from 'type-graphql'
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 { sendAddedContributionMessageEmail } from 'core'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import {
EVENT_ADMIN_CONTRIBUTION_MESSAGE_CREATE,
EVENT_CONTRIBUTION_MESSAGE_CREATE,
} from '@/event/Events'
import { UpdateUnconfirmedContributionContext } from '@/interactions/updateUnconfirmedContribution/UpdateUnconfirmedContribution.context'
import { LogError } from '@/server/LogError'
import { Context, getUser } from '@/server/context'
import { getLogger } from 'log4js'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { LogError } from '@/server/LogError'
import { contributionFrontendLink } from './util/contributions'
import { findContributionMessages } from './util/findContributionMessages'
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()
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 { ContributionStatus } from '@enum/ContributionStatus'
import { Order } from '@enum/Order'
@ -14,13 +8,26 @@ import {
resetToken,
testEnvironment,
} from '@test/helpers'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { ApolloServerTestClient } from 'apollo-server-testing'
import { getLogger } from 'config-schema/test/testSetup'
import {
getFirstDayOfPreviousNMonth,
sendContributionConfirmedEmail,
sendContributionDeletedEmail,
sendContributionDeniedEmail,
} 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 { creations } from '@/seeds/creation/index'
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 { raeuberHotzenplotz } from '@/seeds/users/raeuber-hotzenplotz'
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', () => {
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 { AdminUpdateContributionArgs } from '@arg/AdminUpdateContributionArgs'
import { ContributionArgs } from '@arg/ContributionArgs'
import { Paginated } from '@arg/Paginated'
import { SearchContributionsFilterArgs } from '@arg/SearchContributionsFilterArgs'
import { ContributionMessageType } from '@enum/ContributionMessageType'
import { ContributionStatus } from '@enum/ContributionStatus'
import { ContributionType } from '@enum/ContributionType'
import { AdminUpdateContribution } from '@model/AdminUpdateContribution'
@ -42,15 +16,39 @@ import {
sendContributionConfirmedEmail,
sendContributionDeletedEmail,
sendContributionDeniedEmail,
TransactionTypeId
TransactionTypeId,
} from 'core'
import { calculateDecay, Decay } from 'shared'
import { contributionTransaction } from '@/apis/dltConnector'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { ContributionMessageType } from '@enum/ContributionMessageType'
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 { getLogger } from 'log4js'
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 {
contributionFrontendLink,
loadAllContributions,
@ -61,7 +59,8 @@ import { extractGraphQLFields } from './util/extractGraphQLFields'
import { findContributions } from './util/findContributions'
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)
export class ContributionResolver {
@ -440,7 +439,10 @@ export class ContributionResolver {
try {
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) {
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')
}
const receivedCallDate = new Date()
const dltTransactionPromise = contributionTransaction(contribution, moderatorUser, receivedCallDate)
const dltTransactionPromise = contributionTransaction(
contribution,
moderatorUser,
receivedCallDate,
)
const creations = await getUserCreation(contribution.userId, clientTimezoneOffset, false)
validateContribution(
creations,
@ -541,7 +547,9 @@ export class ContributionResolver {
await dltTransaction.save()
}
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) {
await queryRunner.rollbackTransaction()
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 { User as DbUser } from 'database'
import { CONFIG as CORE_CONFIG } from 'core'
import { AppDatabase, User as DbUser } from 'database'
import { GraphQLError } from 'graphql'
import { DataSource } from 'typeorm'
import { cleanDB, testEnvironment } from '@test/helpers'
import { CONFIG as CORE_CONFIG } from 'core'
import { CONFIG } from '@/config'
import { writeHomeCommunityEntry } from '@/seeds/community'
import { createUser, forgotPassword, setPassword } from '@/seeds/graphql/mutations'
import { queryOptIn } from '@/seeds/graphql/queries'
import { AppDatabase } from 'database'
let mutate: ApolloServerTestClient['mutate']
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 { Order } from '@enum/Order'
import { GdtEntry } from '@model/GdtEntry'
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 { RIGHTS } from '@/auth/RIGHTS'
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 { Context, getUser } from '@/server/context'
import { LogError } from '@/server/LogError'
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 { 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 { userFactory } from '@/seeds/factory/user'
import { login, subscribeNewsletter, unsubscribeNewsletter } from '@/seeds/graphql/mutations'
import { bibiBloxberg } from '@/seeds/users/bibi-bloxberg'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { AppDatabase } from 'database'
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 { ProjectBranding } from '@model/ProjectBranding'
import { Space } from '@model/Space'
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 { RIGHTS } from '@/auth/RIGHTS'
import { LogError } from '@/server/LogError'
import { getLogger } from 'log4js'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { LogError } from '@/server/LogError'
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 { 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 { Authorized, FieldResolver, Query, Resolver } from 'type-graphql'
import { RIGHTS } from '@/auth/RIGHTS'
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 { getLogger } from 'config-schema/test/testSetup'
import {
AppDatabase,
ContributionLink as DbContributionLink,
Event as DbEvent,
Transaction,
@ -9,10 +13,8 @@ import {
import { Decimal } from 'decimal.js-light'
import { GraphQLError } from 'graphql'
import { DataSource } from 'typeorm'
import { UnconfirmedContribution } from '@model/UnconfirmedContribution'
import { cleanDB, resetEntity, resetToken, testEnvironment } from '@test/helpers'
import { CONFIG } from '@/config'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { EventType } from '@/event/Events'
import { creations } from '@/seeds/creation/index'
import { creationFactory } from '@/seeds/factory/creation'
@ -32,11 +34,7 @@ import { listTransactionLinksAdmin } from '@/seeds/graphql/queries'
import { transactionLinks } from '@/seeds/transactionLink/index'
import { bibiBloxberg } from '@/seeds/users/bibi-bloxberg'
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 { CONFIG } from '@/config'
import { AppDatabase } from 'database'
const logErrorLogger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.server.LogError`)
@ -967,7 +965,7 @@ describe('TransactionLinkResolver', () => {
createdAt: expect.any(String),
}),
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),
}),
]),

View File

@ -1,5 +1,3 @@
import { randomBytes } from 'crypto'
import { Paginated } from '@arg/Paginated'
import { TransactionLinkArgs } from '@arg/TransactionLinkArgs'
import { TransactionLinkFilters } from '@arg/TransactionLinkFilters'
@ -12,51 +10,65 @@ import { RedeemJwtLink } from '@model/RedeemJwtLink'
import { TransactionLink, TransactionLinkResult } from '@model/TransactionLink'
import { User } from '@model/User'
import { QueryLinkResult } from '@union/QueryLinkResult'
import { Decay, interpretEncryptedTransferArgs, TransactionTypeId } from 'core'
import {
AppDatabase, Contribution as DbContribution,
Decay,
EncryptedTransferArgs,
fullName,
interpretEncryptedTransferArgs,
TransactionTypeId,
} from 'core'
import { randomBytes } from 'crypto'
import {
AppDatabase,
Contribution as DbContribution,
ContributionLink as DbContributionLink,
FederatedCommunity as DbFederatedCommunity,
DltTransaction as DbDltTransaction,
FederatedCommunity as DbFederatedCommunity,
Transaction as DbTransaction,
TransactionLink as DbTransactionLink,
User as DbUser,
findModeratorCreatingContributionLink,
findTransactionLinkByCode,
getHomeCommunity
getHomeCommunity,
getLastTransaction,
} from 'database'
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 {
contributionTransaction,
deferredTransferTransaction,
redeemDeferredTransferTransaction,
} from '@/apis/dltConnector'
import { RIGHTS } from '@/auth/RIGHTS'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import {
EVENT_CONTRIBUTION_LINK_REDEEM,
EVENT_TRANSACTION_LINK_CREATE,
EVENT_TRANSACTION_LINK_DELETE,
EVENT_TRANSACTION_LINK_REDEEM,
} 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 { DisbursementClientFactory } from '@/federation/client/DisbursementClientFactory'
import { EncryptedTransferArgs } from 'core'
import { getLastTransaction } from 'database'
import { getLogger, Logger } from 'log4js'
import { randombytes_random } from 'sodium-native'
import { Context, getClientTimezoneOffset, getUser } from '@/server/context'
import { LogError } from '@/server/LogError'
import { calculateBalance } from '@/util/validate'
import { CODE_VALID_DAYS_DURATION } from './const/const'
import { executeTransaction } from './TransactionResolver'
import {
getAuthenticatedCommunities,
@ -65,13 +77,9 @@ import {
} from './util/communities'
import { getUserCreation, validateContribution } from './util/creations'
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
export const transactionLinkCode = (date: Date): string => {
@ -83,7 +91,6 @@ export const transactionLinkCode = (date: Date): string => {
)
}
const db = AppDatabase.getInstance()
export const transactionLinkExpireDate = (date: Date): Date => {
@ -130,7 +137,9 @@ export class TransactionLinkResolver {
const startTime = Date.now()
const dltTransaction = await dltTransactionPromise
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) {
dltTransaction.transactionLinkId = transactionLink.id
await DbDltTransaction.save(dltTransaction)
@ -167,14 +176,21 @@ export class TransactionLinkResolver {
})
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)
// wait for dlt transaction to be created
const startTime = Date.now()
const dltTransaction = await dltTransactionPromise
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) {
dltTransaction.transactionLinkId = transactionLink.id
await DbDltTransaction.save(dltTransaction)
@ -382,12 +398,13 @@ export class TransactionLinkResolver {
const startTime = new Date()
const dltTransaction = await dltTransactionPromise
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) {
dltTransaction.transactionId = transaction.id
await dltTransaction.save()
}
}
} catch (e) {
await queryRunner.rollbackTransaction()
@ -508,7 +525,11 @@ export class TransactionLinkResolver {
if (!recipientCom.publicJwtKey) {
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) {
throw new LogError('Redeem JWT was not created successfully')
}
@ -526,14 +547,20 @@ export class TransactionLinkResolver {
args.handshakeID,
)
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!)
if (!signedTransferJwt) {
throw new LogError('SignedTransfer JWT was not created successfully')
}
if (methodLogger.isDebugEnabled()) {
methodLogger.debug('successfully created RedeemJWT-Response with signedTransferJwt:', signedTransferJwt)
methodLogger.debug(
'successfully created RedeemJWT-Response with signedTransferJwt:',
signedTransferJwt,
)
}
return signedTransferJwt
@ -615,7 +642,11 @@ export class TransactionLinkResolver {
if (methodLogger.isDebugEnabled()) {
methodLogger.debug('disburseJwtPayload=', disburseJwtPayload)
}
const jws = await encryptAndSign(disburseJwtPayload, recipientCom.privateJwtKey!, senderCom.publicJwtKey!)
const jws = await encryptAndSign(
disburseJwtPayload,
recipientCom.privateJwtKey!,
senderCom.publicJwtKey!,
)
if (methodLogger.isDebugEnabled()) {
methodLogger.debug('jws=', jws)
}
@ -679,22 +710,34 @@ export class TransactionLinkResolver {
// decode token first to get the EncryptedTransferArgs with the senderCommunity.publicKey as input to verify token
const decodedPayload = decode(code) as SignedTransferPayloadType
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)
if(decodedPayload !== null && decodedPayload.tokentype === SignedTransferPayloadType.SIGNED_TRANSFER_TYPE) {
if (
decodedPayload !== null &&
decodedPayload.tokentype === SignedTransferPayloadType.SIGNED_TRANSFER_TYPE
) {
const signedTransferPayload = new SignedTransferPayloadType(
decodedPayload.publicKey,
decodedPayload.jwt,
decodedPayload.handshakeID)
decodedPayload.handshakeID,
)
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) {
const errmsg = `Sender community not found with publicKey=${signedTransferPayload.publicKey}`
logger.error(errmsg)
throw new Error(errmsg)
}
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)
let verifiedRedeemJwtPayload: RedeemJwtPayloadType | null = null
if (jweVerifyResult === null) {
@ -707,22 +750,34 @@ export class TransactionLinkResolver {
encryptedTransferArgs.jwt = signedTransferPayload.jwt
encryptedTransferArgs.handshakeID = signedTransferPayload.handshakeID
verifiedRedeemJwtPayload = await interpretEncryptedTransferArgs(encryptedTransferArgs) as RedeemJwtPayloadType
verifiedRedeemJwtPayload = (await interpretEncryptedTransferArgs(
encryptedTransferArgs,
)) as RedeemJwtPayloadType
if (logger.isDebugEnabled()) {
logger.debug(`queryRedeemJwtLink() ...`, 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)
throw new Error(errmsg)
}
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)
throw new Error(errmsg)
}
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)
throw new Error(errmsg)
}

View File

@ -1,5 +1,9 @@
import { cleanDB, testEnvironment } from '@test/helpers'
import { ApolloServerTestClient } from 'apollo-server-testing'
import { getLogger } from 'config-schema/test/testSetup'
import { CONFIG as CORE_CONFIG } from 'core'
import {
AppDatabase,
Community as DbCommunity,
Event as DbEvent,
FederatedCommunity as DbFederatedCommunity,
@ -10,9 +14,7 @@ import {
import { GraphQLError } from 'graphql'
import { DataSource, In } from 'typeorm'
import { v4 as uuidv4 } from 'uuid'
import { cleanDB, testEnvironment } from '@test/helpers'
import { CONFIG } from '@/config'
// import { CONFIG } from '@/config'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { EventType } from '@/event/Events'
@ -32,10 +34,6 @@ import { bobBaumeister } from '@/seeds/users/bob-baumeister'
import { garrickOllivander } from '@/seeds/users/garrick-ollivander'
import { peterLustig } from '@/seeds/users/peter-lustig'
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')

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 {
AppDatabase,
countOpenPendingTransactions,
@ -10,45 +23,32 @@ import {
import { Decimal } from 'decimal.js-light'
import { Args, Authorized, Ctx, Mutation, Query, Resolver } from 'type-graphql'
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 { CONFIG } from '@/config'
import {
EVENT_TRANSACTION_RECEIVE, EVENT_TRANSACTION_SEND } from '@/event/Events'
import { LogError } from '@/server/LogError'
import { EVENT_TRANSACTION_RECEIVE, EVENT_TRANSACTION_SEND } from '@/event/Events'
import { Context, getUser } from '@/server/context'
import { LogError } from '@/server/LogError'
import { communityUser } from '@/util/communityUser'
import { calculateBalance } from '@/util/validate'
import { virtualDecayTransaction, virtualLinkTransaction } from '@/util/virtualTransactions'
// import { TRANSACTIONS_LOCK } from 'database'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { getLastTransaction } from 'database'
import { Redis } from 'ioredis'
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 { GdtResolver } from './GdtResolver'
import { getCommunityName, isHomeCommunity } from './util/communities'
import { getTransactionList } from './util/getTransactionList'
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 createLogger = () => getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.TransactionResolver`)
const createLogger = () =>
getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.TransactionResolver`)
export const executeTransaction = async (
amount: Decimal,
@ -66,15 +66,26 @@ export const executeTransaction = async (
const receivedCallDate = new Date()
let dltTransactionPromise: Promise<DbDltTransaction | null> = Promise.resolve(null)
if (!transactionLink) {
dltTransactionPromise = transferTransaction(sender, recipient, amount.toString(), memo, receivedCallDate)
dltTransactionPromise = transferTransaction(
sender,
recipient,
amount.toString(),
memo,
receivedCallDate,
)
} else {
dltTransactionPromise = redeemDeferredTransferTransaction(transactionLink, amount.toString(), receivedCallDate, recipient)
dltTransactionPromise = redeemDeferredTransferTransaction(
transactionLink,
amount.toString(),
receivedCallDate,
recipient,
)
}
try {
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(
`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 dltTransaction = await dltTransactionPromise
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) {
dltTransaction.transactionId = transactionSend.id
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 { ApolloServerTestClient } from 'apollo-server-testing'
import { getLogger } from 'config-schema/test/testSetup'
import {
objectValuesToArray,
sendAccountActivationEmail,
sendAccountMultiRegistrationEmail,
sendResetPasswordEmail,
} from 'core'
import {
AppDatabase,
Community as DbCommunity,
@ -12,23 +27,9 @@ import {
import { GraphQLError } from 'graphql'
import { DataSource } from 'typeorm'
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 { CONFIG } from '@/config'
import {
sendAccountActivationEmail,
sendAccountMultiRegistrationEmail,
sendResetPasswordEmail,
} from 'core'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { EventType } from '@/event/Events'
import { PublishNameType } from '@/graphql/enum/PublishNameType'
import { SecretKeyCryptographyCreateKey } from '@/password/EncryptorUtils'
@ -65,10 +66,6 @@ import { garrickOllivander } from '@/seeds/users/garrick-ollivander'
import { peterLustig } from '@/seeds/users/peter-lustig'
import { stephenHawking } from '@/seeds/users/stephen-hawking'
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'
jest.mock('@/apis/humhub/HumHubClient')
@ -158,7 +155,6 @@ describe('UserResolver', () => {
expect(result).toEqual(
expect.objectContaining({ data: { createUser: { id: expect.any(Number) } } }),
)
})
describe('valid input data', () => {
@ -1054,7 +1050,9 @@ describe('UserResolver', () => {
describe('duration not expired', () => {
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({
errors: [
new GraphQLError(
@ -1071,7 +1069,9 @@ describe('UserResolver', () => {
describe('duration reset to 0', () => {
it('returns true', async () => {
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({
data: {
forgotPassword: true,
@ -1112,7 +1112,9 @@ describe('UserResolver', () => {
describe('request reset password again', () => {
it('throws an error', async () => {
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({
errors: [new GraphQLError('Email already sent less than 10 minutes ago')],
}),
@ -1144,7 +1146,10 @@ describe('UserResolver', () => {
it('throws an error', async () => {
jest.clearAllMocks()
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(
expect.objectContaining({
errors: [
@ -1165,7 +1170,10 @@ describe('UserResolver', () => {
await expect(
query({
query: queryOptIn,
variables: { email: 'bob@baumeister.de', optIn: emailContact.emailVerificationCode.toString() },
variables: {
email: 'bob@baumeister.de',
optIn: emailContact.emailVerificationCode.toString(),
},
}),
).resolves.toEqual(
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 { CreateUserArgs } from '@arg/CreateUserArgs'
import { Paginated } from '@arg/Paginated'
@ -46,15 +17,55 @@ import { User } from '@model/User'
import { SearchUsersResult, UserAdmin } from '@model/UserAdmin'
import { UserContact } from '@model/UserContact'
import { UserLocationResult } from '@model/UserLocationResult'
import { subscribe } from '@/apis/KlicktippController'
import {
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 { Account as HumhubAccount } from '@/apis/humhub/model/Account'
import { GetUser } from '@/apis/humhub/model/GetUser'
import { PostUser } from '@/apis/humhub/model/PostUser'
import { subscribe } from '@/apis/KlicktippController'
import { encode } from '@/auth/JWT'
import { RIGHTS } from '@/auth/RIGHTS'
import { CONFIG } from '@/config'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { PublishNameLogic } from '@/data/PublishName.logic'
import {
EVENT_ADMIN_USER_DELETE,
@ -74,36 +85,22 @@ import {
} from '@/event/Events'
import { isValidPassword } from '@/password/EncryptorUtils'
import { encryptPassword, verifyPassword } from '@/password/PasswordEncryptor'
import { LogError } from '@/server/LogError'
import { Context, getClientTimezoneOffset, getUser } from '@/server/context'
import { LogError } from '@/server/LogError'
import { communityDbUser } from '@/util/communityUser'
import { hasElopageBuys } from '@/util/hasElopageBuys'
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 { Location2Point, Point2Location } from './util/Location2Point'
import { authenticateGmsUserPlayground } from './util/authenticateGmsUserPlayground'
import { compareGmsRelevantUserSettings } from './util/compareGmsRelevantUserSettings'
import { getUserCreations } from './util/creations'
import { extractGraphQLFieldsForSelect } from './util/extractGraphQLFields'
import { findUsers } from './util/findUsers'
import { getKlicktippState } from './util/getKlicktippState'
import { Location2Point, Point2Location } from './util/Location2Point'
import { deleteUserRole, setUserRole } from './util/modifyUserRole'
import { sendUserToGms } from './util/sendUserToGms'
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 DEFAULT_LANGUAGE = 'de'
@ -380,7 +377,9 @@ export class UserResolver {
const homeCom = await getHomeCommunity()
if (!homeCom) {
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) {
dbUser.communityUuid = homeCom.communityUuid
@ -510,7 +509,9 @@ export class UserResolver {
const startTime = new Date()
await dltTransactionPromise
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)
}
@ -813,7 +814,7 @@ export class UserResolver {
if (!homeCom) {
logger.error('no home community found, please start the dht-node first')
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) {
@ -859,9 +860,11 @@ export class UserResolver {
if (context.token) {
const homeCom = await getHomeCommunity()
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(
`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) {
@ -888,9 +891,11 @@ export class UserResolver {
if (context.token) {
const homeCom = await getHomeCommunity()
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(
`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)
@ -976,7 +981,15 @@ export class UserResolver {
@Ctx() context: Context,
): Promise<SearchUsersResult> {
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(
userFields,
query,

View File

@ -1,12 +1,14 @@
import { cleanDB, contributionDateFormatter, testEnvironment } from '@test/helpers'
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 { GraphQLError } from 'graphql'
// import { TRANSACTIONS_LOCK } from 'database'
import { Mutex } from 'redis-semaphore'
import { DataSource } from 'typeorm'
import { v4 as uuidv4 } from 'uuid'
import { cleanDB, contributionDateFormatter, testEnvironment } from '@test/helpers'
import { CONFIG } from '@/config'
import { creationFactory, nMonthsBefore } from '@/seeds/factory/creation'
import { userFactory } from '@/seeds/factory/user'
import {
@ -21,11 +23,6 @@ import {
import { bibiBloxberg } from '@/seeds/users/bibi-bloxberg'
import { bobBaumeister } from '@/seeds/users/bob-baumeister'
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')
@ -53,7 +50,7 @@ afterAll(async () => {
await testEnv.db.getRedisClient().quit()
})
type WorkData = { start: number, end: number }
type WorkData = { start: number; end: number }
async function fakeWork(workData: WorkData[], index: number) {
// const releaseLock = await TRANSACTIONS_LOCK.acquire()
// create a new mutex for every function call, like in production code

View File

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

View File

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

View File

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

View File

@ -1,13 +1,11 @@
import { User as DbUser, UserLoggingView } from 'database'
import { getLogger } from 'log4js'
import { Point } from 'typeorm'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { UpdateUserInfosArgs } from '@/graphql/arg/UpdateUserInfosArgs'
import { GmsPublishLocationType } from '@/graphql/enum/GmsPublishLocationType'
import { PublishNameType } from '@/graphql/enum/PublishNameType'
import { LogError } from '@/server/LogError'
import { getLogger } from 'log4js'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { Point2Location } from './Location2Point'
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 { Order } from '@/graphql/enum/Order'
import {
DEFAULT_PAGINATION_PAGE_SIZE,
FRONTEND_CONTRIBUTIONS_ITEM_ANCHOR_PREFIX,
} 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
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 { ApolloServerTestClient } from 'apollo-server-testing'
import { AppDatabase, Contribution, User } from 'database'
import { DataSource } from 'typeorm'
import { CONFIG } from '@/config'
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 { 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 { AppDatabase } from 'database'
import { AppDatabase, Contribution } from 'database'
import { Decimal } from 'decimal.js-light'
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 logger = getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.graphql.resolver.util.creations`)

View File

@ -1,7 +1,7 @@
import { GraphQLResolveInfo } from 'graphql'
import {
ResolveTree,
parseResolveInfo,
ResolveTree,
simplifyParsedResolveInfoFragmentWithType,
} from 'graphql-parse-resolve-info'
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 { ContributionMessageType } from '@enum/ContributionMessageType'
import { ContributionMessage as DbContributionMessage } from 'database'
import { In } from 'typeorm'
interface FindContributionMessagesOptions {
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 { 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'

View File

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

View File

@ -1,8 +1,7 @@
import { KlickTipp } from '@model/KlickTipp'
import { getLogger } from 'log4js'
import { getKlickTippUser } from '@/apis/KlicktippController'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { getLogger } from 'log4js'
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 { Transaction as DbTransaction } from 'database'
export const getTransactionList = async (
userId: number,

View File

@ -1,11 +1,10 @@
import { Community as DbCommunity, User as DbUser } from 'database'
import { getLogger } from 'log4js'
import { createGmsUser, updateGmsUser } from '@/apis/gms/GmsClient'
import { GmsUser } from '@/apis/gms/model/GmsUser'
import { CONFIG } from '@/config'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { LogError } from '@/server/LogError'
import { getLogger } from 'log4js'
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 { HumHubClient } from '@/apis/humhub/HumHubClient'
import { GetUser } from '@/apis/humhub/model/GetUser'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { UpdateUserInfosArgs } from '@/graphql/arg/UpdateUserInfosArgs'
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'
jest.mock('@/apis/humhub/HumHubClient')

View File

@ -1,16 +1,16 @@
import { User } from 'database'
import { getLogger } from 'log4js'
import { HumHubClient } from '@/apis/humhub/HumHubClient'
import { GetUser } from '@/apis/humhub/model/GetUser'
import { PostUser } from '@/apis/humhub/model/PostUser'
import { ExecutedHumhubAction, syncUser } from '@/apis/humhub/syncUser'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { PublishNameLogic } from '@/data/PublishName.logic'
import { UpdateUserInfosArgs } from '@/graphql/arg/UpdateUserInfosArgs'
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

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 { TransactionLinkFilters } from '@arg/TransactionLinkFilters'
import { Order } from '@enum/Order'
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'

View File

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

View File

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

View File

@ -1,8 +1,7 @@
import { createUnionType } from 'type-graphql'
import { ContributionLink } from '@model/ContributionLink'
import { RedeemJwtLink } from '@model/RedeemJwtLink'
import { TransactionLink } from '@model/TransactionLink'
import { createUnionType } from 'type-graphql'
export const QueryLinkResult = createUnionType({
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 { registerDecorator, ValidationOptions } from 'class-validator'
export function isContributionStatusArray(validationOptions?: ValidationOptions) {
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) {
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'
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) {
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 { registerDecorator, ValidationArguments, ValidationOptions } from 'class-validator'
import { Location2Point } from '@/graphql/resolver/util/Location2Point'

View File

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

View File

@ -1,14 +1,13 @@
import { Contribution, User } from 'database'
import { Decimal } from 'decimal.js-light'
import { getLogger, Logger } from 'log4js'
import { Role } from '@/auth/Role'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { ContributionLogic } from '@/data/Contribution.logic'
import { ContributionMessageBuilder } from '@/data/ContributionMessage.builder'
import { ContributionStatus } from '@/graphql/enum/ContributionStatus'
import { LogError } from '@/server/LogError'
import { Context, getClientTimezoneOffset } from '@/server/context'
import { Logger, getLogger } from 'log4js'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import { LogError } from '@/server/LogError'
export abstract class AbstractUnconfirmedContributionRole {
private availableCreationSums?: Decimal[]
@ -24,7 +23,9 @@ export abstract class AbstractUnconfirmedContributionRole {
if (self.confirmedAt || self.deniedAt) {
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)
}

View File

@ -1,13 +1,12 @@
import { AdminUpdateContributionArgs } from '@arg/AdminUpdateContributionArgs'
import { ContributionArgs } from '@arg/ContributionArgs'
import { Contribution, ContributionMessage } from 'database'
import { Decimal } from 'decimal.js-light'
import { EntityManager, FindOneOptions, FindOptionsRelations } from 'typeorm'
import { AdminUpdateContributionArgs } from '@arg/AdminUpdateContributionArgs'
import { ContributionArgs } from '@arg/ContributionArgs'
import { ContributionMessageArgs } from '@/graphql/arg/ContributionMessageArgs'
import { LogError } from '@/server/LogError'
import { Context } from '@/server/context'
import { LogError } from '@/server/LogError'
import { AbstractUnconfirmedContributionRole } from './AbstractUnconfirmedContribution.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 { 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 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.status(200).json({
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)
// Optional: calculate Key ID (z.B. SHA-256 Fingerprint)
const kid = createHash('sha256')
.update(homeCommunity.publicJwtKey)
.digest('base64url')
const kid = createHash('sha256').update(homeCommunity.publicJwtKey).digest('base64url')
const jwks = {
keys: [

View File

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

View File

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

View File

@ -1,18 +1,12 @@
import { User } from 'database'
import { PasswordEncryptionType } from '@enum/PasswordEncryptionType'
import { CONFIG } from '@/config'
import { LogError } from '@/server/LogError'
import { User } from 'database'
import { getLogger } from 'log4js'
import { LOG4JS_BASE_CATEGORY_NAME } from '@/config/const'
import {
crypto_box_SEEDBYTES,
crypto_hash_sha512_BYTES,
crypto_hash_sha512_STATEBYTES,
crypto_hash_sha512_final,
crypto_hash_sha512_init,
crypto_hash_sha512_STATEBYTES,
crypto_hash_sha512_update,
crypto_pwhash,
crypto_pwhash_MEMLIMIT_MIN,
@ -22,6 +16,10 @@ import {
crypto_shorthash_BYTES,
crypto_shorthash_KEYBYTES,
} 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`)

View File

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

View File

@ -1,9 +1,8 @@
import {
contributionLinkFactory as contributionLinkFactoryDb,
ContributionLinkInterface
} from 'database'
import { ContributionLink } from '@model/ContributionLink'
import {
ContributionLinkInterface,
contributionLinkFactory as contributionLinkFactoryDb,
} from 'database'
export { ContributionLinkInterface }

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