Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions apps/api-v2/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,16 @@ import { ApplicationsModule } from "./sections/applications/applications.module"
import { AuthModule } from "./sections/auth/auth.module";
import { StatusModule } from "./sections/status/status.module";
import { UtilityModule } from "./sections/utility/utility.module";
import { ClaimsModule } from "./sections/claims/claims.module";

@Module({
imports: [
UtilityModule,
AuthModule,
ApplicationsModule,
StatusModule,
AuthModule,
ClaimsModule,
ConfigModule.forRoot({ isGlobal: true, cache: true }),
StatusModule,
UtilityModule,
],
providers: [PrismaService, { provide: APP_GUARD, useClass: AuthGuard }],
})
Expand Down
12 changes: 6 additions & 6 deletions apps/api-v2/src/common/db/external/cachet.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import { firstValueFrom } from "rxjs";
@Injectable()
export class CachetAPIService {
private readonly logger = new Logger(CachetAPIService.name);
private baseURL: string;
private apiToken: string;
private baseURL: string | undefined;
private apiToken: string | undefined;

constructor(
private readonly http: HttpService,
Expand All @@ -26,11 +26,11 @@ export class CachetAPIService {
} else {
this.baseURL = this.configService.get<string>("CACHET_URL") as string;
this.apiToken = this.configService.get<string>("CACHET_TOKEN") as string;
}

this.testConnection().then(() => {
this.logger.log("Cachet API is reachable");
});
this.testConnection().then(() => {
this.logger.log("Cachet API is reachable");
});
}
}

