63 lines
1.7 KiB
TypeScript
63 lines
1.7 KiB
TypeScript
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
|
|
import { Request } from 'express';
|
|
import { Storage } from 'src/objects/storage/entities/storage.entity';
|
|
import { StorageService } from 'src/objects/storage/storage.service';
|
|
import { User } from 'src/objects/user/user.entity';
|
|
|
|
@Injectable()
|
|
export class StorageGuard 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.storageId == null &&
|
|
request.body?.storageId == null &&
|
|
request.query?.storageId == null
|
|
) {
|
|
return true;
|
|
}
|
|
|
|
const storageId = parseInt(
|
|
request.params.storageId ||
|
|
request.body?.storageId ||
|
|
request.query?.storageId,
|
|
10,
|
|
);
|
|
|
|
if (!storageId || isNaN(storageId)) return false;
|
|
|
|
let storageAccess: Storage;
|
|
if (response.locals.room) {
|
|
storageAccess = await this.storageService.getStorageByIdAndRoom(
|
|
storageId,
|
|
response.locals.room.id,
|
|
['addedBy'],
|
|
);
|
|
} else if (response.locals.building) {
|
|
storageAccess = await this.storageService.getStorageByIdAndBuilding(
|
|
storageId,
|
|
response.locals.building.id,
|
|
['addedBy'],
|
|
);
|
|
} else {
|
|
storageAccess = await this.storageService.getStorageByIdAndSub(
|
|
storageId,
|
|
user.sub,
|
|
['addedBy'],
|
|
);
|
|
}
|
|
|
|
if (!storageAccess) return false;
|
|
response.locals.storage = storageAccess;
|
|
|
|
return true;
|
|
}
|
|
}
|