review(): from PR #8656 (#8870)

This commit is contained in:
Antoine Moreaux
2024-12-05 10:46:13 +01:00
committed by GitHub
parent 99caab1412
commit 33e69805cb
36 changed files with 176 additions and 179 deletions

View File

@ -135,7 +135,7 @@ export class UserService extends TypeOrmQueryService<User> {
return user;
}
async saveDefaultWorkspace(userId: string, workspaceId: string) {
async hasUserAccessToWorkspaceOrThrow(userId: string, workspaceId: string) {
const user = await this.userRepository.findOne({
where: {
id: userId,
@ -146,13 +146,20 @@ export class UserService extends TypeOrmQueryService<User> {
relations: ['workspaces'],
});
userValidator.assertIsExist(
userValidator.assertIsDefinedOrThrow(
user,
new AuthException(
'User does not have access to this workspace',
AuthExceptionCode.FORBIDDEN_EXCEPTION,
),
);
}
async saveDefaultWorkspaceIfUserHasAccessOrThrow(
userId: string,
workspaceId: string,
) {
await this.hasUserAccessToWorkspaceOrThrow(userId, workspaceId);
return await this.userRepository.save({
id: userId,

View File

@ -77,7 +77,10 @@ export class UserResolver {
this.environmentService.get('IS_MULTIWORKSPACE_ENABLED') &&
workspaceId
) {
await this.userService.saveDefaultWorkspace(userId, workspaceId);
await this.userService.saveDefaultWorkspaceIfUserHasAccessOrThrow(
userId,
workspaceId,
);
}
const user = await this.userRepository.findOne({
@ -87,7 +90,7 @@ export class UserResolver {
relations: ['defaultWorkspace', 'workspaces', 'workspaces.workspace'],
});
userValidator.assertIsExist(
userValidator.assertIsDefinedOrThrow(
user,
new AuthException('User not found', AuthExceptionCode.USER_NOT_FOUND),
);

View File

@ -1,34 +1,24 @@
import { User } from 'src/engine/core-modules/user/user.entity';
import { CustomException } from 'src/utils/custom-exception';
import { isDefined } from 'src/utils/is-defined';
const assertIsExist = (
const assertIsDefinedOrThrow = (
user: User | undefined | null,
exceptionToThrow: CustomException,
): asserts user is User => {
if (!user) {
if (!isDefined(user)) {
throw exceptionToThrow;
}
};
const isExist = (user: User | undefined | null): user is User => {
return !!user;
};
const assertHasDefaultWorkspace = (
user: User,
exceptionToThrow?: CustomException,
): asserts user is User & { defaultWorkspaceId: string } => {
if (!user.defaultWorkspaceId) {
throw exceptionToThrow;
}
const isUserDefined = (user: User | undefined | null): user is User => {
return isDefined(user);
};
export const userValidator: {
assertIsExist: typeof assertIsExist;
assertHasDefaultWorkspace: typeof assertHasDefaultWorkspace;
isExist: typeof isExist;
assertIsDefinedOrThrow: typeof assertIsDefinedOrThrow;
isDefined: typeof isUserDefined;
} = {
assertIsExist,
assertHasDefaultWorkspace,
isExist,
assertIsDefinedOrThrow,
isDefined: isUserDefined,
};