async testConnection(): Promise<string> {
Expand Down
6 changes: 4 additions & 2 deletions apps/api-v2/src/common/decorators/api-response.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { ResponseDto } from "../dto/response.dto";
*/
export function ApiDefaultResponse<TModel extends Type<any>>(
model: TModel,
options: ApiResponseOptions = {},
{ isArray, ...options }: ApiResponseOptions & { isArray?: boolean } = {},
) {
return applyDecorators(
ApiExtraModels(ResponseDto, model),
Expand All @@ -30,7 +30,9 @@ export function ApiDefaultResponse<TModel extends Type<any>>(
{ $ref: getSchemaPath(ResponseDto) },
{
properties: {
data: { $ref: getSchemaPath(model) },
data: isArray
? { type: "array", items: { $ref: getSchemaPath(model) } }
: { $ref: getSchemaPath(model) },
},
},
],
Expand Down
18 changes: 18 additions & 0 deletions apps/api-v2/src/common/decorators/optional-auth.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { SetMetadata } from "@nestjs/common";

export const IS_AUTH_OPTIONAL_KEY = "isAuthOptional";

/**
* Decorator that makes authentication optional for a route. By default, routes
* require a valid JWT token.
*
* @example
*
* @OptionalAuth()
* @Get('optional-auth-endpoint')
* async getOptionalAuthData(@Request() req: Request) {
* // req.token may be undefined if no valid token is provided
* }
*
*/
export const OptionalAuth = () => SetMetadata(IS_AUTH_OPTIONAL_KEY, true);
13 changes: 13 additions & 0 deletions apps/api-v2/src/common/guards/auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { Reflector } from "@nestjs/core";
import { JwtService } from "@nestjs/jwt";
import { Request } from "express";
import { IS_PUBLIC_KEY } from "../decorators/skip-auth.decorator";
import { IS_AUTH_OPTIONAL_KEY } from "../decorators/optional-auth.decorator";
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
Expand All @@ -31,16 +32,28 @@ export class AuthGuard implements CanActivate {
return true;
}

const isOptional = this.reflector.getAllAndOverride<boolean>(
IS_AUTH_OPTIONAL_KEY,
[context.getHandler(), context.getClass()],
);

// If the route is not public, we proceed with authentication
const request = context.switchToHttp().getRequest<Request>();
const token = this.extractTokenFromHeader(request);

if (!token && isOptional) {
return true;
}

if (!token) {
throw new UnauthorizedException();
}

try {
const payload = await this.jwtService.verifyAsync(token);
request["token"] = payload;
} catch {
// If auth is optional but failed to verify, we still reject the request
throw new UnauthorizedException();
}
return true;
Expand Down
2 changes: 1 addition & 1 deletion apps/api-v2/src/sections/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { AuthService } from "./auth.service";
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
secret: configService.get<string>("JWT_SECRET"),
secret: configService.getOrThrow<string>("JWT_SECRET"),
signOptions: { issuer: "api" },
}),
}),
Expand Down
51 changes: 51 additions & 0 deletions apps/api-v2/src/sections/claims/claims.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { Controller, Get, Req } from "@nestjs/common";
import { ClaimsService } from "./claims.service";
import { Filtered } from "src/common/decorators/filtered.decorator";
import { ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
import { ClaimDto } from "./dto/claim.dto";
import { ApiDefaultResponse } from "src/common/decorators/api-response.decorator";
import { Filter, FilterParams } from "src/common/decorators/filter.decorator";
import { Request } from "express";
import { OptionalAuth } from "src/common/decorators/optional-auth.decorator";

@Controller("claims")
export class ClaimsController {
constructor(private readonly claimsService: ClaimsService) {}

@Get()
@OptionalAuth()
@ApiBearerAuth()
@ApiOperation({
summary: "Get All Claims",
description:
"Returns all claims for the given team. If no team is specified, returns claims for the authenticated team.",
})
@Filtered({
fields: [
{ name: "finished", required: false, type: Boolean },
{ name: "active", required: false, type: Boolean },
{ name: "team", required: false, type: String },
{ name: "slug", required: false, type: Boolean },
],
})
@ApiDefaultResponse(ClaimDto, {
description: "List of claims matching the filters.",
isArray: true,
})
findAll(@Filter() filter: FilterParams, @Req() req: Request) {
const { team, slug, ...otherFilters }: { team?: string; slug?: boolean } =
filter.filter;

const teamFilter: {
buildTeamId?: string;
buildTeam?: { slug: string };
} = (() => {
if (!team && req.token) return { buildTeamId: req.token.id };
if (!team) return {};
if (slug) return { buildTeam: { slug: team } };
return { buildTeamId: team };
})();

return this.claimsService.findAll({ ...otherFilters, ...teamFilter });
}
}
10 changes: 10 additions & 0 deletions apps/api-v2/src/sections/claims/claims.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Module } from "@nestjs/common";
import { PrismaService } from "src/common/db/prisma.service";
import { ClaimsController } from "./claims.controller";
import { ClaimsService } from "./claims.service";

@Module({
controllers: [ClaimsController],
providers: [ClaimsService, PrismaService],
})
export class ClaimsModule {}
18 changes: 18 additions & 0 deletions apps/api-v2/src/sections/claims/claims.service.ts
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Potentially add pagination and sorting like in /applications (not done)

Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Injectable } from "@nestjs/common";
import { FilterParams } from "src/common/decorators/filter.decorator";
import { PrismaService } from "src/common/db/prisma.service";

@Injectable()
export class ClaimsService {
constructor(private readonly prisma: PrismaService) {}

async findAll(filter: FilterParams["filter"]) {
return this.prisma.claim.findMany({
where: filter,
include: {
_count: { select: { builders: true, images: true } },
images: { select: { id: true, name: true, hash: true } },
},
});
}
}
28 changes: 28 additions & 0 deletions apps/api-v2/src/sections/claims/dto/claim.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
export class ClaimDto {
id: string;
ownerId: string | null;
area: string[];
center: string | null;
size: number;
active: boolean;
finished: boolean;
buildTeamId: string;
name: string;
createdAt: string;
externalId: string | null;
description: string | null;
buildings: number;
city: string | null;
osmName: string | null;

_count: {
builders: number;
images: number;
};

images: {
id: string;
name: string;
hash: string;
}[];
}