Skip to content
Merged
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
60 changes: 60 additions & 0 deletions database.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2136,6 +2136,30 @@ export type Database = {
},
]
}
legal_documents: {
Row: {
current_version: number
effective_at: string
kind: string
updated_at: string
url: string
}
Insert: {
current_version?: number
effective_at?: string
kind: string
updated_at?: string
url: string
}
Update: {
current_version?: number
effective_at?: string
kind?: string
updated_at?: string
url?: string
}
Relationships: []
}
locations: {
Row: {
created_at: string | null
Expand Down Expand Up @@ -2217,6 +2241,42 @@ export type Database = {
},
]
}
profile_legal_acceptances: {
Row: {
accepted_at: string
kind: string
user_id: string
version: number
}
Insert: {
accepted_at?: string
kind: string
user_id: string
version: number
}
Update: {
accepted_at?: string
kind?: string
user_id?: string
version?: number
}
Relationships: [
{
foreignKeyName: "profile_legal_acceptances_kind_fkey"
columns: ["kind"]
isOneToOne: false
referencedRelation: "legal_documents"
referencedColumns: ["kind"]
},
{
foreignKeyName: "profile_legal_acceptances_user_id_fkey"
columns: ["user_id"]
isOneToOne: false
referencedRelation: "profiles"
referencedColumns: ["id"]
},
]
}
profile_preferences: {
Row: {
area_unit: string | null
Expand Down
52 changes: 52 additions & 0 deletions src/v1/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { LoginResponseDto } from './dto/login-response.dto';
import { UpdateUserProfileDto } from './dto/update-user-profile.dto';
import { UpdateEmailDto } from './dto/update-email.dto';
import { UpdatePreferencesDto } from './dto/update-preferences.dto';
import { AcceptLegalDto } from './dto/accept-legal.dto';

@Controller({ path: 'auth', version: '1' })
@ApiBearerAuth('bearerAuth')
Expand Down Expand Up @@ -190,6 +191,57 @@ export class AuthController {
return this.authService.updatePreferences(body, user);
}

@Get('legal-status')
@UseGuards(JwtAuthGuard)
@ApiOperation({
summary:
'Which legal documents (ToS/EULA/privacy) the user still has to accept',
})
@ApiOkResponse({
description: 'Per-document acceptance status returned successfully.',
schema: { type: 'object', additionalProperties: true },
})
@ApiUnauthorizedResponse({
description: 'Missing or invalid bearer token.',
type: ErrorResponseDto,
})
@ApiInternalServerErrorResponse({
description: 'Failed to read legal status.',
type: ErrorResponseDto,
})
async getLegalStatus(@CurrentUser() user: AuthenticatedUser) {
return this.authService.getLegalStatus(user);
}

@Post('legal-acceptance')
@UseGuards(JwtAuthGuard)
@ApiOperation({
summary:
'Record acceptance of the current version of the given legal documents',
})
@ApiOkResponse({
description: 'Acceptance recorded; fresh legal status returned.',
schema: { type: 'object', additionalProperties: true },
})
@ApiBadRequestResponse({
description: 'Invalid or unknown document kind.',
type: ErrorResponseDto,
})
@ApiUnauthorizedResponse({
description: 'Missing or invalid bearer token.',
type: ErrorResponseDto,
})
@ApiInternalServerErrorResponse({
description: 'Failed to record legal acceptance.',
type: ErrorResponseDto,
})
async acceptLegal(
@Body() body: AcceptLegalDto,
@CurrentUser() user: AuthenticatedUser,
) {
return this.authService.acceptLegal(body, user);
}

@Throttle({ default: { limit: 2, ttl: 60000 } })
@Post('login')
@ApiOperation({ summary: 'Login with email and password' })
Expand Down
129 changes: 129 additions & 0 deletions src/v1/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,31 @@ import type { TableRow } from '../types/supabase';
import type { AuthenticatedUser } from './authenticated-user';
import { UpdateUserProfileDto } from './dto/update-user-profile.dto';
import { UpdatePreferencesDto } from './dto/update-preferences.dto';
import { AcceptLegalDto } from './dto/accept-legal.dto';

// Accounts on these domains are locked to their corporate identity and may not
// change their email address (checked against the caller's current email).
const RESTRICTED_EMAIL_CHANGE_DOMAINS = ['@cropwatch.io', '@cropwatch.co.jp'];

type ProfileRow = TableRow<'profiles'>;
type PreferencesRow = TableRow<'profile_preferences'>;
type LegalDocumentRow = TableRow<'legal_documents'>;
type LegalAcceptanceRow = TableRow<'profile_legal_acceptances'>;

export interface LegalDocumentStatus {
kind: string;
current_version: number;
url: string;
effective_at: string;
accepted_version: number | null;
accepted_at: string | null;
needs_acceptance: boolean;
}

export interface LegalStatus {
needs_acceptance: boolean;
documents: LegalDocumentStatus[];
}

/** Shape of a PostgREST single/maybeSingle response from the untyped client. */
type QueryResult<T> = { data: T | null; error: PostgrestError | null };
Expand Down Expand Up @@ -323,6 +341,117 @@ export class AuthService {
return data;
}

/**
* Which legal documents (ToS / EULA / privacy) the caller still has to
* accept: their latest recorded acceptance per document vs. the currently
* published version in legal_documents.
*/
async getLegalStatus(user: AuthenticatedUser): Promise<LegalStatus> {
const client = this.supabaseService.getClient();
const userId = user.sub;

const { data: documents, error: documentsError } = (await client
.from('legal_documents')
.select('*')
.order('kind')) as {
data: LegalDocumentRow[] | null;
error: PostgrestError | null;
};
if (documentsError || !documents) {
throw new InternalServerErrorException('Failed to read legal documents');
}

const { data: acceptances, error: acceptancesError } = (await client
.from('profile_legal_acceptances')
.select('kind, version, accepted_at')
.eq('user_id', userId)) as {
data:
| Pick<LegalAcceptanceRow, 'kind' | 'version' | 'accepted_at'>[]
| null;
error: PostgrestError | null;
};
if (acceptancesError) {
throw new InternalServerErrorException(
'Failed to read legal acceptances',
);
}

const documentStatuses: LegalDocumentStatus[] = documents.map((doc) => {
let acceptedVersion: number | null = null;
let acceptedAt: string | null = null;
for (const acceptance of acceptances ?? []) {
if (
acceptance.kind === doc.kind &&
(acceptedVersion === null || acceptance.version > acceptedVersion)
) {
acceptedVersion = acceptance.version;
acceptedAt = acceptance.accepted_at;
}
}
return {
kind: doc.kind,
current_version: doc.current_version,
url: doc.url,
effective_at: doc.effective_at,
accepted_version: acceptedVersion,
accepted_at: acceptedAt,
needs_acceptance:
acceptedVersion === null || acceptedVersion < doc.current_version,
};
});

return {
needs_acceptance: documentStatuses.some((doc) => doc.needs_acceptance),
documents: documentStatuses,
};
}

/**
* Record the caller's acceptance of the CURRENT version of each requested
* document. Versions are stamped server-side; re-accepting an already
* accepted version is a no-op that preserves the original accepted_at.
*/
async acceptLegal(
dto: AcceptLegalDto,
user: AuthenticatedUser,
): Promise<LegalStatus> {
const client = this.supabaseService.getClient();
const userId = user.sub;
const kinds = [...new Set(dto.kinds)];

const { data: documents, error: documentsError } = (await client
.from('legal_documents')
.select('kind, current_version')
.in('kind', kinds)) as {
data: Pick<LegalDocumentRow, 'kind' | 'current_version'>[] | null;
error: PostgrestError | null;
};
if (documentsError || !documents) {
throw new InternalServerErrorException('Failed to read legal documents');
}
if (documents.length !== kinds.length) {
throw new BadRequestException('Unknown legal document kind');
}

const { error: upsertError } = await client
.from('profile_legal_acceptances')
.upsert(
documents.map((doc) => ({
user_id: userId,
kind: doc.kind,
version: doc.current_version,
})),
{ onConflict: 'user_id,kind,version', ignoreDuplicates: true },
);
if (upsertError) {
throw new InternalServerErrorException(
'Failed to record legal acceptance',
);
}

return this.getLegalStatus(user);
}

private readBearerToken(authHeader: string | undefined): string {
const rawHeader = authHeader?.trim() ?? '';
const [scheme, token] = rawHeader.split(' ');
Expand Down
20 changes: 20 additions & 0 deletions src/v1/auth/dto/accept-legal.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { ApiProperty } from '@nestjs/swagger';
import { ArrayNotEmpty, IsArray, IsIn } from 'class-validator';

export const LEGAL_DOCUMENT_KINDS = [
'privacy_policy',
'terms_of_service',
'eula',
] as const;

export type LegalDocumentKind = (typeof LEGAL_DOCUMENT_KINDS)[number];

// Deliberately no version field: the server stamps the current version itself,
// so a client can never record acceptance of a version it was not shown.
export class AcceptLegalDto {
@ApiProperty({ isArray: true, enum: LEGAL_DOCUMENT_KINDS })
@IsArray()
@ArrayNotEmpty()
@IsIn(LEGAL_DOCUMENT_KINDS, { each: true })
kinds: LegalDocumentKind[];
}
36 changes: 36 additions & 0 deletions src/v1/common/__snapshots__/v1-route-input-contract.spec.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,25 @@ exports[`V1 Route Input Contracts matches the full v1 request contract snapshot
{
"components": {
"schemas": {
"AcceptLegalDto": {
"properties": {
"kinds": {
"items": {
"enum": [
"privacy_policy",
"terms_of_service",
"eula",
],
"type": "string",
},
"type": "array",
},
},
"required": [
"kinds",
],
"type": "object",
},
"CreateAirAnnotationDto": {
"properties": {
"created_at": {
Expand Down Expand Up @@ -689,6 +708,23 @@ exports[`V1 Route Input Contracts matches the full v1 request contract snapshot
},
},
},
"/v1/auth/legal-acceptance": {
"post": {
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/AcceptLegalDto",
},
},
},
"required": true,
},
},
},
"/v1/auth/legal-status": {
"get": {},
},
"/v1/auth/login": {
"post": {
"requestBody": {
Expand Down
17 changes: 16 additions & 1 deletion src/v1/common/v1-route-input-contract.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@
beforeAll(async () => {
serviceRegistry = {
air: createMockedMethods(['createNote', 'findOne']),
auth: createMockedMethods(['loginWithPassword']),
auth: createMockedMethods(['loginWithPassword', 'acceptLegal']),
devices: createMockedMethods([
'findAll',
'findAllStatus',
Expand Down Expand Up @@ -467,6 +467,21 @@
rememberMe: true,
},
},
{
auth: true,
expectedCall: {
args: [{ kinds: ['terms_of_service', 'eula'] }, MOCK_USER],
method: 'acceptLegal',
service: 'auth',
},
expectedStatus: 201,
method: 'post',
name: 'POST /v1/auth/legal-acceptance accepts the current body shape',
url: '/v1/auth/legal-acceptance',
body: {
kinds: ['terms_of_service', 'eula'],
},
},
{
auth: true,
expectedCall: {
Expand Down Expand Up @@ -1071,7 +1086,7 @@
];

it.each(successCases)('$name', async (testCase) => {
let req = request(app.getHttpServer())[testCase.method](testCase.url);

Check warning on line 1089 in src/v1/common/v1-route-input-contract.spec.ts

View workflow job for this annotation

GitHub Actions / build

Unsafe argument of type `any` assigned to a parameter of type `App`

Check warning on line 1089 in src/v1/common/v1-route-input-contract.spec.ts

View workflow job for this annotation

GitHub Actions / build

Unsafe argument of type `any` assigned to a parameter of type `App`

if (testCase.auth) {
req = req.set('Authorization', AUTH_HEADER);
Expand Down Expand Up @@ -1109,7 +1124,7 @@
});

it.each(rejectionCases)('$name', async (testCase) => {
let req = request(app.getHttpServer())[testCase.method](testCase.url);

Check warning on line 1127 in src/v1/common/v1-route-input-contract.spec.ts

View workflow job for this annotation

GitHub Actions / build

Unsafe argument of type `any` assigned to a parameter of type `App`

Check warning on line 1127 in src/v1/common/v1-route-input-contract.spec.ts

View workflow job for this annotation

GitHub Actions / build

Unsafe argument of type `any` assigned to a parameter of type `App`

if (testCase.auth) {
req = req.set('Authorization', AUTH_HEADER);
Expand Down
Loading
Loading