50 lines
1.2 KiB
TypeScript
50 lines
1.2 KiB
TypeScript
import {
|
|
CanActivate,
|
|
ExecutionContext,
|
|
Inject,
|
|
Injectable,
|
|
UnauthorizedException,
|
|
} from "@nestjs/common";
|
|
import { QueryHandlerService } from "src/query/handler/query.handler.service";
|
|
|
|
@Injectable()
|
|
export class QueryGuard implements CanActivate {
|
|
constructor(
|
|
@Inject(QueryHandlerService)
|
|
private readonly queryHandlerService: QueryHandlerService
|
|
) {}
|
|
|
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
const request = context.switchToHttp().getRequest();
|
|
const apiToken = request.apiToken;
|
|
|
|
if (!apiToken || !apiToken.project) {
|
|
throw new UnauthorizedException("Project not found for the API token");
|
|
}
|
|
|
|
const queryId = request.params?.id;
|
|
|
|
if (!queryId) {
|
|
throw new UnauthorizedException("Query ID is required");
|
|
}
|
|
|
|
const query = await this.queryHandlerService.getQueryById(queryId);
|
|
|
|
if (!query) {
|
|
throw new UnauthorizedException("Query not found");
|
|
}
|
|
|
|
if (!query.isActive) {
|
|
throw new UnauthorizedException("Query is inactive");
|
|
}
|
|
|
|
if (query.project.id !== apiToken.project.id) {
|
|
throw new UnauthorizedException("You do not have access to this query");
|
|
}
|
|
|
|
request.query = query;
|
|
|
|
return true;
|
|
}
|
|
}
|