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
25 changes: 25 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2022,
"sourceType": "module"
},
"plugins": ["@typescript-eslint"],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"prettier"
],
"env": {
"node": true,
"es2022": true,
"jest": true
},
"rules": {
"@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }],
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/no-explicit-any": "warn"
},
"ignorePatterns": ["dist", "cdk.out", "node_modules", "*.js"]
}
52 changes: 52 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
name: CI

on:
push:
branches: ["**"]
pull_request:
branches: [main]

permissions:
contents: read

jobs:
validate:
name: validate
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4

- name: Set up pnpm
uses: pnpm/action-setup@v4
with:
version: 10.7.1

- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: pnpm

- name: Install dependencies
run: pnpm install --frozen-lockfile

- name: Lint
run: pnpm run lint

- name: Typecheck (backend + infrastructure)
run: pnpm run typecheck

- name: Unit tests (Lambda handlers, services, repositories)
run: pnpm run test:coverage

- name: Upload coverage report
if: always()
uses: actions/upload-artifact@v4
with:
name: backend-coverage
path: backend/coverage
retention-days: 14

- name: cdk synth (validates every stack builds without deploying)
run: pnpm run synth
19 changes: 19 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,22 @@ dist
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
.vite/

# AWS CDK
cdk.out/
infrastructure/cdk.out/
infrastructure/cdk.context.json
*.d.ts
!frontend/**/*.d.ts

# Build output (workspaces)
backend/dist/
infrastructure/dist/

# Local env / secrets
.env.local
.env.*.local

# OS files
.DS_Store

7 changes: 7 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100,
"tabWidth": 2
}
153 changes: 152 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,152 @@
# Azubi_Final_Capstone
# Event Registration & Ticketing System

