Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 | 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 20x 20x 2x 2x 1x 1x 20x 2x 1x 1x 1x 22x 4x 4x 2x 2x 1x 1x 22x 19x 19x 14x 14x 5x 1x 4x 2x 2x 1x 1x 22x 4x 4x 2x 3x 2x 1x 1x 22x 6x 6x 2x 2x 4x 1x 3x 1x 2x 1x 1x | import { z } from 'zod';
import type { App } from '../../../infrastructure/http/build-app';
import { CreateBabyInviteUseCase } from '../../../application/invite/create-baby-invite.use-case';
import { GetInviteByCodeUseCase } from '../../../application/invite/get-invite-by-code.use-case';
import { RedeemInviteUseCase } from '../../../application/invite/redeem-invite.use-case';
import { ListBabyGuardiansUseCase } from '../../../application/baby/list-baby-guardians.use-case';
import { RemoveBabyGuardianUseCase } from '../../../application/baby/remove-baby-guardian.use-case';
import { BabyNotFoundError } from '../../../application/baby/errors/baby-not-found.error';
import { GuardianNotFoundError } from '../../../application/baby/errors/guardian-not-found.error';
import { CannotRemoveOwnerError } from '../../../application/baby/errors/cannot-remove-owner.error';
import { GuardianForbiddenError } from '../../../application/baby/errors/guardian-forbidden.error';
import { InviteNotFoundError } from '../../../application/invite/errors/invite-not-found.error';
import { InviteNoLongerValidError } from '../../../application/invite/errors/invite-no-longer-valid.error';
import { AlreadyGuardianError } from '../../../application/invite/errors/already-guardian.error';
import { DomainError } from '../../../shared/errors/domain-error';
import { PrismaBabyRepository } from '../../../infrastructure/database/repositories/prisma-baby.repository';
import { PrismaBabyGuardianRepository } from '../../../infrastructure/database/repositories/prisma-baby-guardian.repository';
import { PrismaBabyInviteRepository } from '../../../infrastructure/database/repositories/prisma-baby-invite.repository';
import { PrismaUserRepository } from '../../../infrastructure/database/repositories/prisma-user.repository';
import { prisma } from '../../../infrastructure/database/prisma-client';
import { emailService } from '../../../infrastructure/email/email-service.instance';
import { auditLogger } from '../../../infrastructure/audit/audit-logger.instance';
import { env } from '../../../shared/config/env';
import { authenticate } from '../plugins/authenticate';
import { authErrorResponseSchema } from '../schemas/auth.schema';
import {
createInviteBodySchema,
createInviteResponseSchema,
guardianListResponseSchema,
guardianParamsSchema,
inviteBabyParamsSchema,
inviteCodeParamsSchema,
invitePreviewResponseSchema,
redeemInviteResponseSchema,
} from '../schemas/invite.schema';
export async function inviteRoutes(app: App) {
const babyRepository = new PrismaBabyRepository(prisma);
const babyGuardianRepository = new PrismaBabyGuardianRepository(prisma);
const babyInviteRepository = new PrismaBabyInviteRepository(prisma);
const userRepository = new PrismaUserRepository(prisma);
const createBabyInviteUseCase = new CreateBabyInviteUseCase(babyRepository, babyGuardianRepository, babyInviteRepository);
const getInviteByCodeUseCase = new GetInviteByCodeUseCase(babyRepository, babyInviteRepository);
const redeemInviteUseCase = new RedeemInviteUseCase(babyRepository, babyGuardianRepository, babyInviteRepository);
const listBabyGuardiansUseCase = new ListBabyGuardiansUseCase(babyRepository, babyGuardianRepository, userRepository);
const removeBabyGuardianUseCase = new RemoveBabyGuardianUseCase(babyRepository, babyGuardianRepository);
app.route({
method: 'POST',
url: '/babies/:babyId/invites',
preHandler: authenticate,
schema: {
tags: ['Guardians'],
summary: 'Create a guardian invite for a baby',
description:
'Generates a shareable, single-use invite code that grants GUARDIAN access to the baby once redeemed. ' +
'The requester must already be a guardian (any role) of the baby. If inviteeEmail is provided, an ' +
'invite email is sent best-effort — delivery failure never fails the request, since the code/link ' +
'still works if shared manually.',
params: inviteBabyParamsSchema,
body: createInviteBodySchema,
response: {
201: createInviteResponseSchema,
400: authErrorResponseSchema,
401: authErrorResponseSchema,
404: authErrorResponseSchema,
500: authErrorResponseSchema,
},
},
handler: async (request, reply) => {
try {
const invite = await createBabyInviteUseCase.execute({
babyId: request.params.babyId,
requestingUserId: request.userId,
inviteeEmail: request.body.inviteeEmail,
});
auditLogger.log({
userId: request.userId,
action: 'invite.create',
resourceType: 'BabyInvite',
resourceId: invite.id,
babyId: invite.babyId,
});
if (request.body.inviteeEmail) {
const [baby, inviter] = await Promise.all([
babyRepository.findById(invite.babyId),
userRepository.findById(request.userId),
]);
// A demo session takes one click and proves nothing about who holds it, so it must not
// be a way to make this app mail an arbitrary address. The invite itself still works:
// the code comes back in the response, and the screen offers it to share by hand.
if (baby && inviter && !inviter.isDemo) {
const inviteUrl = `${env.CORS_ORIGIN}/invites/${invite.code}`;
emailService.sendGuardianInviteEmail(request.body.inviteeEmail, inviter.name, baby.name, inviteUrl).catch((error: unknown) => {
request.log.warn({ err: error }, 'invite.email_send_failed');
});
}
}
return reply.status(201).send({
code: invite.code,
expiresAt: invite.expiresAt.toISOString(),
});
} catch (error) {
if (error instanceof BabyNotFoundError) {
return reply.status(404).send({ status: 'error', message: error.message });
}
Iif (error instanceof DomainError) {
return reply.status(400).send({ status: 'error', message: error.message });
}
throw error;
}
},
});
app.route({
method: 'GET',
url: '/invites/:code',
schema: {
tags: ['Guardians'],
summary: 'Preview an invite by its code',
description:
'Public endpoint (no authentication required) so the frontend can show baby name/avatar before the ' +
'user logs in. Always returns 200, even for an expired or already-used invite, so the caller can ' +
'render a clear "no longer valid" message instead of a generic error.',
params: inviteCodeParamsSchema,
response: {
200: invitePreviewResponseSchema,
404: authErrorResponseSchema,
500: authErrorResponseSchema,
},
},
handler: async (request, reply) => {
try {
const preview = await getInviteByCodeUseCase.execute(request.params.code);
return reply.status(200).send(preview);
} catch (error) {
if (error instanceof InviteNotFoundError) {
return reply.status(404).send({ status: 'error', message: error.message });
}
throw error;
}
},
});
app.route({
method: 'POST',
url: '/invites/:code/redeem',
preHandler: authenticate,
schema: {
tags: ['Guardians'],
summary: 'Redeem an invite code',
description:
'Grants the authenticated user GUARDIAN access to the invite\'s baby. 410 if the invite is expired or ' +
'already used, 409 if the requester is already a guardian of the baby.',
params: inviteCodeParamsSchema,
response: {
200: redeemInviteResponseSchema,
401: authErrorResponseSchema,
404: authErrorResponseSchema,
409: authErrorResponseSchema,
410: authErrorResponseSchema,
500: authErrorResponseSchema,
},
},
handler: async (request, reply) => {
try {
const result = await redeemInviteUseCase.execute({
code: request.params.code,
requestingUserId: request.userId,
});
auditLogger.log({
userId: request.userId,
action: 'invite.redeem',
resourceType: 'BabyGuardian',
resourceId: request.userId,
babyId: result.babyId,
});
return reply.status(200).send(result);
} catch (error) {
if (error instanceof InviteNotFoundError) {
return reply.status(404).send({ status: 'error', message: error.message });
}
if (error instanceof InviteNoLongerValidError) {
return reply.status(410).send({ status: 'error', message: error.message });
}
if (error instanceof AlreadyGuardianError) {
return reply.status(409).send({ status: 'error', message: error.message });
}
throw error;
}
},
});
app.route({
method: 'GET',
url: '/babies/:babyId/guardians',
preHandler: authenticate,
schema: {
tags: ['Guardians'],
summary: "List a baby's guardians",
description: 'Returns every adult with access to the baby (the OWNER and any GUARDIANs), newest last.',
params: inviteBabyParamsSchema,
response: {
200: guardianListResponseSchema,
401: authErrorResponseSchema,
404: authErrorResponseSchema,
500: authErrorResponseSchema,
},
},
handler: async (request, reply) => {
try {
const guardians = await listBabyGuardiansUseCase.execute({
babyId: request.params.babyId,
requestingUserId: request.userId,
});
return reply.status(200).send(
guardians.map((guardian) => ({
userId: guardian.userId,
name: guardian.name,
email: guardian.email,
role: guardian.role,
joinedAt: guardian.joinedAt.toISOString(),
})),
);
} catch (error) {
if (error instanceof BabyNotFoundError) {
return reply.status(404).send({ status: 'error', message: error.message });
}
throw error;
}
},
});
app.route({
method: 'DELETE',
url: '/babies/:babyId/guardians/:userId',
preHandler: authenticate,
schema: {
tags: ['Guardians'],
summary: 'Remove a guardian from a baby',
description:
'Removes a GUARDIAN from the baby — either the guardian removing themselves ("leave"), or the OWNER ' +
'removing someone else. The OWNER guardian row itself can never be removed this way (400).',
params: guardianParamsSchema,
response: {
204: z.null().describe('Guardian removed successfully'),
400: authErrorResponseSchema,
401: authErrorResponseSchema,
403: authErrorResponseSchema,
404: authErrorResponseSchema,
500: authErrorResponseSchema,
},
},
handler: async (request, reply) => {
try {
await removeBabyGuardianUseCase.execute({
babyId: request.params.babyId,
targetUserId: request.params.userId,
requestingUserId: request.userId,
});
auditLogger.log({
userId: request.userId,
action: 'guardian.remove',
resourceType: 'BabyGuardian',
resourceId: request.params.userId,
babyId: request.params.babyId,
});
return reply.status(204).send(null);
} catch (error) {
if (error instanceof BabyNotFoundError || error instanceof GuardianNotFoundError) {
return reply.status(404).send({ status: 'error', message: error.message });
}
if (error instanceof CannotRemoveOwnerError) {
return reply.status(400).send({ status: 'error', message: error.message });
}
if (error instanceof GuardianForbiddenError) {
return reply.status(403).send({ status: 'error', message: error.message });
}
throw error;
}
},
});
}
|