Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[_] feat: workspace role guard #291

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions src/modules/workspaces/domains/workspace-team-user.domain.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { User } from '../../user/user.domain';
import { WorkspaceTeam } from './workspace-team.domain';
import { WorkspaceTeamUserAttributes } from '../attributes/workspace-team-users.attributes';

export class WorkspaceTeamUser implements WorkspaceTeamUserAttributes {
id: string;
teamId: string;
memberId: string;
team?: WorkspaceTeam;
createdAt: Date;
updatedAt: Date;

constructor({
id,
teamId,
memberId,
team,
createdAt,
updatedAt,
}: WorkspaceTeamUserAttributes & { team?: WorkspaceTeam }) {
this.id = id;
this.teamId = teamId;
this.memberId = memberId;
this.team = team;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
}

static build(
workspaceTeamUser: WorkspaceTeamUserAttributes & {
team?: WorkspaceTeam;
member?: User;
},
): WorkspaceTeamUser {
return new WorkspaceTeamUser(workspaceTeamUser);
}

toJSON() {
return {
id: this.id,
teamId: this.teamId,
memberId: this.memberId,
team: this.team ? this.team.toJSON() : undefined,
createdAt: this.createdAt,
updatedAt: this.updatedAt,
};
}
}
5 changes: 5 additions & 0 deletions src/modules/workspaces/domains/workspace-team.domain.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { User } from '../../user/user.domain';
import { WorkspaceTeamAttributes } from '../attributes/workspace-team.attributes';

