Skip to content

Commit

Permalink
♻️ refactor: add user server api key method in the server mode (lobeh…
Browse files Browse the repository at this point in the history
…ub#4870)

* ♻️ refactor: add user server api key method

* Update user.ts
  • Loading branch information
arvinxx authored Dec 2, 2024
1 parent 77c7aa3 commit 875463a
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion src/database/server/models/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { DeepPartial } from 'utility-types';
import { serverDB } from '@/database/server/core/db';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import { UserGuide, UserPreference } from '@/types/user';
import { UserSettings } from '@/types/user/settings';
import { UserKeyVaults, UserSettings } from '@/types/user/settings';
import { merge } from '@/utils/merge';

import { NewUser, UserItem, userSettings, users } from '../schemas/lobechat';
Expand Down Expand Up @@ -105,6 +105,38 @@ export class UserModel {
};
};

static getUserApiKeys = async (id: string) => {
const result = await serverDB
.select({
settingsKeyVaults: userSettings.keyVaults,
})
.from(userSettings)
.where(eq(userSettings.id, id));

if (!result || !result[0]) {
throw new UserNotFoundError();
}

const state = result[0];

// Decrypt keyVaults
let decryptKeyVaults = {};
if (state.settingsKeyVaults) {
const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
const { wasAuthentic, plaintext } = await gateKeeper.decrypt(state.settingsKeyVaults);

if (wasAuthentic) {
try {
decryptKeyVaults = JSON.parse(plaintext);
} catch (e) {
console.error(`Failed to parse keyVaults ,userId: ${id}. Error:`, e);
}
}
}

return decryptKeyVaults as UserKeyVaults;
};

async updateUser(id: string, value: Partial<UserItem>) {
return serverDB
.update(users)
Expand Down

0 comments on commit 875463a

Please sign in to comment.