66
77import { CanActivate , ExecutionContext , HttpException , HttpStatus , Injectable , Logger } from '@nestjs/common'
88import { Reflector } from '@nestjs/core'
9+ import { HTTP_METHOD } from '../../applications.constants'
910import { COLLABORA_CONTEXT } from '../../files/modules/collabora-online/collabora-online.constants'
1011import { COLLABORA_ONLINE_TO_SPACE_SEGMENTS } from '../../files/modules/collabora-online/collabora-online.utils'
12+ import { isPathExists , isPathIsDir } from '../../files/utils/files'
1113import { SYNC_CONTEXT } from '../../sync/decorators/sync-context.decorator'
1214import { SYNC_PATH_TO_SPACE_SEGMENTS } from '../../sync/utils/routes'
1315import { WEB_DAV_CONTEXT } from '../../webdav/decorators/webdav-context.decorator'
@@ -31,8 +33,16 @@ export class SpaceGuard implements CanActivate {
3133 private readonly spacesManager : SpacesManager
3234 ) { }
3335
34- static checkPermissions ( req : FastifySpaceRequest , logger : Logger , overrideSpacePermission ?: SPACE_OPERATION ) {
35- const permission = overrideSpacePermission || SPACE_HTTP_PERMISSION [ req . method ]
36+ static async checkPermissions ( req : FastifySpaceRequest , logger : Logger , overrideSpacePermission ?: SPACE_OPERATION ) {
37+ let permission : SPACE_OPERATION
38+ if ( req . method === HTTP_METHOD . PUT && ( await isPathExists ( req . space . realPath ) ) && ! ( await isPathIsDir ( req . space . realPath ) ) ) {
39+ // PUT method may either create a new resource or replace an existing one.
40+ // Therefore, we must check whether the target resource already exists to apply the appropriate permission rules.
41+ permission = SPACE_OPERATION . MODIFY
42+ } else {
43+ // The override is applied for specific POST methods that update an existing file rather than creating it.
44+ permission = overrideSpacePermission || SPACE_HTTP_PERMISSION [ req . method ]
45+ }
3646 if ( ! haveSpaceEnvPermissions ( req . space , permission ) ) {
3747 logger . warn ( `is not allowed to ${ req . method } on this space path : *${ req . space . alias } * (${ req . space . id } ) : ${ req . space . url } ` )
3848 throw new HttpException ( 'You are not allowed to do this action' , HttpStatus . FORBIDDEN )
@@ -81,7 +91,7 @@ export class SpaceGuard implements CanActivate {
8191 const skipSpacePermissionsCheck = this . reflector . getAllAndOverride ( SKIP_SPACE_PERMISSIONS_CHECK , [ ctx . getHandler ( ) , ctx . getClass ( ) ] )
8292 if ( skipSpacePermissionsCheck === undefined ) {
8393 const overrideSpacePermission : SPACE_OPERATION = this . reflector . getAllAndOverride ( OverrideSpacePermission , [ ctx . getHandler ( ) , ctx . getClass ( ) ] )
84- SpaceGuard . checkPermissions ( req , this . logger , overrideSpacePermission )
94+ await SpaceGuard . checkPermissions ( req , this . logger , overrideSpacePermission )
8595 }
8696 return true
8797 }
0 commit comments