mirror of
https://github.com/hexastack/hexabot
synced 2025-06-26 18:27:28 +00:00
refactor: rename context to resourceRef
This commit is contained in:
@@ -110,7 +110,7 @@ describe('AttachmentController', () => {
|
||||
file: [],
|
||||
},
|
||||
{} as Request,
|
||||
{ context: 'block_attachment' },
|
||||
{ resourceRef: 'block_attachment' },
|
||||
);
|
||||
await expect(promiseResult).rejects.toThrow(
|
||||
new BadRequestException('No file was selected'),
|
||||
@@ -128,7 +128,7 @@ describe('AttachmentController', () => {
|
||||
{
|
||||
session: { passport: { user: { id: '9'.repeat(24) } } },
|
||||
} as unknown as Request,
|
||||
{ context: 'block_attachment' },
|
||||
{ resourceRef: 'block_attachment' },
|
||||
);
|
||||
const [name] = attachmentFile.filename.split('.');
|
||||
expect(attachmentService.create).toHaveBeenCalledWith({
|
||||
@@ -136,7 +136,7 @@ describe('AttachmentController', () => {
|
||||
type: attachmentFile.mimetype,
|
||||
name: attachmentFile.originalname,
|
||||
location: expect.stringMatching(new RegExp(`^/${name}`)),
|
||||
context: 'block_attachment',
|
||||
resourceRef: 'block_attachment',
|
||||
access: 'public',
|
||||
createdByRef: 'User',
|
||||
createdBy: '9'.repeat(24),
|
||||
@@ -145,7 +145,7 @@ describe('AttachmentController', () => {
|
||||
[
|
||||
{
|
||||
...attachment,
|
||||
context: 'block_attachment',
|
||||
resourceRef: 'block_attachment',
|
||||
createdByRef: 'User',
|
||||
createdBy: '9'.repeat(24),
|
||||
},
|
||||
|
||||
@@ -67,7 +67,7 @@ export class AttachmentController extends BaseController<Attachment> {
|
||||
async filterCount(
|
||||
@Query(
|
||||
new SearchFilterPipe<Attachment>({
|
||||
allowedFields: ['name', 'type', 'context'],
|
||||
allowedFields: ['name', 'type', 'resourceRef'],
|
||||
}),
|
||||
)
|
||||
filters?: TFilterQuery<Attachment>,
|
||||
@@ -97,7 +97,7 @@ export class AttachmentController extends BaseController<Attachment> {
|
||||
@Query(PageQueryPipe) pageQuery: PageQueryDto<Attachment>,
|
||||
@Query(
|
||||
new SearchFilterPipe<Attachment>({
|
||||
allowedFields: ['name', 'type', 'context'],
|
||||
allowedFields: ['name', 'type', 'resourceRef'],
|
||||
}),
|
||||
)
|
||||
filters: TFilterQuery<Attachment>,
|
||||
@@ -130,7 +130,8 @@ export class AttachmentController extends BaseController<Attachment> {
|
||||
async uploadFile(
|
||||
@UploadedFiles() files: { file: Express.Multer.File[] },
|
||||
@Req() req: Request,
|
||||
@Query() { context, access = 'public' }: AttachmentContextParamDto,
|
||||
@Query()
|
||||
{ resourceRef, access = 'public' }: AttachmentContextParamDto,
|
||||
): Promise<Attachment[]> {
|
||||
if (!files || !Array.isArray(files?.file) || files.file.length === 0) {
|
||||
throw new BadRequestException('No file was selected');
|
||||
@@ -149,7 +150,7 @@ export class AttachmentController extends BaseController<Attachment> {
|
||||
name: file.originalname,
|
||||
size: file.size,
|
||||
type: file.mimetype,
|
||||
context,
|
||||
resourceRef,
|
||||
access,
|
||||
createdBy: userId,
|
||||
createdByRef: 'User',
|
||||
|
||||
@@ -25,11 +25,11 @@ import { IsObjectId } from '@/utils/validation-rules/is-object-id';
|
||||
|
||||
import {
|
||||
AttachmentAccess,
|
||||
AttachmentContext,
|
||||
AttachmentCreatedByRef,
|
||||
AttachmentResourceRef,
|
||||
TAttachmentAccess,
|
||||
TAttachmentContext,
|
||||
TAttachmentCreatedByRef,
|
||||
TAttachmentResourceRef,
|
||||
} from '../types';
|
||||
|
||||
export class AttachmentMetadataDto {
|
||||
@@ -67,16 +67,16 @@ export class AttachmentMetadataDto {
|
||||
channel?: Partial<Record<ChannelName, any>>;
|
||||
|
||||
/**
|
||||
* Attachment context
|
||||
* Attachment resource reference
|
||||
*/
|
||||
@ApiProperty({
|
||||
description: 'Attachment Context',
|
||||
enum: Object.values(AttachmentContext),
|
||||
description: 'Attachment Resource Ref',
|
||||
enum: Object.values(AttachmentResourceRef),
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@IsIn(Object.values(AttachmentContext))
|
||||
context: TAttachmentContext;
|
||||
@IsIn(Object.values(AttachmentResourceRef))
|
||||
resourceRef: TAttachmentResourceRef;
|
||||
|
||||
/**
|
||||
* Attachment Owner Type
|
||||
@@ -141,13 +141,13 @@ export class AttachmentDownloadDto extends ObjectIdDto {
|
||||
|
||||
export class AttachmentContextParamDto {
|
||||
@ApiProperty({
|
||||
description: 'Attachment Context',
|
||||
enum: Object.values(AttachmentContext),
|
||||
description: 'Attachment Resource Reference',
|
||||
enum: Object.values(AttachmentResourceRef),
|
||||
})
|
||||
@IsString()
|
||||
@IsIn(Object.values(AttachmentContext))
|
||||
@IsIn(Object.values(AttachmentResourceRef))
|
||||
@IsNotEmpty()
|
||||
context: TAttachmentContext;
|
||||
resourceRef: TAttachmentResourceRef;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'Attachment Access',
|
||||
|
||||
@@ -53,9 +53,9 @@ describe('AttachmentGuard', () => {
|
||||
});
|
||||
|
||||
describe('canActivate', () => {
|
||||
it('should allow GET requests with valid context', async () => {
|
||||
it('should allow GET requests with valid ref', async () => {
|
||||
const mockUser = { roles: ['admin-id'] } as any;
|
||||
const mockContext = ['user_avatar'];
|
||||
const mockRef = ['user_avatar'];
|
||||
|
||||
jest.spyOn(modelService, 'findOne').mockImplementation((criteria) => {
|
||||
return typeof criteria === 'string' ||
|
||||
@@ -84,7 +84,7 @@ describe('AttachmentGuard', () => {
|
||||
const mockExecutionContext = {
|
||||
switchToHttp: jest.fn().mockReturnValue({
|
||||
getRequest: jest.fn().mockReturnValue({
|
||||
query: { where: { context: mockContext } },
|
||||
query: { where: { resourceRef: mockRef } },
|
||||
method: 'GET',
|
||||
user: mockUser,
|
||||
}),
|
||||
@@ -95,11 +95,11 @@ describe('AttachmentGuard', () => {
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('should throw BadRequestException for GET requests with invalid context', async () => {
|
||||
it('should throw BadRequestException for GET requests with invalid ref', async () => {
|
||||
const mockExecutionContext = {
|
||||
switchToHttp: jest.fn().mockReturnValue({
|
||||
getRequest: jest.fn().mockReturnValue({
|
||||
query: { where: { context: 'invalid_context' } },
|
||||
query: { where: { resourceRef: 'invalid_ref' } },
|
||||
method: 'GET',
|
||||
}),
|
||||
}),
|
||||
@@ -120,7 +120,7 @@ describe('AttachmentGuard', () => {
|
||||
? Promise.reject('Invalid ID')
|
||||
: Promise.resolve({
|
||||
id: '9'.repeat(24),
|
||||
context: `user_avatar`,
|
||||
resourceRef: `user_avatar`,
|
||||
} as Attachment);
|
||||
});
|
||||
|
||||
@@ -162,7 +162,7 @@ describe('AttachmentGuard', () => {
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('should allow POST requests with valid context', async () => {
|
||||
it('should allow POST requests with a valid ref', async () => {
|
||||
const mockUser = { roles: ['editor-id'] } as any;
|
||||
|
||||
jest.spyOn(modelService, 'findOne').mockImplementation((criteria) => {
|
||||
@@ -191,7 +191,7 @@ describe('AttachmentGuard', () => {
|
||||
const mockExecutionContext = {
|
||||
switchToHttp: jest.fn().mockReturnValue({
|
||||
getRequest: jest.fn().mockReturnValue({
|
||||
query: { context: 'block_attachment' },
|
||||
query: { resourceRef: 'block_attachment' },
|
||||
method: 'POST',
|
||||
user: mockUser,
|
||||
}),
|
||||
|
||||
@@ -26,8 +26,11 @@ import { Action } from '@/user/types/action.type';
|
||||
import { TModel } from '@/user/types/model.type';
|
||||
|
||||
import { AttachmentService } from '../services/attachment.service';
|
||||
import { TAttachmentContext } from '../types';
|
||||
import { isAttachmentContext, isAttachmentContextArray } from '../utilities';
|
||||
import { TAttachmentResourceRef } from '../types';
|
||||
import {
|
||||
isAttachmentResourceRef,
|
||||
isAttachmentResourceRefArray,
|
||||
} from '../utilities';
|
||||
|
||||
@Injectable()
|
||||
export class AttachmentGuard implements CanActivate {
|
||||
@@ -39,9 +42,9 @@ export class AttachmentGuard implements CanActivate {
|
||||
|
||||
private permissionMap: Record<
|
||||
Action,
|
||||
Record<TAttachmentContext, [TModel, Action][]>
|
||||
Record<TAttachmentResourceRef, [TModel, Action][]>
|
||||
> = {
|
||||
// Read attachments by context
|
||||
// Read attachments by ref
|
||||
[Action.READ]: {
|
||||
setting_attachment: [
|
||||
['setting', Action.READ],
|
||||
@@ -62,7 +65,7 @@ export class AttachmentGuard implements CanActivate {
|
||||
['attachment', Action.READ],
|
||||
],
|
||||
},
|
||||
// Create attachments by context
|
||||
// Create attachments by ref
|
||||
[Action.CREATE]: {
|
||||
setting_attachment: [
|
||||
['setting', Action.UPDATE],
|
||||
@@ -88,7 +91,7 @@ export class AttachmentGuard implements CanActivate {
|
||||
['attachment', Action.CREATE],
|
||||
],
|
||||
},
|
||||
// Delete attachments by context
|
||||
// Delete attachments by ref
|
||||
[Action.DELETE]: {
|
||||
setting_attachment: [
|
||||
['setting', Action.UPDATE],
|
||||
@@ -156,27 +159,27 @@ export class AttachmentGuard implements CanActivate {
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the user is authorized to perform a given action on a attachment based on its context and user roles.
|
||||
* Checks if the user is authorized to perform a given action on a attachment based on the resource reference and user roles.
|
||||
*
|
||||
* @param action - The action on the attachment.
|
||||
* @param user - The current user.
|
||||
* @param context - The context of the attachment (e.g., user_avatar, setting_attachment).
|
||||
* @param resourceRef - The resource ref of the attachment (e.g., user_avatar, setting_attachment).
|
||||
* @returns A promise that resolves to `true` if the user has the required upload permission, otherwise `false`.
|
||||
*/
|
||||
private async isAuthorized(
|
||||
action: Action,
|
||||
user: Express.User & User,
|
||||
context: TAttachmentContext,
|
||||
resourceRef: TAttachmentResourceRef,
|
||||
): Promise<boolean> {
|
||||
if (!action) {
|
||||
throw new TypeError('Invalid action');
|
||||
}
|
||||
|
||||
if (!context) {
|
||||
throw new TypeError('Invalid context');
|
||||
if (!resourceRef) {
|
||||
throw new TypeError('Invalid resource ref');
|
||||
}
|
||||
|
||||
const permissions = this.permissionMap[action][context];
|
||||
const permissions = this.permissionMap[action][resourceRef];
|
||||
|
||||
if (!permissions.length) {
|
||||
return false;
|
||||
@@ -214,17 +217,21 @@ export class AttachmentGuard implements CanActivate {
|
||||
throw new NotFoundException('Attachment not found!');
|
||||
}
|
||||
|
||||
return await this.isAuthorized(Action.READ, user, attachment.context);
|
||||
return await this.isAuthorized(
|
||||
Action.READ,
|
||||
user,
|
||||
attachment.resourceRef,
|
||||
);
|
||||
} else if (query.where) {
|
||||
const { context = [] } = query.where as qs.ParsedQs;
|
||||
const { resourceRef = [] } = query.where as qs.ParsedQs;
|
||||
|
||||
if (!isAttachmentContextArray(context)) {
|
||||
throw new BadRequestException('Invalid context param');
|
||||
if (!isAttachmentResourceRefArray(resourceRef)) {
|
||||
throw new BadRequestException('Invalid resource ref');
|
||||
}
|
||||
|
||||
return (
|
||||
await Promise.all(
|
||||
context.map((c) => this.isAuthorized(Action.READ, user, c)),
|
||||
resourceRef.map((c) => this.isAuthorized(Action.READ, user, c)),
|
||||
)
|
||||
).every(Boolean);
|
||||
} else {
|
||||
@@ -233,12 +240,12 @@ export class AttachmentGuard implements CanActivate {
|
||||
}
|
||||
// upload() endpoint
|
||||
case 'POST': {
|
||||
const { context = '' } = query;
|
||||
if (!isAttachmentContext(context)) {
|
||||
throw new BadRequestException('Invalid context param');
|
||||
const { resourceRef = '' } = query;
|
||||
if (!isAttachmentResourceRef(resourceRef)) {
|
||||
throw new BadRequestException('Invalid resource ref');
|
||||
}
|
||||
|
||||
return await this.isAuthorized(Action.CREATE, user, context);
|
||||
return await this.isAuthorized(Action.CREATE, user, resourceRef);
|
||||
}
|
||||
// deleteOne() endpoint
|
||||
case 'DELETE': {
|
||||
@@ -252,7 +259,7 @@ export class AttachmentGuard implements CanActivate {
|
||||
return await this.isAuthorized(
|
||||
Action.DELETE,
|
||||
user,
|
||||
attachment.context,
|
||||
attachment.resourceRef,
|
||||
);
|
||||
} else {
|
||||
throw new BadRequestException('Invalid params');
|
||||
|
||||
@@ -16,7 +16,7 @@ export const attachment: Attachment = {
|
||||
size: 343370,
|
||||
location:
|
||||
'/Screenshot from 2022-03-11 08-41-27-2a9799a8b6109c88fd9a7a690c1101934c.png',
|
||||
context: 'block_attachment',
|
||||
resourceRef: 'block_attachment',
|
||||
access: 'public',
|
||||
id: '65940d115178607da65c82b6',
|
||||
createdAt: new Date(),
|
||||
@@ -47,7 +47,7 @@ export const attachments: Attachment[] = [
|
||||
location:
|
||||
'/app/src/attachment/uploads/Screenshot from 2022-03-11 08-41-27-2a9799a8b6109c88fd9a7a690c1101934c.png',
|
||||
channel: { ['some-channel']: {} },
|
||||
context: 'block_attachment',
|
||||
resourceRef: 'block_attachment',
|
||||
access: 'public',
|
||||
id: '65940d115178607da65c82b7',
|
||||
createdAt: new Date(),
|
||||
@@ -62,7 +62,7 @@ export const attachments: Attachment[] = [
|
||||
location:
|
||||
'/app/src/attachment/uploads/Screenshot from 2022-03-18 08-58-15-af61e7f71281f9fd3f1ad7ad10107741c.png',
|
||||
channel: { ['some-channel']: {} },
|
||||
context: 'block_attachment',
|
||||
resourceRef: 'block_attachment',
|
||||
access: 'public',
|
||||
id: '65940d115178607da65c82b8',
|
||||
createdAt: new Date(),
|
||||
|
||||
@@ -25,11 +25,11 @@ import {
|
||||
|
||||
import {
|
||||
AttachmentAccess,
|
||||
AttachmentContext,
|
||||
AttachmentCreatedByRef,
|
||||
AttachmentResourceRef,
|
||||
TAttachmentAccess,
|
||||
TAttachmentContext,
|
||||
TAttachmentCreatedByRef,
|
||||
TAttachmentResourceRef,
|
||||
} from '../types';
|
||||
import { MIME_REGEX } from '../utilities';
|
||||
|
||||
@@ -97,13 +97,13 @@ export class AttachmentStub extends BaseSchema {
|
||||
createdByRef: TAttachmentCreatedByRef;
|
||||
|
||||
/**
|
||||
* Context of the attachment
|
||||
* Resource reference of the attachment
|
||||
*/
|
||||
@Prop({ type: String, enum: Object.values(AttachmentContext) })
|
||||
context: TAttachmentContext;
|
||||
@Prop({ type: String, enum: Object.values(AttachmentResourceRef) })
|
||||
resourceRef: TAttachmentResourceRef;
|
||||
|
||||
/**
|
||||
* Context of the attachment
|
||||
* Access level of the attachment
|
||||
*/
|
||||
@Prop({ type: String, enum: Object.values(AttachmentAccess) })
|
||||
access: TAttachmentAccess;
|
||||
|
||||
@@ -30,7 +30,7 @@ import { BaseService } from '@/utils/generics/base-service';
|
||||
import { AttachmentMetadataDto } from '../dto/attachment.dto';
|
||||
import { AttachmentRepository } from '../repositories/attachment.repository';
|
||||
import { Attachment } from '../schemas/attachment.schema';
|
||||
import { TAttachmentContext } from '../types';
|
||||
import { TAttachmentResourceRef } from '../types';
|
||||
import {
|
||||
fileExists,
|
||||
generateUniqueFilename,
|
||||
@@ -158,13 +158,13 @@ export class AttachmentService extends BaseService<Attachment> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the attachment root directory given the context
|
||||
* Get the attachment root directory given the resource reference
|
||||
*
|
||||
* @param context The attachment context
|
||||
* @param ref The attachment resource reference
|
||||
* @returns The root directory path
|
||||
*/
|
||||
getRootDirByContext(context: TAttachmentContext) {
|
||||
return context === 'subscriber_avatar' || context === 'user_avatar'
|
||||
getRootDirByResourceRef(ref: TAttachmentResourceRef) {
|
||||
return ref === 'subscriber_avatar' || ref === 'user_avatar'
|
||||
? config.parameters.avatarDir
|
||||
: config.parameters.uploadDir;
|
||||
}
|
||||
@@ -186,7 +186,7 @@ export class AttachmentService extends BaseService<Attachment> {
|
||||
const storedDto = await this.getStoragePlugin()?.store?.(file, metadata);
|
||||
return storedDto ? await this.create(storedDto) : null;
|
||||
} else {
|
||||
const rootDir = this.getRootDirByContext(metadata.context);
|
||||
const rootDir = this.getRootDirByResourceRef(metadata.resourceRef);
|
||||
const uniqueFilename = generateUniqueFilename(metadata.name);
|
||||
const filePath = resolve(join(rootDir, sanitizeFilename(uniqueFilename)));
|
||||
|
||||
@@ -244,7 +244,7 @@ export class AttachmentService extends BaseService<Attachment> {
|
||||
|
||||
return streamableFile;
|
||||
} else {
|
||||
const rootDir = this.getRootDirByContext(attachment.context);
|
||||
const rootDir = this.getRootDirByResourceRef(attachment.resourceRef);
|
||||
const path = resolve(join(rootDir, attachment.location));
|
||||
|
||||
if (!fileExists(path)) {
|
||||
|
||||
@@ -20,10 +20,10 @@ export enum AttachmentCreatedByRef {
|
||||
export type TAttachmentCreatedByRef = `${AttachmentCreatedByRef}`;
|
||||
|
||||
/**
|
||||
* Defines the various contexts in which an attachment can exist.
|
||||
* These contexts influence how the attachment is uploaded, stored, and accessed:
|
||||
* Defines the various resource references in which an attachment can exist.
|
||||
* These resource references influence how the attachment is uploaded, stored, and accessed:
|
||||
*/
|
||||
export enum AttachmentContext {
|
||||
export enum AttachmentResourceRef {
|
||||
SettingAttachment = 'setting_attachment', // Attachments related to app settings, restricted to users with specific permissions.
|
||||
UserAvatar = 'user_avatar', // Avatar files for users, only the current user can upload, accessible to those with appropriate permissions.
|
||||
SubscriberAvatar = 'subscriber_avatar', // Avatar files for subscribers, uploaded programmatically, accessible to authorized users.
|
||||
@@ -32,7 +32,7 @@ export enum AttachmentContext {
|
||||
MessageAttachment = 'message_attachment', // Files sent or received via messages, uploaded programmatically, accessible to users with inbox permissions.;
|
||||
}
|
||||
|
||||
export type TAttachmentContext = `${AttachmentContext}`;
|
||||
export type TAttachmentResourceRef = `${AttachmentResourceRef}`;
|
||||
|
||||
export enum AttachmentAccess {
|
||||
Public = 'public',
|
||||
|
||||
@@ -15,7 +15,7 @@ import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import { config } from '@/config';
|
||||
|
||||
import { AttachmentContext, TAttachmentContext } from '../types';
|
||||
import { AttachmentResourceRef, TAttachmentResourceRef } from '../types';
|
||||
|
||||
export const MIME_REGEX = /^[a-z-]+\/[0-9a-z\-.]+$/gm;
|
||||
|
||||
@@ -82,27 +82,30 @@ export const generateUniqueFilename = (originalname: string) => {
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks if the given context is of type TAttachmentContext.
|
||||
* Checks if the given ref is of type TAttachmentResourceRef.
|
||||
*
|
||||
* @param ctx - The context to check.
|
||||
* @returns True if the context is of type TAttachmentContext, otherwise false.
|
||||
* @param ref - The ref to check.
|
||||
* @returns True if the ref is of type TAttachmentResourceRef, otherwise false.
|
||||
*/
|
||||
export const isAttachmentContext = (ctx: any): ctx is TAttachmentContext => {
|
||||
return Object.values(AttachmentContext).includes(ctx);
|
||||
export const isAttachmentResourceRef = (
|
||||
ref: any,
|
||||
): ref is TAttachmentResourceRef => {
|
||||
return Object.values(AttachmentResourceRef).includes(ref);
|
||||
};
|
||||
AttachmentResourceRef;
|
||||
|
||||
/**
|
||||
* Checks if the given list is an array of TAttachmentContext.
|
||||
* Checks if the given list is an array of TAttachmentResourceRef.
|
||||
*
|
||||
* @param ctxList - The list of contexts to check.
|
||||
* @returns True if all items in the list are of type TAttachmentContext, otherwise false.
|
||||
* @param refList - The list of resource references to check.
|
||||
* @returns True if all items in the list are of type TAttachmentResourceRef, otherwise false.
|
||||
*/
|
||||
export const isAttachmentContextArray = (
|
||||
ctxList: any,
|
||||
): ctxList is TAttachmentContext[] => {
|
||||
export const isAttachmentResourceRefArray = (
|
||||
refList: any,
|
||||
): refList is TAttachmentResourceRef[] => {
|
||||
return (
|
||||
Array.isArray(ctxList) &&
|
||||
ctxList.length > 0 &&
|
||||
ctxList.every(isAttachmentContext)
|
||||
Array.isArray(refList) &&
|
||||
refList.length > 0 &&
|
||||
refList.every(isAttachmentResourceRef)
|
||||
);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user