This commit is contained in:
commit
0fb94b6a1b
25
.dockerignore
Normal file
25
.dockerignore
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
node_modules
|
||||||
|
.next
|
||||||
|
.next_old
|
||||||
|
.next_old/*
|
||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
.github
|
||||||
|
.vscode
|
||||||
|
.idea
|
||||||
|
docs
|
||||||
|
nginx
|
||||||
|
scripts/dev-scripts-*.sh
|
||||||
|
*.log
|
||||||
|
*.md
|
||||||
|
!vitest.config.ts
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
.env*.local
|
||||||
|
coverage
|
||||||
|
*.tsbuildinfo
|
||||||
|
tt.md
|
||||||
|
Dockerfile
|
||||||
|
Dockerfile.dev
|
||||||
|
docker-compose.yaml
|
||||||
|
docker-compose.dev.yaml
|
||||||
@ -20,3 +20,12 @@ S3_BUCKET_NAME=monuments-images
|
|||||||
# App
|
# App
|
||||||
NEXT_PUBLIC_APP_URL=https://testbed.mk
|
NEXT_PUBLIC_APP_URL=https://testbed.mk
|
||||||
NEXT_PUBLIC_APP_DOMAIN=testbed.mk
|
NEXT_PUBLIC_APP_DOMAIN=testbed.mk
|
||||||
|
|
||||||
|
# Admin
|
||||||
|
# 64+ random hex chars. Generate with: openssl rand -hex 32
|
||||||
|
ADMIN_SESSION_SECRET=your-random-64-char-secret-here-change-it-in-production
|
||||||
|
|
||||||
|
# Super-admin (stored as bcrypt hash, NOT plaintext). Generate with:
|
||||||
|
# node -e "import('bcryptjs').then(b => b.default.hash('YOUR_PASSWORD', 12).then(console.log))"
|
||||||
|
SUPER_ADMIN_USERNAME=super
|
||||||
|
SUPER_ADMIN_PASSWORD_HASH=$2a$12$REPLACE_WITH_BCRYPT_HASH_OF_YOUR_PASSWORD
|
||||||
54
.github/workflows/ci.yml
vendored
Normal file
54
.github/workflows/ci.yml
vendored
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main, admin]
|
||||||
|
pull_request:
|
||||||
|
branches: [main, admin]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 15
|
||||||
|
|
||||||
|
env:
|
||||||
|
ADMIN_SESSION_SECRET: ${{ secrets.ADMIN_SESSION_SECRET || '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef' }}
|
||||||
|
SUPER_ADMIN_USERNAME: super
|
||||||
|
SUPER_ADMIN_PASSWORD_HASH: ${{ secrets.SUPER_ADMIN_PASSWORD_HASH || '$2a$12$abcdefghijklmnopqrstuv' }}
|
||||||
|
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/ci
|
||||||
|
NEXT_PUBLIC_APP_DOMAIN: ci.test
|
||||||
|
NEXT_PUBLIC_APP_URL: https://ci.test
|
||||||
|
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: pk_test_placeholder
|
||||||
|
CLERK_SECRET_KEY: sk_test_placeholder
|
||||||
|
S3_ENDPOINT: https://s3.example.com
|
||||||
|
S3_REGION: eu-2
|
||||||
|
S3_ACCESS_KEY_ID: placeholder
|
||||||
|
S3_SECRET_ACCESS_KEY: placeholder
|
||||||
|
S3_BUCKET_NAME: ci-bucket
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 20
|
||||||
|
cache: npm
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: npm ci
|
||||||
|
|
||||||
|
- name: Generate Prisma client
|
||||||
|
run: npx prisma generate
|
||||||
|
|
||||||
|
- name: Typecheck
|
||||||
|
run: npm run typecheck
|
||||||
|
|
||||||
|
- name: Lint
|
||||||
|
run: npm run lint
|
||||||
|
continue-on-error: true
|
||||||
|
|
||||||
|
- name: Tests
|
||||||
|
run: npm test
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
run: npm run build
|
||||||
3
.gitignore
vendored
3
.gitignore
vendored
@ -28,6 +28,7 @@ yarn-error.log*
|
|||||||
# env files
|
# env files
|
||||||
.env
|
.env
|
||||||
.env*.local
|
.env*.local
|
||||||
|
.env.superadmin
|
||||||
|
|
||||||
# vercel
|
# vercel
|
||||||
.vercel
|
.vercel
|
||||||
@ -37,4 +38,4 @@ yarn-error.log*
|
|||||||
next-env.d.ts
|
next-env.d.ts
|
||||||
|
|
||||||
# docker
|
# docker
|
||||||
certbot/
|
/.next_old/
|
||||||
|
|||||||
22
Dockerfile
22
Dockerfile
@ -10,7 +10,14 @@ FROM base AS builder
|
|||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
RUN apk add --no-cache openssl
|
RUN apk add --no-cache openssl
|
||||||
COPY --from=deps /app/node_modules ./node_modules
|
COPY --from=deps /app/node_modules ./node_modules
|
||||||
COPY . .
|
COPY package.json package-lock.json ./
|
||||||
|
COPY next.config.ts ./
|
||||||
|
COPY tsconfig.json ./
|
||||||
|
COPY postcss.config.mjs ./
|
||||||
|
COPY eslint.config.mjs ./
|
||||||
|
COPY prisma ./prisma
|
||||||
|
COPY src ./src
|
||||||
|
COPY public ./public
|
||||||
RUN npx prisma generate
|
RUN npx prisma generate
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
@ -18,7 +25,7 @@ FROM base AS runner
|
|||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
RUN apk add --no-cache openssl
|
RUN apk add --no-cache openssl wget
|
||||||
|
|
||||||
RUN addgroup --system --gid 1001 nodejs
|
RUN addgroup --system --gid 1001 nodejs
|
||||||
RUN adduser --system --uid 1001 nextjs
|
RUN adduser --system --uid 1001 nextjs
|
||||||
@ -27,7 +34,13 @@ COPY --from=builder /app/public ./public
|
|||||||
COPY --from=builder /app/.next/standalone ./
|
COPY --from=builder /app/.next/standalone ./
|
||||||
COPY --from=builder /app/.next/static ./.next/static
|
COPY --from=builder /app/.next/static ./.next/static
|
||||||
COPY --from=builder /app/prisma ./prisma
|
COPY --from=builder /app/prisma ./prisma
|
||||||
COPY --from=builder /app/node_modules ./node_modules
|
COPY --from=builder /app/node_modules/.prisma ./node_modules/.prisma
|
||||||
|
COPY --from=builder /app/node_modules/@prisma ./node_modules/@prisma
|
||||||
|
|
||||||
|
# The `prisma` CLI is not part of the standalone trace, and `npx prisma`
|
||||||
|
# fails non-interactively in the runner. Install it (pinned to the project's
|
||||||
|
# Prisma version) so `scripts/start.sh` can run `prisma migrate deploy`.
|
||||||
|
RUN npm install --no-save --no-audit --no-fund prisma@5.22.0
|
||||||
|
|
||||||
COPY scripts/start.sh /app/start.sh
|
COPY scripts/start.sh /app/start.sh
|
||||||
RUN chmod +x /app/start.sh
|
RUN chmod +x /app/start.sh
|
||||||
@ -40,4 +53,7 @@ EXPOSE 3000
|
|||||||
ENV PORT=3000
|
ENV PORT=3000
|
||||||
ENV HOSTNAME="0.0.0.0"
|
ENV HOSTNAME="0.0.0.0"
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
||||||
|
CMD wget --quiet --spider http://localhost:3000/api/check-subdomain?slug=__health || exit 1
|
||||||
|
|
||||||
CMD ["/bin/sh", "/app/start.sh"]
|
CMD ["/bin/sh", "/app/start.sh"]
|
||||||
@ -23,6 +23,7 @@ services:
|
|||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
env_file:
|
env_file:
|
||||||
- .env
|
- .env
|
||||||
|
- .env.superadmin
|
||||||
environment:
|
environment:
|
||||||
DATABASE_URL: postgresql://postgres:postgres@db:5432/monuments
|
DATABASE_URL: postgresql://postgres:postgres@db:5432/monuments
|
||||||
ports:
|
ports:
|
||||||
|
|||||||
59
docs/admin.md
Normal file
59
docs/admin.md
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
# Admin flow
|
||||||
|
|
||||||
|
## Roles
|
||||||
|
|
||||||
|
- **SUPER_ADMIN**: provisioned from environment. Has full power — creates
|
||||||
|
and deletes regular admins, generates codes, resets passwords.
|
||||||
|
- **ADMIN**: created by a SUPER_ADMIN via the admin panel. Can only
|
||||||
|
generate and delete their own codes.
|
||||||
|
|
||||||
|
## Authentication
|
||||||
|
|
||||||
|
The admin layer uses a **custom HMAC-signed cookie**, separate from
|
||||||
|
Clerk (which is for end-users only):
|
||||||
|
|
||||||
|
- `POST /api/admin/login` — verifies credentials, sets an
|
||||||
|
`admin_session` cookie signed with `ADMIN_SESSION_SECRET`.
|
||||||
|
- `POST /api/admin/logout` — clears the cookie.
|
||||||
|
- `src/lib/admin-session.ts` — sign/verify helpers, plus
|
||||||
|
`requireAdmin` / `requireAdminPost` / `requireSuperAdminPost`
|
||||||
|
guards that handle auth + same-origin (CSRF) checks for admin
|
||||||
|
API routes.
|
||||||
|
- All admin POST routes run through `requireAdminPost` (or
|
||||||
|
`requireSuperAdminPost`), which enforces `Origin`/`Referer`/`Host`
|
||||||
|
matching `NEXT_PUBLIC_APP_URL`.
|
||||||
|
|
||||||
|
## Super-admin provisioning
|
||||||
|
|
||||||
|
Username and bcrypt-hashed password are read from env:
|
||||||
|
|
||||||
|
- `SUPER_ADMIN_USERNAME` (default `super`)
|
||||||
|
- `SUPER_ADMIN_PASSWORD_HASH` — bcrypt hash, NOT plaintext. Generate
|
||||||
|
with:
|
||||||
|
```sh
|
||||||
|
node -e "import('bcryptjs').then(b => b.default.hash('YOUR_PASSWORD', 12).then(console.log))"
|
||||||
|
```
|
||||||
|
|
||||||
|
Because `Code.createdById` is a non-nullable FK to `AdminUser`, the
|
||||||
|
env super-admin also needs a row in `AdminUser`. Provisioning is
|
||||||
|
handled by `prisma/seed.cjs`, which upserts the SUPER_ADMIN row from
|
||||||
|
the same env values. Run `npm run db:seed` after starting the DB; the
|
||||||
|
container's `scripts/start.sh` also runs it automatically on every
|
||||||
|
boot (after `prisma migrate deploy`).
|
||||||
|
|
||||||
|
## Codes
|
||||||
|
|
||||||
|
- A `Code` is a 12-char uppercase hex string generated by `POST /api/admin/codes`.
|
||||||
|
- Users validate a code via `POST /api/validate-code`. The claim is
|
||||||
|
atomic (uses `updateMany` with `usedByUserId: null` guard) so a code
|
||||||
|
can't be claimed by two concurrent requests.
|
||||||
|
- `Code.createdById` is a non-nullable FK to `AdminUser` with
|
||||||
|
`onDelete: Restrict` (Prisma default). You cannot delete an admin who
|
||||||
|
has issued codes — they audit-protect the code trail.
|
||||||
|
|
||||||
|
## Rate limiting + brute-force defence
|
||||||
|
|
||||||
|
- `/api/admin/login`: 5 attempts/min per IP (`adminLoginLimiter`).
|
||||||
|
- `/api/validate-code`: 20 attempts/min per IP (`validateCodeLimiter`).
|
||||||
|
- Other admin mutating routes are also CSRF-guarded.
|
||||||
|
- All limiters live in `src/lib/rate-limit.ts`.
|
||||||
282
docs/adminImplem.md
Normal file
282
docs/adminImplem.md
Normal file
@ -0,0 +1,282 @@
|
|||||||
|
# SuperAdmin & Admin + Code Access System — Implementation Plan
|
||||||
|
|
||||||
|
> ## ⚠ Historical implementation plan — see `docs/admin.md` for current state
|
||||||
|
>
|
||||||
|
> This was the original plan doc. Several specifics differ from the
|
||||||
|
> actual implementation (`src/lib/admin-session.ts`,
|
||||||
|
> `src/app/api/admin/*`, `src/app/admin/**`):
|
||||||
|
>
|
||||||
|
> - Cookie **path**: planned as `/admin`; shipped as `/` (so admin
|
||||||
|
> API routes under `/api/admin/*` receive the cookie).
|
||||||
|
> - **Super-admin credentials**: planned as hardcoded `super`/`admin`;
|
||||||
|
> shipped from env (`SUPER_ADMIN_USERNAME` + `SUPER_ADMIN_PASSWORD_HASH`,
|
||||||
|
> bcrypt) — see `docs/admin.md`.
|
||||||
|
> - **Super-admin row in `AdminUser`**: planned as optional seed;
|
||||||
|
> required by the `Code.createdById` FK and provisioned by
|
||||||
|
> `prisma/seed.cjs` (run by `scripts/start.sh` on boot).
|
||||||
|
> - **Rate limiting, CSRF/Origin checks, password complexity, atomic
|
||||||
|
> code claim** (updateMany guard): all added in Phases 1–6 and not
|
||||||
|
> in the original plan.
|
||||||
|
> - All admin API routes now funnel through `requireAdmin` /
|
||||||
|
> `requireAdminPost` / `requireSuperAdminPost` in
|
||||||
|
> `src/lib/admin-session.ts`; the rolling-helpers in
|
||||||
|
> `admin-session.ts` supersede the inline `getAdminSession()` checks
|
||||||
|
> described per-route in this top-of-the-doc walkthrough.
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Implement SuperAdmin/admin role management and code-gated memorial creation as outlined in `admin.md`.
|
||||||
|
|
||||||
|
- SuperAdmin: hardcoded username `super`, password `admin`
|
||||||
|
- SuperAdmin creates admin accounts
|
||||||
|
- Admins generate access codes
|
||||||
|
- Users must enter a valid code during onboarding to create memories
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 1 — Database & Dependencies
|
||||||
|
|
||||||
|
### New Prisma Models (`prisma/schema.prisma`)
|
||||||
|
|
||||||
|
```prisma
|
||||||
|
enum Role {
|
||||||
|
SUPER_ADMIN
|
||||||
|
ADMIN
|
||||||
|
}
|
||||||
|
|
||||||
|
model AdminUser {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
username String @unique
|
||||||
|
passwordHash String
|
||||||
|
role Role @default(ADMIN)
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
createdCodes Code[]
|
||||||
|
}
|
||||||
|
|
||||||
|
model Code {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
code String @unique
|
||||||
|
createdById String
|
||||||
|
createdBy AdminUser @relation(fields: [createdById], references: [id])
|
||||||
|
usedByUserId String? // User.clerkId
|
||||||
|
usedAt DateTime?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
expiresAt DateTime?
|
||||||
|
|
||||||
|
@@index([code])
|
||||||
|
@@index([usedByUserId])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### New Dependencies
|
||||||
|
|
||||||
|
- `bcryptjs` + `@types/bcryptjs` — hash admin passwords
|
||||||
|
|
||||||
|
### Seed SuperAdmin
|
||||||
|
|
||||||
|
Seed script or migration that creates the SuperAdmin `AdminUser` record with hashed password. However, the login itself checks hardcoded `super`/`admin` first (and also queries DB by role for token auth), so the seed is optional — used mainly for listing in the admin panel.
|
||||||
|
|
||||||
|
### Migration
|
||||||
|
|
||||||
|
`npx prisma migrate dev --name add_admin_and_code`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 2 — Admin Auth
|
||||||
|
|
||||||
|
Admin auth is separate from Clerk. Uses a signed HMAC cookie.
|
||||||
|
|
||||||
|
### `src/lib/admin-session.ts` (new)
|
||||||
|
|
||||||
|
Helpers:
|
||||||
|
|
||||||
|
- `createAdminSession(username: string, role: Role): string` — sign a cookie value with HMAC-SHA256 using `ADMIN_SESSION_SECRET` env var
|
||||||
|
- `verifyAdminSession(token: string): { username: string; role: Role } | null` — verify and decode
|
||||||
|
- `getAdminSession(): { username: string; role: Role } | null` — read from `request.cookies` or `cookies()`
|
||||||
|
- Cookie name: `admin_session`
|
||||||
|
|
||||||
|
Payload: `{ username, role, iat }` serialized + HMAC signature.
|
||||||
|
|
||||||
|
### `src/app/api/admin/login/route.ts` (new)
|
||||||
|
|
||||||
|
- POST: accept `{ username, password }`
|
||||||
|
- If `username === "super"` and `password === "admin"` → set session with role `SUPER_ADMIN`
|
||||||
|
- Else query `AdminUser` where `username === username`, compare with `bcrypt.compare`
|
||||||
|
- Return `{ success: true }` and set `admin_session` cookie (httpOnly, secure, sameSite=lax, path=/admin)
|
||||||
|
- On failure: `401`
|
||||||
|
|
||||||
|
### `src/app/api/admin/logout/route.ts` (new)
|
||||||
|
|
||||||
|
- POST: clear `admin_session` cookie
|
||||||
|
|
||||||
|
### `src/app/api/admin/change-password/route.ts` (new)
|
||||||
|
|
||||||
|
- POST: accept `{ currentPassword, newPassword }`
|
||||||
|
- Verify admin session, then verify current password against DB
|
||||||
|
- Hash new password, update `AdminUser` record
|
||||||
|
|
||||||
|
### `src/app/admin/login/page.tsx` (new)
|
||||||
|
|
||||||
|
- Macedonian UI: username/password form
|
||||||
|
- On submit → `POST /api/admin/login`
|
||||||
|
- On success → redirect to `/admin/dashboard`
|
||||||
|
- Show error on failure
|
||||||
|
|
||||||
|
### `src/middleware.ts` (modify)
|
||||||
|
|
||||||
|
- Add `/admin(.*)` and `/api/admin(.*)` to the Clerk exclude list
|
||||||
|
- Before Clerk middleware runs: if path starts with `/admin`, check admin session cookie
|
||||||
|
- No/invalid cookie → redirect to `/admin/login`
|
||||||
|
- Valid → allow
|
||||||
|
- If path starts with `/api/admin`, check admin session cookie
|
||||||
|
- No/invalid cookie → return `401`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 3 — Admin Panel
|
||||||
|
|
||||||
|
All UI in Macedonian. Layout with sidebar navigation.
|
||||||
|
|
||||||
|
### `src/app/admin/layout.tsx` (new)
|
||||||
|
|
||||||
|
- Checks admin session (server component)
|
||||||
|
- Redirects to `/admin/login` if not authenticated
|
||||||
|
- Provides sidebar with links: Dashboard, Users (SuperAdmin only), Codes
|
||||||
|
- Logout button
|
||||||
|
|
||||||
|
### `src/app/admin/dashboard/page.tsx` (new)
|
||||||
|
|
||||||
|
- Stats cards:
|
||||||
|
- Total AdminUsers count
|
||||||
|
- Total Codes generated
|
||||||
|
- Codes used vs unused
|
||||||
|
- Simple overview
|
||||||
|
|
||||||
|
### `src/app/admin/users/page.tsx` (new)
|
||||||
|
|
||||||
|
- Accessible only to `SUPER_ADMIN`
|
||||||
|
- Table of admin users (username, role, created at)
|
||||||
|
- Button to create new admin (modal/page with username + password fields)
|
||||||
|
- Button to delete admin (with confirmation)
|
||||||
|
- Inline password reset option
|
||||||
|
|
||||||
|
### `src/app/admin/users/create/page.tsx` or modal (new)
|
||||||
|
|
||||||
|
- Form: username, password (with confirmation)
|
||||||
|
- POST to `/api/admin/users/`
|
||||||
|
|
||||||
|
### `src/app/admin/codes/page.tsx` (new)
|
||||||
|
|
||||||
|
- "Generate Code" button → POST `/api/admin/codes` → returns new code string, displays it
|
||||||
|
- Table of all codes: code value, who created it, status (used/unused), used by, used at
|
||||||
|
- Admin can see their own codes. SuperAdmin sees all.
|
||||||
|
- Delete code button
|
||||||
|
|
||||||
|
### `src/app/api/admin/users/route.ts` (new)
|
||||||
|
|
||||||
|
- GET: list all `AdminUser` (SuperAdmin only)
|
||||||
|
- POST: create `AdminUser` with hashed password (SuperAdmin only)
|
||||||
|
|
||||||
|
### `src/app/api/admin/users/[id]/route.ts` (new)
|
||||||
|
|
||||||
|
- DELETE: remove `AdminUser` (SuperAdmin only)
|
||||||
|
- PUT: reset password (SuperAdmin only)
|
||||||
|
|
||||||
|
### `src/app/api/admin/codes/route.ts` (new)
|
||||||
|
|
||||||
|
- GET: list codes (Admins see their own, SuperAdmin sees all)
|
||||||
|
- POST: generate a new code (`crypto.randomBytes(6).toString('hex').toUpperCase()` → 12 chars), store with `createdById` from session
|
||||||
|
|
||||||
|
### `src/app/api/admin/codes/[id]/route.ts` (new)
|
||||||
|
|
||||||
|
- DELETE: remove unused code
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 4 — Code Gating
|
||||||
|
|
||||||
|
### `src/app/api/validate-code/route.ts` (new)
|
||||||
|
|
||||||
|
- Requires Clerk auth (`auth()` from `@clerk/nextjs/server`)
|
||||||
|
- POST: `{ code: string }`
|
||||||
|
- Look up `Code` where `code === code` and `usedByUserId === null`
|
||||||
|
- If not found → `{ valid: false, error: "Невалиден или веќе искористен код" }`
|
||||||
|
- If found → update `usedByUserId = userId`, `usedAt = now()`
|
||||||
|
- Return `{ valid: true }`
|
||||||
|
|
||||||
|
### `src/app/onboarding/page.tsx` (modify)
|
||||||
|
|
||||||
|
- Add `"Код"` as step 0 (before "Податоци")
|
||||||
|
- STEPS becomes: `["Код", "Податоци", "Датуми", "Фотографии", "Поддомен", "Шаблон"]`
|
||||||
|
- Step 0: single input for code + "Потврди" button
|
||||||
|
- Calls `POST /api/validate-code`
|
||||||
|
- On success → shows green checkmark, enables "Продолжи"
|
||||||
|
- On failure → shows error, blocks progression
|
||||||
|
- Once validated, user can proceed to step 1
|
||||||
|
- `canProceed()` for step 0 returns true only if code validated successfully
|
||||||
|
|
||||||
|
### `src/app/api/publish/route.ts` (modify)
|
||||||
|
|
||||||
|
- After Clerk auth check, query: `prisma.code.findFirst({ where: { usedByUserId: userId } })`
|
||||||
|
- If no code found → return `403` with `"Потребен е валиден код за креирање спомен страница"`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 5 — Environment & Build
|
||||||
|
|
||||||
|
### New Env Variable
|
||||||
|
|
||||||
|
```
|
||||||
|
ADMIN_SESSION_SECRET=<random-64-char-string>
|
||||||
|
```
|
||||||
|
|
||||||
|
Add to `.env.example` and `docker-compose` files.
|
||||||
|
|
||||||
|
### Build & Verify
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install bcryptjs
|
||||||
|
npm install -D @types/bcryptjs
|
||||||
|
npx prisma migrate dev --name add_admin_and_code
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
Verify:
|
||||||
|
- [ ] Admin login at `/admin/login` with `super`/`admin`
|
||||||
|
- [ ] Create admin user from admin panel
|
||||||
|
- [ ] Login as created admin
|
||||||
|
- [ ] Generate code from admin panel
|
||||||
|
- [ ] Sign up as new user via Clerk
|
||||||
|
- [ ] Enter code in onboarding step 0
|
||||||
|
- [ ] Proceed through onboarding and publish
|
||||||
|
- [ ] Verify publish fails without valid code
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## File Change Summary
|
||||||
|
|
||||||
|
### New Files
|
||||||
|
| Path | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `src/lib/admin-session.ts` | HMAC cookie helpers |
|
||||||
|
| `src/app/admin/login/page.tsx` | Admin login form |
|
||||||
|
| `src/app/admin/layout.tsx` | Admin layout with sidebar |
|
||||||
|
| `src/app/admin/dashboard/page.tsx` | Dashboard stats |
|
||||||
|
| `src/app/admin/users/page.tsx` | Admin user management |
|
||||||
|
| `src/app/admin/codes/page.tsx` | Code generation & listing |
|
||||||
|
| `src/app/api/admin/login/route.ts` | Admin login API |
|
||||||
|
| `src/app/api/admin/logout/route.ts` | Admin logout API |
|
||||||
|
| `src/app/api/admin/change-password/route.ts` | Self-service password change |
|
||||||
|
| `src/app/api/admin/users/route.ts` | List/create admin users |
|
||||||
|
| `src/app/api/admin/users/[id]/route.ts` | Delete/reset-password admin user |
|
||||||
|
| `src/app/api/admin/codes/route.ts` | List/create codes |
|
||||||
|
| `src/app/api/admin/codes/[id]/route.ts` | Delete code |
|
||||||
|
| `src/app/api/validate-code/route.ts` | Public code validation |
|
||||||
|
|
||||||
|
### Modified Files
|
||||||
|
| Path | Change |
|
||||||
|
|------|--------|
|
||||||
|
| `prisma/schema.prisma` | Add `AdminUser` and `Code` models |
|
||||||
|
| `src/middleware.ts` | Exclude `/admin/*` from Clerk, add admin session check |
|
||||||
|
| `src/app/onboarding/page.tsx` | Add code step (step 0) |
|
||||||
|
| `src/app/api/publish/route.ts` | Add code usage check before publish |
|
||||||
@ -109,6 +109,15 @@ S3_BUCKET_NAME=monuments-images
|
|||||||
NEXT_PUBLIC_APP_URL=https://testbed.mk
|
NEXT_PUBLIC_APP_URL=https://testbed.mk
|
||||||
NEXT_PUBLIC_APP_DOMAIN=testbed.mk
|
NEXT_PUBLIC_APP_DOMAIN=testbed.mk
|
||||||
|
|
||||||
|
# Admin session signing secret (64+ random hex chars; openssl rand -hex 32)
|
||||||
|
ADMIN_SESSION_SECRET=your-random-64-char-secret
|
||||||
|
|
||||||
|
# Super-admin — username + BCRYPT HASH (not plaintext). Generate with:
|
||||||
|
# node -e "import('bcryptjs').then(b => b.default.hash('YOUR_PASSWORD', 12).then(console.log))"
|
||||||
|
# Coolify UI env vars are passed to the container literally — no `$` escaping needed.
|
||||||
|
SUPER_ADMIN_USERNAME=super
|
||||||
|
SUPER_ADMIN_PASSWORD_HASH=$2b$12$REPLACE_WITH_BCRYPT_HASH
|
||||||
|
|
||||||
# Node
|
# Node
|
||||||
NODE_ENV=production
|
NODE_ENV=production
|
||||||
```
|
```
|
||||||
@ -116,6 +125,11 @@ NODE_ENV=production
|
|||||||
**Important:**
|
**Important:**
|
||||||
- `DATABASE_URL` must point to the Coolify **internal** hostname (`spomeniqr-db`), not `localhost`.
|
- `DATABASE_URL` must point to the Coolify **internal** hostname (`spomeniqr-db`), not `localhost`.
|
||||||
- Use your **production** Clerk keys (`pk_live_` / `sk_live_`), not the test ones.
|
- Use your **production** Clerk keys (`pk_live_` / `sk_live_`), not the test ones.
|
||||||
|
- Use a **different, strong** super-admin password than your local development one.
|
||||||
|
- The `super` admin row is provisioned automatically on container start by
|
||||||
|
`scripts/start.sh` (`node prisma/seed.cjs` after migrations). If you instead
|
||||||
|
use a custom Nixpacks start command (Option A below), run the seed manually
|
||||||
|
after the first deploy: `npx prisma db seed`.
|
||||||
|
|
||||||
## Step 5: Configure Domain & Subdomain Routing
|
## Step 5: Configure Domain & Subdomain Routing
|
||||||
|
|
||||||
@ -315,6 +329,9 @@ npx prisma db push
|
|||||||
| `S3_BUCKET_NAME` | Yes | S3 bucket name |
|
| `S3_BUCKET_NAME` | Yes | S3 bucket name |
|
||||||
| `NEXT_PUBLIC_APP_URL` | Yes | `https://testbed.mk` |
|
| `NEXT_PUBLIC_APP_URL` | Yes | `https://testbed.mk` |
|
||||||
| `NEXT_PUBLIC_APP_DOMAIN` | Yes | `testbed.mk` |
|
| `NEXT_PUBLIC_APP_DOMAIN` | Yes | `testbed.mk` |
|
||||||
|
| `ADMIN_SESSION_SECRET` | Yes | Secret signing admin session cookies (openssl rand -hex 32) |
|
||||||
|
| `SUPER_ADMIN_USERNAME` | No | Super-admin username (default `super`) |
|
||||||
|
| `SUPER_ADMIN_PASSWORD_HASH` | No | Super-admin bcrypt hash; if unset, super login is unavailable |
|
||||||
| `NODE_ENV` | Yes | `production` |
|
| `NODE_ENV` | Yes | `production` |
|
||||||
|
|
||||||
## Useful Coolify Commands
|
## Useful Coolify Commands
|
||||||
@ -104,9 +104,24 @@ S3_BUCKET_NAME=monuments-images
|
|||||||
# App
|
# App
|
||||||
NEXT_PUBLIC_APP_URL=https://testbed.mk
|
NEXT_PUBLIC_APP_URL=https://testbed.mk
|
||||||
NEXT_PUBLIC_APP_DOMAIN=testbed.mk
|
NEXT_PUBLIC_APP_DOMAIN=testbed.mk
|
||||||
|
|
||||||
|
# Admin session signing secret (64+ random hex chars; openssl rand -hex 32)
|
||||||
|
ADMIN_SESSION_SECRET=your-random-64-char-secret
|
||||||
|
|
||||||
|
# Super-admin — username + BCRYPT HASH (not plaintext) of the super-admin password.
|
||||||
|
# Generate the hash with:
|
||||||
|
# node -e "import('bcryptjs').then(b => b.default.hash('YOUR_PASSWORD', 12).then(console.log))"
|
||||||
|
# If you run the app via `docker compose` with these vars in a `.env` env_file,
|
||||||
|
# you MUST escape every `$` as `$$` (e.g. `$$2b$$12$$...`). Newer Compose
|
||||||
|
# versions interpolate env_file values and will otherwise strip the `$2b$12`
|
||||||
|
# prefix, silently breaking super-admin login. If the vars are provided via a
|
||||||
|
# platform UI (Coolify/Vercel) they are passed literally and need no escaping.
|
||||||
|
SUPER_ADMIN_USERNAME=super
|
||||||
|
SUPER_ADMIN_PASSWORD_HASH=$2b$12$REPLACE_WITH_BCRYPT_HASH
|
||||||
```
|
```
|
||||||
|
|
||||||
**Important**: Use a strong, unique password for `POSTGRES_PASSWORD`.
|
**Important**: Use a strong, unique password for `POSTGRES_PASSWORD`. Do **not**
|
||||||
|
reuse the development super-admin password (`Irina@7654321`) in production.
|
||||||
|
|
||||||
### Create the Prisma Migration
|
### Create the Prisma Migration
|
||||||
|
|
||||||
@ -135,6 +150,14 @@ npx prisma migrate dev --name init
|
|||||||
|
|
||||||
Then commit the generated migration files. The `scripts/start.sh` entrypoint will run `npx prisma migrate deploy` automatically on every container start.
|
Then commit the generated migration files. The `scripts/start.sh` entrypoint will run `npx prisma migrate deploy` automatically on every container start.
|
||||||
|
|
||||||
|
### Super-admin provisioning
|
||||||
|
|
||||||
|
The `super` admin is provisioned from the environment on **every container
|
||||||
|
start**: `scripts/start.sh` runs `node prisma/seed.cjs` after migrations. It
|
||||||
|
upserts the `SUPER_ADMIN_USERNAME` row (role `SUPER_ADMIN`) with the bcrypt hash
|
||||||
|
from `SUPER_ADMIN_PASSWORD_HASH`. If the hash is unset the seed is skipped
|
||||||
|
(logged). No manual seeding is required on first deploy.
|
||||||
|
|
||||||
## 4. Configure Contabo S3
|
## 4. Configure Contabo S3
|
||||||
|
|
||||||
### Create the Bucket
|
### Create the Bucket
|
||||||
@ -462,3 +485,6 @@ docker compose exec app printenv DATABASE_URL
|
|||||||
| `S3_BUCKET_NAME` | Yes | S3 bucket name (monuments-images) |
|
| `S3_BUCKET_NAME` | Yes | S3 bucket name (monuments-images) |
|
||||||
| `NEXT_PUBLIC_APP_URL` | Yes | Public URL (https://testbed.mk) |
|
| `NEXT_PUBLIC_APP_URL` | Yes | Public URL (https://testbed.mk) |
|
||||||
| `NEXT_PUBLIC_APP_DOMAIN` | Yes | Domain only (testbed.mk) |
|
| `NEXT_PUBLIC_APP_DOMAIN` | Yes | Domain only (testbed.mk) |
|
||||||
|
| `ADMIN_SESSION_SECRET` | Yes | Secret signing admin session cookies (openssl rand -hex 32) |
|
||||||
|
| `SUPER_ADMIN_USERNAME` | No | Super-admin username (default `super`) |
|
||||||
|
| `SUPER_ADMIN_PASSWORD_HASH` | No | Super-admin bcrypt hash; if unset, super login is unavailable |
|
||||||
@ -1,5 +1,43 @@
|
|||||||
# 🏛️ City Monuments Memories — Platform Architecture & Implementation Plan
|
# 🏛️ City Monuments Memories — Platform Architecture & Implementation Plan
|
||||||
|
|
||||||
|
> ## ⚠ Historical spec — partially out of sync with the implementation
|
||||||
|
>
|
||||||
|
> This document is the **original architecture plan**. The shipped code
|
||||||
|
> has drifted from it in several ways; treat this as historical design
|
||||||
|
> context, not current documentation.
|
||||||
|
>
|
||||||
|
> Known deltas (see `docs/admin.md` and the source for the source of
|
||||||
|
> truth):
|
||||||
|
>
|
||||||
|
> - **Storage**: described as "UploadThing" + "Vercel Blob"; the
|
||||||
|
> implementation uses **AWS-compatible S3 (Contabo Object Storage)**
|
||||||
|
> via `@aws-sdk/client-s3`. There is an in-house presigned-URL helper
|
||||||
|
> in `src/lib/upload.ts` (currently the upload route still proxies
|
||||||
|
> through the server with magic-byte validation; presigned direct-to-S3
|
||||||
|
> flow is implemented but not yet wired into the client).
|
||||||
|
> - **File Upload**: 5MB cap, JPEG/PNG/WebP only (GIF was removed).
|
||||||
|
> - **Auth**: described as "Clerk only". The implementation uses
|
||||||
|
> **dual-track auth**: Clerk for end-users, plus a custom
|
||||||
|
> **HMAC-signed cookie** for admins (`src/lib/admin-session.ts`).
|
||||||
|
> Admin session secret comes from `ADMIN_SESSION_SECRET`; super-admin
|
||||||
|
> credentials from `SUPER_ADMIN_USERNAME` + `SUPER_ADMIN_PASSWORD_HASH`
|
||||||
|
> (bcrypt) — previously hardcoded `super`/`admin`, now removed.
|
||||||
|
> - **Deployment**: described as "Vercel". Actual deploy is **Docker
|
||||||
|
> (standalone Next.js) behind Traefik (Coolify)**. The `nginx/conf.d/*`
|
||||||
|
> configs have been deleted.
|
||||||
|
> - **Subdomain routing**: described as "Vercel Wildcard Domains";
|
||||||
|
> middleware parses the `Host` header (not `X-Subdomain`) behind the
|
||||||
|
> Traefik reverse proxy.
|
||||||
|
> - **Schema**: see `prisma/schema.prisma` for the current shape. Most
|
||||||
|
> notably `bornDate`/`passedDate` are deliberately kept as bounded
|
||||||
|
> `VARCHAR(50)` (imprecise free-text like "1960" or "early 1990s"),
|
||||||
|
> not `DateTime`.
|
||||||
|
> - **Rate limiting + CSRF** are now enforced on admin + sensitive
|
||||||
|
> public routes (see `src/lib/rate-limit.ts`).
|
||||||
|
> - **QR codes** are rendered in-house via the `qrcode` package, not
|
||||||
|
> via the external `api.qrserver.com` service.
|
||||||
|
|
||||||
|
|
||||||
## 1. Tech Stack
|
## 1. Tech Stack
|
||||||
|
|
||||||
| Layer | Technology | Why |
|
| Layer | Technology | Why |
|
||||||
111
next.config.ts
111
next.config.ts
@ -1,19 +1,116 @@
|
|||||||
import type { NextConfig } from "next";
|
import type { NextConfig } from "next";
|
||||||
|
|
||||||
|
const s3Host = process.env.S3_ENDPOINT
|
||||||
|
? new URL(process.env.S3_ENDPOINT).hostname
|
||||||
|
: "";
|
||||||
|
|
||||||
|
// Derive the Clerk frontend API host from the publishable key so the
|
||||||
|
// CSP allowlist always matches the active environment. Clerk supports
|
||||||
|
// two publishable key formats:
|
||||||
|
//
|
||||||
|
// 1) "Encoded" form (older): pk_test_<base64slug>$
|
||||||
|
// The base64 portion decodes to "<slug>.clerk.accounts.dev" (test)
|
||||||
|
// or "<slug>.clerk.services" (live). Trailing '$' is a separator.
|
||||||
|
//
|
||||||
|
// 2) "Readable" form (newer): pk_test_<slug>-<randomSuffix>
|
||||||
|
// -> <slug>.clerk.accounts.dev (test) or <slug>.clerk.services.
|
||||||
|
// The slug may itself contain hyphens and digits, so only the
|
||||||
|
// final dash-group is captured as the suffix.
|
||||||
|
function clerkFrontendApiHost(): string | null {
|
||||||
|
const key = process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY;
|
||||||
|
if (!key) return null;
|
||||||
|
|
||||||
|
// Form 1: base64-encoded FAPI URL. Match everything between the
|
||||||
|
// 'pk_test_'/'pk_live_' prefix and an optional trailing '$'.
|
||||||
|
const enc = key.match(/^pk_(test|live)_([A-Za-z0-9+/=_-]+)\$?$/);
|
||||||
|
if (enc) {
|
||||||
|
const b64 = enc[2].replace(/-/g, "+").replace(/_/g, "/");
|
||||||
|
if (/^[A-Za-z0-9+/=]+$/.test(b64)) {
|
||||||
|
try {
|
||||||
|
const padded = b64 + "=".repeat((4 - (b64.length % 4)) % 4);
|
||||||
|
const decoded = Buffer.from(padded, "base64").toString("utf8");
|
||||||
|
// If the decoded string doesn't look like a Clerk FAPI host
|
||||||
|
// (e.g. it's garbage from decoding a non-base64 readable-form
|
||||||
|
// key), fall through to form 2 rather than returning null.
|
||||||
|
const fapi = decodeFapiHost(decoded);
|
||||||
|
if (fapi) return fapi;
|
||||||
|
} catch {
|
||||||
|
// fall through to form 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// fall through to form 2 if the slug is non-base64 (e.g. readable form)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Form 2: readable slug + random suffix.
|
||||||
|
const m = key.match(/^pk_(test|live)_(.+?)-([a-z0-9]+)$/i);
|
||||||
|
if (!m) return null;
|
||||||
|
const slug = m[2].toLowerCase();
|
||||||
|
return m[1].toLowerCase() === "test"
|
||||||
|
? `${slug}.clerk.accounts.dev`
|
||||||
|
: `${slug}.clerk.services`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeFapiHost(decoded: string): string | null {
|
||||||
|
// The decoded string is the FAPI host (e.g.
|
||||||
|
// 'useful-louse-74.clerk.accounts.dev$'). Note: the encoded base64
|
||||||
|
// payload always carries the literal FAPI host regardless of test vs
|
||||||
|
// live mode — both `pk_test_...` and `pk_live_...` can decode to an
|
||||||
|
// '.accounts.dev' host when the deployment is on the test endpoint.
|
||||||
|
// We accept either well-known Clerk FAPI host pattern.
|
||||||
|
const host = decoded.trim().replace(/\$$/, "").trim().toLowerCase();
|
||||||
|
if (host.endsWith(".clerk.accounts.dev") || host.endsWith(".clerk.services")) {
|
||||||
|
return host;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const clerkFapiHost = clerkFrontendApiHost();
|
||||||
|
|
||||||
|
const csp = [
|
||||||
|
"default-src 'self'",
|
||||||
|
// Clerk user avatars are served from img.clerk.com; S3 hosts are
|
||||||
|
// also allowed for memorial uploads. data:/blob: for in-app previews.
|
||||||
|
"img-src 'self' data: blob: https://img.clerk.com https:",
|
||||||
|
"font-src 'self' data:",
|
||||||
|
"style-src 'self' 'unsafe-inline'",
|
||||||
|
// script-src: must include the Clerk FAPI host because Clerk JS is
|
||||||
|
// loaded from <fapiHost>/npm/@clerk/clerk-js@<v>/dist/clerk.browser.js
|
||||||
|
"script-src 'self' 'unsafe-inline' 'unsafe-eval'" +
|
||||||
|
(clerkFapiHost ? ` https://${clerkFapiHost}` : ""),
|
||||||
|
// connect-src: Clerk JS talks to <fapiHost> for all session calls.
|
||||||
|
"connect-src 'self' https://api.clerk.com" +
|
||||||
|
(clerkFapiHost ? ` https://${clerkFapiHost} wss://${clerkFapiHost}` : ""),
|
||||||
|
"frame-ancestors 'self'",
|
||||||
|
].join("; ");
|
||||||
|
|
||||||
|
const securityHeaders = [
|
||||||
|
{ key: "Strict-Transport-Security", value: "max-age=63072000; includeSubDomains; preload" },
|
||||||
|
{ key: "X-Frame-Options", value: "SAMEORIGIN" },
|
||||||
|
{ key: "X-Content-Type-Options", value: "nosniff" },
|
||||||
|
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
|
||||||
|
{ key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=()" },
|
||||||
|
{ key: "Content-Security-Policy", value: csp },
|
||||||
|
];
|
||||||
|
|
||||||
const nextConfig: NextConfig = {
|
const nextConfig: NextConfig = {
|
||||||
output: "standalone",
|
output: "standalone",
|
||||||
|
poweredByHeader: false,
|
||||||
|
compress: true,
|
||||||
images: {
|
images: {
|
||||||
remotePatterns: [
|
remotePatterns: [
|
||||||
|
{ protocol: "https", hostname: "img.clerk.com" },
|
||||||
|
...(s3Host ? [{ protocol: "https", hostname: s3Host }] : []),
|
||||||
|
] as NonNullable<NonNullable<NextConfig["images"]>["remotePatterns"]>,
|
||||||
|
},
|
||||||
|
async headers() {
|
||||||
|
return [
|
||||||
{
|
{
|
||||||
protocol: "https",
|
source: "/:path*",
|
||||||
hostname: process.env.S3_ENDPOINT?.replace("https://", "") || "",
|
headers: securityHeaders,
|
||||||
},
|
},
|
||||||
{
|
];
|
||||||
protocol: "http",
|
|
||||||
hostname: process.env.S3_ENDPOINT?.replace("http://", "") || "",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export default nextConfig;
|
export default nextConfig;
|
||||||
|
|
||||||
|
|||||||
@ -1,32 +0,0 @@
|
|||||||
upstream nextjs {
|
|
||||||
server app:3000;
|
|
||||||
}
|
|
||||||
|
|
||||||
server {
|
|
||||||
listen 80;
|
|
||||||
server_name testbed.mk *.testbed.mk;
|
|
||||||
|
|
||||||
location / {
|
|
||||||
proxy_pass http://nextjs;
|
|
||||||
proxy_http_version 1.1;
|
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
|
||||||
proxy_set_header Connection 'upgrade';
|
|
||||||
proxy_set_header Host $host;
|
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
|
||||||
|
|
||||||
set $subdomain "";
|
|
||||||
if ($host ~* "^([a-z0-9-]+)\.testbed\.mk$") {
|
|
||||||
set $subdomain $1;
|
|
||||||
}
|
|
||||||
|
|
||||||
proxy_set_header X-Subdomain $subdomain;
|
|
||||||
}
|
|
||||||
|
|
||||||
location /_next/static/ {
|
|
||||||
proxy_pass http://nextjs;
|
|
||||||
proxy_cache_valid 200 365d;
|
|
||||||
add_header Cache-Control "public, immutable";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,53 +0,0 @@
|
|||||||
upstream nextjs {
|
|
||||||
server app:3000;
|
|
||||||
}
|
|
||||||
|
|
||||||
server {
|
|
||||||
listen 80;
|
|
||||||
server_name testbed.mk *.testbed.mk;
|
|
||||||
|
|
||||||
location /.well-known/acme-challenge/ {
|
|
||||||
root /var/www/certbot;
|
|
||||||
}
|
|
||||||
|
|
||||||
location / {
|
|
||||||
return 301 https://$host$request_uri;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
server {
|
|
||||||
listen 443 ssl;
|
|
||||||
http2 on;
|
|
||||||
server_name testbed.mk *.testbed.mk;
|
|
||||||
|
|
||||||
ssl_certificate /etc/letsencrypt/live/testbed.mk/fullchain.pem;
|
|
||||||
ssl_certificate_key /etc/letsencrypt/live/testbed.mk/privkey.pem;
|
|
||||||
|
|
||||||
ssl_protocols TLSv1.2 TLSv1.3;
|
|
||||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
|
||||||
ssl_prefer_server_ciphers on;
|
|
||||||
|
|
||||||
location / {
|
|
||||||
proxy_pass http://nextjs;
|
|
||||||
proxy_http_version 1.1;
|
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
|
||||||
proxy_set_header Connection 'upgrade';
|
|
||||||
proxy_set_header Host $host;
|
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
|
||||||
|
|
||||||
set $subdomain "";
|
|
||||||
if ($host ~* "^([a-z0-9-]+)\.testbed\.mk$") {
|
|
||||||
set $subdomain $1;
|
|
||||||
}
|
|
||||||
|
|
||||||
proxy_set_header X-Subdomain $subdomain;
|
|
||||||
}
|
|
||||||
|
|
||||||
location /_next/static/ {
|
|
||||||
proxy_pass http://nextjs;
|
|
||||||
proxy_cache_valid 200 365d;
|
|
||||||
add_header Cache-Control "public, immutable";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
1876
package-lock.json
generated
1876
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
18
package.json
18
package.json
@ -7,16 +7,25 @@
|
|||||||
"build": "next build",
|
"build": "next build",
|
||||||
"start": "next start",
|
"start": "next start",
|
||||||
"lint": "eslint",
|
"lint": "eslint",
|
||||||
|
"test": "vitest run",
|
||||||
|
"test:watch": "vitest",
|
||||||
|
"typecheck": "tsc --noEmit",
|
||||||
"db:migrate": "prisma migrate dev",
|
"db:migrate": "prisma migrate dev",
|
||||||
"db:push": "prisma db push",
|
"db:push": "prisma db push",
|
||||||
"db:studio": "prisma studio",
|
"db:studio": "prisma studio",
|
||||||
"db:generate": "prisma generate"
|
"db:generate": "prisma generate",
|
||||||
|
"db:seed": "node prisma/seed.cjs"
|
||||||
|
},
|
||||||
|
"prisma": {
|
||||||
|
"seed": "node prisma/seed.cjs"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@aws-sdk/client-s3": "^3.1073.0",
|
"@aws-sdk/client-s3": "^3.1073.0",
|
||||||
"@aws-sdk/s3-request-presigner": "^3.1073.0",
|
"@aws-sdk/s3-request-presigner": "^3.1073.0",
|
||||||
"@clerk/nextjs": "^7.5.7",
|
"@clerk/nextjs": "^7.5.7",
|
||||||
"@prisma/client": "^5.22.0",
|
"@prisma/client": "^5.22.0",
|
||||||
|
"bcryptjs": "^3.0.3",
|
||||||
|
"lru-cache": "^11.0.0",
|
||||||
"next": "^15.5.19",
|
"next": "^15.5.19",
|
||||||
"qrcode": "^1.5.4",
|
"qrcode": "^1.5.4",
|
||||||
"react": "19.2.4",
|
"react": "19.2.4",
|
||||||
@ -25,7 +34,8 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@tailwindcss/postcss": "^4",
|
"@tailwindcss/postcss": "^4",
|
||||||
"@types/node": "^20",
|
"@types/bcryptjs": "^2.4.6",
|
||||||
|
"@types/node": "^20.19.43",
|
||||||
"@types/qrcode": "^1.5.6",
|
"@types/qrcode": "^1.5.6",
|
||||||
"@types/react": "^19",
|
"@types/react": "^19",
|
||||||
"@types/react-dom": "^19",
|
"@types/react-dom": "^19",
|
||||||
@ -34,6 +44,8 @@
|
|||||||
"eslint-config-next": "^15.5.19",
|
"eslint-config-next": "^15.5.19",
|
||||||
"prisma": "^5.22.0",
|
"prisma": "^5.22.0",
|
||||||
"tailwindcss": "^4",
|
"tailwindcss": "^4",
|
||||||
"typescript": "^5"
|
"tsx": "^4.23.3",
|
||||||
|
"typescript": "^5",
|
||||||
|
"vitest": "^2.1.9"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -0,0 +1,40 @@
|
|||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "Role" AS ENUM ('SUPER_ADMIN', 'ADMIN');
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "AdminUser" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"username" TEXT NOT NULL,
|
||||||
|
"passwordHash" TEXT NOT NULL,
|
||||||
|
"role" "Role" NOT NULL DEFAULT 'ADMIN',
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "AdminUser_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "Code" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"code" TEXT NOT NULL,
|
||||||
|
"createdById" TEXT NOT NULL,
|
||||||
|
"usedByUserId" TEXT,
|
||||||
|
"usedAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "Code_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "AdminUser_username_key" ON "AdminUser"("username");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "Code_code_key" ON "Code"("code");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "Code_code_idx" ON "Code"("code");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "Code_usedByUserId_idx" ON "Code"("usedByUserId");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "Code" ADD CONSTRAINT "Code_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "AdminUser"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
@ -0,0 +1,43 @@
|
|||||||
|
-- Phase 6 schema hardening
|
||||||
|
-- Adds @db.VarChar() length bounds to all string columns, updatedAt to
|
||||||
|
-- Image/AdminUser/Code, an index on Image.key, and documents the
|
||||||
|
-- existing Code.createdById onDelete:RESTRICT behaviour with a schema
|
||||||
|
-- comment (no DDL change there; it was already RESTRICT by default).
|
||||||
|
|
||||||
|
-- === User: add VarChar bounds ===
|
||||||
|
ALTER TABLE "User" ALTER COLUMN "id" SET DATA TYPE VARCHAR(30);
|
||||||
|
ALTER TABLE "User" ALTER COLUMN "clerkId" SET DATA TYPE VARCHAR(100);
|
||||||
|
ALTER TABLE "User" ALTER COLUMN "email" SET DATA TYPE VARCHAR(255);
|
||||||
|
ALTER TABLE "User" ALTER COLUMN "name" SET DATA TYPE VARCHAR(100);
|
||||||
|
ALTER TABLE "User" ALTER COLUMN "subdomain" SET DATA TYPE VARCHAR(32);
|
||||||
|
ALTER TABLE "User" ALTER COLUMN "title" SET DATA TYPE VARCHAR(100);
|
||||||
|
ALTER TABLE "User" ALTER COLUMN "description" SET DATA TYPE VARCHAR(2000);
|
||||||
|
ALTER TABLE "User" ALTER COLUMN "bornDate" SET DATA TYPE VARCHAR(50);
|
||||||
|
ALTER TABLE "User" ALTER COLUMN "passedDate" SET DATA TYPE VARCHAR(50);
|
||||||
|
|
||||||
|
-- === Image: bounds + updatedAt + index on key ===
|
||||||
|
ALTER TABLE "Image" ALTER COLUMN "id" SET DATA TYPE VARCHAR(30);
|
||||||
|
ALTER TABLE "Image" ALTER COLUMN "url" SET DATA TYPE VARCHAR(255);
|
||||||
|
ALTER TABLE "Image" ALTER COLUMN "key" SET DATA TYPE VARCHAR(255);
|
||||||
|
ALTER TABLE "Image" ALTER COLUMN "userId" SET DATA TYPE VARCHAR(30);
|
||||||
|
ALTER TABLE "Image" ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;
|
||||||
|
CREATE INDEX "Image_key_idx" ON "Image"("key");
|
||||||
|
|
||||||
|
-- === AdminUser: bounds + updatedAt ===
|
||||||
|
ALTER TABLE "AdminUser" ALTER COLUMN "id" SET DATA TYPE VARCHAR(30);
|
||||||
|
ALTER TABLE "AdminUser" ALTER COLUMN "username" SET DATA TYPE VARCHAR(50);
|
||||||
|
ALTER TABLE "AdminUser" ALTER COLUMN "passwordHash" SET DATA TYPE VARCHAR(100);
|
||||||
|
ALTER TABLE "AdminUser" ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;
|
||||||
|
|
||||||
|
-- === Code: bounds + updatedAt ===
|
||||||
|
ALTER TABLE "Code" ALTER COLUMN "id" SET DATA TYPE VARCHAR(30);
|
||||||
|
ALTER TABLE "Code" ALTER COLUMN "code" SET DATA TYPE VARCHAR(12);
|
||||||
|
ALTER TABLE "Code" ALTER COLUMN "createdById" SET DATA TYPE VARCHAR(30);
|
||||||
|
ALTER TABLE "Code" ALTER COLUMN "usedByUserId" SET DATA TYPE VARCHAR(100);
|
||||||
|
ALTER TABLE "Code" ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;
|
||||||
|
|
||||||
|
-- Backfill any rows whose string columns exceed the new bounds (defensive;
|
||||||
|
-- production data was capped at the maxLength on the input side already but
|
||||||
|
-- the persistence layer was unbounded). Truncating is safer than failing.
|
||||||
|
UPDATE "User" SET "bornDate" = LEFT("bornDate", 50) WHERE "bornDate" IS NOT NULL AND LENGTH("bornDate") > 50;
|
||||||
|
UPDATE "User" SET "passedDate" = LEFT("passedDate", 50) WHERE "passedDate" IS NOT NULL AND LENGTH("passedDate") > 50;
|
||||||
@ -9,30 +9,67 @@ datasource db {
|
|||||||
}
|
}
|
||||||
|
|
||||||
model User {
|
model User {
|
||||||
id String @id @default(cuid())
|
id String @id @default(cuid()) @db.VarChar(30)
|
||||||
clerkId String @unique
|
clerkId String @unique @db.VarChar(100)
|
||||||
email String?
|
email String? @db.VarChar(255)
|
||||||
name String?
|
name String? @db.VarChar(100)
|
||||||
subdomain String @unique
|
subdomain String @unique @db.VarChar(32)
|
||||||
templateId Int @default(1)
|
templateId Int @default(1)
|
||||||
title String?
|
title String? @db.VarChar(100)
|
||||||
description String?
|
description String? @db.VarChar(2000)
|
||||||
bornDate String?
|
// Free-form text — intentionally accepts imprecise values like "1960"
|
||||||
passedDate String?
|
// or "early 1990s", not a parseable date. If structured date queries
|
||||||
published Boolean @default(false)
|
// become needed, add a parallel bornDateParsed DateTime? column.
|
||||||
createdAt DateTime @default(now())
|
bornDate String? @db.VarChar(50)
|
||||||
updatedAt DateTime @updatedAt
|
passedDate String? @db.VarChar(50)
|
||||||
|
published Boolean @default(false)
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
images Image[]
|
images Image[]
|
||||||
}
|
}
|
||||||
|
|
||||||
model Image {
|
model Image {
|
||||||
id String @id @default(cuid())
|
id String @id @default(cuid()) @db.VarChar(30)
|
||||||
url String
|
url String @db.VarChar(255)
|
||||||
key String
|
key String @db.VarChar(255)
|
||||||
order Int
|
order Int
|
||||||
userId String
|
userId String @db.VarChar(30)
|
||||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
@@index([userId])
|
@@index([userId])
|
||||||
|
@@index([key])
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Role {
|
||||||
|
SUPER_ADMIN
|
||||||
|
ADMIN
|
||||||
|
}
|
||||||
|
|
||||||
|
model AdminUser {
|
||||||
|
id String @id @default(cuid()) @db.VarChar(30)
|
||||||
|
username String @unique @db.VarChar(50)
|
||||||
|
passwordHash String @db.VarChar(100)
|
||||||
|
role Role @default(ADMIN)
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
createdCodes Code[]
|
||||||
|
}
|
||||||
|
|
||||||
|
model Code {
|
||||||
|
id String @id @default(cuid()) @db.VarChar(30)
|
||||||
|
code String @unique @db.VarChar(12)
|
||||||
|
// onDelete: Restrict (Prisma default) — preventing deletion of an
|
||||||
|
// AdminUser that has issued codes is intentional; we don't want
|
||||||
|
// orphaned codes with no audit trail of who created them.
|
||||||
|
createdById String @db.VarChar(30)
|
||||||
|
createdBy AdminUser @relation(fields: [createdById], references: [id])
|
||||||
|
usedByUserId String? @db.VarChar(100)
|
||||||
|
usedAt DateTime?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
@@index([code])
|
||||||
|
@@index([usedByUserId])
|
||||||
}
|
}
|
||||||
42
prisma/seed.cjs
Normal file
42
prisma/seed.cjs
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
const { PrismaClient, Role } = require("@prisma/client");
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const username = process.env.SUPER_ADMIN_USERNAME || "super";
|
||||||
|
const hash = process.env.SUPER_ADMIN_PASSWORD_HASH;
|
||||||
|
|
||||||
|
if (!hash) {
|
||||||
|
console.warn(
|
||||||
|
"[seed] SUPER_ADMIN_PASSWORD_HASH env not set; skipping super-admin provisioning."
|
||||||
|
);
|
||||||
|
console.warn(
|
||||||
|
"[seed] Generate one with: node -e \"import('bcryptjs').then(b => b.default.hash('YOUR_PASSWORD', 12).then(console.log))\""
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.adminUser.upsert({
|
||||||
|
where: { username },
|
||||||
|
update: {
|
||||||
|
passwordHash: hash,
|
||||||
|
role: Role.SUPER_ADMIN,
|
||||||
|
},
|
||||||
|
create: {
|
||||||
|
username,
|
||||||
|
passwordHash: hash,
|
||||||
|
role: Role.SUPER_ADMIN,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(`[seed] Super-admin '${username}' provisioned.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
|
.catch((e) => {
|
||||||
|
console.error("[seed] failed:", e);
|
||||||
|
process.exit(1);
|
||||||
|
})
|
||||||
|
.finally(async () => {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
});
|
||||||
@ -9,9 +9,13 @@ echo "CLERK_SECRET_KEY: ${CLERK_SECRET_KEY:+set}"
|
|||||||
echo "S3_ENDPOINT: ${S3_ENDPOINT:+set}"
|
echo "S3_ENDPOINT: ${S3_ENDPOINT:+set}"
|
||||||
|
|
||||||
echo "Running Prisma migrations..."
|
echo "Running Prisma migrations..."
|
||||||
npx prisma migrate deploy || {
|
if ! npx prisma migrate deploy; then
|
||||||
echo "WARNING: Prisma migrations failed, continuing anyway..."
|
echo "ERROR: Prisma migrations failed. Aborting start."
|
||||||
}
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Provisioning super-admin (skips if SUPER_ADMIN_PASSWORD_HASH unset)..."
|
||||||
|
node prisma/seed.cjs
|
||||||
|
|
||||||
echo "Starting Next.js server on 0.0.0.0:3000..."
|
echo "Starting Next.js server on 0.0.0.0:3000..."
|
||||||
exec node server.js
|
exec node server.js
|
||||||
78
src/app/admin/(auth)/login/page.tsx
Normal file
78
src/app/admin/(auth)/login/page.tsx
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
|
||||||
|
export default function AdminLoginPage() {
|
||||||
|
const router = useRouter();
|
||||||
|
const [username, setUsername] = useState("");
|
||||||
|
const [password, setPassword] = useState("");
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setLoading(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/admin/login", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ username, password }),
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(data.error || "Најавата не успеа");
|
||||||
|
}
|
||||||
|
router.push("/admin/dashboard");
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : "Најавата не успеа");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen items-center justify-center bg-stone-100">
|
||||||
|
<div className="w-full max-w-sm rounded-lg bg-white p-8 shadow-sm">
|
||||||
|
<h1 className="mb-6 text-center text-xl font-semibold text-stone-900">Администрација</h1>
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label htmlFor="username" className="block text-sm font-medium text-stone-700">
|
||||||
|
Корисничко име
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="username"
|
||||||
|
type="text"
|
||||||
|
value={username}
|
||||||
|
onChange={(e) => setUsername(e.target.value)}
|
||||||
|
className="mt-1 block w-full rounded-lg border border-stone-200 px-3 py-2.5 text-stone-900 placeholder:text-stone-400 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
|
||||||
|
autoComplete="username"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label htmlFor="password" className="block text-sm font-medium text-stone-700">
|
||||||
|
Лозинка
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="password"
|
||||||
|
type="password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
className="mt-1 block w-full rounded-lg border border-stone-200 px-3 py-2.5 text-stone-900 placeholder:text-stone-400 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
|
||||||
|
autoComplete="current-password"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{error && <p className="text-sm text-red-600">{error}</p>}
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={loading || !username || !password}
|
||||||
|
className="w-full rounded-lg bg-primary px-6 py-2.5 text-sm font-medium text-white transition-colors hover:bg-primary-light disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{loading ? "Најавување..." : "Најави се"}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
57
src/app/admin/(panel)/AdminSidebar.tsx
Normal file
57
src/app/admin/(panel)/AdminSidebar.tsx
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useRouter, usePathname } from "next/navigation";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
username: string;
|
||||||
|
role: "SUPER_ADMIN" | "ADMIN";
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function AdminSidebar({ username, role }: Props) {
|
||||||
|
const router = useRouter();
|
||||||
|
const pathname = usePathname();
|
||||||
|
|
||||||
|
const handleLogout = async () => {
|
||||||
|
await fetch("/api/admin/logout", { method: "POST", credentials: "include" });
|
||||||
|
router.push("/admin/login");
|
||||||
|
};
|
||||||
|
|
||||||
|
const links = [
|
||||||
|
{ href: "/admin/dashboard", label: "Контролна табла" },
|
||||||
|
...(role === "SUPER_ADMIN" ? [{ href: "/admin/users", label: "Администратори" }] : []),
|
||||||
|
{ href: "/admin/codes", label: "Кодови" },
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<aside className="flex w-64 flex-col bg-primary text-white">
|
||||||
|
<div className="border-b border-white/10 px-6 py-5">
|
||||||
|
<h2 className="text-lg font-semibold">СпоменQR</h2>
|
||||||
|
<p className="mt-1 text-xs text-white/60">
|
||||||
|
{username} {role === "SUPER_ADMIN" ? "(SuperAdmin)" : "(Admin)"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<nav className="flex-1 space-y-1 px-3 py-4">
|
||||||
|
{links.map((link) => (
|
||||||
|
<Link
|
||||||
|
key={link.href}
|
||||||
|
href={link.href}
|
||||||
|
className={`block rounded-md px-3 py-2 text-sm transition-colors ${
|
||||||
|
pathname === link.href ? "bg-white/15 text-white" : "text-white/70 hover:bg-white/10 hover:text-white"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{link.label}
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
<div className="border-t border-white/10 px-3 py-4">
|
||||||
|
<button
|
||||||
|
onClick={handleLogout}
|
||||||
|
className="block w-full rounded-md px-3 py-2 text-left text-sm text-white/70 transition-colors hover:bg-white/10 hover:text-white"
|
||||||
|
>
|
||||||
|
Одјави се
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
);
|
||||||
|
}
|
||||||
144
src/app/admin/(panel)/codes/page.tsx
Normal file
144
src/app/admin/(panel)/codes/page.tsx
Normal file
@ -0,0 +1,144 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
|
interface Code {
|
||||||
|
id: string;
|
||||||
|
code: string;
|
||||||
|
usedByUserId: string | null;
|
||||||
|
usedAt: string | null;
|
||||||
|
createdAt: string;
|
||||||
|
createdBy: { username: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function AdminCodesPage() {
|
||||||
|
const [codes, setCodes] = useState<Code[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [generating, setGenerating] = useState(false);
|
||||||
|
const [newCode, setNewCode] = useState("");
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
|
||||||
|
const fetchCodes = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/admin/codes", { credentials: "include" });
|
||||||
|
if (res.ok) {
|
||||||
|
setCodes(await res.json());
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchCodes();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleGenerate = async () => {
|
||||||
|
setGenerating(true);
|
||||||
|
setError("");
|
||||||
|
setNewCode("");
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/admin/codes", { method: "POST", credentials: "include" });
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(data.error || "Грешка при генерирање");
|
||||||
|
}
|
||||||
|
setNewCode(data.code);
|
||||||
|
fetchCodes();
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : "Грешка при генерирање");
|
||||||
|
} finally {
|
||||||
|
setGenerating(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDelete = async (id: string) => {
|
||||||
|
if (!confirm("Дали сте сигурни?")) return;
|
||||||
|
try {
|
||||||
|
await fetch(`/api/admin/codes/${id}`, { method: "DELETE", credentials: "include" });
|
||||||
|
fetchCodes();
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="mb-8 flex items-center justify-between">
|
||||||
|
<h1 className="text-2xl font-semibold text-stone-900">Кодови</h1>
|
||||||
|
<button
|
||||||
|
onClick={handleGenerate}
|
||||||
|
disabled={generating}
|
||||||
|
className="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-primary-light disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{generating ? "Генерирање..." : "Генерирај код"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{newCode && (
|
||||||
|
<div className="mb-8 rounded-lg border border-green-200 bg-green-50 p-4">
|
||||||
|
<p className="text-sm font-medium text-green-800">Нов код:</p>
|
||||||
|
<p className="mt-1 text-2xl font-bold tracking-widest text-green-900">{newCode}</p>
|
||||||
|
<p className="mt-1 text-xs text-green-600">Копирајте го кодот. Ќе биде прикажан само еднаш.</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div className="mb-8 rounded-lg bg-red-50 p-4 text-sm text-red-700">{error}</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="rounded-lg bg-white shadow-sm">
|
||||||
|
{loading ? (
|
||||||
|
<p className="p-6 text-sm text-stone-500">Вчитување...</p>
|
||||||
|
) : codes.length === 0 ? (
|
||||||
|
<p className="p-6 text-sm text-stone-500">Нема генерирани кодови</p>
|
||||||
|
) : (
|
||||||
|
<table className="w-full text-left text-sm">
|
||||||
|
<thead className="border-b border-stone-200">
|
||||||
|
<tr>
|
||||||
|
<th className="px-6 py-3 font-medium text-stone-500">Код</th>
|
||||||
|
<th className="px-6 py-3 font-medium text-stone-500">Креиран од</th>
|
||||||
|
<th className="px-6 py-3 font-medium text-stone-500">Креиран</th>
|
||||||
|
<th className="px-6 py-3 font-medium text-stone-500">Статус</th>
|
||||||
|
<th className="px-6 py-3 font-medium text-stone-500">Акции</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-stone-100">
|
||||||
|
{codes.map((item) => (
|
||||||
|
<tr key={item.id} className="hover:bg-stone-50">
|
||||||
|
<td className="px-6 py-4 font-mono text-stone-900">{item.code}</td>
|
||||||
|
<td className="px-6 py-4 text-stone-600">{item.createdBy.username}</td>
|
||||||
|
<td className="px-6 py-4 text-stone-600">{new Date(item.createdAt).toLocaleDateString("mk-MK")}</td>
|
||||||
|
<td className="px-6 py-4">
|
||||||
|
{item.usedByUserId ? (
|
||||||
|
<span className="inline-flex rounded-full bg-green-100 px-2.5 py-0.5 text-xs font-medium text-green-800">
|
||||||
|
Искористен
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className="inline-flex rounded-full bg-stone-100 px-2.5 py-0.5 text-xs font-medium text-stone-600">
|
||||||
|
Неискористен
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-4">
|
||||||
|
{!item.usedByUserId && (
|
||||||
|
<button
|
||||||
|
onClick={() => handleDelete(item.id)}
|
||||||
|
className="text-sm text-red-600 hover:underline"
|
||||||
|
>
|
||||||
|
Избриши
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
29
src/app/admin/(panel)/dashboard/page.tsx
Normal file
29
src/app/admin/(panel)/dashboard/page.tsx
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
|
||||||
|
export default async function AdminDashboardPage() {
|
||||||
|
const [adminCount, codeCount, usedCodeCount] = await Promise.all([
|
||||||
|
prisma.adminUser.count(),
|
||||||
|
prisma.code.count(),
|
||||||
|
prisma.code.count({ where: { usedByUserId: { not: null } } }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<h1 className="mb-8 text-2xl font-semibold text-stone-900">Контролна табла</h1>
|
||||||
|
<div className="grid gap-6 sm:grid-cols-3">
|
||||||
|
<div className="rounded-lg bg-white p-6 shadow-sm">
|
||||||
|
<p className="text-sm text-stone-500">Администратори</p>
|
||||||
|
<p className="mt-1 text-3xl font-semibold text-stone-900">{adminCount}</p>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-lg bg-white p-6 shadow-sm">
|
||||||
|
<p className="text-sm text-stone-500">Генерирани кодови</p>
|
||||||
|
<p className="mt-1 text-3xl font-semibold text-stone-900">{codeCount}</p>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-lg bg-white p-6 shadow-sm">
|
||||||
|
<p className="text-sm text-stone-500">Искористени кодови</p>
|
||||||
|
<p className="mt-1 text-3xl font-semibold text-stone-900">{usedCodeCount}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
21
src/app/admin/(panel)/layout.tsx
Normal file
21
src/app/admin/(panel)/layout.tsx
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
import { getAdminSession } from "@/lib/admin-session";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import AdminSidebar from "./AdminSidebar";
|
||||||
|
|
||||||
|
// Admin pages must always render against the live session — never at build
|
||||||
|
// time (static generation would run DB queries during `next build`).
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export default async function AdminLayout({ children }: { children: React.ReactNode }) {
|
||||||
|
const session = await getAdminSession();
|
||||||
|
if (!session) {
|
||||||
|
redirect("/admin/login");
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen bg-stone-100">
|
||||||
|
<AdminSidebar username={session.username} role={session.role} />
|
||||||
|
<main className="flex-1 p-8">{children}</main>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
189
src/app/admin/(panel)/users/page.tsx
Normal file
189
src/app/admin/(panel)/users/page.tsx
Normal file
@ -0,0 +1,189 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
|
interface AdminUser {
|
||||||
|
id: string;
|
||||||
|
username: string;
|
||||||
|
role: string;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function AdminUsersPage() {
|
||||||
|
const [users, setUsers] = useState<AdminUser[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [showCreate, setShowCreate] = useState(false);
|
||||||
|
const [newUsername, setNewUsername] = useState("");
|
||||||
|
const [newPassword, setNewPassword] = useState("");
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
|
||||||
|
const fetchUsers = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/admin/users", { credentials: "include" });
|
||||||
|
if (res.ok) {
|
||||||
|
setUsers(await res.json());
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchUsers();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleCreate = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/admin/users", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
credentials: "include",
|
||||||
|
body: JSON.stringify({ username: newUsername, password: newPassword }),
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const data = await res.json();
|
||||||
|
throw new Error(data.error || "Грешка при креирање");
|
||||||
|
}
|
||||||
|
setShowCreate(false);
|
||||||
|
setNewUsername("");
|
||||||
|
setNewPassword("");
|
||||||
|
fetchUsers();
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : "Грешка при креирање");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDelete = async (id: string) => {
|
||||||
|
if (!confirm("Дали сте сигурни дека сакате да го избришете овој администратор?")) return;
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/admin/users/${id}`, { method: "DELETE", credentials: "include" });
|
||||||
|
if (res.ok) {
|
||||||
|
fetchUsers();
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleResetPassword = async (id: string) => {
|
||||||
|
const newPw = prompt("Внесете нова лозинка:");
|
||||||
|
if (!newPw || newPw.length < 6) {
|
||||||
|
alert("Лозинката мора да има најмалку 6 карактери");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/admin/users/${id}`, {
|
||||||
|
method: "PUT",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
credentials: "include",
|
||||||
|
body: JSON.stringify({ password: newPw }),
|
||||||
|
});
|
||||||
|
if (res.ok) {
|
||||||
|
alert("Лозинката е променета");
|
||||||
|
} else {
|
||||||
|
const data = await res.json();
|
||||||
|
alert(data.error || "Грешка");
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
alert("Грешка");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="mb-8 flex items-center justify-between">
|
||||||
|
<h1 className="text-2xl font-semibold text-stone-900">Администратори</h1>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowCreate(!showCreate)}
|
||||||
|
className="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-primary-light"
|
||||||
|
>
|
||||||
|
{showCreate ? "Откажи" : "Креирај администратор"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{showCreate && (
|
||||||
|
<form onSubmit={handleCreate} className="mb-8 rounded-lg bg-white p-6 shadow-sm">
|
||||||
|
<div className="mb-4 grid gap-4 sm:grid-cols-2">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-stone-700">Корисничко име</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={newUsername}
|
||||||
|
onChange={(e) => setNewUsername(e.target.value)}
|
||||||
|
className="mt-1 block w-full rounded-lg border border-stone-200 px-3 py-2.5 text-stone-900 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-stone-700">Лозинка</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={newPassword}
|
||||||
|
onChange={(e) => setNewPassword(e.target.value)}
|
||||||
|
className="mt-1 block w-full rounded-lg border border-stone-200 px-3 py-2.5 text-stone-900 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
|
||||||
|
required
|
||||||
|
minLength={6}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{error && <p className="mb-4 text-sm text-red-600">{error}</p>}
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="rounded-lg bg-primary px-6 py-2 text-sm font-medium text-white transition-colors hover:bg-primary-light"
|
||||||
|
>
|
||||||
|
Креирај
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="rounded-lg bg-white shadow-sm">
|
||||||
|
{loading ? (
|
||||||
|
<p className="p-6 text-sm text-stone-500">Вчитување...</p>
|
||||||
|
) : users.length === 0 ? (
|
||||||
|
<p className="p-6 text-sm text-stone-500">Нема администратори</p>
|
||||||
|
) : (
|
||||||
|
<table className="w-full text-left text-sm">
|
||||||
|
<thead className="border-b border-stone-200">
|
||||||
|
<tr>
|
||||||
|
<th className="px-6 py-3 font-medium text-stone-500">Корисничко име</th>
|
||||||
|
<th className="px-6 py-3 font-medium text-stone-500">Улога</th>
|
||||||
|
<th className="px-6 py-3 font-medium text-stone-500">Креиран</th>
|
||||||
|
<th className="px-6 py-3 font-medium text-stone-500">Акции</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-stone-100">
|
||||||
|
{users.map((user) => (
|
||||||
|
<tr key={user.id} className="hover:bg-stone-50">
|
||||||
|
<td className="px-6 py-4 text-stone-900">{user.username}</td>
|
||||||
|
<td className="px-6 py-4 text-stone-600">{user.role === "SUPER_ADMIN" ? "SuperAdmin" : "Admin"}</td>
|
||||||
|
<td className="px-6 py-4 text-stone-600">{new Date(user.createdAt).toLocaleDateString("mk-MK")}</td>
|
||||||
|
<td className="space-x-2 px-6 py-4">
|
||||||
|
<button
|
||||||
|
onClick={() => handleResetPassword(user.id)}
|
||||||
|
className="text-sm text-primary hover:underline"
|
||||||
|
>
|
||||||
|
Промени лозинка
|
||||||
|
</button>
|
||||||
|
{user.role !== "SUPER_ADMIN" && (
|
||||||
|
<button
|
||||||
|
onClick={() => handleDelete(user.id)}
|
||||||
|
className="text-sm text-red-600 hover:underline"
|
||||||
|
>
|
||||||
|
Избриши
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
54
src/app/api/admin/change-password/route.ts
Normal file
54
src/app/api/admin/change-password/route.ts
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { hash, compare } from "bcryptjs";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { requireAdminPost } from "@/lib/admin-session";
|
||||||
|
import { ADMIN_PASSWORD_MIN_LENGTH } from "@/lib/config";
|
||||||
|
|
||||||
|
function strongEnough(password: string): boolean {
|
||||||
|
if (password.length < ADMIN_PASSWORD_MIN_LENGTH) return false;
|
||||||
|
return /[A-Za-z]/.test(password) && /\d/.test(password);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const guard = await requireAdminPost()(req);
|
||||||
|
if ("response" in guard) return guard.response;
|
||||||
|
const { session } = guard;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (session.username === "super") {
|
||||||
|
return NextResponse.json({ error: "SuperAdmin не може да ја промени лозинката преку овој метод" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { currentPassword, newPassword } = await req.json();
|
||||||
|
if (!currentPassword || !newPassword) {
|
||||||
|
return NextResponse.json({ error: "Тековната и новата лозинка се задолжителни" }, { status: 400 });
|
||||||
|
}
|
||||||
|
if (!strongEnough(newPassword)) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: `Новата лозинка мора да има најмалку ${ADMIN_PASSWORD_MIN_LENGTH} карактери и да содржи буква и цифра` },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const admin = await prisma.adminUser.findUnique({ where: { username: session.username } });
|
||||||
|
if (!admin) {
|
||||||
|
return NextResponse.json({ error: "Администраторот не е пронајден" }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const valid = await compare(currentPassword, admin.passwordHash);
|
||||||
|
if (!valid) {
|
||||||
|
return NextResponse.json({ error: "Тековната лозинка е неточна" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const passwordHash = await hash(newPassword, 12);
|
||||||
|
await prisma.adminUser.update({
|
||||||
|
where: { username: session.username },
|
||||||
|
data: { passwordHash },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ success: true });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Change password error:", error);
|
||||||
|
return NextResponse.json({ error: "Внатрешна грешка на серверот" }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
28
src/app/api/admin/codes/[id]/route.ts
Normal file
28
src/app/api/admin/codes/[id]/route.ts
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { requireAdminPost } from "@/lib/admin-session";
|
||||||
|
|
||||||
|
export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const guard = await requireAdminPost()(req);
|
||||||
|
if ("response" in guard) return guard.response;
|
||||||
|
const { session } = guard;
|
||||||
|
|
||||||
|
const { id } = await params;
|
||||||
|
const code = await prisma.code.findUnique({ where: { id } });
|
||||||
|
if (!code) {
|
||||||
|
return NextResponse.json({ error: "Кодот не е пронајден" }, { status: 404 });
|
||||||
|
}
|
||||||
|
if (code.usedByUserId) {
|
||||||
|
return NextResponse.json({ error: "Не можете да избришете искористен код" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (session.role !== "SUPER_ADMIN") {
|
||||||
|
const admin = await prisma.adminUser.findUnique({ where: { username: session.username } });
|
||||||
|
if (!admin || code.createdById !== admin.id) {
|
||||||
|
return NextResponse.json({ error: "Немате дозвола" }, { status: 403 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.code.delete({ where: { id } });
|
||||||
|
return NextResponse.json({ success: true });
|
||||||
|
}
|
||||||
45
src/app/api/admin/codes/route.ts
Normal file
45
src/app/api/admin/codes/route.ts
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { randomBytes } from "crypto";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { requireAdmin, requireAdminPost } from "@/lib/admin-session";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
const guard = await requireAdmin()();
|
||||||
|
if ("response" in guard) return guard.response;
|
||||||
|
const { session } = guard;
|
||||||
|
|
||||||
|
const where = session.role === "SUPER_ADMIN" ? {} : { createdBy: { username: session.username } };
|
||||||
|
|
||||||
|
const codes = await prisma.code.findMany({
|
||||||
|
where,
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
include: { createdBy: { select: { username: true } } },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json(codes);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const guard = await requireAdminPost()(req);
|
||||||
|
if ("response" in guard) return guard.response;
|
||||||
|
const { session } = guard;
|
||||||
|
|
||||||
|
const admin = await prisma.adminUser.findUnique({ where: { username: session.username } });
|
||||||
|
if (!admin) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Администраторот не е пронајден во базата. Кодови може да креираат само администратори со запис во базата." },
|
||||||
|
{ status: 404 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const code = randomBytes(6).toString("hex").toUpperCase();
|
||||||
|
|
||||||
|
const created = await prisma.code.create({
|
||||||
|
data: {
|
||||||
|
code,
|
||||||
|
createdById: admin.id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json(created, { status: 201 });
|
||||||
|
}
|
||||||
59
src/app/api/admin/login/route.ts
Normal file
59
src/app/api/admin/login/route.ts
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { compare } from "bcryptjs";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { createAdminSession, cookieOptions } from "@/lib/admin-session";
|
||||||
|
import { adminLoginLimiter, rateLimitHeaders } from "@/lib/rate-limit";
|
||||||
|
import { SUPER_ADMIN_USERNAME, SUPER_ADMIN_PASSWORD_HASH } from "@/lib/config";
|
||||||
|
|
||||||
|
function clientIp(req: NextRequest): string {
|
||||||
|
const fwd = req.headers.get("x-forwarded-for");
|
||||||
|
if (fwd) return fwd.split(",")[0].trim();
|
||||||
|
return req.headers.get("x-real-ip") || "unknown";
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const ip = clientIp(req);
|
||||||
|
const limit = adminLoginLimiter.limit(`admin-login:${ip}`);
|
||||||
|
if (!limit.success) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Премногу обиди. Обидете се повторно подоцна." },
|
||||||
|
{ status: 429, headers: rateLimitHeaders(limit) }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { username, password } = await req.json();
|
||||||
|
if (!username || !password) {
|
||||||
|
return NextResponse.json({ error: "Корисничко име и лозинка се задолжителни" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (username === SUPER_ADMIN_USERNAME && SUPER_ADMIN_PASSWORD_HASH) {
|
||||||
|
const valid = await compare(password, SUPER_ADMIN_PASSWORD_HASH);
|
||||||
|
if (!valid) {
|
||||||
|
return NextResponse.json({ error: "Невалидно корисничко име или лозинка" }, { status: 401 });
|
||||||
|
}
|
||||||
|
const session = await createAdminSession({ username: SUPER_ADMIN_USERNAME, role: "SUPER_ADMIN" });
|
||||||
|
const res = NextResponse.json({ success: true });
|
||||||
|
res.cookies.set(cookieOptions(session));
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
const admin = await prisma.adminUser.findUnique({ where: { username } });
|
||||||
|
if (!admin) {
|
||||||
|
return NextResponse.json({ error: "Невалидно корисничко име или лозинка" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const valid = await compare(password, admin.passwordHash);
|
||||||
|
if (!valid) {
|
||||||
|
return NextResponse.json({ error: "Невалидно корисничко име или лозинка" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const session = await createAdminSession({ username: admin.username, role: admin.role });
|
||||||
|
const res = NextResponse.json({ success: true });
|
||||||
|
res.cookies.set(cookieOptions(session));
|
||||||
|
return res;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Admin login error:", error);
|
||||||
|
return NextResponse.json({ error: "Внатрешна грешка на серверот" }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
20
src/app/api/admin/logout/route.ts
Normal file
20
src/app/api/admin/logout/route.ts
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { COOKIE_NAME_ADMIN, requireAdminPost } from "@/lib/admin-session";
|
||||||
|
|
||||||
|
export async function POST(req: Request) {
|
||||||
|
const guard = await requireAdminPost()(req as never);
|
||||||
|
if ("response" in guard) return guard.response;
|
||||||
|
|
||||||
|
const res = NextResponse.json({ success: true });
|
||||||
|
res.cookies.set({
|
||||||
|
name: COOKIE_NAME_ADMIN,
|
||||||
|
value: "",
|
||||||
|
httpOnly: true,
|
||||||
|
secure: process.env.NODE_ENV === "production",
|
||||||
|
sameSite: "lax",
|
||||||
|
path: "/",
|
||||||
|
maxAge: 0,
|
||||||
|
});
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
59
src/app/api/admin/users/[id]/route.ts
Normal file
59
src/app/api/admin/users/[id]/route.ts
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { hash } from "bcryptjs";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { requireSuperAdminPost } from "@/lib/admin-session";
|
||||||
|
import { ADMIN_PASSWORD_MIN_LENGTH } from "@/lib/config";
|
||||||
|
|
||||||
|
function strongEnough(password: string): boolean {
|
||||||
|
if (password.length < ADMIN_PASSWORD_MIN_LENGTH) return false;
|
||||||
|
return /[A-Za-z]/.test(password) && /\d/.test(password);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const guard = await requireSuperAdminPost()(req);
|
||||||
|
if ("response" in guard) return guard.response;
|
||||||
|
|
||||||
|
const { id } = await params;
|
||||||
|
const user = await prisma.adminUser.findUnique({ where: { id } });
|
||||||
|
if (!user) {
|
||||||
|
return NextResponse.json({ error: "Администраторот не е пронајден" }, { status: 404 });
|
||||||
|
}
|
||||||
|
if (user.role === "SUPER_ADMIN") {
|
||||||
|
return NextResponse.json({ error: "Не можете да избришете SuperAdmin" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.adminUser.delete({ where: { id } });
|
||||||
|
return NextResponse.json({ success: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const guard = await requireSuperAdminPost()(req);
|
||||||
|
if ("response" in guard) return guard.response;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { id } = await params;
|
||||||
|
const { password } = await req.json();
|
||||||
|
if (!password || !strongEnough(password)) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: `Лозинката мора да има најмалку ${ADMIN_PASSWORD_MIN_LENGTH} карактери и да содржи буква и цифра` },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await prisma.adminUser.findUnique({ where: { id } });
|
||||||
|
if (!user) {
|
||||||
|
return NextResponse.json({ error: "Администраторот не е пронајден" }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const passwordHash = await hash(password, 12);
|
||||||
|
await prisma.adminUser.update({
|
||||||
|
where: { id },
|
||||||
|
data: { passwordHash },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ success: true });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Update admin error:", error);
|
||||||
|
return NextResponse.json({ error: "Внатрешна грешка на серверот" }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
54
src/app/api/admin/users/route.ts
Normal file
54
src/app/api/admin/users/route.ts
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { hash } from "bcryptjs";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { requireAdmin, requireSuperAdminPost } from "@/lib/admin-session";
|
||||||
|
import { ADMIN_PASSWORD_MIN_LENGTH } from "@/lib/config";
|
||||||
|
|
||||||
|
function strongEnough(password: string): boolean {
|
||||||
|
if (password.length < ADMIN_PASSWORD_MIN_LENGTH) return false;
|
||||||
|
return /[A-Za-z]/.test(password) && /\d/.test(password);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
const guard = await requireAdmin(true)();
|
||||||
|
if ("response" in guard) return guard.response;
|
||||||
|
|
||||||
|
const users = await prisma.adminUser.findMany({
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json(users);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const guard = await requireSuperAdminPost()(req);
|
||||||
|
if ("response" in guard) return guard.response;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { username, password } = await req.json();
|
||||||
|
if (!username || !password) {
|
||||||
|
return NextResponse.json({ error: "Корисничко име и лозинка се задолжителни" }, { status: 400 });
|
||||||
|
}
|
||||||
|
if (!strongEnough(password)) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: `Лозинката мора да има најмалку ${ADMIN_PASSWORD_MIN_LENGTH} карактери и да содржи буква и цифра` },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = await prisma.adminUser.findUnique({ where: { username } });
|
||||||
|
if (existing) {
|
||||||
|
return NextResponse.json({ error: "Корисничкото име веќе постои" }, { status: 409 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const passwordHash = await hash(password, 12);
|
||||||
|
const user = await prisma.adminUser.create({
|
||||||
|
data: { username, passwordHash, role: "ADMIN" },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json(user, { status: 201 });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Create admin error:", error);
|
||||||
|
return NextResponse.json({ error: "Внатрешна грешка на серверот" }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,17 +1,42 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { checkSubdomainLimiter, rateLimitHeaders } from "@/lib/rate-limit";
|
||||||
|
import { SUBDOMAIN_REGEX, SUBDOMAIN_MIN_LENGTH, SUBDOMAIN_MAX_LENGTH } from "@/lib/config";
|
||||||
|
|
||||||
|
function clientIp(req: NextRequest): string {
|
||||||
|
const fwd = req.headers.get("x-forwarded-for");
|
||||||
|
if (fwd) return fwd.split(",")[0].trim();
|
||||||
|
return req.headers.get("x-real-ip") || "unknown";
|
||||||
|
}
|
||||||
|
|
||||||
export async function GET(req: NextRequest) {
|
export async function GET(req: NextRequest) {
|
||||||
const slug = req.nextUrl.searchParams.get("slug");
|
const ip = clientIp(req);
|
||||||
|
const limit = checkSubdomainLimiter.limit(`check-subdomain:${ip}`);
|
||||||
|
if (!limit.success) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ available: false, error: "Премногу обиди. Обидете се повторно подоцна." },
|
||||||
|
{ status: 429, headers: rateLimitHeaders(limit) }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if (!slug || slug.length < 3) {
|
const raw = req.nextUrl.searchParams.get("slug") || "";
|
||||||
return NextResponse.json({ available: false });
|
const slug = raw.toLowerCase().trim();
|
||||||
|
|
||||||
|
if (
|
||||||
|
slug.length < SUBDOMAIN_MIN_LENGTH ||
|
||||||
|
slug.length > SUBDOMAIN_MAX_LENGTH ||
|
||||||
|
!SUBDOMAIN_REGEX.test(slug)
|
||||||
|
) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ available: false },
|
||||||
|
{ headers: { "Cache-Control": "private, max-age=60" } }
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const existing = await prisma.user.findUnique({ where: { subdomain: slug } });
|
const existing = await prisma.user.findUnique({ where: { subdomain: slug } });
|
||||||
|
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ available: !existing },
|
{ available: !existing },
|
||||||
{ headers: { "Cache-Control": "no-store" } }
|
{ headers: { "Cache-Control": "private, max-age=60" } }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -2,16 +2,17 @@ import { NextRequest, NextResponse } from "next/server";
|
|||||||
import { GetObjectCommand } from "@aws-sdk/client-s3";
|
import { GetObjectCommand } from "@aws-sdk/client-s3";
|
||||||
import { Readable } from "stream";
|
import { Readable } from "stream";
|
||||||
import { s3Client, S3_BUCKET } from "@/lib/s3";
|
import { s3Client, S3_BUCKET } from "@/lib/s3";
|
||||||
|
import { isAllowedImageKey } from "@/lib/config";
|
||||||
|
|
||||||
export async function GET(req: NextRequest) {
|
export async function GET(req: NextRequest) {
|
||||||
const key = req.nextUrl.searchParams.get("key");
|
const key = req.nextUrl.searchParams.get("key");
|
||||||
|
|
||||||
if (!key) {
|
if (!key) {
|
||||||
return NextResponse.json({ error: "Missing key parameter" }, { status: 400 });
|
return NextResponse.json({ error: "Недостасува параметар key" }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!key.startsWith("uploads/")) {
|
if (!isAllowedImageKey(key)) {
|
||||||
return NextResponse.json({ error: "Invalid key" }, { status: 400 });
|
return NextResponse.json({ error: "Невалиден клуч" }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@ -35,13 +36,13 @@ export async function GET(req: NextRequest) {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
const message = error instanceof Error ? error.message : "Unknown error";
|
const message = error instanceof Error ? error.message : "Непозната грешка";
|
||||||
console.error("Image proxy error:", message);
|
console.error("Image proxy error:", message);
|
||||||
|
|
||||||
if (message.includes("NoSuchKey") || message.includes("404")) {
|
if (message.includes("NoSuchKey") || message.includes("404")) {
|
||||||
return NextResponse.json({ error: "Image not found" }, { status: 404 });
|
return NextResponse.json({ error: "Сликата не е пронајдена" }, { status: 404 });
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json({ error: "Failed to fetch image" }, { status: 500 });
|
return NextResponse.json({ error: "Не успеа преземањето на сликата" }, { status: 500 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1,9 +1,18 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { auth } from "@clerk/nextjs/server";
|
import { auth } from "@clerk/nextjs/server";
|
||||||
import { revalidateTag } from "next/cache";
|
import { revalidateTag } from "next/cache";
|
||||||
|
import { Prisma } from "@prisma/client";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { prisma } from "@/lib/prisma";
|
||||||
import { generateMonumentQR } from "@/lib/qrcode";
|
import { generateMonumentQR } from "@/lib/qrcode";
|
||||||
import { getPublicUrl } from "@/lib/upload";
|
import { getPublicUrl } from "@/lib/upload";
|
||||||
|
import {
|
||||||
|
SUBDOMAIN_REGEX,
|
||||||
|
SUBDOMAIN_MIN_LENGTH,
|
||||||
|
SUBDOMAIN_MAX_LENGTH,
|
||||||
|
TITLE_MAX_LENGTH,
|
||||||
|
DESCRIPTION_MAX_LENGTH,
|
||||||
|
APP_DOMAIN,
|
||||||
|
} from "@/lib/config";
|
||||||
|
|
||||||
export async function POST(req: NextRequest) {
|
export async function POST(req: NextRequest) {
|
||||||
const { userId } = await auth();
|
const { userId } = await auth();
|
||||||
@ -11,93 +20,105 @@ export async function POST(req: NextRequest) {
|
|||||||
return NextResponse.json({ error: "Неавторизирано" }, { status: 401 });
|
return NextResponse.json({ error: "Неавторизирано" }, { status: 401 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const hasCode = await prisma.code.findFirst({
|
||||||
|
where: { usedByUserId: userId },
|
||||||
|
});
|
||||||
|
if (!hasCode) {
|
||||||
|
return NextResponse.json({ error: "Потребен е валиден код за креирање спомен страница" }, { status: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const body = await req.json();
|
const body = await req.json();
|
||||||
const { title, description, bornDate, passedDate, subdomain, templateId, images } = body;
|
const { title, description, bornDate, passedDate, subdomain, templateId, images } = body;
|
||||||
|
|
||||||
if (!title?.trim()) {
|
if (!title?.trim() || title.length > TITLE_MAX_LENGTH) {
|
||||||
return NextResponse.json({ error: "Името е задолжително" }, { status: 400 });
|
return NextResponse.json({ error: `Името е задолжително (макс. ${TITLE_MAX_LENGTH} карактери)` }, { status: 400 });
|
||||||
}
|
}
|
||||||
if (!subdomain || subdomain.length < 3) {
|
if (description && description.length > DESCRIPTION_MAX_LENGTH) {
|
||||||
return NextResponse.json({ error: "Поддоменот мора да има најмалку 3 карактери" }, { status: 400 });
|
return NextResponse.json({ error: `Описот е преголем (макс. ${DESCRIPTION_MAX_LENGTH} карактери)` }, { status: 400 });
|
||||||
}
|
}
|
||||||
if (!/^[a-z0-9][a-z0-9-]*[a-z0-9]$/.test(subdomain)) {
|
if (!subdomain || subdomain.length < SUBDOMAIN_MIN_LENGTH || subdomain.length > SUBDOMAIN_MAX_LENGTH) {
|
||||||
|
return NextResponse.json({ error: `Поддоменот мора да има ${SUBDOMAIN_MIN_LENGTH}-${SUBDOMAIN_MAX_LENGTH} карактери` }, { status: 400 });
|
||||||
|
}
|
||||||
|
if (!SUBDOMAIN_REGEX.test(subdomain)) {
|
||||||
return NextResponse.json({ error: "Поддоменот може да содржи само мали букви, цифри и цртички" }, { status: 400 });
|
return NextResponse.json({ error: "Поддоменот може да содржи само мали букви, цифри и цртички" }, { status: 400 });
|
||||||
}
|
}
|
||||||
if (templateId < 1 || templateId > 3) {
|
if (templateId < 1 || templateId > 3) {
|
||||||
return NextResponse.json({ error: "Невалиден шаблон" }, { status: 400 });
|
return NextResponse.json({ error: "Невалиден шаблон" }, { status: 400 });
|
||||||
}
|
}
|
||||||
if (!images || images.length === 0 || images.length > 3) {
|
if (!Array.isArray(images) || images.length === 0 || images.length > 3) {
|
||||||
return NextResponse.json({ error: "Потребни се 1-3 фотографии" }, { status: 400 });
|
return NextResponse.json({ error: "Потребни се 1-3 фотографии" }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const existing = await prisma.user.findUnique({ where: { subdomain } });
|
|
||||||
if (existing && existing.clerkId !== userId) {
|
|
||||||
return NextResponse.json({ error: "Поддоменот е веќе зафатен" }, { status: 409 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const existingUser = await prisma.user.findUnique({ where: { clerkId: userId } });
|
const existingUser = await prisma.user.findUnique({ where: { clerkId: userId } });
|
||||||
|
if (existingUser && existingUser.subdomain !== subdomain) {
|
||||||
let user;
|
const conflict = await prisma.user.findUnique({ where: { subdomain } });
|
||||||
if (existingUser) {
|
if (conflict && conflict.clerkId !== userId) {
|
||||||
if (existingUser.subdomain !== subdomain) {
|
return NextResponse.json({ error: "Поддоменот е веќе зафатен" }, { status: 409 });
|
||||||
revalidateTag(`memorial-${existingUser.subdomain}`);
|
|
||||||
}
|
}
|
||||||
await prisma.image.deleteMany({ where: { userId: existingUser.id } });
|
|
||||||
user = await prisma.user.update({
|
|
||||||
where: { clerkId: userId },
|
|
||||||
data: {
|
|
||||||
title,
|
|
||||||
description,
|
|
||||||
bornDate: bornDate || null,
|
|
||||||
passedDate: passedDate || null,
|
|
||||||
subdomain,
|
|
||||||
templateId,
|
|
||||||
published: true,
|
|
||||||
images: {
|
|
||||||
create: images.map((img: { key: string }, i: number) => ({
|
|
||||||
url: getPublicUrl(img.key),
|
|
||||||
key: img.key,
|
|
||||||
order: i + 1,
|
|
||||||
})),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
include: { images: true },
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
user = await prisma.user.create({
|
|
||||||
data: {
|
|
||||||
clerkId: userId,
|
|
||||||
title,
|
|
||||||
description,
|
|
||||||
bornDate: bornDate || null,
|
|
||||||
passedDate: passedDate || null,
|
|
||||||
subdomain,
|
|
||||||
templateId,
|
|
||||||
published: true,
|
|
||||||
images: {
|
|
||||||
create: images.map((img: { key: string }, i: number) => ({
|
|
||||||
url: getPublicUrl(img.key),
|
|
||||||
key: img.key,
|
|
||||||
order: i + 1,
|
|
||||||
})),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
include: { images: true },
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
revalidateTag("memorial");
|
const imageData = images.map((img: { key: string }, i: number) => ({
|
||||||
revalidateTag(`memorial-${subdomain}`);
|
url: getPublicUrl(img.key),
|
||||||
|
key: img.key,
|
||||||
|
order: i + 1,
|
||||||
|
}));
|
||||||
|
|
||||||
const qrCode = await generateMonumentQR(subdomain);
|
try {
|
||||||
|
const user = await prisma.$transaction(async (tx) => {
|
||||||
|
if (existingUser) {
|
||||||
|
if (existingUser.subdomain !== subdomain) {
|
||||||
|
revalidateTag(`memorial-${existingUser.subdomain}`);
|
||||||
|
}
|
||||||
|
await tx.image.deleteMany({ where: { userId: existingUser.id } });
|
||||||
|
return tx.user.update({
|
||||||
|
where: { clerkId: userId },
|
||||||
|
data: {
|
||||||
|
title: title.trim(),
|
||||||
|
description: description || null,
|
||||||
|
bornDate: bornDate || null,
|
||||||
|
passedDate: passedDate || null,
|
||||||
|
subdomain,
|
||||||
|
templateId,
|
||||||
|
published: true,
|
||||||
|
images: { create: imageData },
|
||||||
|
},
|
||||||
|
include: { images: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return tx.user.create({
|
||||||
|
data: {
|
||||||
|
clerkId: userId,
|
||||||
|
title: title.trim(),
|
||||||
|
description: description || null,
|
||||||
|
bornDate: bornDate || null,
|
||||||
|
passedDate: passedDate || null,
|
||||||
|
subdomain,
|
||||||
|
templateId,
|
||||||
|
published: true,
|
||||||
|
images: { create: imageData },
|
||||||
|
},
|
||||||
|
include: { images: true },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
return NextResponse.json({
|
revalidateTag("memorial");
|
||||||
success: true,
|
revalidateTag(`memorial-${subdomain}`);
|
||||||
monumentUrl: `https://${subdomain}.${process.env.NEXT_PUBLIC_APP_DOMAIN}`,
|
|
||||||
qrCode,
|
const qrCode = await generateMonumentQR(subdomain);
|
||||||
user,
|
|
||||||
});
|
return NextResponse.json({
|
||||||
|
success: true,
|
||||||
|
monumentUrl: `https://${subdomain}.${APP_DOMAIN}`,
|
||||||
|
qrCode,
|
||||||
|
user,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002") {
|
||||||
|
return NextResponse.json({ error: "Поддоменот е веќе зафатен" }, { status: 409 });
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Publish error:", error);
|
console.error("Publish error:", error);
|
||||||
return NextResponse.json({ error: "Внатрешна грешка на серверот" }, { status: 500 });
|
return NextResponse.json({ error: "Внатрешна грешка на серверот" }, { status: 500 });
|
||||||
|
|||||||
@ -3,9 +3,25 @@ import { auth } from "@clerk/nextjs/server";
|
|||||||
import { PutObjectCommand } from "@aws-sdk/client-s3";
|
import { PutObjectCommand } from "@aws-sdk/client-s3";
|
||||||
import { v4 as uuidv4 } from "uuid";
|
import { v4 as uuidv4 } from "uuid";
|
||||||
import { s3Client, S3_BUCKET, getPublicUrl } from "@/lib/s3";
|
import { s3Client, S3_BUCKET, getPublicUrl } from "@/lib/s3";
|
||||||
import { MAX_FILE_SIZE, ALLOWED_TYPES } from "@/lib/upload";
|
import { MAX_FILE_SIZE, detectImageType } from "@/lib/upload";
|
||||||
|
import { uploadLimiter, rateLimitHeaders } from "@/lib/rate-limit";
|
||||||
|
|
||||||
|
function clientIp(req: NextRequest): string {
|
||||||
|
const fwd = req.headers.get("x-forwarded-for");
|
||||||
|
if (fwd) return fwd.split(",")[0].trim();
|
||||||
|
return req.headers.get("x-real-ip") || "unknown";
|
||||||
|
}
|
||||||
|
|
||||||
export async function POST(req: NextRequest) {
|
export async function POST(req: NextRequest) {
|
||||||
|
const ip = clientIp(req);
|
||||||
|
const limit = uploadLimiter.limit(`upload:${ip}`);
|
||||||
|
if (!limit.success) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Премногу обиди. Обидете се повторно подоцна." },
|
||||||
|
{ status: 429, headers: rateLimitHeaders(limit) }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const { userId } = await auth();
|
const { userId } = await auth();
|
||||||
if (!userId) {
|
if (!userId) {
|
||||||
return NextResponse.json({ error: "Неавторизирано" }, { status: 401 });
|
return NextResponse.json({ error: "Неавторизирано" }, { status: 401 });
|
||||||
@ -19,24 +35,28 @@ export async function POST(req: NextRequest) {
|
|||||||
return NextResponse.json({ error: "Нема подадено датотека" }, { status: 400 });
|
return NextResponse.json({ error: "Нема подадено датотека" }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!ALLOWED_TYPES.includes(file.type)) {
|
|
||||||
return NextResponse.json({ error: "Невалиден тип на датотека" }, { status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (file.size > MAX_FILE_SIZE) {
|
if (file.size > MAX_FILE_SIZE) {
|
||||||
return NextResponse.json({ error: "Датотеката е премногу голема (макс. 5MB)" }, { status: 400 });
|
return NextResponse.json({ error: "Датотеката е премногу голема (макс. 5MB)" }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const ext = file.type.split("/")[1];
|
|
||||||
const key = `uploads/${userId}/${uuidv4()}.${ext}`;
|
|
||||||
const buffer = Buffer.from(await file.arrayBuffer());
|
const buffer = Buffer.from(await file.arrayBuffer());
|
||||||
|
const detected = detectImageType(buffer);
|
||||||
|
if (!detected) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Невалиден тип на датотека. Дозволени: JPEG, PNG, WebP." },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const ext = detected.split("/")[1];
|
||||||
|
const key = `uploads/${userId}/${uuidv4()}.${ext === "jpeg" ? "jpg" : ext}`;
|
||||||
|
|
||||||
await s3Client.send(
|
await s3Client.send(
|
||||||
new PutObjectCommand({
|
new PutObjectCommand({
|
||||||
Bucket: S3_BUCKET,
|
Bucket: S3_BUCKET,
|
||||||
Key: key,
|
Key: key,
|
||||||
Body: buffer,
|
Body: buffer,
|
||||||
ContentType: file.type,
|
ContentType: detected,
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
67
src/app/api/validate-code/route.ts
Normal file
67
src/app/api/validate-code/route.ts
Normal file
@ -0,0 +1,67 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { auth } from "@clerk/nextjs/server";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { validateCodeLimiter, rateLimitHeaders } from "@/lib/rate-limit";
|
||||||
|
|
||||||
|
function clientIp(req: NextRequest): string {
|
||||||
|
const fwd = req.headers.get("x-forwarded-for");
|
||||||
|
if (fwd) return fwd.split(",")[0].trim();
|
||||||
|
return req.headers.get("x-real-ip") || "unknown";
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const ip = clientIp(req);
|
||||||
|
const limit = validateCodeLimiter.limit(`validate-code:${ip}`);
|
||||||
|
if (!limit.success) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Премногу обиди. Обидете се повторно подоцна." },
|
||||||
|
{ status: 429, headers: rateLimitHeaders(limit) }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { userId } = await auth();
|
||||||
|
if (!userId) {
|
||||||
|
return NextResponse.json({ error: "Неавторизирано" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { code } = await req.json();
|
||||||
|
if (!code?.trim()) {
|
||||||
|
return NextResponse.json({ error: "Кодот е задолжителен" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizedCode = code.trim().toUpperCase();
|
||||||
|
if (!/^[A-F0-9]{12}$/.test(normalizedCode)) {
|
||||||
|
return NextResponse.json({ valid: false, error: "Невалиден код" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = await prisma.code.findUnique({ where: { code: normalizedCode } });
|
||||||
|
if (!existing) {
|
||||||
|
return NextResponse.json({ valid: false, error: "Невалиден код" });
|
||||||
|
}
|
||||||
|
if (existing.usedByUserId) {
|
||||||
|
return NextResponse.json({ valid: false, error: "Кодот е веќе искористен" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const alreadyUsed = await prisma.code.findFirst({
|
||||||
|
where: { usedByUserId: userId },
|
||||||
|
});
|
||||||
|
if (alreadyUsed) {
|
||||||
|
return NextResponse.json({ valid: false, error: "Веќе имате искористено код" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated = await prisma.code.updateMany({
|
||||||
|
where: { id: existing.id, usedByUserId: null },
|
||||||
|
data: { usedByUserId: userId, usedAt: new Date() },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (updated.count === 0) {
|
||||||
|
return NextResponse.json({ valid: false, error: "Кодот е веќе искористен" });
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({ valid: true });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Validate code error:", error);
|
||||||
|
return NextResponse.json({ error: "Внатрешна грешка на серверот" }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -6,6 +6,8 @@ import { UserButton } from "@clerk/nextjs";
|
|||||||
import CopyButton from "@/components/CopyButton";
|
import CopyButton from "@/components/CopyButton";
|
||||||
import DeleteMonumentButton from "@/components/DeleteMonumentButton";
|
import DeleteMonumentButton from "@/components/DeleteMonumentButton";
|
||||||
import DeleteImageButton from "@/components/DeleteImageButton";
|
import DeleteImageButton from "@/components/DeleteImageButton";
|
||||||
|
import { generateMonumentQR } from "@/lib/qrcode";
|
||||||
|
import { APP_DOMAIN } from "@/lib/config";
|
||||||
|
|
||||||
export default async function DashboardPage() {
|
export default async function DashboardPage() {
|
||||||
const { userId } = await auth();
|
const { userId } = await auth();
|
||||||
@ -20,7 +22,8 @@ export default async function DashboardPage() {
|
|||||||
redirect("/onboarding");
|
redirect("/onboarding");
|
||||||
}
|
}
|
||||||
|
|
||||||
const monumentUrl = `https://${user.subdomain}.${process.env.NEXT_PUBLIC_APP_DOMAIN}`;
|
const monumentUrl = `https://${user.subdomain}.${APP_DOMAIN}`;
|
||||||
|
const qrCode = await generateMonumentQR(user.subdomain);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-stone-50">
|
<div className="min-h-screen bg-stone-50">
|
||||||
@ -78,14 +81,15 @@ export default async function DashboardPage() {
|
|||||||
<h3 className="text-lg font-medium text-stone-900">QR код</h3>
|
<h3 className="text-lg font-medium text-stone-900">QR код</h3>
|
||||||
<p className="mt-1 text-sm text-stone-500">Прикажете го овој QR код на споменикот за да можат посетителите да ја прочитаат приказната.</p>
|
<p className="mt-1 text-sm text-stone-500">Прикажете го овој QR код на споменикот за да можат посетителите да ја прочитаат приказната.</p>
|
||||||
<div className="mt-4 rounded-lg border border-stone-200 bg-white p-4">
|
<div className="mt-4 rounded-lg border border-stone-200 bg-white p-4">
|
||||||
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
<img
|
<img
|
||||||
src={`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(monumentUrl)}`}
|
src={qrCode}
|
||||||
alt="QR код"
|
alt="QR код"
|
||||||
className="h-48 w-48"
|
className="h-48 w-48"
|
||||||
/>
|
/>
|
||||||
<a
|
<a
|
||||||
href={`https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=${encodeURIComponent(monumentUrl)}`}
|
href={qrCode}
|
||||||
download
|
download={`${user.subdomain}-qr.png`}
|
||||||
className="mt-4 inline-block rounded-lg bg-primary px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-primary-light"
|
className="mt-4 inline-block rounded-lg bg-primary px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-primary-light"
|
||||||
>
|
>
|
||||||
Превземи QR код
|
Превземи QR код
|
||||||
|
|||||||
30
src/app/error.tsx
Normal file
30
src/app/error.tsx
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect } from "react";
|
||||||
|
|
||||||
|
export default function Error({
|
||||||
|
error,
|
||||||
|
reset,
|
||||||
|
}: {
|
||||||
|
error: Error & { digest?: string };
|
||||||
|
reset: () => void;
|
||||||
|
}) {
|
||||||
|
useEffect(() => {
|
||||||
|
console.error(error);
|
||||||
|
}, [error]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen flex-col items-center justify-center px-6 text-center">
|
||||||
|
<h1 className="text-3xl font-semibold text-stone-900">Настана грешка</h1>
|
||||||
|
<p className="mt-2 max-w-md text-sm text-stone-500">
|
||||||
|
Нешто тргна наопаку. Обидете се повторно или контактирајте н ако проблемот persist.
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
onClick={reset}
|
||||||
|
className="mt-6 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-primary-light"
|
||||||
|
>
|
||||||
|
Обиди се повторно
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -1,6 +1,7 @@
|
|||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import { Geist, Geist_Mono } from "next/font/google";
|
import { Geist, Geist_Mono } from "next/font/google";
|
||||||
import { ClerkProvider } from "@clerk/nextjs";
|
import { ClerkProvider } from "@clerk/nextjs";
|
||||||
|
import { APP_URL } from "@/lib/config";
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
|
|
||||||
const geistSans = Geist({
|
const geistSans = Geist({
|
||||||
@ -14,7 +15,11 @@ const geistMono = Geist_Mono({
|
|||||||
});
|
});
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: "СпоменQR — Во спомен на",
|
metadataBase: new URL(APP_URL),
|
||||||
|
title: {
|
||||||
|
default: "СпоменQR — Во спомен на",
|
||||||
|
template: "%s · СпоменQR",
|
||||||
|
},
|
||||||
description: "Креирајте убави спомен страници со QR кодови. Оддадете почит и зачувајте ги спомените на најблиските.",
|
description: "Креирајте убави спомен страници со QR кодови. Оддадете почит и зачувајте ги спомените на најблиските.",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
7
src/app/loading.tsx
Normal file
7
src/app/loading.tsx
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
export default function Loading() {
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen items-center justify-center">
|
||||||
|
<div className="h-8 w-8 animate-spin rounded-full border-2 border-stone-200 border-t-primary" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -6,7 +6,7 @@ import ImageUploader from "@/components/ImageUploader";
|
|||||||
import SubdomainPicker from "@/components/SubdomainPicker";
|
import SubdomainPicker from "@/components/SubdomainPicker";
|
||||||
import TemplatePicker from "@/components/TemplatePicker";
|
import TemplatePicker from "@/components/TemplatePicker";
|
||||||
|
|
||||||
const STEPS = ["Податоци", "Датуми", "Фотографии", "Поддомен", "Шаблон"] as const;
|
const STEPS = ["Код", "Податоци", "Датуми", "Фотографии", "Поддомен", "Шаблон"] as const;
|
||||||
|
|
||||||
export default function OnboardingWizard() {
|
export default function OnboardingWizard() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@ -14,6 +14,10 @@ export default function OnboardingWizard() {
|
|||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
|
|
||||||
|
const [code, setCode] = useState("");
|
||||||
|
const [codeValidated, setCodeValidated] = useState(false);
|
||||||
|
const [codeValidating, setCodeValidating] = useState(false);
|
||||||
|
|
||||||
const [title, setTitle] = useState("");
|
const [title, setTitle] = useState("");
|
||||||
const [description, setDescription] = useState("");
|
const [description, setDescription] = useState("");
|
||||||
const [bornDate, setBornDate] = useState("");
|
const [bornDate, setBornDate] = useState("");
|
||||||
@ -24,15 +28,37 @@ export default function OnboardingWizard() {
|
|||||||
|
|
||||||
const canProceed = () => {
|
const canProceed = () => {
|
||||||
switch (step) {
|
switch (step) {
|
||||||
case 0: return title.trim().length > 0;
|
case 0: return codeValidated;
|
||||||
case 1: return true;
|
case 1: return title.trim().length > 0;
|
||||||
case 2: return images.length > 0;
|
case 2: return true;
|
||||||
case 3: return subdomain.length >= 3;
|
case 3: return images.length > 0;
|
||||||
case 4: return templateId >= 1 && templateId <= 3;
|
case 4: return subdomain.length >= 3;
|
||||||
|
case 5: return templateId >= 1 && templateId <= 3;
|
||||||
default: return false;
|
default: return false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleValidateCode = async () => {
|
||||||
|
setCodeValidating(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/validate-code", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ code }),
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (!data.valid) {
|
||||||
|
throw new Error(data.error || "Невалиден код");
|
||||||
|
}
|
||||||
|
setCodeValidated(true);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : "Грешка при валидација");
|
||||||
|
} finally {
|
||||||
|
setCodeValidating(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const handlePublish = async () => {
|
const handlePublish = async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError("");
|
setError("");
|
||||||
@ -100,6 +126,42 @@ export default function OnboardingWizard() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{step === 0 && (
|
{step === 0 && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<p className="text-sm text-stone-500">
|
||||||
|
Внесете го кодот што го добивте за да креирате спомен страница.
|
||||||
|
</p>
|
||||||
|
<div className="flex gap-3">
|
||||||
|
<input
|
||||||
|
id="code"
|
||||||
|
type="text"
|
||||||
|
value={code}
|
||||||
|
onChange={(e) => {
|
||||||
|
setCode(e.target.value.toUpperCase());
|
||||||
|
setCodeValidated(false);
|
||||||
|
}}
|
||||||
|
placeholder="Внесете код"
|
||||||
|
className="mt-1 block flex-1 rounded-lg border border-stone-200 px-3 py-2.5 font-mono text-lg uppercase tracking-widest text-stone-900 placeholder:text-stone-400 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
|
||||||
|
maxLength={20}
|
||||||
|
disabled={codeValidated}
|
||||||
|
/>
|
||||||
|
{!codeValidated ? (
|
||||||
|
<button
|
||||||
|
onClick={handleValidateCode}
|
||||||
|
disabled={code.trim().length === 0 || codeValidating}
|
||||||
|
className="mt-1 rounded-lg bg-primary px-6 py-2.5 text-sm font-medium text-white transition-colors hover:bg-primary-light disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{codeValidating ? "Проверка..." : "Потврди"}
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<div className="mt-1 flex items-center rounded-lg bg-green-50 px-4 py-2.5 text-sm font-medium text-green-700">
|
||||||
|
Потврден
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{step === 1 && (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div>
|
<div>
|
||||||
<label htmlFor="title" className="block text-sm font-medium text-stone-700">
|
<label htmlFor="title" className="block text-sm font-medium text-stone-700">
|
||||||
@ -132,7 +194,7 @@ export default function OnboardingWizard() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{step === 1 && (
|
{step === 2 && (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<p className="text-sm text-stone-500">
|
<p className="text-sm text-stone-500">
|
||||||
Овие се опционални. Можете да внесете точни датуми, приближни години, или да ги оставите празни.
|
Овие се опционални. Можете да внесете точни датуми, приближни години, или да ги оставите празни.
|
||||||
@ -168,18 +230,18 @@ export default function OnboardingWizard() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{step === 2 && (
|
{step === 3 && (
|
||||||
<ImageUploader
|
<ImageUploader
|
||||||
images={images}
|
images={images}
|
||||||
onImagesChange={(newImages) => setImages(newImages as typeof images)}
|
onImagesChange={(newImages) => setImages(newImages as typeof images)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{step === 3 && (
|
{step === 4 && (
|
||||||
<SubdomainPicker value={subdomain} onChange={setSubdomain} />
|
<SubdomainPicker value={subdomain} onChange={setSubdomain} />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{step === 4 && (
|
{step === 5 && (
|
||||||
<TemplatePicker
|
<TemplatePicker
|
||||||
value={templateId}
|
value={templateId}
|
||||||
onChange={setTemplateId}
|
onChange={setTemplateId}
|
||||||
|
|||||||
@ -2,10 +2,7 @@
|
|||||||
|
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { useUser } from "@clerk/nextjs";
|
import { useUser } from "@clerk/nextjs";
|
||||||
|
import { MAX_FILE_SIZE, ALLOWED_TYPES, MAX_FILES } from "@/lib/upload";
|
||||||
const MAX_FILES = 3;
|
|
||||||
const MAX_FILE_SIZE = 5 * 1024 * 1024;
|
|
||||||
const ALLOWED_TYPES = ["image/jpeg", "image/png", "image/webp", "image/gif"];
|
|
||||||
|
|
||||||
interface ImageData {
|
interface ImageData {
|
||||||
key: string;
|
key: string;
|
||||||
@ -31,12 +28,12 @@ export default function ImageUploader({ images, onImagesChange }: ImageUploaderP
|
|||||||
if (remaining <= 0) return;
|
if (remaining <= 0) return;
|
||||||
|
|
||||||
const validFiles = Array.from(files)
|
const validFiles = Array.from(files)
|
||||||
.filter((f) => ALLOWED_TYPES.includes(f.type))
|
.filter((f) => (ALLOWED_TYPES as readonly string[]).includes(f.type))
|
||||||
.filter((f) => f.size <= MAX_FILE_SIZE)
|
.filter((f) => f.size <= MAX_FILE_SIZE)
|
||||||
.slice(0, remaining);
|
.slice(0, remaining);
|
||||||
|
|
||||||
if (validFiles.length === 0) {
|
if (validFiles.length === 0) {
|
||||||
setError("Невалиден тип на датотека или големина. Дозволени: JPEG, PNG, WebP, GIF до 5MB.");
|
setError("Невалиден тип на датотека или големина. Дозволени: JPEG, PNG, WebP до 5MB.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -44,31 +41,43 @@ export default function ImageUploader({ images, onImagesChange }: ImageUploaderP
|
|||||||
setUploading(true);
|
setUploading(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
const baseOrder = images.length;
|
||||||
|
const results = await Promise.allSettled(
|
||||||
|
validFiles.map(async (file, idx) => {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append("file", file);
|
||||||
|
const res = await fetch("/api/upload", {
|
||||||
|
method: "POST",
|
||||||
|
body: formData,
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
throw new Error(data.error || "Не успеа качувањето");
|
||||||
|
}
|
||||||
|
const { key, url } = await res.json();
|
||||||
|
return { key, url, order: baseOrder + idx + 1 };
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
const newImages = [...images];
|
const newImages = [...images];
|
||||||
const newPreviews = [...previews];
|
const newPreviews = [...previews];
|
||||||
|
const failures: string[] = [];
|
||||||
for (const file of validFiles) {
|
for (const r of results) {
|
||||||
const formData = new FormData();
|
if (r.status === "fulfilled") {
|
||||||
formData.append("file", file);
|
newImages.push({ key: r.value.key, order: r.value.order, url: r.value.url });
|
||||||
|
newPreviews.push({ key: r.value.key, url: r.value.url, order: r.value.order });
|
||||||
const res = await fetch("/api/upload", {
|
} else {
|
||||||
method: "POST",
|
failures.push(r.reason instanceof Error ? r.reason.message : "Не успеа качувањето");
|
||||||
body: formData,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!res.ok) {
|
|
||||||
const data = await res.json();
|
|
||||||
throw new Error(data.error || "Не успеа качувањето");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const { key, url } = await res.json();
|
|
||||||
const order = newImages.length + 1;
|
|
||||||
newImages.push({ key, order, url });
|
|
||||||
newPreviews.push({ key, url, order });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onImagesChange(newImages);
|
onImagesChange(newImages);
|
||||||
setPreviews(newPreviews);
|
setPreviews(newPreviews);
|
||||||
|
if (failures.length > 0) {
|
||||||
|
setError(failures.join("; "));
|
||||||
|
} else {
|
||||||
|
setError("");
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err instanceof Error ? err.message : "Не успеа качувањето");
|
setError(err instanceof Error ? err.message : "Не успеа качувањето");
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@ -1,6 +1,11 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useEffect, useCallback } from "react";
|
import { useState, useEffect, useCallback } from "react";
|
||||||
|
import {
|
||||||
|
APP_DOMAIN,
|
||||||
|
SUBDOMAIN_MIN_LENGTH,
|
||||||
|
SUBDOMAIN_MAX_LENGTH,
|
||||||
|
} from "@/lib/config";
|
||||||
|
|
||||||
interface SubdomainPickerProps {
|
interface SubdomainPickerProps {
|
||||||
value: string;
|
value: string;
|
||||||
@ -14,7 +19,7 @@ export default function SubdomainPicker({ value, onChange }: SubdomainPickerProp
|
|||||||
const slug = value.toLowerCase().replace(/[^a-z0-9-]/g, "").replace(/-+/g, "-").replace(/^-|-$/g, "");
|
const slug = value.toLowerCase().replace(/[^a-z0-9-]/g, "").replace(/-+/g, "-").replace(/^-|-$/g, "");
|
||||||
|
|
||||||
const checkAvailability = useCallback(async (s: string) => {
|
const checkAvailability = useCallback(async (s: string) => {
|
||||||
if (s.length < 3) {
|
if (s.length < SUBDOMAIN_MIN_LENGTH) {
|
||||||
setAvailable(null);
|
setAvailable(null);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -51,10 +56,10 @@ export default function SubdomainPicker({ value, onChange }: SubdomainPickerProp
|
|||||||
onChange={(e) => onChange(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, "").replace(/-+/g, "-"))}
|
onChange={(e) => onChange(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, "").replace(/-+/g, "-"))}
|
||||||
placeholder="нпр. maria-novakovska"
|
placeholder="нпр. maria-novakovska"
|
||||||
className="flex-1 rounded-l-lg border-0 px-3 py-2 text-stone-900 placeholder:text-stone-400 focus:outline-none focus:ring-1 focus:ring-primary"
|
className="flex-1 rounded-l-lg border-0 px-3 py-2 text-stone-900 placeholder:text-stone-400 focus:outline-none focus:ring-1 focus:ring-primary"
|
||||||
maxLength={63}
|
maxLength={SUBDOMAIN_MAX_LENGTH}
|
||||||
/>
|
/>
|
||||||
<span className="rounded-r-lg bg-stone-50 px-3 py-2 text-sm text-stone-500 border-l border-stone-200">
|
<span className="rounded-r-lg bg-stone-50 px-3 py-2 text-sm text-stone-500 border-l border-stone-200">
|
||||||
.{process.env.NEXT_PUBLIC_APP_DOMAIN || "testbed.mk"}
|
.{APP_DOMAIN}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -62,13 +67,13 @@ export default function SubdomainPicker({ value, onChange }: SubdomainPickerProp
|
|||||||
<div className="text-sm">
|
<div className="text-sm">
|
||||||
{checking && <p className="text-stone-500">Проверка на достапност...</p>}
|
{checking && <p className="text-stone-500">Проверка на достапност...</p>}
|
||||||
{!checking && available === true && (
|
{!checking && available === true && (
|
||||||
<p className="text-green-600">✓ {slug}.testbed.mk е достапен!</p>
|
<p className="text-green-600">✓ {slug}.{APP_DOMAIN} е достапен!</p>
|
||||||
)}
|
)}
|
||||||
{!checking && available === false && (
|
{!checking && available === false && (
|
||||||
<p className="text-red-600">✗ Овој поддомен е веќе зафатен.</p>
|
<p className="text-red-600">✗ Овој поддомен е веќе зафатен.</p>
|
||||||
)}
|
)}
|
||||||
{!checking && available === null && slug.length > 0 && slug.length < 3 && (
|
{!checking && available === null && slug.length > 0 && slug.length < SUBDOMAIN_MIN_LENGTH && (
|
||||||
<p className="text-stone-400">Потребни се најмалку 3 карактери.</p>
|
<p className="text-stone-400">Потребни се најмалку {SUBDOMAIN_MIN_LENGTH} карактери.</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
81
src/lib/__tests__/admin-session.test.ts
Normal file
81
src/lib/__tests__/admin-session.test.ts
Normal file
@ -0,0 +1,81 @@
|
|||||||
|
import { describe, it, expect, beforeAll } from "vitest";
|
||||||
|
import {
|
||||||
|
createAdminSession,
|
||||||
|
verifyAdminSession,
|
||||||
|
COOKIE_NAME_ADMIN,
|
||||||
|
cookieOptions,
|
||||||
|
} from "../admin-session";
|
||||||
|
|
||||||
|
const SECRET = "a".repeat(64);
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
process.env.ADMIN_SESSION_SECRET = SECRET;
|
||||||
|
process.env.NEXT_PUBLIC_APP_URL = "https://testbed.mk";
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("admin-session.sign/verify", () => {
|
||||||
|
it("round-trips a valid session", async () => {
|
||||||
|
const token = await createAdminSession({ username: "alice", role: "ADMIN" });
|
||||||
|
const parsed = await verifyAdminSession(token);
|
||||||
|
expect(parsed).toEqual({ username: "alice", role: "ADMIN" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("round-trips SUPER_ADMIN role", async () => {
|
||||||
|
const token = await createAdminSession({ username: "super", role: "SUPER_ADMIN" });
|
||||||
|
const parsed = await verifyAdminSession(token);
|
||||||
|
expect(parsed).toEqual({ username: "super", role: "SUPER_ADMIN" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects a tampered payload (signature no longer matches)", async () => {
|
||||||
|
const token = await createAdminSession({ username: "alice", role: "ADMIN" });
|
||||||
|
const [payload, sig] = token.split(".");
|
||||||
|
const tamperedPayload = btoa(
|
||||||
|
JSON.stringify({ username: "alice", role: "SUPER_ADMIN" })
|
||||||
|
);
|
||||||
|
const tampered = `${tamperedPayload}.${sig}`;
|
||||||
|
const parsed = await verifyAdminSession(tampered);
|
||||||
|
expect(parsed).toBeNull();
|
||||||
|
expect(payload).not.toEqual(tamperedPayload);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects a tampered signature", async () => {
|
||||||
|
const token = await createAdminSession({ username: "alice", role: "ADMIN" });
|
||||||
|
const [payload] = token.split(".");
|
||||||
|
const forgedSig = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
|
||||||
|
const forged = `${payload}.${forgedSig}`;
|
||||||
|
const parsed = await verifyAdminSession(forged);
|
||||||
|
expect(parsed).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects a malformed token without separator", async () => {
|
||||||
|
const parsed = await verifyAdminSession("just-a-string-no-separator");
|
||||||
|
expect(parsed).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects a token whose payload is not valid base64 JSON", async () => {
|
||||||
|
const fakePayload = btoa("not-json-at-all");
|
||||||
|
const fakeToken = `${fakePayload}.aaaaaaaa`;
|
||||||
|
const parsed = await verifyAdminSession(fakeToken);
|
||||||
|
expect(parsed).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("admin-session.cookieOptions", () => {
|
||||||
|
it("emits the documented cookie name and secure flags", () => {
|
||||||
|
const opts = cookieOptions("token-value");
|
||||||
|
expect(opts.name).toBe(COOKIE_NAME_ADMIN);
|
||||||
|
expect(opts.value).toBe("token-value");
|
||||||
|
expect(opts.httpOnly).toBe(true);
|
||||||
|
expect(opts.sameSite).toBe("lax");
|
||||||
|
expect(opts.path).toBe("/");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("marks the cookie secure only in production", () => {
|
||||||
|
const prev = process.env.NODE_ENV;
|
||||||
|
process.env.NODE_ENV = "production";
|
||||||
|
expect(cookieOptions("x").secure).toBe(true);
|
||||||
|
process.env.NODE_ENV = "test";
|
||||||
|
expect(cookieOptions("x").secure).toBe(false);
|
||||||
|
process.env.NODE_ENV = prev;
|
||||||
|
});
|
||||||
|
});
|
||||||
47
src/lib/__tests__/rate-limit.test.ts
Normal file
47
src/lib/__tests__/rate-limit.test.ts
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||||
|
import { RateLimiter } from "../rate-limit";
|
||||||
|
|
||||||
|
describe("RateLimiter", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("allows up to maxTokens requests within a window", () => {
|
||||||
|
const limiter = new RateLimiter(3, 60_000);
|
||||||
|
expect(limiter.limit("k").success).toBe(true);
|
||||||
|
expect(limiter.limit("k").success).toBe(true);
|
||||||
|
expect(limiter.limit("k").success).toBe(true);
|
||||||
|
expect(limiter.limit("k").success).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("tracks keys independently", () => {
|
||||||
|
const limiter = new RateLimiter(2, 60_000);
|
||||||
|
expect(limiter.limit("a").success).toBe(true);
|
||||||
|
expect(limiter.limit("b").success).toBe(true);
|
||||||
|
expect(limiter.limit("a").success).toBe(true);
|
||||||
|
expect(limiter.limit("a").success).toBe(false);
|
||||||
|
expect(limiter.limit("b").success).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("refills after the window elapses", () => {
|
||||||
|
const limiter = new RateLimiter(1, 60_000);
|
||||||
|
expect(limiter.limit("k").success).toBe(true);
|
||||||
|
expect(limiter.limit("k").success).toBe(false);
|
||||||
|
vi.advanceTimersByTime(60_001);
|
||||||
|
expect(limiter.limit("k").success).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("decrements remaining on each success", () => {
|
||||||
|
const limiter = new RateLimiter(3, 60_000);
|
||||||
|
expect(limiter.limit("k").remaining).toBe(2);
|
||||||
|
expect(limiter.limit("k").remaining).toBe(1);
|
||||||
|
expect(limiter.limit("k").remaining).toBe(0);
|
||||||
|
const blocked = limiter.limit("k");
|
||||||
|
expect(blocked.success).toBe(false);
|
||||||
|
expect(blocked.remaining).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
142
src/lib/admin-session.ts
Normal file
142
src/lib/admin-session.ts
Normal file
@ -0,0 +1,142 @@
|
|||||||
|
import { cookies } from "next/headers";
|
||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { getAppOrigin } from "./config";
|
||||||
|
|
||||||
|
const COOKIE_NAME = "admin_session";
|
||||||
|
const SEP = ".";
|
||||||
|
|
||||||
|
function sameOriginRequest(req: NextRequest): boolean {
|
||||||
|
const origin = req.headers.get("origin");
|
||||||
|
const referer = req.headers.get("referer");
|
||||||
|
const expected = getAppOrigin().replace(/\/$/, "");
|
||||||
|
const host = req.headers.get("host");
|
||||||
|
const expectedHost = getAppOrigin().replace(/^https?:\/\//, "").replace(/\/$/, "");
|
||||||
|
if (origin) {
|
||||||
|
return origin.replace(/\/$/, "") === expected;
|
||||||
|
}
|
||||||
|
if (referer) {
|
||||||
|
try {
|
||||||
|
const u = new URL(referer);
|
||||||
|
return u.origin.replace(/\/$/, "") === expected;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return host === expectedHost;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getSecret(): string {
|
||||||
|
const secret = process.env.ADMIN_SESSION_SECRET;
|
||||||
|
if (!secret) throw new Error("ADMIN_SESSION_SECRET env var is not set");
|
||||||
|
return secret;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sign(payload: string): Promise<string> {
|
||||||
|
const encoder = new TextEncoder();
|
||||||
|
const key = await crypto.subtle.importKey(
|
||||||
|
"raw",
|
||||||
|
encoder.encode(getSecret()),
|
||||||
|
{ name: "HMAC", hash: "SHA-256" },
|
||||||
|
false,
|
||||||
|
["sign"],
|
||||||
|
);
|
||||||
|
const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(payload));
|
||||||
|
return btoa(String.fromCharCode(...new Uint8Array(sig)));
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdminSession {
|
||||||
|
username: string;
|
||||||
|
role: "SUPER_ADMIN" | "ADMIN";
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createAdminSession(data: AdminSession): Promise<string> {
|
||||||
|
const payload = btoa(JSON.stringify(data));
|
||||||
|
return payload + SEP + (await sign(payload));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function verifyAdminSession(token: string): Promise<AdminSession | null> {
|
||||||
|
const sepIdx = token.lastIndexOf(SEP);
|
||||||
|
if (sepIdx === -1) return null;
|
||||||
|
const payload = token.slice(0, sepIdx);
|
||||||
|
const sig = token.slice(sepIdx + 1);
|
||||||
|
const expectedSig = await sign(payload);
|
||||||
|
if (sig.length !== expectedSig.length) return null;
|
||||||
|
try {
|
||||||
|
if (!constantTimeEqual(sig, expectedSig)) return null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return JSON.parse(atob(payload));
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function constantTimeEqual(a: string, b: string): boolean {
|
||||||
|
if (a.length !== b.length) return false;
|
||||||
|
let result = 0;
|
||||||
|
for (let i = 0; i < a.length; i++) {
|
||||||
|
result |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
||||||
|
}
|
||||||
|
return result === 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const COOKIE_NAME_ADMIN = COOKIE_NAME;
|
||||||
|
|
||||||
|
export function cookieOptions(value: string) {
|
||||||
|
return {
|
||||||
|
name: COOKIE_NAME,
|
||||||
|
value,
|
||||||
|
httpOnly: true,
|
||||||
|
secure: process.env.NODE_ENV === "production",
|
||||||
|
sameSite: "lax" as const,
|
||||||
|
path: "/",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getAdminSession(): Promise<AdminSession | null> {
|
||||||
|
const store = await cookies();
|
||||||
|
const token = store.get(COOKIE_NAME)?.value;
|
||||||
|
if (!token) return null;
|
||||||
|
return verifyAdminSession(token);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function requireAdmin(requireSuper = false) {
|
||||||
|
return async function check(): Promise<{ session: AdminSession } | { response: NextResponse }> {
|
||||||
|
const session = await getAdminSession();
|
||||||
|
if (!session) {
|
||||||
|
return {
|
||||||
|
response: NextResponse.json({ error: "Неавторизирано" }, { status: 401 }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (requireSuper && session.role !== "SUPER_ADMIN") {
|
||||||
|
return {
|
||||||
|
response: NextResponse.json({ error: "Немате дозвола" }, { status: 403 }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { session };
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function requireAdminPost() {
|
||||||
|
return async function check(req: NextRequest): Promise<{ session: AdminSession } | { response: NextResponse }> {
|
||||||
|
if (!sameOriginRequest(req)) {
|
||||||
|
return {
|
||||||
|
response: NextResponse.json({ error: "Невалидно потекло на барање" }, { status: 403 }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return requireAdmin()();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function requireSuperAdminPost() {
|
||||||
|
return async function check(req: NextRequest): Promise<{ session: AdminSession } | { response: NextResponse }> {
|
||||||
|
if (!sameOriginRequest(req)) {
|
||||||
|
return {
|
||||||
|
response: NextResponse.json({ error: "Невалидно потекло на барање" }, { status: 403 }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return requireAdmin(true)();
|
||||||
|
};
|
||||||
|
}
|
||||||
28
src/lib/config.ts
Normal file
28
src/lib/config.ts
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
export const APP_DOMAIN =
|
||||||
|
process.env.NEXT_PUBLIC_APP_DOMAIN || "testbed.mk";
|
||||||
|
|
||||||
|
export const APP_URL = process.env.NEXT_PUBLIC_APP_URL || `https://${APP_DOMAIN}`;
|
||||||
|
|
||||||
|
export const SUBDOMAIN_REGEX = /^[a-z0-9][a-z0-9-]*[a-z0-9]$/;
|
||||||
|
|
||||||
|
export const SUBDOMAIN_MIN_LENGTH = 3;
|
||||||
|
export const SUBDOMAIN_MAX_LENGTH = 32;
|
||||||
|
|
||||||
|
export const TITLE_MAX_LENGTH = 100;
|
||||||
|
export const DESCRIPTION_MAX_LENGTH = 2000;
|
||||||
|
|
||||||
|
export const ADMIN_PASSWORD_MIN_LENGTH = 12;
|
||||||
|
|
||||||
|
export const IMAGE_KEY_REGEX =
|
||||||
|
/^uploads\/[a-zA-Z0-9_-]+\/[a-f0-9-]+\.(jpe?g|png|webp)$/i;
|
||||||
|
|
||||||
|
export function isAllowedImageKey(key: string): boolean {
|
||||||
|
return IMAGE_KEY_REGEX.test(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const SUPER_ADMIN_USERNAME = process.env.SUPER_ADMIN_USERNAME || "super";
|
||||||
|
export const SUPER_ADMIN_PASSWORD_HASH = process.env.SUPER_ADMIN_PASSWORD_HASH || "";
|
||||||
|
|
||||||
|
export function getAppOrigin(): string {
|
||||||
|
return APP_URL;
|
||||||
|
}
|
||||||
@ -4,6 +4,22 @@ const globalForPrisma = globalThis as unknown as {
|
|||||||
prisma: PrismaClient | undefined;
|
prisma: PrismaClient | undefined;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const prisma = globalForPrisma.prisma ?? new PrismaClient();
|
function getPrisma(): PrismaClient {
|
||||||
|
if (!globalForPrisma.prisma) {
|
||||||
|
globalForPrisma.prisma = new PrismaClient();
|
||||||
|
}
|
||||||
|
return globalForPrisma.prisma;
|
||||||
|
}
|
||||||
|
|
||||||
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
|
// Lazy singleton: `new PrismaClient()` throws during `next build` when
|
||||||
|
// DATABASE_URL is absent (e.g. in a Docker builder stage where env files
|
||||||
|
// aren't present). Defer construction until the first real query so merely
|
||||||
|
// importing this module never fails. Method calls are bound to the real
|
||||||
|
// instance so `this` is preserved.
|
||||||
|
export const prisma = new Proxy({} as PrismaClient, {
|
||||||
|
get(_target, prop) {
|
||||||
|
const client = getPrisma();
|
||||||
|
const value = (client as unknown as Record<PropertyKey, unknown>)[prop];
|
||||||
|
return typeof value === "function" ? value.bind(client) : value;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|||||||
@ -1,7 +1,8 @@
|
|||||||
import QRCode from "qrcode";
|
import QRCode from "qrcode";
|
||||||
|
import { APP_DOMAIN } from "./config";
|
||||||
|
|
||||||
export async function generateMonumentQR(subdomain: string): Promise<string> {
|
export async function generateMonumentQR(subdomain: string): Promise<string> {
|
||||||
const url = `https://${subdomain}.${process.env.NEXT_PUBLIC_APP_DOMAIN}`;
|
const url = `https://${subdomain}.${APP_DOMAIN}`;
|
||||||
const qrBuffer = await QRCode.toBuffer(url, {
|
const qrBuffer = await QRCode.toBuffer(url, {
|
||||||
type: "png",
|
type: "png",
|
||||||
width: 400,
|
width: 400,
|
||||||
@ -14,3 +15,16 @@ export async function generateMonumentQR(subdomain: string): Promise<string> {
|
|||||||
|
|
||||||
return `data:image/png;base64,${qrBuffer.toString("base64")}`;
|
return `data:image/png;base64,${qrBuffer.toString("base64")}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function generateMonumentQRPng(subdomain: string): Promise<Buffer> {
|
||||||
|
const url = `https://${subdomain}.${APP_DOMAIN}`;
|
||||||
|
return QRCode.toBuffer(url, {
|
||||||
|
type: "png",
|
||||||
|
width: 400,
|
||||||
|
margin: 2,
|
||||||
|
color: {
|
||||||
|
dark: "#1a1a2e",
|
||||||
|
light: "#ffffff",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
61
src/lib/rate-limit.ts
Normal file
61
src/lib/rate-limit.ts
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
import { LRUCache } from "lru-cache";
|
||||||
|
|
||||||
|
export interface RateLimitResult {
|
||||||
|
success: boolean;
|
||||||
|
remaining: number;
|
||||||
|
resetAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Bucket {
|
||||||
|
count: number;
|
||||||
|
resetAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class RateLimiter {
|
||||||
|
private cache: LRUCache<string, Bucket>;
|
||||||
|
private maxTokens: number;
|
||||||
|
private windowMs: number;
|
||||||
|
|
||||||
|
constructor(maxTokens: number, windowMs: number, capacity = 10000) {
|
||||||
|
this.maxTokens = maxTokens;
|
||||||
|
this.windowMs = windowMs;
|
||||||
|
this.cache = new LRUCache<string, Bucket>({
|
||||||
|
max: capacity,
|
||||||
|
ttl: windowMs,
|
||||||
|
ttlResolution: windowMs,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
limit(key: string): RateLimitResult {
|
||||||
|
const now = Date.now();
|
||||||
|
const existing = this.cache.get(key);
|
||||||
|
if (!existing || existing.resetAt <= now) {
|
||||||
|
const resetAt = now + this.windowMs;
|
||||||
|
const bucket: Bucket = { count: 1, resetAt };
|
||||||
|
this.cache.set(key, bucket);
|
||||||
|
return { success: true, remaining: this.maxTokens - 1, resetAt };
|
||||||
|
}
|
||||||
|
if (existing.count >= this.maxTokens) {
|
||||||
|
return { success: false, remaining: 0, resetAt: existing.resetAt };
|
||||||
|
}
|
||||||
|
existing.count += 1;
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
remaining: this.maxTokens - existing.count,
|
||||||
|
resetAt: existing.resetAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const adminLoginLimiter = new RateLimiter(5, 60_000);
|
||||||
|
export const validateCodeLimiter = new RateLimiter(20, 60_000);
|
||||||
|
export const checkSubdomainLimiter = new RateLimiter(60, 60_000);
|
||||||
|
export const uploadLimiter = new RateLimiter(10, 60_000);
|
||||||
|
|
||||||
|
export function rateLimitHeaders(result: RateLimitResult): Record<string, string> {
|
||||||
|
return {
|
||||||
|
"X-RateLimit-Limit": String(result.success ? result.remaining + 1 : result.remaining),
|
||||||
|
"X-RateLimit-Remaining": String(Math.max(result.remaining, 0)),
|
||||||
|
"X-RateLimit-Reset": String(Math.floor(result.resetAt / 1000)),
|
||||||
|
};
|
||||||
|
}
|
||||||
@ -1,216 +0,0 @@
|
|||||||
import type { MemorialData } from "@/types";
|
|
||||||
|
|
||||||
function formatDates(born: string | null, passed: string | null): string {
|
|
||||||
if (born && passed) return `${born} \u2014 ${passed}`;
|
|
||||||
if (passed) return passed;
|
|
||||||
if (born) return born;
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
function MemorialFooter({ name }: { name: string | null }) {
|
|
||||||
return (
|
|
||||||
<footer className="border-t border-stone-200 py-10 text-center">
|
|
||||||
<div className="mx-auto mb-3 flex h-8 w-8 items-center justify-center rounded-full bg-amber-100">
|
|
||||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="h-5 w-5 text-amber-600">
|
|
||||||
<path d="M12 3C7 8 4 11 4 14.5C4 18 7 21 12 21C17 21 20 18 20 14.5C20 11 17 8 12 3Z" strokeLinecap="round" strokeLinejoin="round" />
|
|
||||||
</svg>
|
|
||||||
</div>
|
|
||||||
<p className="text-sm italic text-stone-400">Во спомен на</p>
|
|
||||||
{name && <p className="mt-1 text-xs text-stone-400">{name}</p>}
|
|
||||||
</footer>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function renderTemplate(templateId: number, data: MemorialData) {
|
|
||||||
switch (templateId) {
|
|
||||||
case 1:
|
|
||||||
return <TemplateElegance data={data} />;
|
|
||||||
case 2:
|
|
||||||
return <TemplateCinematic data={data} />;
|
|
||||||
case 3:
|
|
||||||
return <TemplateSerene data={data} />;
|
|
||||||
default:
|
|
||||||
return <TemplateElegance data={data} />;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function TemplateElegance({ data }: { data: MemorialData }) {
|
|
||||||
const sortedImages = [...data.images].sort((a, b) => a.order - b.order);
|
|
||||||
const heroImage = sortedImages[0];
|
|
||||||
const gridImages = sortedImages.slice(1);
|
|
||||||
const dates = formatDates(data.bornDate, data.passedDate);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-stone-50 font-serif">
|
|
||||||
{heroImage && (
|
|
||||||
<div className="relative h-[55vh] w-full overflow-hidden">
|
|
||||||
<img src={heroImage.url} alt={data.title || "Спомен"} className="h-full w-full object-cover object-top" />
|
|
||||||
<div className="absolute inset-0 bg-gradient-to-t from-stone-900/70 via-stone-900/20 to-transparent" />
|
|
||||||
<div className="absolute bottom-10 left-0 right-0 text-center">
|
|
||||||
<h1 className="text-4xl font-bold tracking-wide text-white md:text-6xl drop-shadow-lg">
|
|
||||||
{data.title || "Во спомен на"}
|
|
||||||
</h1>
|
|
||||||
{dates && (
|
|
||||||
<p className="mt-3 text-lg tracking-widest text-stone-200 uppercase drop-shadow">
|
|
||||||
{dates}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{!heroImage && (
|
|
||||||
<div className="mx-auto max-w-2xl px-6 pt-24 text-center">
|
|
||||||
<h1 className="text-4xl font-bold tracking-wide text-stone-900 md:text-6xl">
|
|
||||||
{data.title || "Во спомен на"}
|
|
||||||
</h1>
|
|
||||||
{dates && (
|
|
||||||
<p className="mt-4 text-lg tracking-widest text-stone-400 uppercase">{dates}</p>
|
|
||||||
)}
|
|
||||||
<div className="mx-auto mt-6 h-px w-16 bg-amber-400" />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="mx-auto max-w-3xl px-6 py-14">
|
|
||||||
{data.description && (
|
|
||||||
<div className="text-center">
|
|
||||||
<p className="text-lg leading-relaxed text-stone-700 whitespace-pre-wrap md:text-xl">
|
|
||||||
{data.description}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{gridImages.length > 0 && (
|
|
||||||
<div className="mt-14 grid grid-cols-1 gap-4 sm:grid-cols-2">
|
|
||||||
{gridImages.map((img) => (
|
|
||||||
<div key={img.id} className="overflow-hidden rounded-lg shadow-md">
|
|
||||||
<img src={img.url} alt="" className="h-64 w-full object-cover transition-transform duration-500 hover:scale-105" />
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<MemorialFooter name={data.title} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function TemplateCinematic({ data }: { data: MemorialData }) {
|
|
||||||
const sortedImages = [...data.images].sort((a, b) => a.order - b.order);
|
|
||||||
const dates = formatDates(data.bornDate, data.passedDate);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-zinc-950 text-white">
|
|
||||||
{sortedImages.length > 0 && (
|
|
||||||
<>
|
|
||||||
<div className="relative h-screen w-full">
|
|
||||||
<img src={sortedImages[0].url} alt={data.title || "Спомен"} className="h-full w-full object-cover object-top" />
|
|
||||||
<div className="absolute inset-0 bg-gradient-to-t from-black/90 via-black/40 to-transparent" />
|
|
||||||
<div className="absolute bottom-16 left-8 right-8 md:left-16">
|
|
||||||
<h1 className="text-5xl font-black tracking-tight md:text-8xl drop-shadow-2xl">
|
|
||||||
{data.title || "Во спомен на"}
|
|
||||||
</h1>
|
|
||||||
{dates && (
|
|
||||||
<p className="mt-3 text-lg font-light tracking-widest text-zinc-300 uppercase md:text-xl">
|
|
||||||
{dates}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
{data.description && (
|
|
||||||
<p className="mt-6 max-w-2xl text-base leading-relaxed text-zinc-300 md:text-lg line-clamp-4">
|
|
||||||
{data.description}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{sortedImages.length > 1 && (
|
|
||||||
<div className="grid grid-cols-2 gap-0.5 md:grid-cols-3">
|
|
||||||
{sortedImages.slice(1).map((img) => (
|
|
||||||
<div key={img.id} className="relative aspect-square overflow-hidden">
|
|
||||||
<img src={img.url} alt="" className="h-full w-full object-cover" />
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{sortedImages.length === 0 && (
|
|
||||||
<div className="flex min-h-screen items-center justify-center px-8">
|
|
||||||
<div className="max-w-2xl text-center">
|
|
||||||
<h1 className="text-5xl font-black tracking-tight md:text-8xl">
|
|
||||||
{data.title || "Во спомен на"}
|
|
||||||
</h1>
|
|
||||||
{dates && (
|
|
||||||
<p className="mt-4 text-lg font-light tracking-widest text-zinc-400 uppercase">{dates}</p>
|
|
||||||
)}
|
|
||||||
{data.description && (
|
|
||||||
<p className="mt-8 text-base leading-relaxed text-zinc-400 whitespace-pre-wrap md:text-lg">
|
|
||||||
{data.description}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<footer className="py-12 text-center">
|
|
||||||
<div className="mx-auto mb-3 flex h-8 w-8 items-center justify-center rounded-full bg-white/10">
|
|
||||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="h-5 w-5 text-zinc-500">
|
|
||||||
<path d="M12 3C7 8 4 11 4 14.5C4 18 7 21 12 21C17 21 20 18 20 14.5C20 11 17 8 12 3Z" strokeLinecap="round" strokeLinejoin="round" />
|
|
||||||
</svg>
|
|
||||||
</div>
|
|
||||||
<p className="text-sm italic text-zinc-500">Во спомен на</p>
|
|
||||||
</footer>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function TemplateSerene({ data }: { data: MemorialData }) {
|
|
||||||
const sortedImages = [...data.images].sort((a, b) => a.order - b.order);
|
|
||||||
const dates = formatDates(data.bornDate, data.passedDate);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-white">
|
|
||||||
<div className="mx-auto max-w-xl px-6 py-20 md:py-28">
|
|
||||||
<div className="text-center">
|
|
||||||
{sortedImages.length > 0 && (
|
|
||||||
<div className="mx-auto mb-8 h-40 w-40 overflow-hidden rounded-full shadow-lg">
|
|
||||||
<img src={sortedImages[0].url} alt={data.title || "Спомен"} className="h-full w-full object-cover object-top" />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<h1 className="text-3xl font-light tracking-tight text-zinc-900 md:text-5xl">
|
|
||||||
{data.title || "Во спомен на"}
|
|
||||||
</h1>
|
|
||||||
|
|
||||||
{dates && (
|
|
||||||
<p className="mt-3 text-sm tracking-[0.2em] text-zinc-400 uppercase">{dates}</p>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="mx-auto mt-6 h-px w-12 bg-blue-200" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{data.description && (
|
|
||||||
<div className="mt-10 border-l-2 border-blue-100 pl-6">
|
|
||||||
<p className="text-base leading-7 text-zinc-600 whitespace-pre-wrap md:text-lg">
|
|
||||||
{data.description}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{sortedImages.length > 1 && (
|
|
||||||
<div className="mt-12 flex gap-4 overflow-x-auto pb-4">
|
|
||||||
{sortedImages.slice(1).map((img) => (
|
|
||||||
<div key={img.id} className="flex-shrink-0">
|
|
||||||
<img src={img.url} alt="" className="h-56 w-auto rounded-lg shadow-sm object-cover" />
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<MemorialFooter name={data.title} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
74
src/lib/templates/Cinematic.tsx
Normal file
74
src/lib/templates/Cinematic.tsx
Normal file
@ -0,0 +1,74 @@
|
|||||||
|
import type { MemorialData } from "@/types";
|
||||||
|
import { formatDates } from "./shared";
|
||||||
|
|
||||||
|
export function TemplateCinematic({ data }: { data: MemorialData }) {
|
||||||
|
const sortedImages = [...data.images].sort((a, b) => a.order - b.order);
|
||||||
|
const dates = formatDates(data.bornDate, data.passedDate);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-zinc-950 text-white">
|
||||||
|
{sortedImages.length > 0 && (
|
||||||
|
<>
|
||||||
|
<div className="relative h-screen w-full">
|
||||||
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
|
<img src={sortedImages[0].url} alt={data.title || "Спомен"} className="h-full w-full object-cover object-top" />
|
||||||
|
<div className="absolute inset-0 bg-gradient-to-t from-black/90 via-black/40 to-transparent" />
|
||||||
|
<div className="absolute bottom-16 left-8 right-8 md:left-16">
|
||||||
|
<h1 className="text-5xl font-black tracking-tight md:text-8xl drop-shadow-2xl">
|
||||||
|
{data.title || "Во спомен на"}
|
||||||
|
</h1>
|
||||||
|
{dates && (
|
||||||
|
<p className="mt-3 text-lg font-light tracking-widest text-zinc-300 uppercase md:text-xl">
|
||||||
|
{dates}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{data.description && (
|
||||||
|
<p className="mt-6 max-w-2xl text-base leading-relaxed text-zinc-300 md:text-lg line-clamp-4">
|
||||||
|
{data.description}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{sortedImages.length > 1 && (
|
||||||
|
<div className="grid grid-cols-2 gap-0.5 md:grid-cols-3">
|
||||||
|
{sortedImages.slice(1).map((img) => (
|
||||||
|
<div key={img.id} className="relative aspect-square overflow-hidden">
|
||||||
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
|
<img src={img.url} alt="" className="h-full w-full object-cover" />
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{sortedImages.length === 0 && (
|
||||||
|
<div className="flex min-h-screen items-center justify-center px-8">
|
||||||
|
<div className="max-w-2xl text-center">
|
||||||
|
<h1 className="text-5xl font-black tracking-tight md:text-8xl">
|
||||||
|
{data.title || "Во спомен на"}
|
||||||
|
</h1>
|
||||||
|
{dates && (
|
||||||
|
<p className="mt-4 text-lg font-light tracking-widest text-zinc-400 uppercase">{dates}</p>
|
||||||
|
)}
|
||||||
|
{data.description && (
|
||||||
|
<p className="mt-8 text-base leading-relaxed text-zinc-400 whitespace-pre-wrap md:text-lg">
|
||||||
|
{data.description}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<footer className="py-12 text-center">
|
||||||
|
<div className="mx-auto mb-3 flex h-8 w-8 items-center justify-center rounded-full bg-white/10">
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="h-5 w-5 text-zinc-500">
|
||||||
|
<path d="M12 3C7 8 4 11 4 14.5C4 18 7 21 12 21C17 21 20 18 20 14.5C20 11 17 8 12 3Z" strokeLinecap="round" strokeLinejoin="round" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm italic text-zinc-500">Во спомен на</p>
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
66
src/lib/templates/Elegance.tsx
Normal file
66
src/lib/templates/Elegance.tsx
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
import type { MemorialData } from "@/types";
|
||||||
|
import { formatDates, MemorialFooter } from "./shared";
|
||||||
|
|
||||||
|
export function TemplateElegance({ data }: { data: MemorialData }) {
|
||||||
|
const sortedImages = [...data.images].sort((a, b) => a.order - b.order);
|
||||||
|
const heroImage = sortedImages[0];
|
||||||
|
const gridImages = sortedImages.slice(1);
|
||||||
|
const dates = formatDates(data.bornDate, data.passedDate);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-stone-50 font-serif">
|
||||||
|
{heroImage && (
|
||||||
|
<div className="relative h-[55vh] w-full overflow-hidden">
|
||||||
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
|
<img src={heroImage.url} alt={data.title || "Спомен"} className="h-full w-full object-cover object-top" />
|
||||||
|
<div className="absolute inset-0 bg-gradient-to-t from-stone-900/70 via-stone-900/20 to-transparent" />
|
||||||
|
<div className="absolute bottom-10 left-0 right-0 text-center">
|
||||||
|
<h1 className="text-4xl font-bold tracking-wide text-white md:text-6xl drop-shadow-lg">
|
||||||
|
{data.title || "Во спомен на"}
|
||||||
|
</h1>
|
||||||
|
{dates && (
|
||||||
|
<p className="mt-3 text-lg tracking-widest text-stone-200 uppercase drop-shadow">
|
||||||
|
{dates}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!heroImage && (
|
||||||
|
<div className="mx-auto max-w-2xl px-6 pt-24 text-center">
|
||||||
|
<h1 className="text-4xl font-bold tracking-wide text-stone-900 md:text-6xl">
|
||||||
|
{data.title || "Во спомен на"}
|
||||||
|
</h1>
|
||||||
|
{dates && (
|
||||||
|
<p className="mt-4 text-lg tracking-widest text-stone-400 uppercase">{dates}</p>
|
||||||
|
)}
|
||||||
|
<div className="mx-auto mt-6 h-px w-16 bg-amber-400" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="mx-auto max-w-3xl px-6 py-14">
|
||||||
|
{data.description && (
|
||||||
|
<div className="text-center">
|
||||||
|
<p className="text-lg leading-relaxed text-stone-700 whitespace-pre-wrap md:text-xl">
|
||||||
|
{data.description}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{gridImages.length > 0 && (
|
||||||
|
<div className="mt-14 grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||||
|
{gridImages.map((img) => (
|
||||||
|
<div key={img.id} className="overflow-hidden rounded-lg shadow-md">
|
||||||
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
|
<img src={img.url} alt="" className="h-64 w-full object-cover transition-transform duration-500 hover:scale-105" />
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<MemorialFooter name={data.title} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
53
src/lib/templates/Serene.tsx
Normal file
53
src/lib/templates/Serene.tsx
Normal file
@ -0,0 +1,53 @@
|
|||||||
|
import type { MemorialData } from "@/types";
|
||||||
|
import { formatDates, MemorialFooter } from "./shared";
|
||||||
|
|
||||||
|
export function TemplateSerene({ data }: { data: MemorialData }) {
|
||||||
|
const sortedImages = [...data.images].sort((a, b) => a.order - b.order);
|
||||||
|
const dates = formatDates(data.bornDate, data.passedDate);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-white">
|
||||||
|
<div className="mx-auto max-w-xl px-6 py-20 md:py-28">
|
||||||
|
<div className="text-center">
|
||||||
|
{sortedImages.length > 0 && (
|
||||||
|
<div className="mx-auto mb-8 h-40 w-40 overflow-hidden rounded-full shadow-lg">
|
||||||
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
|
<img src={sortedImages[0].url} alt={data.title || "Спомен"} className="h-full w-full object-cover object-top" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<h1 className="text-3xl font-light tracking-tight text-zinc-900 md:text-5xl">
|
||||||
|
{data.title || "Во спомен на"}
|
||||||
|
</h1>
|
||||||
|
|
||||||
|
{dates && (
|
||||||
|
<p className="mt-3 text-sm tracking-[0.2em] text-zinc-400 uppercase">{dates}</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="mx-auto mt-6 h-px w-12 bg-blue-200" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{data.description && (
|
||||||
|
<div className="mt-10 border-l-2 border-blue-100 pl-6">
|
||||||
|
<p className="text-base leading-7 text-zinc-600 whitespace-pre-wrap md:text-lg">
|
||||||
|
{data.description}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{sortedImages.length > 1 && (
|
||||||
|
<div className="mt-12 flex gap-4 overflow-x-auto pb-4">
|
||||||
|
{sortedImages.slice(1).map((img) => (
|
||||||
|
<div key={img.id} className="flex-shrink-0">
|
||||||
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
|
<img src={img.url} alt="" className="h-56 w-auto rounded-lg shadow-sm object-cover" />
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<MemorialFooter name={data.title} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
20
src/lib/templates/index.tsx
Normal file
20
src/lib/templates/index.tsx
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
import type { MemorialData } from "@/types";
|
||||||
|
import { TemplateElegance } from "./Elegance";
|
||||||
|
import { TemplateCinematic } from "./Cinematic";
|
||||||
|
import { TemplateSerene } from "./Serene";
|
||||||
|
|
||||||
|
export { TemplateElegance, TemplateCinematic, TemplateSerene };
|
||||||
|
export { formatDates, MemorialFooter } from "./shared";
|
||||||
|
|
||||||
|
export function renderTemplate(templateId: number, data: MemorialData) {
|
||||||
|
switch (templateId) {
|
||||||
|
case 1:
|
||||||
|
return <TemplateElegance data={data} />;
|
||||||
|
case 2:
|
||||||
|
return <TemplateCinematic data={data} />;
|
||||||
|
case 3:
|
||||||
|
return <TemplateSerene data={data} />;
|
||||||
|
default:
|
||||||
|
return <TemplateElegance data={data} />;
|
||||||
|
}
|
||||||
|
}
|
||||||
22
src/lib/templates/shared.tsx
Normal file
22
src/lib/templates/shared.tsx
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
import type { MemorialData } from "@/types";
|
||||||
|
|
||||||
|
export function formatDates(born: string | null, passed: string | null): string {
|
||||||
|
if (born && passed) return `${born} \u2014 ${passed}`;
|
||||||
|
if (passed) return passed;
|
||||||
|
if (born) return born;
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MemorialFooter({ name }: { name: string | null }) {
|
||||||
|
return (
|
||||||
|
<footer className="border-t border-stone-200 py-10 text-center">
|
||||||
|
<div className="mx-auto mb-3 flex h-8 w-8 items-center justify-center rounded-full bg-amber-100">
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="h-5 w-5 text-amber-600">
|
||||||
|
<path d="M12 3C7 8 4 11 4 14.5C4 18 7 21 12 21C17 21 20 18 20 14.5C20 11 17 8 12 3Z" strokeLinecap="round" strokeLinejoin="round" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm italic text-stone-400">Во спомен на</p>
|
||||||
|
{name && <p className="mt-1 text-xs text-stone-400">{name}</p>}
|
||||||
|
</footer>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -4,16 +4,38 @@ import { v4 as uuidv4 } from "uuid";
|
|||||||
import { s3Client, S3_BUCKET, getPublicUrl } from "./s3";
|
import { s3Client, S3_BUCKET, getPublicUrl } from "./s3";
|
||||||
|
|
||||||
const MAX_FILE_SIZE = 5 * 1024 * 1024;
|
const MAX_FILE_SIZE = 5 * 1024 * 1024;
|
||||||
const ALLOWED_TYPES = ["image/jpeg", "image/png", "image/webp", "image/gif"];
|
const ALLOWED_TYPES = ["image/jpeg", "image/png", "image/webp"] as const;
|
||||||
const MAX_FILES = 3;
|
const MAX_FILES = 3;
|
||||||
|
|
||||||
export { MAX_FILE_SIZE, ALLOWED_TYPES, MAX_FILES, getPublicUrl };
|
export { MAX_FILE_SIZE, ALLOWED_TYPES, MAX_FILES, getPublicUrl };
|
||||||
|
|
||||||
|
export type AllowedImageType = (typeof ALLOWED_TYPES)[number];
|
||||||
|
|
||||||
|
const MAGIC_BYTES: Record<AllowedImageType, Array<(buf: Buffer) => boolean>> = {
|
||||||
|
"image/jpeg": [(b) => b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff],
|
||||||
|
"image/png": [(b) => b.length >= 8 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47 && b[4] === 0x0d && b[5] === 0x0a && b[6] === 0x1a && b[7] === 0x0a],
|
||||||
|
"image/webp": [(b) => b.length >= 12 && b.slice(0, 4).toString("ascii") === "RIFF" && b.slice(8, 12).toString("ascii") === "WEBP"],
|
||||||
|
};
|
||||||
|
|
||||||
|
export function detectImageType(buf: Buffer): AllowedImageType | null {
|
||||||
|
for (const type of ALLOWED_TYPES) {
|
||||||
|
if (MAGIC_BYTES[type].some((check) => check(buf))) return type;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sanitizeUploadKey(key: string): string {
|
||||||
|
if (!/^uploads\/[a-zA-Z0-9_-]+\/[a-f0-9-]+\.(jpe?g|png|webp)$/i.test(key)) {
|
||||||
|
throw new Error("Invalid key format");
|
||||||
|
}
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
|
||||||
export async function generatePresignedUrl(
|
export async function generatePresignedUrl(
|
||||||
contentType: string,
|
contentType: string,
|
||||||
userId: string
|
userId: string
|
||||||
): Promise<{ url: string; key: string; publicUrl: string }> {
|
): Promise<{ url: string; key: string; publicUrl: string }> {
|
||||||
if (!ALLOWED_TYPES.includes(contentType)) {
|
if (!ALLOWED_TYPES.includes(contentType as AllowedImageType)) {
|
||||||
throw new Error(`Invalid content type: ${contentType}`);
|
throw new Error(`Invalid content type: ${contentType}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,9 +1,14 @@
|
|||||||
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
|
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
|
||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import type { NextRequest } from "next/server";
|
import type { NextRequest } from "next/server";
|
||||||
|
import { verifyAdminSession, COOKIE_NAME_ADMIN } from "@/lib/admin-session";
|
||||||
|
|
||||||
const isProtectedRoute = createRouteMatcher(["/dashboard(.*)", "/onboarding(.*)", "/api/publish(.*)", "/api/upload(.*)", "/api/user(.*)"]);
|
const isProtectedRoute = createRouteMatcher(["/dashboard(.*)", "/onboarding(.*)", "/api/publish(.*)", "/api/upload(.*)", "/api/user(.*)"]);
|
||||||
|
|
||||||
|
function isAdminRoute(pathname: string): boolean {
|
||||||
|
return pathname.startsWith("/admin") || pathname.startsWith("/api/admin");
|
||||||
|
}
|
||||||
|
|
||||||
function getSubdomain(req: NextRequest): string | null {
|
function getSubdomain(req: NextRequest): string | null {
|
||||||
const host = req.headers.get("host");
|
const host = req.headers.get("host");
|
||||||
if (!host) return null;
|
if (!host) return null;
|
||||||
@ -25,6 +30,22 @@ function getSubdomain(req: NextRequest): string | null {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default clerkMiddleware(async (auth, req: NextRequest) => {
|
export default clerkMiddleware(async (auth, req: NextRequest) => {
|
||||||
|
if (isAdminRoute(req.nextUrl.pathname)) {
|
||||||
|
if (req.nextUrl.pathname === "/admin/login" || req.nextUrl.pathname === "/api/admin/login") {
|
||||||
|
return NextResponse.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = req.cookies.get(COOKIE_NAME_ADMIN)?.value;
|
||||||
|
if (!token || !(await verifyAdminSession(token))) {
|
||||||
|
if (req.nextUrl.pathname.startsWith("/api/")) {
|
||||||
|
return NextResponse.json({ error: "Неавторизирано" }, { status: 401 });
|
||||||
|
}
|
||||||
|
return NextResponse.redirect(new URL("/admin/login", req.url));
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.next();
|
||||||
|
}
|
||||||
|
|
||||||
if (isProtectedRoute(req)) {
|
if (isProtectedRoute(req)) {
|
||||||
await auth.protect();
|
await auth.protect();
|
||||||
}
|
}
|
||||||
|
|||||||
@ -34,9 +34,13 @@
|
|||||||
"**/*.tsx",
|
"**/*.tsx",
|
||||||
".next/types/**/*.ts",
|
".next/types/**/*.ts",
|
||||||
".next/dev/types/**/*.ts",
|
".next/dev/types/**/*.ts",
|
||||||
"**/*.mts"
|
"**/*.mts",
|
||||||
|
"vitest.config.ts"
|
||||||
],
|
],
|
||||||
"exclude": [
|
"exclude": [
|
||||||
"node_modules"
|
"node_modules",
|
||||||
|
".next",
|
||||||
|
".next_old",
|
||||||
|
"src/**/*.test.ts"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
15
vitest.config.ts
Normal file
15
vitest.config.ts
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
import { defineConfig } from "vitest/config";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
resolve: {
|
||||||
|
alias: {
|
||||||
|
"@": path.resolve(__dirname, "src"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
test: {
|
||||||
|
environment: "node",
|
||||||
|
include: ["src/**/*.test.ts"],
|
||||||
|
globals: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
Loading…
Reference in New Issue
Block a user