export class WorkspaceTeam implements WorkspaceTeamAttributes {
Expand All @@ -24,6 +25,10 @@ export class WorkspaceTeam implements WorkspaceTeamAttributes {
this.updatedAt = updatedAt;
}

isUserManager(userUuid: User['uuid']) {
apsantiso marked this conversation as resolved.
Show resolved Hide resolved
return userUuid === this.managerId;
}

static build(teamAttributes: WorkspaceTeamAttributes): WorkspaceTeam {
return new WorkspaceTeam(teamAttributes);
}
Expand Down
57 changes: 57 additions & 0 deletions src/modules/workspaces/domains/workspace-user.domain.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { WorkspaceUserAttributes } from '../attributes/workspace-users.attributes';

export class WorkspaceUser implements WorkspaceUserAttributes {
id: string;
memberId: string;
key: string;
workspaceId: string;
spaceLimit: bigint;
driveUsage: bigint;
backupsUsage: bigint;
deactivated: boolean;
createdAt: Date;
updatedAt: Date;

constructor({
id,
memberId,
key,
workspaceId,
spaceLimit,
driveUsage,
backupsUsage,
deactivated,
createdAt,
updatedAt,
}: WorkspaceUserAttributes) {
this.id = id;
this.memberId = memberId;
this.key = key;
this.workspaceId = workspaceId;
this.spaceLimit = spaceLimit;
this.driveUsage = driveUsage;
this.backupsUsage = backupsUsage;
this.deactivated = deactivated;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
}

static build(workspaceUser: WorkspaceUserAttributes): WorkspaceUser {
return new WorkspaceUser(workspaceUser);
}

toJSON() {
return {
id: this.id,
memberId: this.memberId,
key: this.key,
workspaceId: this.workspaceId,
spaceLimit: this.spaceLimit.toString(),
driveUsage: this.driveUsage.toString(),
backupsUsage: this.backupsUsage.toString(),
deactivated: this.deactivated,
createdAt: this.createdAt,
updatedAt: this.updatedAt,
};
}
}
5 changes: 5 additions & 0 deletions src/modules/workspaces/domains/workspaces.domain.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { UserAttributes } from '../../user/user.attributes';
import { WorkspaceAttributes } from '../attributes/workspace.attributes';

export class Workspace implements WorkspaceAttributes {
Expand Down Expand Up @@ -40,6 +41,10 @@ export class Workspace implements WorkspaceAttributes {
return new Workspace(user);
}

isUserOwner(userUuid: UserAttributes['uuid']) {
apsantiso marked this conversation as resolved.
Show resolved Hide resolved
return userUuid === this.ownerId;
}

toJSON() {
return {
id: this.id,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { SetMetadata } from '@nestjs/common';

export enum WorkspaceRole {
OWNER = 'owner',
MANAGER = 'manager',
MEMBER = 'member',
}

export enum AccessContext {
WORKSPACE = 'workspace',
TEAM = 'team',
}

export const WorkspaceContextIdFieldName = {
[AccessContext.WORKSPACE]: 'workspaceId',
[AccessContext.TEAM]: 'teamId',
};

export interface AccessOptions {
accessContext: AccessContext;
requiredRole: WorkspaceRole;
idSource: 'params' | 'body' | 'query';
}

export const WorkspaceRequiredAccess = (
accessContext: AccessContext,
requiredRole: WorkspaceRole,
idSource: 'params' | 'body' | 'query' = 'params',
) => SetMetadata('accessControl', { accessContext, requiredRole, idSource });
114 changes: 114 additions & 0 deletions src/modules/workspaces/guards/workspaces.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// flexible-access.guard.ts
apsantiso marked this conversation as resolved.
Show resolved Hide resolved
import {
CanActivate,
ExecutionContext,
ForbiddenException,
Injectable,
Logger,
NotFoundException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { WorkspacesUsecases } from '../workspaces.usecase';
import {
AccessContext,
AccessOptions,
WorkspaceContextIdFieldName,
WorkspaceRole,
} from './workspace-required-access.decorator';

@Injectable()
export class WorkspaceGuard implements CanActivate {
constructor(
private reflector: Reflector,
private workspaceUseCases: WorkspacesUsecases,
) {}

async canActivate(context: ExecutionContext): Promise<boolean> {
const accessOptions: AccessOptions = this.reflector.get(
'accessControl',
context.getHandler(),
);

if (!accessOptions) {
return true;
}

const { requiredRole, accessContext, idSource } = accessOptions;

const request = context.switchToHttp().getRequest();
const user = request.user;

const id = this.getIdFromRequest(
request,
idSource,
WorkspaceContextIdFieldName[accessContext],
);

if (accessContext === AccessContext.WORKSPACE) {
return this.checkUserWorkspaceRole(user.uuid, id, requiredRole);
} else if (accessContext === AccessContext.TEAM) {
return this.checkUserTeamRole(user.uuid, id, requiredRole);
}

return false;
}

private async checkUserWorkspaceRole(
apsantiso marked this conversation as resolved.
Show resolved Hide resolved
userUuid: string,
workspaceId: string,
role: WorkspaceRole,
) {
const { workspace, workspaceUser } =
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This destructuring could fail if the result from the database is null, could not?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Either the workspace or the workspaceUser can be null. I handled that case in the usecase so a plain and not destructurable null is never returned.

await this.workspaceUseCases.findUserInWorkspace(userUuid, workspaceId);

if (!workspace) {
throw new NotFoundException('Workspace not found');
}

if (
!workspaceUser ||
!(role === WorkspaceRole.OWNER && workspace.isUserOwner(userUuid))
apsantiso marked this conversation as resolved.
Show resolved Hide resolved
) {
Logger.log(
`[WORKSPACES/GUARD]: user has no requiered access to workspace. id: ${workspaceId} userUuid: ${userUuid} `,
);
throw new ForbiddenException('You have no access to this workspace');
}

return !!workspaceUser;
}

private async checkUserTeamRole(
apsantiso marked this conversation as resolved.
Show resolved Hide resolved
userUuid: string,
teamId: string,
role: WorkspaceRole,
) {
const { team, teamUser } = await this.workspaceUseCases.findUserInTeam(
userUuid,
teamId,
);

const workspace = await this.workspaceUseCases.findById(team.workspaceId);
if (workspace.isUserOwner(userUuid)) {
return true;
}

if (teamUser && role === WorkspaceRole.MANAGER) {
return team.isUserManager(userUuid);
}

if (teamUser && role === WorkspaceRole.MEMBER) {
return true;
}

throw new ForbiddenException('You have no access to this team');
}

private getIdFromRequest(
request,
source: 'params' | 'body' | 'query',
field: string,
): string | undefined {
return request[source]?.[field];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { WorkspaceTeamUserAttributes } from '../attributes/workspace-team-users.
@Table({
underscored: true,
timestamps: true,
tableName: 'teams_users',
tableName: 'workspace_teams_users',
})
export class WorkspaceTeamUserModel
extends Model
Expand Down
4 changes: 4 additions & 0 deletions src/modules/workspaces/models/workspace.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
PrimaryKey,
ForeignKey,
BelongsTo,
HasMany,
} from 'sequelize-typescript';
import { UserModel } from '../../user/user.model';
import { WorkspaceUserModel } from './workspace-users.model';
Expand Down Expand Up @@ -60,6 +61,9 @@ export class WorkspaceModel extends Model implements WorkspaceAttributes {
@Column(DataType.UUID)
workspaceUserId: string;

@HasMany(() => WorkspaceUserModel)
workspaceUsers: WorkspaceUserModel[];

@Column
createdAt: Date;

Expand Down
28 changes: 28 additions & 0 deletions src/modules/workspaces/repositories/team.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import { WorkspaceTeamModel } from '../models/workspace-team.model';
import { WorkspaceTeamUserModel } from '../models/workspace-team-users.model';
import { WorkspaceTeam } from '../domains/workspace-team.domain';
import { WorkspaceTeamAttributes } from '../attributes/workspace-team.attributes';
import { UserAttributes } from '../../user/user.attributes';
import { WorkspaceTeamUser } from '../domains/workspace-team-user.domain';

@Injectable()
export class SequelizeWorkspaceTeamRepository {
Expand Down Expand Up @@ -44,6 +46,26 @@ export class SequelizeWorkspaceTeamRepository {
return result.map((teamUser) => User.build({ ...teamUser.member }));
}

async getTeamUserAndTeamByTeamId(
userUuid: UserAttributes['uuid'],
teamId: WorkspaceTeamAttributes['id'],
) {
const team = await this.teamModel.findOne({
where: { id: teamId },
include: {
required: false,
model: WorkspaceTeamUserModel,
where: { memberId: userUuid },
},
});
return {
team: team ? this.toDomain(team) : null,
teamUser: team.teamUsers[0]
? this.teamUserToDomain(team.teamUsers[0])
: null,
};
}

async getTeamById(
teamId: WorkspaceTeamAttributes['id'],
): Promise<WorkspaceTeam | null> {
Expand Down Expand Up @@ -85,4 +107,10 @@ export class SequelizeWorkspaceTeamRepository {
...model.toJSON(),
});
}

teamUserToDomain(model: WorkspaceTeamUserModel): WorkspaceTeamUser {
return WorkspaceTeamUser.build({
...model.toJSON(),
});
}
}
Loading
Loading