63 lines
1.8 KiB
TypeScript
63 lines
1.8 KiB
TypeScript
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
|
|
import { Request } from 'express';
|
|
import { StorageSet } from 'src/objects/storage/entities/storage-set.entity';
|
|
import { StorageService } from 'src/objects/storage/storage.service';
|
|
import { User } from 'src/objects/user/user.entity';
|
|
|
|
@Injectable()
|
|
export class StorageSetGuard implements CanActivate {
|
|
constructor(private readonly storageService: StorageService) {}
|
|
|
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
const http = context.switchToHttp();
|
|
const request = http.getRequest() as Request;
|
|
const response = http.getResponse();
|
|
|
|
const user = response.locals.user as User;
|
|
if (!user) return false;
|
|
|
|
if (
|
|
request.params.storageSetId == null &&
|
|
request.body?.storageSetId == null &&
|
|
request.query?.storageSetId == null
|
|
) {
|
|
return true;
|
|
}
|
|
|
|
const storageSetId = parseInt(
|
|
request.params.storageSetId ||
|
|
request.body?.storageSetId ||
|
|
request.query?.storageSetId,
|
|
10,
|
|
);
|
|
|
|
if (!storageSetId || isNaN(storageSetId)) return false;
|
|
|
|
let storageSetAccess: StorageSet;
|
|
if (response.locals.room) {
|
|
storageSetAccess = await this.storageService.getStorageSetByIdAndRoom(
|
|
storageSetId,
|
|
response.locals.room.id,
|
|
['addedBy'],
|
|
);
|
|
} else if (response.locals.building) {
|
|
storageSetAccess = await this.storageService.getStorageSetByIdAndBuilding(
|
|
storageSetId,
|
|
response.locals.building.id,
|
|
['addedBy'],
|
|
);
|
|
} else {
|
|
storageSetAccess = await this.storageService.getStorageSetByIdAndSub(
|
|
storageSetId,
|
|
user.sub,
|
|
['addedBy'],
|
|
);
|
|
}
|
|
|
|
if (!storageSetAccess) return false;
|
|
response.locals.storageSet = storageSetAccess;
|
|
|
|
return true;
|
|
}
|
|
}
|