Improvements

This commit is contained in:
Daniel Hougaard
2024-06-12 00:28:11 +02:00
parent 985116c6f2
commit 869be3c273
2 changed files with 19 additions and 60 deletions

View File

@@ -94,6 +94,14 @@ export const userDALFactory = (db: TDbClient) => {
}
};
const findMergeableUsers = async (email: string, tx?: Knex) => {
const users = await (tx || db)(TableName.Users).where((builder) => {
void builder.where({ email, isEmailVerified: true }).orWhere({ email, isAccepted: false });
});
return users;
};
const updateUserEncryptionByUserId = async (userId: string, data: TUserEncryptionKeysUpdate, tx?: Knex) => {
try {
const [userEnc] = await (tx || db)(TableName.UserEncryptionKey)
@@ -154,6 +162,7 @@ export const userDALFactory = (db: TDbClient) => {
findUsersByProjectMembershipIds,
upsertUserEncryptionKey,
createUserEncryption,
findMergeableUsers,
findOneUserAction,
createUserAction
};

View File

@@ -12,6 +12,7 @@ type TUserServiceFactoryDep = {
userDAL: Pick<
TUserDALFactory,
| "find"
| "findMergeableUsers"
| "findOne"
| "findById"
| "transaction"
@@ -86,13 +87,7 @@ export const userServiceFactory = ({
);
// check if there are users with the same email.
const users = await userDAL.find(
{
email,
isEmailVerified: true
},
{ tx }
);
const users = await userDAL.findMergeableUsers(email, tx);
if (users.length > 1) {
// merge users
@@ -134,59 +129,14 @@ export const userServiceFactory = ({
);
}
} else {
const existingUserWithUsername = await userDAL.findOne({
username: email
});
if (existingUserWithUsername && existingUserWithUsername.id !== user.id) {
// merge users
const mergeUserOrgMembershipSet = new Set(
(await orgMembershipDAL.find({ userId: existingUserWithUsername.id }, { tx })).map((m) => m.orgId)
);
const myOrgMemberships = (await orgMembershipDAL.find({ userId: user.id }, { tx })).filter(
(m) => !mergeUserOrgMembershipSet.has(m.orgId)
);
const userAliases = await userAliasDAL.find(
{
userId: user.id
},
{ tx }
);
// delete current user
await userDAL.deleteById(user.id, tx);
if (myOrgMemberships.length) {
await orgMembershipDAL.insertMany(
myOrgMemberships.map((orgMembership) => ({
...orgMembership,
userId: existingUserWithUsername.id
})),
tx
);
}
if (userAliases.length) {
await userAliasDAL.insertMany(
userAliases.map((userAlias) => ({
...userAlias,
userId: existingUserWithUsername.id
})),
tx
);
}
} else {
// update current user's username to [email]
await userDAL.updateById(
user.id,
{
username: email
},
tx
);
}
// update current user's username to [email]
await userDAL.updateById(
user.id,
{
username: email
},
tx
);
}
});
};