[![CI](https://github.com/ForkYeahMan/Azubi_Final_Capstone/actions/workflows/ci.yml/badge.svg)](https://github.com/ForkYeahMan/Azubi_Final_Capstone/actions/workflows/ci.yml)

A serverless Event Registration & Ticketing System on AWS — replaces
Microsoft Forms + Excel with a scalable REST API. Admins, Event Organizers,
and Users each get a role-scoped API; events go through an approval
workflow before they're public; registration issues an organizer-provided
ticket link by email.

See [docs/architecture.md](docs/architecture.md) for the system design,
[docs/data-model.md](docs/data-model.md) for the DynamoDB schema,
[docs/api.md](docs/api.md) for the full endpoint reference,
[docs/security.md](docs/security.md) for the API security controls applied,
[docs/branching-strategy.md](docs/branching-strategy.md) for how changes
flow into `main`, and [docs/decisions.md](docs/decisions.md) for why each
major choice was made.

## Monorepo layout

```text
.
├── backend/ Lambda source (TypeScript) — handlers, services, repositories
├── infrastructure/ AWS CDK app (TypeScript) — one stack per concern
├── frontend/ placeholder — design/build pending further instructions
├── docs/ architecture, data model, API reference, ADRs
├── scripts/ seed-admin.ts — creates the first Admin account
└── .github/workflows/ CI — lint, typecheck, unit tests, cdk synth on every push/PR
```

Backend and infrastructure are pnpm workspaces sharing one `pnpm install`
and one TypeScript toolchain.

## Prerequisites

- Node.js 20+ and [pnpm](https://pnpm.io) 9+ (`corepack enable` or
`npm install -g pnpm`)
- An AWS account with credentials configured (`aws configure` or SSO)
- `cdk bootstrap` run once per account/region (see below)

## Setup

```bash
pnpm install
```

This installs both workspaces (`backend`, `infrastructure`) and the root
tooling (ESLint, Prettier, ts-node for `scripts/`).

## Backend — build & test

```bash
pnpm --filter backend build # tsc typecheck + emit
pnpm test # Jest unit tests (services, repositories, lib)
pnpm run test:coverage
```

The backend has no local server — Lambdas are only meaningfully runnable
once deployed (or via `sam local` / manual invocation with a crafted event,
not included here). Unit tests mock the AWS SDK (`aws-sdk-client-mock`) and
the repository layer, so business logic in `services/` is fully covered
without touching real AWS resources.

## Continuous integration

Every push and every PR into `main` runs
[`.github/workflows/ci.yml`](.github/workflows/ci.yml): lint → typecheck
(backend + infrastructure) → unit tests with coverage → `cdk synth`
(validates all six stacks build without needing AWS credentials). See
[docs/branching-strategy.md](docs/branching-strategy.md) for how this gates
merges to `main`. Check the
[Actions tab](https://github.com/ForkYeahMan/Azubi_Final_Capstone/actions)
for build history and logs.

## Infrastructure — deploy

```bash
# One-time per AWS account/region:
cd infrastructure
pnpm run bootstrap

# See what would change:
pnpm run diff

# Deploy everything (Database → Auth → Notifications → Api → Monitoring → Budget):
pnpm run deploy
```

By default the app deploys to stage `dev` and sends Budget/CloudWatch/SES
alerts to a placeholder email baked into
[infrastructure/lib/config/environment.ts](infrastructure/lib/config/environment.ts).
Override both via CDK context flags:

```bash
cd infrastructure
npx cdk deploy --all \
-c stage=dev \
-c alertEmail=you@example.com \
-c monthlyBudgetUsd=10
```

**After deploying**, two manual one-time steps are required because SES
starts in sandbox mode:

1. AWS emails a verification link to `alertEmail` (the SES sender
identity) — click it before any notification email will send.
2. While in the SES sandbox, **recipient** addresses must also be verified
(Admins reviewing test signups, organizers/users registering with test
accounts) — verify them in the SES console, or request SES production
access once you're ready for real end users.

### Creating the first Admin

Admins are never self-service (see
[docs/decisions.md](docs/decisions.md#auth-amazon-cognito-over-hand-rolled-jwt)).
After the `Auth` and `Database` stacks deploy, grab their outputs and run:

```bash
USER_POOL_ID=<from AuthStack output/console> \
USERS_TABLE_NAME=<from DatabaseStack, e.g. event-ticketing-dev-users> \
AWS_REGION=<your region> \
pnpm run seed:admin -- --email admin@example.com --name "Site Admin" --password 'Str0ngP@ssw0rd'
```

### Tearing down

```bash
cd infrastructure
pnpm run destroy
```

`dev`-stage DynamoDB tables and the Cognito User Pool are destroyed with
the stack; `prod`-stage versions of both are retained on stack deletion
(see `RemovalPolicy` in `database-stack.ts` / `auth-stack.ts`) as a
safety net against accidental data loss.

## Frontend

Not started yet — design and implementation are pending further
instructions. `frontend/` currently holds a placeholder only.

## Cost & monitoring

Every resource is pay-per-use (Lambda, API Gateway HTTP API, DynamoDB
on-demand) with no idle compute, so a dev/demo deployment should stay well
inside AWS Free Tier. The `Budget` stack alerts by email at 80% actual /
100% forecasted spend against a configurable monthly threshold
(`monthlyBudgetUsd`, default $10) as a guardrail. The `Monitoring` stack
tracks API request/error counts, Lambda duration, DynamoDB throttles, and
alarms if the API error rate exceeds 5% over a 5-minute window — see
[docs/architecture.md](docs/architecture.md) and
[docs/security.md](docs/security.md) for details.
53 changes: 53 additions & 0 deletions backend/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Backend

Lambda handlers, business logic, and DynamoDB access for the Event
Registration & Ticketing System.

## Layout

```text
src/
├── handlers/ one file per Lambda, exports `handler`
│ ├── auth/ signup, confirm, login, refresh, password reset, Cognito post-confirmation trigger
│ ├── events/ create/list/get/update/cancel, organizer's own listing
│ ├── admin/ review queue, approve/reject, user listing, role updates
│ ├── registrations/ register/cancel, "my registrations", event roster
│ └── notifications/ SNS subscriber that sends email via SES
├── services/ business rules; the only layer handlers call into
├── repositories/ the only layer that talks to DynamoDB
├── models/ shared TypeScript types and enums
└── lib/ cross-cutting: http helpers, errors, auth-context, validation (Zod), logging (Powertools), SNS publish helper
```

Handlers are intentionally thin: parse/validate the request, call a
service, map the result to an HTTP response. This keeps business rules
(who can do what, when an event moves between statuses, capacity
enforcement) testable without mocking API Gateway event shapes in every
test — see `tests/unit/services/`.

## Commands

```bash
pnpm run build # tsc typecheck + emit (used by CDK's NodejsFunction bundler at synth time too)
pnpm run typecheck # tsc --noEmit
pnpm test # Jest
pnpm run test:coverage
pnpm run lint
```

## Conventions

- **Errors**: throw one of the typed errors in `lib/errors.ts`
(`BadRequestError`, `ForbiddenError`, `NotFoundError`, `ConflictError`,
...). `withErrorHandling` in `lib/http.ts` catches these and maps them to
the correct status code and `{ error: { code, message } }` body
automatically — handlers never need their own try/catch.
- **Auth**: `getAuthContext(event)` in `lib/auth-context.ts` extracts
`{ userId, email, groups }` from the claims API Gateway's Cognito JWT
authorizer attaches to the request; `requireRole(ctx, ...roles)` throws
`ForbiddenError` if the caller lacks all of them. Ownership checks
(e.g. "only the organizer who created this event") happen in the
service layer, not the handler.
- **Validation**: every request body/query goes through a Zod schema in
`lib/validation.ts` via `parse(schema, data)`, which throws
`BadRequestError` with a readable message on failure.
10 changes: 10 additions & 0 deletions backend/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/** @type {import('jest').Config} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
rootDir: '.',
testMatch: ['<rootDir>/tests/**/*.test.ts'],
collectCoverageFrom: ['src/**/*.ts', '!src/handlers/**/index.ts'],
coverageDirectory: 'coverage',
clearMocks: true,
};
37 changes: 37 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"name": "@azubi-ticketing/backend",
"version": "1.0.0",
"private": true,
"description": "Lambda handlers, services, and repositories for the Event Registration & Ticketing System",
"main": "index.js",
"scripts": {
"build": "tsc -p tsconfig.json",
"lint": "eslint src --ext .ts",
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"typecheck": "tsc --noEmit -p tsconfig.json"
},
"dependencies": {
"@aws-lambda-powertools/logger": "^2.11.0",
"@aws-lambda-powertools/metrics": "^2.11.0",
"@aws-lambda-powertools/tracer": "^2.11.0",
"@aws-sdk/client-cognito-identity-provider": "^3.658.1",
"@aws-sdk/client-sesv2": "^3.658.1",
"@aws-sdk/client-sns": "^3.658.1",
"@aws-sdk/client-dynamodb": "^3.658.1",
"@aws-sdk/lib-dynamodb": "^3.658.1",
"@aws-sdk/util-dynamodb": "^3.658.1",
"ulid": "^2.3.0",
"zod": "^3.23.8"
},
"devDependencies": {
"@types/aws-lambda": "^8.10.145",
"@types/jest": "^29.5.13",
"@types/node": "^20.16.5",
"aws-sdk-client-mock": "^4.0.2",
"jest": "^29.7.0",
"ts-jest": "^29.2.5",
"typescript": "^5.5.4"
}
}
22 changes: 22 additions & 0 deletions backend/src/handlers/admin/list-events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import type { APIGatewayProxyEventV2WithJWTAuthorizer } from 'aws-lambda';
import { z } from 'zod';
import { getAuthContext, requireRole } from '../../lib/auth-context';
import { ok, withErrorHandling } from '../../lib/http';
import { parse } from '../../lib/validation';
import { EventStatus, Role } from '../../models/enums';
import { AdminService } from '../../services/admin-service';

const querySchema = z.object({
status: z.nativeEnum(EventStatus).default(EventStatus.PENDING_REVIEW),
limit: z.coerce.number().int().min(1).max(100).default(20),
cursor: z.string().optional(),
});

export const handler = withErrorHandling<APIGatewayProxyEventV2WithJWTAuthorizer>(async (event) => {
const ctx = getAuthContext(event);
requireRole(ctx, Role.ADMIN);

const query = parse(querySchema, event.queryStringParameters ?? {});
const page = await AdminService.listEvents(query.status, query.limit, query.cursor);
return ok(page);
});
Loading
Loading