Skip to content

Your favorite shift management application!

feat!: auth system (v2) (#98)

panteL9dafae7e557c
diff --git a/.env.example b/.env.example
index c071ae3..8319f41 100644
--- a/.env.example
+++ b/.env.example
@@ -1,25 +1,152 @@
-# BetterShift Environment Variables Example
+# ==============================================================================
+# BetterShift Environment Configuration
+# ==============================================================================
+# Copy this file to .env and configure according to your needs
+# Some values are pre-filled with defaults, others require your input
+
+
+# ==============================================================================
+# DATABASE
+# ==============================================================================
-# Database Configuration
DATABASE_URL=file:./data/sqlite.db
-# GitHub API Configuration (for version endpoint)
+
+# ==============================================================================
+# APPLICATION SETTINGS
+# ==============================================================================
+
+# Node.js environment (NOT supported in Docker)
+NODE_ENV=production
+HOSTNAME=0.0.0.0
+
+# Internationalization
+DEFAULT_LOCALE=en # Options: en, de, it
+TZ=Europe/Berlin # Application timezone
+
+
+# ==============================================================================
+# AUTHENTICATION SYSTEM
+# ==============================================================================
+# Note: Auth is enabled by default for better security
+
+# Core Auth Configuration
+AUTH_ENABLED=true # Set to false to disable authentication
+
+# REQUIRED if AUTH_ENABLED=true:
+BETTER_AUTH_SECRET= # Generate with: npx @better-auth/cli secret
+BETTER_AUTH_URL=http://localhost:3000 # Your application URL
+
+# Security
+# BETTER_AUTH_TRUSTED_ORIGINS=http://localhost:3000,https://yourdomain.com # Comma-separated list of allowed origins for CORS
+
+# Access Control
+ALLOW_USER_REGISTRATION=true # Enable/disable new user signups
+ALLOW_GUEST_ACCESS=false # Allow viewing calendars without login
+
+# Session Management (server-side only)
+# SESSION_MAX_AGE=604800 # Session lifetime: 7 days (seconds)
+# SESSION_UPDATE_AGE=86400 # Session refresh interval: 1 day (seconds)
+
+
+# ==============================================================================
+# OAUTH PROVIDERS
+# ==============================================================================
+# Note: CLIENT_IDs are exposed to client for UI detection
+# CLIENT_SECRETs remain server-only
+# Callback URLs: {BETTER_AUTH_URL}/api/auth/callback/{provider}
+
+# Google OAuth
+# GOOGLE_CLIENT_ID=
+# GOOGLE_CLIENT_SECRET=
+
+# GitHub OAuth
+# GITHUB_CLIENT_ID=
+# GITHUB_CLIENT_SECRET=
+
+# Discord OAuth
+# DISCORD_CLIENT_ID=
+# DISCORD_CLIENT_SECRET=
+
+
+# ==============================================================================
+# CUSTOM OIDC PROVIDER
+# ==============================================================================
+# Note: Client IDs are exposed to client for UI detection
+# Client Secrets remain server-only
+# Callback URL: {BETTER_AUTH_URL}/api/auth/oauth2/callback/custom-oidc
+
+# CUSTOM_OIDC_ENABLED=false
+# CUSTOM_OIDC_NAME=Custom SSO # Display name on login button
+# CUSTOM_OIDC_CLIENT_ID=
+# CUSTOM_OIDC_CLIENT_SECRET=
+# CUSTOM_OIDC_ISSUER=https://sso.example.com/.well-known/openid-configuration
+# CUSTOM_OIDC_SCOPES=openid profile email # Space-separated list
+
+
+# ==============================================================================
+# GITHUB INTEGRATION
+# ==============================================================================
+# Used for version information endpoint
+
GITHUB_REPO_OWNER=panteLx
GITHUB_REPO_NAME=BetterShift
GITHUB_BRANCH=main
-# GITHUB_TOKEN=your_github_token_here # Optional: Increases GitHub API rate limits from 60 to 5000 requests/hour
-# Cache Settings (in seconds)
-VERSION_CACHE_DURATION=3600 # Version info cache: 1 hour in seconds
-GITHUB_API_REVALIDATE=3600 # GitHub API revalidation: 1 hour in seconds
+# Optional: Increases API rate limit from 60 to 5000 requests/hour
+# GITHUB_TOKEN=
-# Internationalization (i18n)
-DEFAULT_LOCALE=en # Default language if browser detection fails. Options: en, de
-# Timezone Setting
-TZ=Europe/Berlin # Set the application's timezone (e.g., Europe/Berlin)
+# ==============================================================================
+# RATE LIMITING
+# ==============================================================================
-# Application Settings (NOT supported on Docker deployments)
-NODE_ENV=production
-PORT=3000
-HOSTNAME=0.0.0.0
+# All settings are optional - defaults shown in comments
+
+# Authentication
+# RATE_LIMIT_AUTH_REQUESTS=5 # Per IP
+# RATE_LIMIT_AUTH_WINDOW=60 # 1 minute
+
+# RATE_LIMIT_REGISTER_REQUESTS=3 # Per IP
+# RATE_LIMIT_REGISTER_WINDOW=600 # 10 minutes
+
+# RATE_LIMIT_PASSWORD_CHANGE_REQUESTS=3 # Per user
+# RATE_LIMIT_PASSWORD_CHANGE_WINDOW=3600 # 1 hour
+
+# Account Management
+# RATE_LIMIT_ACCOUNT_DELETE_REQUESTS=1 # Per user
+# RATE_LIMIT_ACCOUNT_DELETE_WINDOW=3600 # 1 hour
+
+# RATE_LIMIT_UPLOAD_AVATAR_REQUESTS=5 # Per user
+# RATE_LIMIT_UPLOAD_AVATAR_WINDOW=300 # 5 minutes
+
+# Real-Time Features
+# RATE_LIMIT_SSE_CONNECTIONS=10 # Per user
+# RATE_LIMIT_SSE_WINDOW=10 # 10 seconds
+
+# Calendar Operations
+# RATE_LIMIT_CALENDAR_CREATE_REQUESTS=10 # Per user
+# RATE_LIMIT_CALENDAR_CREATE_WINDOW=3600 # 1 hour
+
+# RATE_LIMIT_EXTERNAL_SYNC_REQUESTS=5 # Per calendar
+# RATE_LIMIT_EXTERNAL_SYNC_WINDOW=300 # 5 minutes
+
+# Export Features
+# RATE_LIMIT_EXPORT_PDF_REQUESTS=10 # Per user
+# RATE_LIMIT_EXPORT_PDF_WINDOW=600 # 10 minutes
+
+# Calendar Access Tokens (Share Links)
+# RATE_LIMIT_TOKEN_VALIDATION_REQUESTS=10 # Per IP
+# RATE_LIMIT_TOKEN_VALIDATION_WINDOW=60 # 1 minute
+# RATE_LIMIT_TOKEN_CREATION_REQUESTS=10 # Per calendar
+# RATE_LIMIT_TOKEN_CREATION_WINDOW=3600 # 1 hour
+
+# Admin Panel (per admin user)
+# RATE_LIMIT_ADMIN_USER_MUTATIONS=10 # User ban/unban/delete/edit
+# RATE_LIMIT_ADMIN_USER_MUTATIONS_WINDOW=60 # 1 minute
+# RATE_LIMIT_ADMIN_PASSWORD_RESET=5 # Password reset for users
+# RATE_LIMIT_ADMIN_PASSWORD_RESET_WINDOW=300 # 5 minutes
+# RATE_LIMIT_ADMIN_BULK_OPERATIONS=3 # Bulk delete/transfer calendars
+# RATE_LIMIT_ADMIN_BULK_OPERATIONS_WINDOW=300 # 5 minutes
+# RATE_LIMIT_ADMIN_CALENDAR_MUTATIONS=10 # Calendar delete/transfer/edit
+# RATE_LIMIT_ADMIN_CALENDAR_MUTATIONS_WINDOW=60 # 1 minute
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index b40a6e3..4b62dcb 100644
--- a/.github/copilot-instructions.md
+++ b/.github/copilot-instructions.md
@@ -1,296 +1,385 @@
-# BetterShift Copilot Instructions
+# BetterShift AI Coding Instructions
-## Quick Reference
+## Project Overview
-- **Framework**: Next.js 16 App Router + React 19
-- **Database**: SQLite + Drizzle ORM (`./data/sqlite.db`)
-- **UI**: Tailwind CSS 4 + shadcn/ui + BaseSheet component
-- **i18n**: next-intl (de/en/it) - always use informal "du" in German
-- **Critical**: Never use `db:push`, always generate migrations
-- **State**: ALWAYS use existing hooks from `hooks/` - NEVER implement custom fetch logic
+**BetterShift** is a modern shift management web application for variable work schedules. Users manage unlimited calendars with one-click shift toggles, external calendar sync (iCal/Google/Outlook), calendar sharing with granular permissions, reusable presets, and multi-language support. Built with **Next.js 16 (App Router)**, **React 19**, **SQLite + Drizzle ORM**, and **Better Auth**.
-## Core Architecture
+## Tech Stack Quick Reference
-### Tech Stack
+- **Frontend**: Next.js 16 (App Router), React 19, TypeScript 5 (strict mode)
+- **UI**: Tailwind CSS 4, shadcn/ui (Radix UI primitives), Lucide icons, Motion animations
+- **Database**: SQLite (via better-sqlite3) + Drizzle ORM 0.44
+- **Auth**: Better Auth 1.4 (enabled by default) - email/password + OAuth (Google/GitHub/Discord) + custom OIDC
+- **i18n**: next-intl 4.5 - Supported locales: `en`, `de`, `it`
+- **Key Libraries**: date-fns, ical.js, jsPDF, @dnd-kit, recharts, sonner (toasts)
-- **Framework**: Next.js 16 with App Router (`app/` directory)
-- **UI**: React 19, Tailwind CSS 4, shadcn/ui components (`components/ui/`)
-- **Database**: SQLite via Drizzle ORM (file: `./data/sqlite.db`)
-- **i18n**: next-intl (German/English/Italian, cookie-based + browser detection)
-- **State**: Client-side with React hooks, custom hooks in `hooks/`
+## Architecture Patterns
-### Database Schema
+### 1. Server Components First
-Core tables with cascade relationships:
+- **Default**: All components under `app/` are Server Components unless marked with `"use client"`
+- **Client boundaries**: Components in `/components` are `"use client"` by default (interactive UI)
+- API routes are in `app/api/**` with `GET/POST/PUT/PATCH/DELETE` exports
-- `calendars` → `shifts`, `shiftPresets`, `calendarNotes` (cascade delete)
-- `shiftPresets` → `shifts` (set null on delete)
-- IDs: `crypto.randomUUID()`, Timestamps: integers (auto-converted to Date)
-- Passwords: SHA-256 hashed via `lib/password-utils.ts`
+### 2. Database Layer
-### Database Migrations
+**Location**: [`lib/db/schema.ts`](lib/db/schema.ts)
+
+**Key tables**:
+
+- `user`, `session`, `account`, `verification` (Better Auth tables)
+- `calendars` - has `ownerId` (nullable), `guestPermission` (`none`/`read`/`write`)
+- `calendarShares` - many-to-many with permissions (`owner`/`admin`/`write`/`read`)
+- `shifts`, `presets`, `notes`, `externalSyncs`, `syncLogs`
+
+**Migrations**: Use Drizzle Kit commands:
```bash
-npm run db:generate # Generate migration files
-npm run db:migrate # Apply migrations
+npm run db:generate # Generate SQL from schema changes
+npm run db:migrate # Apply migrations to database
+npm run db:studio # Open Drizzle Studio GUI
```
-**Critical**: Never use `db:push` - prefer explicit migrations. Schema changes require updating `lib/db/schema.ts` AND generating migrations.
+### 3. Authentication & Permissions
-### API Routes
+**Feature flag**: Auth is **enabled by default** (`AUTH_ENABLED=true`) for better security. Can be disabled by setting `AUTH_ENABLED=false`.
-Next.js 16 pattern - dynamic params are async:
+**Configuration**: [`lib/auth.ts`](lib/auth.ts), [`lib/auth/env.ts`](lib/auth/env.ts), [`lib/public-config.ts`](lib/public-config.ts)
-```typescript
-// Dynamic routes - ALWAYS await params
-export async function PUT(
- request: Request,
- { params }: { params: Promise<{ id: string }> }
-) {
- const { id } = await params;
-}
-```
+#### Hybrid Approach: When to Use Better Auth vs. Custom Code
-### Password Protection
+**✅ Use Better Auth for:**
-Two-tier system via `passwordHash` and `isLocked`:
+- **Authentication**: Login, logout, session management, token handling
+- **OAuth**: Google, GitHub, Discord, custom OIDC integration
+- **Admin Operations**: `auth.api.banUser()`, `auth.api.setUserPassword()`, `auth.api.removeUser()`
+- **Access Control Config**: Role registration (`lib/auth/access-control.ts`) - only for Better Auth internal use
-- **Write-Only** (`isLocked=false`): Password for mutations only
-- **Full Lock** (`isLocked=true`): Password for all operations
+**✅ Use Custom Code for:**
-**Key Implementation**:
+- **Permission Checks**: All `canEditUser()`, `canDeleteUser()`, `canBanUser()` functions in `lib/auth/admin.ts`
+- **Calendar Permissions**: `owner > admin > write > read` hierarchy in `lib/auth/permissions.ts`
+- **Admin UI Logic**: User management, filtering, sorting (direct DB queries)
+- **Audit Logging**: App-specific event tracking in `lib/audit-log.ts`
-```typescript
-// GET - check isLocked flag
-if (calendar.passwordHash && calendar.isLocked) {
- // Require password
-}
+**Why**: Better Auth handles auth operations (with automatic session revocation, BCrypt hashing, etc.), while custom code provides synchronous, simple permission checks without async overhead. See [`MIGRATION_PLAN.md`](MIGRATION_PLAN.md) for full details.
-// POST/PUT/DELETE - always check passwordHash
-if (calendar.passwordHash) {
- // Require password
-}
+#### Calendar Permission Hierarchy
+
+**Permission hierarchy** (highest to lowest):
+
+1. `owner` - Created the calendar, full control
+2. `admin` - Can manage shares and settings
+3. `write` - Can edit shifts/notes/presets
+4. `read` - View only
+
+**Critical functions** in [`lib/auth/permissions.ts`](lib/auth/permissions.ts):
+
+- `getUserCalendarPermission(userId, calendarId)` - Returns permission level or `null`
+- `checkPermission(userId, calendarId, required)` - Boolean check with hierarchy
+- `getUserAccessibleCalendars(userId)` - Returns all calendars user can access
+- `canViewCalendar(userId, calendarId)` - Shorthand for read permission check
+
+**Guest access**: When auth is enabled, unauthenticated users (`userId = null`) can access calendars with `guestPermission != "none"`. Use `allowGuestAccess()` to check if feature is enabled.
+
+#### Session Management
+
+**Session utilities** in [`lib/auth/sessions.ts`](lib/auth/sessions.ts):
+
+```typescript
+import {
+ getSessionUser,
+ getUserSessions,
+ revokeAllSessions,
+} from "@/lib/auth/sessions";
+
+// Get current user from request (API routes)
+const user = await getSessionUser(request.headers);
+
+// Session management (API routes only - for bulk operations)
+const sessions = await getUserSessions(userId, currentSessionId);
+await revokeAllSessions(userId, exceptCurrentId); // Bulk revoke all except current
```
-**Client-Side Flow**:
+**Client-side session management**: Use Better Auth's built-in client functions:
-- Use `lib/password-cache.ts`: `getCachedPassword()`, `verifyAndCachePassword()`, `setCachedPassword()`, `removeCachedPassword()`
-- All data hooks auto-include cached passwords in requests
-- Locked calendars show integrated unlock form - no page reload needed
-- Hooks return empty arrays on 401 (graceful degradation)
+```typescript
+import { authClient } from "@/lib/auth/client";
-### State Management & Custom Hooks
+// List all active sessions for current user
+const sessions = await authClient.listSessions();
-**CRITICAL: ALWAYS use existing custom hooks instead of implementing custom logic.**
+// Revoke all other sessions (except current)
+await authClient.revokeOtherSessions();
+```
-#### Available Custom Hooks
+**Session management hook** in [`hooks/useSessions.ts`](hooks/useSessions.ts):
-**Data Management** (CRUD operations):
+```typescript
+const { sessions, isLoading, revokeAllSessions } = useSessions();
-- `useCalendars()` - Calendar CRUD with auto-password caching
-- `useShifts()` - Shift CRUD with optimistic updates
-- `usePresets()` - Preset fetching with silent refresh
-- `usePresetManagement()` - Preset CRUD operations
-- `useNotes()` - Note CRUD with password protection
-- `useShiftStats()` - Aggregated shift statistics
-- `useCompareCalendars()` - Multi-calendar data for compare mode
+// Revoke all other sessions
+await revokeAllSessions(); // Uses authClient.revokeOtherSessions() internally
+```
-**Action Hooks** (Complex operations):
+**Note**: Individual session revocation is not supported to prevent users from accidentally revoking their own active session. Only "revoke all other sessions" is available.
-- `useShiftActions()` - Shift operations with password handling & optimistic UI
-- `useNoteActions()` - Note dialog state & submission flow
+**UI permission checks**: Use `useCalendarPermission(calendarId)` hook:
-**Password Management**:
+```typescript
+const { canEdit, canDelete, canShare, permission } =
+ useCalendarPermission(calendarId);
+```
-- `usePasswordManagement()` - Central password state & verification
-- `usePasswordProtection()` - Per-component password utilities
+### 4. Public Configuration (Environment Variables)
-**UI/Form Hooks**:
+**NO MORE `NEXT_PUBLIC_` prefixes!** Server-only variables are exposed to the client safely via SSR injection.
-- `useDirtyState()` - Unsaved changes tracking (ALWAYS use for forms/sheets)
-- `useShiftForm()` - Shift form state & preset application
-- `useDialogStates()` - Centralized dialog visibility state
-- `useViewSettings()` - View preferences with localStorage
+**Architecture**:
-**External Sync & SSE**:
+- **Server-side**: [`lib/public-config.ts`](lib/public-config.ts) - `getPublicConfig()` function defines what's exposed
+- **Client-side**: [`hooks/usePublicConfig.ts`](hooks/usePublicConfig.ts) - `usePublicConfig()` hook for React components
+- **SSR Injection**: Config injected as `window.__PUBLIC_CONFIG__` in root layout (zero latency)
-- `useExternalSync()` - iCal/webcal subscription management
-- `useSSEConnection()` - Real-time updates via Server-Sent Events
+**Usage patterns**:
-#### Hook Usage Rules
+```typescript
+// Server Components (direct access)
+import { getPublicConfig } from "@/lib/public-config";
+const config = getPublicConfig();
+if (config.auth.enabled) {
+ /* ... */
+}
-**DO:**
+// Client Components (use hook)
+import { usePublicConfig } from "@/hooks/usePublicConfig";
+const { auth, oauth, oidc } = usePublicConfig();
+if (auth.enabled) {
+ /* ... */
+}
-- ✅ ALWAYS use existing hooks for CRUD (never custom `fetch()` logic)
-- ✅ Use `getCachedPassword()` / `verifyAndCachePassword()` for password handling
-- ✅ Use `useDirtyState` for all forms/sheets with input
-- ✅ Pass `onPasswordRequired` callbacks to hooks that support it
+// Auth-specific helper hook
+import { useAuthFeatures } from "@/hooks/useAuthFeatures";
+const { isAuthEnabled, allowRegistration, allowGuest, providers } =
+ useAuthFeatures();
+```
-**DON'T:**
+**Environment variables** (no duplicates needed):
-- ❌ NEVER implement custom `fetch()` calls for shifts/presets/notes/calendars
-- ❌ NEVER manually manage password state - use password hooks
-- ❌ NEVER implement custom dirty state tracking
+```bash
+# Auth config (automatically exposed to client)
+AUTH_ENABLED=true
+BETTER_AUTH_URL=http://localhost:3000
+ALLOW_USER_REGISTRATION=true
+ALLOW_GUEST_ACCESS=false
+```
-**See `app/page.tsx` for complete hook integration pattern.**
+**Key functions**:
-### Internationalization
+- `getPublicConfig()` - Server: Returns config object with all public values
+- `usePublicConfig()` - Client: Hook to access config in React components
+- `useAuthFeatures()` - Client: Convenience hook for auth-related flags
+- Feature flags in [`lib/auth/feature-flags.ts`](lib/auth/feature-flags.ts) are SERVER-ONLY now
-next-intl setup: `messages/{de,en,it}.json` - cookie-based with browser detection fallback
+### 5. Real-Time Updates (SSE)
-**Usage**:
+**Event stream**: [`app/api/events/stream/route.ts`](app/api/events/stream/route.ts) - Server-Sent Events endpoint
+
+**Event emitter**: [`lib/event-emitter.ts`](lib/event-emitter.ts) - Singleton pattern with HMR support
+
+**Emit events after mutations**:
```typescript
-const t = useTranslations();
-t("shift.create"); // Feature-specific keys
-t("common.created", { item: t("shift.shift_one") }); // Parametrized
+import { eventEmitter } from "@/lib/event-emitter";
+
+// After creating/updating/deleting
+eventEmitter.emit("calendar-change", {
+ type: "shift" | "preset" | "note" | "calendar" | "sync-log",
+ action: "create" | "update" | "delete" | "reorder",
+ calendarId: string,
+ data: unknown,
+});
```
-**Key Structure** (centralized to avoid duplicates):
+**Client connection**: Use `useSSEConnection` hook in [`hooks/useSSEConnection.ts`](hooks/useSSEConnection.ts) - automatically reconnects, handles visibility changes, and triggers data refreshes.
+
+### 6. Component Architecture
-- `common.*` - CRUD operations with `{item}` parameter (`created`, `updated`, `deleted`, `createError`, `updateError`, `deleteError`)
-- `validation.*` - All validation messages (`passwordMatch`, `passwordIncorrect`, `urlInvalid`, etc.)
-- `form.*` - Reusable form labels (`nameLabel`, `colorLabel`, `passwordLabel`, `notesLabel`, `urlLabel`)
-- Feature namespaces - Specific keys (`shift.startTime`, `calendar.select`, etc.)
+**Sheet pattern** (side panel): All forms use [`components/ui/base-sheet.tsx`](components/ui/base-sheet.tsx):
-**Rules**:
+- Unsaved changes confirmation via `useDirtyState` hook
+- Consistent header/footer styling with gradient backgrounds
+- Example: [`components/shift-sheet.tsx`](components/shift-sheet.tsx)
-- ALWAYS add new keys to all three language files (de.json, en.json, it.json)
-- German: ALWAYS use informal "du" form (never "Sie")
-- Check `common.*`, `validation.*`, `form.*` before creating new keys
+**Dialog pattern**: Use [`components/ui/dialog.tsx`](components/ui/dialog.tsx) from shadcn/ui
-### Component Design Patterns
+- List views, confirmations, and read-only displays
+- Example: [`components/shifts-overview-dialog.tsx`](components/shifts-overview-dialog.tsx)
-#### Sheets
+**Custom hooks pattern**:
-**Use `BaseSheet` for simple forms** (create, edit, settings):
+- Data fetching: `useShifts`, `usePresets`, `useNotes`, `useCalendars` (in `/hooks`)
+- Actions: `useShiftActions`, `useNoteActions` (handle CRUD + optimistic updates)
+- Forms: `useShiftForm`, `usePresetManagement` (form state + validation)
+
+### 7. Internationalization
+
+**Config**: [`lib/i18n.ts`](lib/i18n.ts) - Detects locale from cookie (`NEXT_LOCALE`) or `Accept-Language` header
+
+**Usage**:
```typescript
-<BaseSheet
- open={open}
- onOpenChange={onOpenChange}
- title={t("sheet.title")}
- showSaveButton
- onSave={handleSave}
- isSaving={isSaving}
- saveDisabled={!isValid || !isDirty}
- hasUnsavedChanges={isDirty}
- maxWidth="md" // sm|md|lg|xl
->
- {/* Form content */}
-</BaseSheet>
-```
+import { useTranslations } from "next-intl";
-**Custom sheets only for**: Multi-step wizards, complex layouts, custom footer actions
+const t = useTranslations();
+t("shift.title"); // Returns translated string
+t("common.createError", { item: t("shift.title") }); // With interpolation
+```
-**Styling**: Gradient headers (`from-primary/10 via-primary/5`), border opacity (`border-border/50`), consistent padding (`px-6 py-6`), sticky footer
+**Message files**: [`messages/en.json`](messages/en.json), `de.json`, `it.json` - Nested JSON structure
-**ALWAYS use `useDirtyState` hook** for unsaved changes tracking - see `preset-manage-sheet.tsx` for reference.
+### 8. External Calendar Sync
-#### Other Patterns
+**iCal parsing**: Uses `ical.js` library to parse `.ics` feeds
-- **Dialogs**: Read-only info or confirmations only (no forms)
-- **Confirmation**: Use `ConfirmationDialog` component (NEVER native `confirm()`)
-- **Colors**: Use `ColorPicker` component (`components/ui/color-picker.tsx`) for all color selections - supports preset colors + custom picker
-- **Color Format**: `PRESET_COLORS` array, hex format, 20% opacity for backgrounds
-- **Dates**: `formatDateToLocal()` for YYYY-MM-DD
+**Sync flow**:
-### UI/UX Design Principles
+1. User adds external sync URL + calendar mapping
+2. Manual/auto sync triggers [`app/api/external-syncs/[id]/sync/route.ts`](app/api/external-syncs/[id]/sync/route.ts)
+3. Shifts created with `syncedFromExternal: true`, `externalSyncId` set
+4. Sync logs stored in `syncLogs` table for error tracking
-#### Live Updates via SSE
+**Read-only enforcement**: Synced shifts cannot be edited/deleted by users. Check `shift.syncedFromExternal` before allowing mutations.
-All components must support real-time updates via Server-Sent Events:
+## Development Workflow
-- Listen to relevant SSE events (shift, preset, note, sync-log updates)
-- Use silent refresh patterns: `fetchData(false)` to update without loading states
-- Implement refresh triggers: counter-based props (e.g., `syncLogRefreshTrigger`)
-- Avoid flashing/blinking during updates - update data smoothly without UI disruption
+### Environment Setup
-#### Sheet Design Standards
+**Required files**:
-- **Simple Sheets**: Use `BaseSheet` component (handles styling, dirty state, buttons)
-- **Complex Sheets**: Follow custom pattern (see Component Design Patterns section)
-- **Key Requirements**:
- - Gradient backgrounds for visual depth
- - Consistent padding (`px-6`, `py-6`, `py-4`)
- - Border styling with reduced opacity (`border-border/50`)
- - Sticky footer with always-visible Save button
- - Full-height layout: `flex flex-col` with `flex-1 overflow-y-auto`
- - Gradient text for titles (`bg-gradient-to-r from-foreground to-foreground/70`)
+- `.env` - Copy from `.env.example` and configure
+- `sqlite.db` - Auto-created on first run
-### Calendar Interactions
+**Critical env vars**:
-- **Left-click**: Toggle shift with selected preset
-- **Right-click**: Open note dialog (prevent default context menu)
-- **Toggle logic**: Delete if exists, create if not
-- **Indicators**: `<StickyNote>` icon for days with notes
+- `DATABASE_URL` - Default: `file:./sqlite.db`
+- `AUTH_ENABLED` - Enable/disable auth system (default: `true`)
+- `BETTER_AUTH_SECRET` - Required if auth enabled (generate with `npx @better-auth/cli secret`)
+- `BETTER_AUTH_URL` - Auth callback URL (e.g., `http://localhost:3000`)
-## Docker & Production
+**Note**: No `NEXT_PUBLIC_` prefixes needed - client values are automatically exposed via [`lib/public-config.ts`](lib/public-config.ts)
-### Local Development
+### Running the App
```bash
-npm install
-npm run db:migrate # One-time setup
-npm run dev # http://localhost:3000
+npm install # Install dependencies
+npm run dev # Start dev server (localhost:3000)
+npm run build # Production build
+npm run lint # ESLint check
+npm run test # Run lint + build (CI check)
```
### Docker Deployment
```bash
-cp docker-compose.override.yml.example docker-compose.override.yml
-docker-compose up -d --build
-docker compose exec bettershift npm run db:migrate
+docker-compose up -d --build # Build and start container
```
-**Note**: Dockerfile uses `next/standalone` output. `drizzle.config.ts` must be in runner stage for migrations.
+Pre-built images: `ghcr.io/pantelx/bettershift:latest` (stable), `:dev` (bleeding edge)
-## Common Gotchas
+### Database Changes
-1. **Next.js 16**: Dynamic route params are async - always `await params`
-2. **SQLite Timestamps**: Use `{ mode: "timestamp" }`, stored as integers, auto-converted to Date
-3. **Cascade Deletes**: Deleting calendar removes all shifts/presets/notes
-4. **Sheets vs Dialogs**: Use BaseSheet for simple forms, custom sheets for complex layouts, Dialogs only for read-only info
-5. **Color Format**: Store hex (`#3b82f6`), use 20% opacity for backgrounds (`${color}20`)
-6. **Mobile UI**: Separate calendar selector with `showMobileCalendarDialog`
+1. Modify [`lib/db/schema.ts`](lib/db/schema.ts)
+2. Generate migration: `npm run db:generate`
+3. Review SQL in `drizzle/` folder
+4. Apply migration: `npm run db:migrate`
-## Adding New Features
+## Common Patterns
-### New Database Table
+### API Route Structure
-1. Add table definition to `lib/db/schema.ts` with relationships
-2. Export types: `export type TableName = typeof tableName.$inferSelect;`
-3. Run `npm run db:generate && npm run db:migrate`
-4. Create API routes: `app/api/tablename/route.ts` and `app/api/tablename/[id]/route.ts`
-5. Add translations to all language files (`messages/{de,en,it}.json`)
-6. Create custom hook in `hooks/` for CRUD operations (follow existing patterns)
+```typescript
+import { NextRequest, NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { checkPermission } from "@/lib/auth/permissions";
+import { eventEmitter } from "@/lib/event-emitter";
+
+export async function POST(request: NextRequest) {
+ const user = await getSessionUser(request.headers);
+ const { calendarId, ...data } = await request.json();
+
+ // Check permissions
+ const canEdit = await checkPermission(user?.id, calendarId, "write");
+ if (!canEdit) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
+ }
+
+ // Perform database operation
+ const [result] = await db
+ .insert(table)
+ .values({ ...data, calendarId })
+ .returning();
+
+ // Emit SSE event
+ eventEmitter.emit("calendar-change", {
+ type: "shift",
+ action: "create",
+ calendarId,
+ data: result,
+ });
+
+ return NextResponse.json(result, { status: 201 });
+}
+```
-## Development Workflow
+### Optimistic Updates
-**Local Setup**:
+See [`hooks/useShifts.ts`](hooks/useShifts.ts) `createShift` function:
-```bash
-npm install
-npm run db:migrate # One-time setup
-npm run dev # http://localhost:3000
-```
+1. Generate temp ID: `temp-${Date.now()}`
+2. Add optimistic item to state immediately
+3. Make API call
+4. On error: Remove temp item, show toast
+5. On success: Replace temp item with real data from API
-**Docker**:
+### Date Handling
-```bash
-cp docker-compose.override.yml.example docker-compose.override.yml
-docker-compose up -d --build
-docker compose exec bettershift npm run db:migrate
-```
+**Always use local dates** (no timezone conversions):
+
+- Store dates as `YYYY-MM-DD` strings in SQLite
+- Use `formatDateToLocal(date)` from [`lib/date-utils.ts`](lib/date-utils.ts) before saving
+- Display with `date-fns` + locale from `getDateLocale(locale)`
+
+## Migration Context
+
+**Status**: Auth system migration is **in progress**. See [`MIGRATION_PLAN.md`](MIGRATION_PLAN.md) for full details.
+
+**Backward compatibility**: All features work without auth enabled. Auth can be disabled by setting `AUTH_ENABLED=false`. When auth is off, all users have `owner` permission to all calendars.
-**Debugging**:
+## Key Files Reference
-- Database GUI: `npm run db:studio`
-- Build check: `npm run build`
-- All API errors logged via `console.error()`
+- [`app/page.tsx`](app/page.tsx) - Main calendar view (1300+ lines, complex state management)
+- [`lib/db/schema.ts`](lib/db/schema.ts) - Complete database schema (Better Auth + app tables)
+- [`lib/auth/permissions.ts`](lib/auth/permissions.ts) - Permission checks and calendar access logic
+- [`lib/auth/sessions.ts`](lib/auth/sessions.ts) - Session management & current user utilities (request context + Better Auth integration)
+- [`hooks/useSessions.ts`](hooks/useSessions.ts) - Client-side session management hook (uses Better Auth client)
+- [`lib/public-config.ts`](lib/public-config.ts) - Server-side public config definition (no NEXT*PUBLIC*\*)
+- [`hooks/usePublicConfig.ts`](hooks/usePublicConfig.ts) - Client-side config access hook
+- [`hooks/useAuthFeatures.ts`](hooks/useAuthFeatures.ts) - Auth-specific feature flags hook
+- [`components/calendar-grid.tsx`](components/calendar-grid.tsx) - Core calendar rendering with shift display
+- [`hooks/useSSEConnection.ts`](hooks/useSSEConnection.ts) - Real-time sync connection management
+- [`MIGRATION_PLAN.md`](MIGRATION_PLAN.md) - Detailed auth migration plan with phases and todos
-## Code Style
+## Important Notes
-- **Language**: English for all code, comments, variable names
-- **Comments**: Only for complex/non-obvious logic
-- **Code clarity**: Self-documenting names over comments
+- **No NEXT*PUBLIC***: Use `getPublicConfig()` on server, `usePublicConfig()` hook on client - never `process.env.NEXT_PUBLIC_*`
+- **Better Auth first**: Always check [Better Auth docs](https://www.better-auth.com/docs) before implementing auth features - use built-in methods, don't reinvent
+- **SSE is required**: All mutations must emit events to keep clients in sync
+- **Permission checks everywhere**: Check permissions in both API routes (server) and UI (client) for security + UX
+- **Strict TypeScript**: No `any` types, use Drizzle-inferred types from schema
+- **Translations required**: All user-facing strings must use `t()` function
+- **Guest mode**: When auth enabled, respect `guestPermission` on calendars for unauthenticated access
diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml
index 24f3153..2d705b6 100644
--- a/.github/workflows/pr-checks.yml
+++ b/.github/workflows/pr-checks.yml
@@ -28,6 +28,9 @@ jobs:
- name: Build Test (includes TypeScript check)
run: npm run build
+ - name: i18n Check
+ run: npm run i18n
+
- name: Database Migration Test
run: |
npm run db:generate
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 7033f16..ccc71af 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -32,6 +32,9 @@ jobs:
- name: Build Test (includes TypeScript check)
run: npm run build
+ - name: i18n Check
+ run: npm run i18n
+
- name: Database Migration Test
run: |
npm run db:generate
diff --git a/.gitignore b/.gitignore
index 3c88dc8..a9fe888 100644
--- a/.gitignore
+++ b/.gitignore
@@ -69,11 +69,14 @@ Thumbs.db
# version info (generated at build time)
public/version.json
+# Avatar uploads
+public/uploads/avatars/*
+
# PWA files (auto-generated by next-pwa)
public/sw.js
public/sw.js.map
public/workbox-*.js
public/workbox-*.js.map
-# scripts (local testing scripts)
-test-changelog.sh
\ No newline at end of file
+# Local scripts
+.LOCAL
\ No newline at end of file
diff --git a/Dockerfile b/Dockerfile
index 8080ae9..fc6693f 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,18 +1,25 @@
# Dockerfile for BetterShift Production
-# Stage 1: Builder
+# Stage 1: Dependencies
+FROM node:20-alpine AS deps
+RUN apk add --no-cache libc6-compat
+WORKDIR /app
+
+# Copy only package files for better caching
+COPY package.json package-lock.json ./
+RUN --mount=type=cache,target=/root/.npm-deps \
+ npm ci --cache /root/.npm-deps
+
+# Stage 2: Builder
FROM node:20-alpine AS builder
-RUN apk add --no-cache libc6-compat python3 make g++
+RUN apk add --no-cache libc6-compat
WORKDIR /app
-# Build argument for version (set during docker build)
+# Build argument for version
ARG VERSION=dev
-# Copy package files and install ALL dependencies
-# These layers are cached unless package files change
-COPY package.json package-lock.json ./
-RUN --mount=type=cache,target=/root/.npm \
- npm ci
+# Copy dependencies from deps stage
+COPY --from=deps /app/node_modules ./node_modules
# Copy source code
COPY . .
@@ -21,20 +28,37 @@ COPY . .
ENV NEXT_TELEMETRY_DISABLED=1
ENV NODE_ENV=production
-# Build the application
-RUN npm run build
+# Build the application with cache mount
+RUN --mount=type=cache,target=/app/.next/cache \
+ npm run build
-# Stage 2: Runner
-FROM node:20-alpine AS runner
+# Stage 3: Production dependencies
+FROM node:20-alpine AS prod-deps
RUN apk add --no-cache libc6-compat
WORKDIR /app
+# Copy package files
+COPY package.json package-lock.json ./
+
+# Install only production dependencies
+RUN --mount=type=cache,target=/root/.npm-prod \
+ npm ci --omit=dev --cache /root/.npm-prod && \
+ npm cache clean --force
+
+# Stage 4: Runner
+FROM node:20-alpine AS runner
+RUN apk add --no-cache libc6-compat dumb-init
+WORKDIR /app
+
# Get VERSION from builder stage
ARG VERSION=dev
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
+# Create data directory
+RUN mkdir -p /app/data
+
# Copy necessary files from builder
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
@@ -44,22 +68,21 @@ COPY --from=builder /app/lib ./lib
COPY --from=builder /app/package.json ./package.json
COPY --from=builder /app/drizzle.config.ts ./drizzle.config.ts
-# Install only production dependencies (including drizzle-kit now)
-COPY --from=builder /app/package-lock.json ./package-lock.json
-RUN --mount=type=cache,target=/root/.npm \
- npm ci --only=production
+# Copy production dependencies
+COPY --from=prod-deps /app/node_modules ./node_modules
-# Write VERSION to file for runtime access
+# Write VERSION to file
RUN echo "$VERSION" > /app/.version
-# Create data directory for SQLite database
-RUN mkdir -p /app/data
-
# Expose port
EXPOSE 3000
-ENV PORT=3000
-ENV HOSTNAME="0.0.0.0"
+# Health check
+HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
+ CMD node -e "require('http').get('http://localhost:3000', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})"
+
+# Use dumb-init to handle signals properly
+ENTRYPOINT ["/usr/bin/dumb-init", "--"]
-# Start the application
-CMD ["node", "server.js"]
\ No newline at end of file
+# Start with migration, then server
+CMD ["sh", "-c", "npm run db:migrate && node server.js"]
\ No newline at end of file
diff --git a/README.md b/README.md
index b3e136a..b39259a 100644
--- a/README.md
+++ b/README.md
@@ -1,271 +1,180 @@
<div align="center">
- <img src="public/android/android-launchericon-512-512.png" alt="BetterShift Logo" width="300" height="300" />
-</div>
+ <img src="public/android/android-launchericon-512-512.png" alt="BetterShift Logo" width="140" height="140" />
+
+ # BetterShift
-<h1 align="center" id="title">BetterShift</h1>
-<div align="center">
+**Modern shift management for variable work schedules**
-![BetterShift](https://img.shields.io/badge/BetterShift-Shift%20Management-blue?style=for-the-badge)
-![Version](https://img.shields.io/github/v/release/pantelx/bettershift?style=for-the-badge&label=Version)
-![Checks](https://img.shields.io/github/check-runs/pantelx/bettershift/main?style=for-the-badge&label=Checks)
+![Version](https://img.shields.io/github/v/release/pantelx/bettershift?style=flat-square&label=version)
+![Build](https://img.shields.io/github/check-runs/pantelx/bettershift/main?style=flat-square&label=build)
+![License](https://img.shields.io/github/license/pantelx/bettershift?style=flat-square)
-[![Discord](https://img.shields.io/badge/Discord-Join%20our%20Community-7289DA?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/Ma4SnagqwE)
-[![Buy Me A Coffee](https://img.shields.io/badge/Support-Buy%20Me%20A%20Coffee-orange?style=for-the-badge)](https://buymeacoffee.com/pantel)
-[![GitHub Sponsors](https://img.shields.io/badge/Sponsor-GitHub-ea4aaa?style=for-the-badge&logo=github&logoColor=white)](https://github.com/sponsors/pantelx)
+[Demo](https://bettershift.pantelx.com) · [Documentation](#documentation) · [Quick Start](#quick-start) · [Discord](https://discord.gg/Ma4SnagqwE)
</div>
-> **Note**
->
-> BetterShift is a modern shift management application designed to simplify variable work schedules. Manage unlimited calendars with one-click shift toggles, reusable presets, and real-time synchronization across devices. Features include external calendar integration (Google, Outlook, iCal), password-protected calendars, ICS/PDF export, live statistics, calendar comparison and multi-language support. Built with Next.js 16 and SQLite for fast, self-hosted deployment.
-
-## 🔗 Quick Links
-
-**Demo:** [bettershift.pantelx.com](https://bettershift.pantelx.com)
-
-**Discord Server:** [Join our Discord for community discussions and support](https://discord.gg/Ma4SnagqwE)
-
-**Self-Hosting:** [Check out the Deployment Guide](#%EF%B8%8F-deployment-guide)
-
-**Support the Project:** [Buy Me A Coffee](https://www.buymeacoffee.com/pantel) or [Become a GitHub Sponsor](https://github.com/sponsors/pantelx)
-
---
-## ✨ Key Features
-
-### 📅 Calendar & Shift Management
-
-- **Multiple Calendars** — Unlimited calendars with custom names and colors
-- **Interactive Month View** — Clean, week-based calendar layout with one-click shift toggles
-- **Quick Actions** — Left-click to add/remove shifts, right-click to add notes or events
-- **External Calendar Sync** — Subscribe to Google, Outlook or iCal calendars with auto/manual refresh
-- **Sync Monitoring** — Real-time sync status and error notifications
-- **Calendar Comparison** — Overlay multiple calendars for easy shift comparison
-
-### 🎨 Customization & Organization
-
-- **Shift Presets** — Reusable templates with custom labels, times, and colors
-- **Visual Organization** — Color-code calendars and shifts for instant recognition
-- **Auto-Save Templates** — Automatically save shift configurations for future use
-- **Export Options** — Download as ICS or PDF with flexible time range filters
-
-### 🔒 Security & Privacy
-
-- **Password Protection** — SHA-256 encrypted calendar passwords
-- **Per-Calendar Access** — Different security levels for each calendar
-
-### 📊 Analytics & Live Updates
+BetterShift is a self-hosted shift management application for teams and individuals with variable work schedules. Create unlimited calendars, toggle shifts with a single click, and share them with your team via user accounts, links, or public access. Sync external calendars from Google, Outlook, or iCal, export to ICS/PDF, and manage everything through an admin panel with role-based permissions and audit logging.
-- **Real-Time Statistics** — Instant shift tracking and hour calculations with visual charts
-- **Server-Sent Events** — Changes sync instantly across all open browser tabs
+## Features
-### 🌍 Multi-Language & Themes
-
-- **Built-in Translations** — Full German, English, and Italian support
-- **Dark/Light Theme** — Toggle themes with system preference detection
-- **Responsive Design** — Optimized for desktop and mobile devices
-
-### 🔔 Modern Stack & Updates
-
-- **Auto Update Checks** — Detects new releases with visual notifications
-- **Integrated Changelog** — View release notes directly in the app
-- **PWA Support** — Installable as a Progressive Web App
-- **Next.js 16 + React 19** — Latest App Router architecture
-- **SQLite + Drizzle ORM** — Type-safe database with file-based storage
-- **Docker Ready** — Two-command deployment with Docker Compose
+| Feature | Description |
+| ------------------ | --------------------------------------------------------------- |
+| **Calendars** | Unlimited calendars with custom colors and names |
+| **Presets** | Reusable shift templates with labels, times, and colors |
+| **External Sync** | Subscribe to Google Calendar, Outlook, or iCal feeds |
+| **Sharing** | Share via user accounts, guest access, or shareable links |
+| **Authentication** | Email/password, OAuth (Google, GitHub, Discord), or custom OIDC |
+| **Admin Panel** | User management, calendar administration, audit logging |
+| **Statistics** | Real-time shift tracking with visual charts |
+| **Export** | Download calendars as ICS or PDF |
+| **Localization** | English, German, Italian |
+| **PWA** | Installable on mobile and desktop |
---
-## 🛠️ Deployment Guide
-
-### 🐳 Docker Deployment
-
-Deploy using Docker for easy containerized hosting:
-
-**Option 1: Using pre-built images from GitHub Container Registry**
-
-Available image tags:
+## Quick Start
-- `:latest` - Latest stable release (recommended for production)
-- `:v1.0.0` - Specific version (use for pinned deployments)
-- `:dev` - Latest development build from main branch (bleeding edge, may be unstable)
-- `:pr-123` - Pull request builds (for testing PRs before merge)
+### Docker
```bash
-# Pull the latest stable release (recommended)
-$ docker pull ghcr.io/pantelx/bettershift:latest
-
-# Or pull the latest development build
-$ docker pull ghcr.io/pantelx/bettershift:dev
-
-# Or pull a specific version
-$ docker pull ghcr.io/pantelx/bettershift:v1.0.0
-
-# Run the container
-$ docker run -d \
+docker run -d \
-p 3000:3000 \
-v ./data:/app/data \
+ -e BETTER_AUTH_SECRET=$(openssl rand -base64 32) \
+ -e BETTER_AUTH_URL=http://localhost:3000 \
--name bettershift \
ghcr.io/pantelx/bettershift:latest
-
-# Apply database migrations
-$ docker exec bettershift npm run db:migrate
```
-**Option 2: Build locally with docker-compose**
-
-```bash
-# Clone the repository
-$ git clone https://github.com/pantelx/bettershift.git && cd bettershift
-
-# Copy the example environment file
-$ cp .env.example .env
+Open http://localhost:3000. The first registered user becomes superadmin.
-# Adjust .env settings as needed
-
-# Build and start the container
-$ docker-compose up -d --build
-
-# Apply database migrations
-$ docker compose exec bettershift npm run db:migrate
-
-# Access the application at http://localhost:3000 (or your configured port)
-```
-
-### 🏗️ Production Build
+### Docker Compose
```bash
-# Build the application
-$ npm run build
-
-# Start production server
-$ npm start
+git clone https://github.com/pantelx/bettershift.git
+cd bettershift
+cp .env.example .env
+# Edit .env and set BETTER_AUTH_SECRET
+docker-compose up -d
```
-### 💻 Local Development
+### From Source
```bash
-# Clone the repository
-$ git clone https://github.com/pantelx/bettershift.git && cd bettershift
-
-# Install dependencies
-$ npm install
-
-# Copy the example environment file
-$ cp .env.example .env
-
-# Adjust .env settings as needed
-
-# Set up the database
-$ npm run db:migrate
-
-# Start the development server
-$ npm run dev
-
-# Open your browser at http://localhost:3000
+git clone https://github.com/pantelx/bettershift.git
+cd bettershift
+npm install
+cp .env.example .env
+npm run db:migrate
+npm run dev
```
---
-## 📦 Versioning & Releases
-
-### Available Docker Tags
-
-**Stable Releases**:
+## Documentation
-- `ghcr.io/pantelx/bettershift:latest` - Always points to the latest stable release
-- `ghcr.io/pantelx/bettershift:v1.0.1` - Specific version (immutable)
-- `ghcr.io/pantelx/bettershift:v1.0` - Latest patch of minor version
-- `ghcr.io/pantelx/bettershift:v1` - Latest minor of major version
+| Document | Description |
+| ------------------------------------------------ | ----------------------------------------- |
+| [Authentication Setup](docs/AUTH_SETUP.md) | Email/password, OAuth, OIDC configuration |
+| [Admin Panel](docs/ADMIN_PANEL.md) | User management, calendar administration |
+| [Permissions](docs/PERMISSIONS.md) | Sharing, access tokens, guest access |
+| [Migration Guide](docs/MIGRATION_AUTH_TOGGLE.md) | Enable auth on existing instances |
-**Development Builds**:
+---
-- `ghcr.io/pantelx/bettershift:dev` - Latest development build from main branch (unstable)
+## Configuration
----
+### Required
-## 🗄️ Database Management
+```bash
+AUTH_ENABLED=true
+BETTER_AUTH_SECRET= # npx @better-auth/cli secret
+BETTER_AUTH_URL=http://localhost:3000
+```
-### Available Commands
+### Optional: OAuth Providers
```bash
-# Generate new migrations after schema changes
-$ npm run db:generate
+GOOGLE_CLIENT_ID=
+GOOGLE_CLIENT_SECRET=
-# Apply migrations to the database
-$ npm run db:migrate
+GITHUB_CLIENT_ID=
+GITHUB_CLIENT_SECRET=
-# Open Drizzle Studio (database GUI)
-$ npm run db:studio
+DISCORD_CLIENT_ID=
+DISCORD_CLIENT_SECRET=
```
-> **Note**
->
-> Never run `npm run db:push` in production. Always use migrations (`db:generate` + `db:migrate`) for safe schema changes.
+### Optional: Custom OIDC
----
+```bash
+CUSTOM_OIDC_ENABLED=true
+CUSTOM_OIDC_NAME=Company SSO
+CUSTOM_OIDC_CLIENT_ID=
+CUSTOM_OIDC_CLIENT_SECRET=
+CUSTOM_OIDC_ISSUER=https://sso.example.com/.well-known/openid-configuration
+```
-## 🧪 Testing & Quality Assurance
+See [.env.example](.env.example) for all options.
-### Local Testing
+---
-Run these commands before submitting a pull request:
+## Database Commands
```bash
-# Run all tests (lint + build with TypeScript check)
-$ npm test
+npm run db:migrate # Apply migrations
+npm run db:generate # Generate migrations after schema changes
+npm run db:studio # Open Drizzle Studio GUI
+```
-# Full CI test suite (includes database migration test)
-$ npm run test:ci
+---
-# Run individual checks
-$ npm run lint # ESLint code quality check
-$ npm run build # Next.js production build (includes TypeScript validation)
+## Docker Images
-```
+Images are available at `ghcr.io/pantelx/bettershift`:
-**Recommended Pre-Commit Workflow:**
-
-1. Run `npm test` to catch issues early
-2. Fix any TypeScript or linting errors
-3. Ensure build completes successfully
-4. Commit and push your changes
+| Tag | Description |
+| -------- | ---------------------------- |
+| `latest` | Latest stable release |
+| `vX.Y.Z` | Specific version |
+| `dev` | Development build (unstable) |
---
-## 💖 Support the Project
-
-Your support helps maintain and improve this project! Please consider:
+## Tech Stack
-- [Buy me a coffee](https://www.buymeacoffee.com/pantel)
-- [Become a GitHub Sponsor](https://github.com/sponsors/pantelx)
-- Join our Discord community for support and updates
-- Contribute on GitHub
+| Layer | Technology |
+| --------- | --------------------------------- |
+| Framework | Next.js 16, React 19, TypeScript |
+| Database | SQLite, Drizzle ORM |
+| Auth | Better Auth |
+| UI | Tailwind CSS, shadcn/ui, Radix UI |
+| i18n | next-intl |
---
-## 🤝 Contributing
+## Contributing
-Contributions are welcome! Please feel free to submit a Pull Request.
+Contributions are welcome. Please follow these steps:
1. Fork the repository
-2. Create your feature branch (`git checkout -b feature/amazing-feature`)
-3. Commit your changes (`git commit -m 'Add some amazing feature'`)
-4. Push to the branch (`git push origin feature/amazing-feature`)
-5. Open a Pull Request
+2. Create a feature branch
+3. Run `npm test` before committing
+4. Submit a pull request
---
-## 🙏 Credits
-
-Special thanks to:
+## Support
-- All contributors who have contributed through code, testing, and ideas
-- The community for their feedback, support, and patience
-- Project supporters who have financially supported this initiative
+- [Discord](https://discord.gg/Ma4SnagqwE) - Community and support
+- [GitHub Issues](https://github.com/pantelx/bettershift/issues) - Bug reports and feature requests
+- [Buy Me a Coffee](https://www.buymeacoffee.com/pantel) - Support development
+- [GitHub Sponsors](https://github.com/sponsors/pantelx) - Become a sponsor
---
-## 📄 License
+## License
-MIT
+MIT License. See [LICENSE](LICENSE) for details.
diff --git a/app/admin/calendars/page.tsx b/app/admin/calendars/page.tsx
new file mode 100644
index 0000000..364629e
--- /dev/null
+++ b/app/admin/calendars/page.tsx
@@ -0,0 +1,433 @@
+"use client";
+
+import { useState, useEffect } from "react";
+import { useTranslations } from "next-intl";
+import {
+ Search,
+ Filter,
+ AlertCircle,
+ Send,
+ Trash2,
+ X,
+ RefreshCw,
+} from "lucide-react";
+import { Input } from "@/components/ui/input";
+import { Button } from "@/components/ui/button";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { FullscreenLoader } from "@/components/fullscreen-loader";
+import { CalendarTable } from "@/components/admin/calendar-table";
+import { CalendarDetailsSheet } from "@/components/admin/calendar-details-sheet";
+import { CalendarEditSheet } from "@/components/admin/calendar-edit-sheet";
+import { CalendarTransferSheet } from "@/components/admin/calendar-transfer-sheet";
+import { CalendarDeleteDialog } from "@/components/admin/calendar-delete-dialog";
+import { CalendarBulkDeleteDialog } from "@/components/admin/calendar-bulk-delete-dialog";
+import {
+ useAdminCalendars,
+ type AdminCalendar,
+ type CalendarFilters,
+ type CalendarSort,
+} from "@/hooks/useAdminCalendars";
+import { useAdminLevel } from "@/hooks/useAdminAccess";
+
+export default function AdminCalendarsPage() {
+ const t = useTranslations();
+ const { fetchCalendars, deleteCalendar, bulkDeleteCalendars, isLoading } =
+ useAdminCalendars();
+ const adminLevel = useAdminLevel();
+ const isSuperAdmin = adminLevel === "superadmin";
+
+ // State
+ const [calendars, setCalendars] = useState<AdminCalendar[]>([]);
+ const [orphanedCount, setOrphanedCount] = useState(0);
+
+ // Filters & Sort
+ const [searchQuery, setSearchQuery] = useState("");
+ const [statusFilter, setStatusFilter] = useState<
+ "all" | "orphaned" | "with-owner"
+ >("all");
+ const sortField = "createdAt" as const;
+ const sortDirection = "desc" as const;
+
+ // Selection
+ const [selectedIds, setSelectedIds] = useState<string[]>([]);
+
+ // Dialogs & Sheets
+ const [selectedCalendar, setSelectedCalendar] =
+ useState<AdminCalendar | null>(null);
+ const [showDetailsSheet, setShowDetailsSheet] = useState(false);
+ const [showEditSheet, setShowEditSheet] = useState(false);
+ const [showTransferSheet, setShowTransferSheet] = useState(false);
+ const [showDeleteDialog, setShowDeleteDialog] = useState(false);
+ const [showBulkDeleteDialog, setShowBulkDeleteDialog] = useState(false);
+
+ // Bulk operations
+ const [showBulkTransferSheet, setShowBulkTransferSheet] = useState(false);
+ const [calendarsForBulkTransfer, setCalendarsForBulkTransfer] = useState<
+ AdminCalendar[]
+ >([]);
+
+ // Load calendars
+ const loadCalendars = async () => {
+ const filters: CalendarFilters = {
+ search: searchQuery || undefined,
+ status: statusFilter,
+ };
+
+ const sort: CalendarSort = {
+ field: sortField,
+ direction: sortDirection,
+ };
+
+ const result = await fetchCalendars(filters, sort);
+
+ if (result) {
+ setCalendars(result.calendars);
+ setOrphanedCount(result.orphanedCount);
+ }
+ };
+
+ // Initial load
+ useEffect(() => {
+ const filters: CalendarFilters = {
+ search: searchQuery || undefined,
+ status: statusFilter,
+ };
+
+ const sort: CalendarSort = {
+ field: sortField,
+ direction: sortDirection,
+ };
+
+ const loadData = async () => {
+ const result = await fetchCalendars(filters, sort);
+
+ if (result) {
+ setCalendars(result.calendars);
+ setOrphanedCount(result.orphanedCount);
+ }
+ };
+
+ loadData();
+ }, [searchQuery, statusFilter, sortField, sortDirection, fetchCalendars]);
+
+ // Selection handlers
+ const handleToggleSelect = (calendarId: string) => {
+ setSelectedIds((prev) =>
+ prev.includes(calendarId)
+ ? prev.filter((id) => id !== calendarId)
+ : [...prev, calendarId]
+ );
+ };
+
+ const handleToggleSelectAll = () => {
+ if (selectedIds.length === calendars.length) {
+ setSelectedIds([]);
+ } else {
+ setSelectedIds(calendars.map((cal) => cal.id));
+ }
+ };
+
+ const handleClearSelection = () => {
+ setSelectedIds([]);
+ };
+
+ // Handlers
+ const handleCalendarClick = (calendar: AdminCalendar) => {
+ setSelectedCalendar(calendar);
+ setShowDetailsSheet(true);
+ };
+
+ const handleEditCalendar = (calendar: AdminCalendar) => {
+ setSelectedCalendar(calendar);
+ setShowEditSheet(true);
+ };
+
+ const handleTransferCalendar = (calendar: AdminCalendar) => {
+ setSelectedCalendar(calendar);
+ setShowTransferSheet(true);
+ };
+
+ const handleDeleteCalendar = (calendar: AdminCalendar) => {
+ setSelectedCalendar(calendar);
+ setShowDeleteDialog(true);
+ };
+
+ const handleBulkTransfer = () => {
+ const selectedCalendars = calendars.filter((cal) =>
+ selectedIds.includes(cal.id)
+ );
+ setCalendarsForBulkTransfer(selectedCalendars);
+ setShowBulkTransferSheet(true);
+ };
+
+ const handleBulkDelete = () => {
+ if (selectedIds.length === 0) return;
+ setShowBulkDeleteDialog(true);
+ };
+
+ const handleBulkDeleteConfirm = async () => {
+ if (selectedIds.length === 0) return;
+
+ const success = await bulkDeleteCalendars(selectedIds);
+ if (success) {
+ setSelectedIds([]);
+ await loadCalendars();
+ }
+ };
+
+ const handleDeleteConfirm = async () => {
+ if (!selectedCalendar) return;
+ const success = await deleteCalendar(selectedCalendar.id);
+ if (success) {
+ setShowDeleteDialog(false);
+ setSelectedCalendar(null);
+ await loadCalendars();
+ }
+ };
+
+ const handleSuccess = async () => {
+ setShowEditSheet(false);
+ setShowTransferSheet(false);
+ setShowBulkTransferSheet(false);
+ setSelectedCalendar(null);
+ setCalendarsForBulkTransfer([]);
+ setSelectedIds([]);
+ await loadCalendars();
+ };
+
+ const handleEditFromDetails = () => {
+ setShowDetailsSheet(false);
+ setShowEditSheet(true);
+ };
+
+ const handleTransferFromDetails = () => {
+ setShowDetailsSheet(false);
+ setShowTransferSheet(true);
+ };
+
+ const handleDeleteFromDetails = () => {
+ setShowDetailsSheet(false);
+ setShowDeleteDialog(true);
+ };
+
+ const isAllSelected =
+ calendars.length > 0 && selectedIds.length === calendars.length;
+ const hasOrphanedCalendars = orphanedCount > 0;
+ const showOrphanedBanner =
+ hasOrphanedCalendars && statusFilter !== "with-owner";
+
+ if (isLoading && calendars.length === 0) {
+ return <FullscreenLoader />;
+ }
+
+ return (
+ <>
+ <div className="space-y-6">
+ {/* Header */}
+ <div className="flex items-center justify-between">
+ <div>
+ <h2 className="text-3xl font-bold tracking-tight">
+ {t("admin.calendars.title")}
+ </h2>
+ <p className="text-muted-foreground mt-2">
+ {t("admin.calendars.description")}
+ </p>
+ </div>
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={() => loadCalendars()}
+ disabled={isLoading}
+ >
+ <RefreshCw className={isLoading ? "animate-spin" : ""} />
+ </Button>
+ </div>
+
+ {/* Orphaned Calendars Warning Banner */}
+ {showOrphanedBanner && (
+ <div className="flex items-start gap-3 p-4 rounded-lg bg-red-50 dark:bg-red-950/20 border border-red-200 dark:border-red-900">
+ <AlertCircle className="h-5 w-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5" />
+ <div className="flex-1">
+ <p className="text-sm font-medium text-red-800 dark:text-red-200">
+ {t("admin.calendars.orphanedWarning", { count: orphanedCount })}
+ </p>
+ <p className="text-xs text-red-700 dark:text-red-300 mt-1">
+ {t("admin.calendars.orphanedWarningDescription")}
+ </p>
+ </div>
+ </div>
+ )}
+
+ {/* Filters */}
+ <div className="flex flex-col sm:flex-row gap-4">
+ <div className="relative flex-1">
+ <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
+ <Input
+ type="text"
+ placeholder={t("admin.calendars.searchPlaceholder")}
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ className="pl-10"
+ />
+ </div>
+ <Select
+ value={statusFilter}
+ onValueChange={(value: "all" | "orphaned" | "with-owner") =>
+ setStatusFilter(value)
+ }
+ >
+ <SelectTrigger className="w-full sm:w-[200px]">
+ <div className="flex items-center gap-2">
+ <Filter className="h-4 w-4" />
+ <SelectValue />
+ </div>
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">
+ {t("admin.calendars.allStatuses")}
+ </SelectItem>
+ <SelectItem value="orphaned">
+ {t("admin.calendars.orphanedOnly")}
+ </SelectItem>
+ <SelectItem value="with-owner">
+ {t("admin.calendars.withOwner")}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
+ {/* Results Count */}
+ <div className="flex items-center justify-between text-sm text-muted-foreground">
+ <p>
+ {t("admin.calendars.calendarsCount", { count: calendars.length })}
+ </p>
+ </div>
+
+ {/* Bulk Actions Toolbar */}
+ {selectedIds.length > 0 && (
+ <div className="flex items-center justify-between p-4 rounded-lg border bg-muted/50">
+ <div className="flex items-center gap-3">
+ <span className="text-sm font-medium">
+ {t("admin.calendars.selectedCount", {
+ count: selectedIds.length,
+ })}
+ </span>
+ </div>
+ <div className="flex items-center gap-2">
+ <Button variant="outline" size="sm" onClick={handleBulkTransfer}>
+ <Send className="h-4 w-4 mr-2" />
+ {t("admin.calendars.transferSelected")}
+ </Button>
+ {isSuperAdmin && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handleBulkDelete}
+ className="text-destructive hover:text-destructive"
+ >
+ <Trash2 className="h-4 w-4 mr-2" />
+ {t("common.deleteSelected")}
+ </Button>
+ )}
+ <Button variant="ghost" size="sm" onClick={handleClearSelection}>
+ <X className="h-4 w-4 mr-2" />
+ {t("admin.calendars.clearSelection")}
+ </Button>
+ </div>
+ </div>
+ )}
+
+ {/* Calendar Table */}
+ {calendars.length === 0 ? (
+ <div className="text-center py-12 border border-dashed rounded-lg">
+ <p className="text-muted-foreground">
+ {searchQuery
+ ? t("admin.calendars.noSearchResults")
+ : t("admin.calendars.noCalendarsFound")}
+ </p>
+ </div>
+ ) : (
+ <CalendarTable
+ calendars={calendars}
+ selectedIds={selectedIds}
+ onToggleSelect={handleToggleSelect}
+ onToggleSelectAll={handleToggleSelectAll}
+ isAllSelected={isAllSelected}
+ onCalendarClick={handleCalendarClick}
+ onEditCalendar={handleEditCalendar}
+ onTransferCalendar={handleTransferCalendar}
+ onDeleteCalendar={handleDeleteCalendar}
+ />
+ )}
+
+ {/* Calendar Details Sheet */}
+ {selectedCalendar && (
+ <CalendarDetailsSheet
+ open={showDetailsSheet}
+ onOpenChange={setShowDetailsSheet}
+ calendarId={selectedCalendar.id}
+ onEdit={handleEditFromDetails}
+ onTransfer={handleTransferFromDetails}
+ onDelete={handleDeleteFromDetails}
+ />
+ )}
+
+ {/* Calendar Edit Sheet */}
+ {selectedCalendar && (
+ <CalendarEditSheet
+ open={showEditSheet}
+ onOpenChange={setShowEditSheet}
+ calendar={selectedCalendar}
+ onSuccess={handleSuccess}
+ />
+ )}
+
+ {/* Calendar Transfer Sheet (Single) */}
+ {selectedCalendar && (
+ <CalendarTransferSheet
+ open={showTransferSheet}
+ onOpenChange={setShowTransferSheet}
+ calendars={[selectedCalendar]}
+ onSuccess={handleSuccess}
+ />
+ )}
+
+ {/* Calendar Transfer Sheet (Bulk) */}
+ {calendarsForBulkTransfer.length > 0 && (
+ <CalendarTransferSheet
+ open={showBulkTransferSheet}
+ onOpenChange={setShowBulkTransferSheet}
+ calendars={calendarsForBulkTransfer}
+ onSuccess={handleSuccess}
+ />
+ )}
+
+ {/* Calendar Delete Dialog */}
+ {selectedCalendar && (
+ <CalendarDeleteDialog
+ open={showDeleteDialog}
+ onOpenChange={setShowDeleteDialog}
+ calendar={selectedCalendar}
+ onConfirm={handleDeleteConfirm}
+ />
+ )}
+
+ {/* Calendar Bulk Delete Dialog */}
+ {selectedIds.length > 0 && (
+ <CalendarBulkDeleteDialog
+ open={showBulkDeleteDialog}
+ onOpenChange={setShowBulkDeleteDialog}
+ calendars={calendars.filter((cal) => selectedIds.includes(cal.id))}
+ onConfirm={handleBulkDeleteConfirm}
+ />
+ )}
+ </div>
+ </>
+ );
+}
diff --git a/app/admin/layout.tsx b/app/admin/layout.tsx
new file mode 100644
index 0000000..3c090f3
--- /dev/null
+++ b/app/admin/layout.tsx
@@ -0,0 +1,83 @@
+"use client";
+
+import { useState, useEffect } from "react";
+import { AdminSidebar } from "@/components/admin/admin-sidebar";
+import { AdminHeader } from "@/components/admin/admin-header";
+import { useRequireAdmin } from "@/hooks/useAdminAccess";
+import { FullscreenLoader } from "@/components/fullscreen-loader";
+import { useAuth } from "@/hooks/useAuth";
+
+/**
+ * Admin Panel Layout
+ *
+ * Features:
+ * - Custom layout wrapper for all admin pages
+ * - Includes AdminSidebar (collapsible) and AdminHeader (breadcrumbs)
+ * - Access control: Redirects non-admins to home page
+ * - Responsive design with sidebar + main content area
+ */
+export default function AdminLayout({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ const { isLoading } = useAuth();
+ const [sidebarWidth, setSidebarWidth] = useState(280);
+ const [isMobileSidebarOpen, setIsMobileSidebarOpen] = useState(false);
+
+ // Require admin access (redirects non-admins)
+ useRequireAdmin("/");
+
+ // Listen for sidebar width changes
+ useEffect(() => {
+ const handleResize = () => {
+ // Mobile: 0px (hidden), Desktop: Check if collapsed (80px) or expanded (280px)
+ if (window.innerWidth < 1024) {
+ setSidebarWidth(0);
+ } else {
+ setSidebarWidth(280); // Default to expanded on desktop
+ }
+ };
+
+ handleResize(); // Initial check
+ window.addEventListener("resize", handleResize);
+ return () => window.removeEventListener("resize", handleResize);
+ }, []);
+
+ // Show loader while checking auth
+ if (isLoading) {
+ return <FullscreenLoader />;
+ }
+
+ return (
+ <div className="flex h-screen overflow-hidden">
+ {/* Sidebar Navigation */}
+ <AdminSidebar
+ onWidthChange={setSidebarWidth}
+ isMobileOpen={isMobileSidebarOpen}
+ onMobileClose={() => setIsMobileSidebarOpen(false)}
+ />
+
+ {/* Main Content Area */}
+ <div
+ className="flex-1 flex flex-col overflow-hidden transition-all duration-300"
+ style={{
+ marginLeft:
+ typeof window !== "undefined" && window.innerWidth >= 1024
+ ? `${sidebarWidth}px`
+ : "0",
+ }}
+ >
+ {/* Header */}
+ <AdminHeader onMenuClick={() => setIsMobileSidebarOpen(true)} />
+
+ {/* Page Content */}
+ <main className="flex-1 overflow-y-auto">
+ <div className="container max-w-7xl mx-auto p-4 sm:p-6">
+ {children}
+ </div>
+ </main>
+ </div>
+ </div>
+ );
+}
diff --git a/app/admin/logs/page.tsx b/app/admin/logs/page.tsx
new file mode 100644
index 0000000..cde728a
--- /dev/null
+++ b/app/admin/logs/page.tsx
@@ -0,0 +1,709 @@
+"use client";
+
+import React, { useState, useEffect, useMemo, useTransition } from "react";
+import { useTranslations, useLocale } from "next-intl";
+import { useAuditLogs, type AuditLog } from "@/hooks/useAuditLogs";
+import { FullscreenLoader } from "@/components/fullscreen-loader";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Checkbox } from "@/components/ui/checkbox";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Badge } from "@/components/ui/badge";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { AuditLogDetailsDialog } from "@/components/admin/audit-log-details-dialog";
+import { AuditLogDeleteDialog } from "@/components/admin/audit-log-delete-dialog";
+import {
+ ChevronLeft,
+ ChevronRight,
+ RefreshCw,
+ Trash2,
+ Search,
+ ChevronDown,
+ ChevronUp,
+ Filter,
+ X,
+} from "lucide-react";
+import { format } from "date-fns";
+import { getDateLocale } from "@/lib/locales";
+import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
+import { useIsSuperAdmin } from "@/hooks/useAdminAccess";
+
+/**
+ * Admin Audit Logs Page
+ *
+ * Features:
+ * - View all audit logs (admin + superadmin)
+ * - Advanced filters (action, severity, user, date range)
+ * - Sortable columns
+ * - Expandable rows for metadata
+ * - Pagination (50 per page)
+ * - Delete old logs (superadmin only)
+ * - Responsive design
+ */
+export default function AdminAuditLogsPage() {
+ const t = useTranslations();
+ const locale = useLocale();
+ const dateLocale = getDateLocale(locale);
+ const { fetchAuditLogs, isLoading } = useAuditLogs();
+ const isSuperAdmin = useIsSuperAdmin();
+
+ // Data State
+ const [logs, setLogs] = useState<AuditLog[]>([]);
+ const [total, setTotal] = useState(0);
+ const [page, setPage] = useState(0);
+ const limit = 25;
+
+ // Filter State
+ const [actionFilter, setActionFilter] = useState<string>("all");
+ const [severityFilter, setSeverityFilter] = useState<string>("all");
+ const [searchQuery, setSearchQuery] = useState("");
+ const [debouncedSearch, setDebouncedSearch] = useState("");
+ const [startDate, setStartDate] = useState("");
+ const [endDate, setEndDate] = useState("");
+
+ // UI State
+ const [isPending, startTransition] = useTransition();
+ const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set());
+ const [selectedLogIds, setSelectedLogIds] = useState<string[]>([]);
+ const [sortColumn, setSortColumn] = useState<
+ "timestamp" | "action" | "severity" | "user" | "ipAddress" | null
+ >("timestamp");
+ const [sortDirection, setSortDirection] = useState<"asc" | "desc">("desc");
+ const [selectedLog, setSelectedLog] = useState<AuditLog | null>(null);
+ const [showDetailsDialog, setShowDetailsDialog] = useState(false);
+ const [showDeleteDialog, setShowDeleteDialog] = useState(false);
+
+ // Memoized helper functions for badge colors
+ const getSeverityColor = useMemo(
+ () => (severity: string) => {
+ switch (severity) {
+ case "info":
+ return "bg-blue-500/10 text-blue-500 border-blue-500/20";
+ case "warning":
+ return "bg-yellow-500/10 text-yellow-500 border-yellow-500/20";
+ case "error":
+ return "bg-orange-500/10 text-orange-500 border-orange-500/20";
+ case "critical":
+ return "bg-red-500/10 text-red-500 border-red-500/20";
+ default:
+ return "bg-gray-500/10 text-gray-500 border-gray-500/20";
+ }
+ },
+ []
+ );
+
+ const getActionColor = useMemo(
+ () => (action: string) => {
+ if (action.startsWith("admin.")) {
+ return "bg-red-500/10 text-red-500 border-red-500/20";
+ }
+ if (action.startsWith("calendar.")) {
+ return "bg-blue-500/10 text-blue-500 border-blue-500/20";
+ }
+ if (action.startsWith("auth.")) {
+ return "bg-green-500/10 text-green-500 border-green-500/20";
+ }
+ if (action.startsWith("security.")) {
+ return "bg-orange-500/10 text-orange-500 border-orange-500/20";
+ }
+ return "bg-gray-500/10 text-gray-500 border-gray-500/20";
+ },
+ []
+ );
+
+ const getUserInitials = useMemo(
+ () => (name: string | null) => {
+ if (!name) return "?";
+ return name
+ .split(" ")
+ .map((n) => n[0])
+ .join("")
+ .toUpperCase()
+ .slice(0, 2);
+ },
+ []
+ );
+
+ // Debounce search query
+ useEffect(() => {
+ const timer = setTimeout(() => {
+ setDebouncedSearch(searchQuery);
+ }, 500);
+
+ return () => clearTimeout(timer);
+ }, [searchQuery]);
+
+ // Load logs
+ const loadLogs = async () => {
+ startTransition(async () => {
+ const filters = {
+ action: actionFilter !== "all" ? actionFilter : undefined,
+ severity:
+ severityFilter !== "all"
+ ? (severityFilter as "info" | "warning" | "error" | "critical")
+ : undefined,
+ search: debouncedSearch || undefined,
+ startDate: startDate || undefined,
+ endDate: endDate || undefined,
+ };
+
+ // Backend now supports all sort columns including user and ipAddress
+ const sort = {
+ sortBy: sortColumn || "timestamp",
+ sortOrder: sortDirection,
+ };
+
+ const result = await fetchAuditLogs(filters, sort, {
+ limit,
+ offset: page * limit,
+ });
+
+ if (result) {
+ setLogs(result.logs);
+ setTotal(result.pagination.total);
+ }
+ });
+ };
+
+ // Initial load and reload on filter/page/sort change
+ useEffect(() => {
+ loadLogs();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [
+ page,
+ actionFilter,
+ severityFilter,
+ debouncedSearch,
+ startDate,
+ endDate,
+ sortColumn,
+ sortDirection,
+ ]);
+
+ // Toggle row expansion
+ const toggleRow = (logId: string) => {
+ setExpandedRows((prev) => {
+ const newSet = new Set(prev);
+ if (newSet.has(logId)) {
+ newSet.delete(logId);
+ } else {
+ newSet.add(logId);
+ }
+ return newSet;
+ });
+ };
+
+ // Handle sort column click - now triggers backend sort
+ const handleSort = (
+ column: "timestamp" | "action" | "severity" | "user" | "ipAddress"
+ ) => {
+ if (sortColumn === column) {
+ setSortDirection((prev) => (prev === "asc" ? "desc" : "asc"));
+ } else {
+ setSortColumn(column);
+ setSortDirection("desc");
+ }
+ };
+
+ // Handle pagination
+ const goToNextPage = () => {
+ if (page * limit + logs.length < total) {
+ setPage((prev) => prev + 1);
+ }
+ };
+
+ const goToPreviousPage = () => {
+ if (page > 0) {
+ setPage((prev) => prev - 1);
+ }
+ };
+
+ // Clear filters
+ const clearFilters = () => {
+ setActionFilter("all");
+ setSeverityFilter("all");
+ setSearchQuery("");
+ setStartDate("");
+ setEndDate("");
+ setPage(0);
+ };
+
+ // Checkbox selection handlers
+ const toggleLogSelection = (logId: string) => {
+ setSelectedLogIds((prev) =>
+ prev.includes(logId)
+ ? prev.filter((id) => id !== logId)
+ : [...prev, logId]
+ );
+ };
+
+ const toggleSelectAll = () => {
+ if (selectedLogIds.length === logs.length) {
+ setSelectedLogIds([]);
+ } else {
+ setSelectedLogIds(logs.map((log) => log.id));
+ }
+ };
+
+ const clearSelection = () => {
+ setSelectedLogIds([]);
+ };
+
+ const isAllSelected =
+ logs.length > 0 && selectedLogIds.length === logs.length;
+
+ if (isLoading && !isPending) {
+ return <FullscreenLoader />;
+ }
+
+ return (
+ <div className="space-y-6">
+ {/* Header */}
+ <div className="flex items-center justify-between">
+ <div>
+ <h2 className="text-3xl font-bold tracking-tight">
+ {t("admin.auditLogs")}
+ </h2>
+ <p className="text-muted-foreground mt-2">
+ {t("admin.auditLogsDescription")}
+ </p>
+ </div>
+ <div className="flex items-center gap-2">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={loadLogs}
+ disabled={isLoading}
+ >
+ <RefreshCw
+ className={isLoading ? "animate-spin h-4 w-4" : "h-4 w-4"}
+ />
+ </Button>
+ {isSuperAdmin && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setShowDeleteDialog(true)}
+ >
+ <Trash2 className="h-4 w-4" />
+ <span className="hidden sm:inline ml-2">
+ {t("admin.deleteOldLogs")}
+ </span>
+ </Button>
+ )}
+ </div>
+ </div>
+
+ {/* Filters */}
+ <div className="flex flex-col gap-4">
+ <div className="flex flex-col sm:flex-row gap-4">
+ {/* Search */}
+ <div className="relative flex-1">
+ <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
+ <Input
+ placeholder={t("admin.searchLogs")}
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ className="pl-10"
+ />
+ </div>
+
+ {/* Action Type Filter */}
+ <Select value={actionFilter} onValueChange={setActionFilter}>
+ <SelectTrigger className="w-full sm:w-[200px]">
+ <Filter className="h-4 w-4 mr-2" />
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">{t("admin.allActions")}</SelectItem>
+ <SelectItem value="admin.">{t("admin.adminActions")}</SelectItem>
+ <SelectItem value="calendar.">
+ {t("admin.calendarActions")}
+ </SelectItem>
+ <SelectItem value="auth.">{t("admin.authActions")}</SelectItem>
+ <SelectItem value="security.">
+ {t("admin.securityActions")}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+
+ {/* Severity Filter */}
+ <Select value={severityFilter} onValueChange={setSeverityFilter}>
+ <SelectTrigger className="w-full sm:w-[180px]">
+ <Filter className="h-4 w-4 mr-2" />
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">
+ {t("common.filters.allSeverities")}
+ </SelectItem>
+ <SelectItem value="info">{t("common.severity.info")}</SelectItem>
+ <SelectItem value="warning">
+ {t("common.severity.warning")}
+ </SelectItem>
+ <SelectItem value="error">
+ {t("common.severity.error")}
+ </SelectItem>
+ <SelectItem value="critical">
+ {t("common.severity.critical")}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
+ {/* Date Range Filters */}
+ <div className="flex flex-col sm:flex-row gap-4">
+ <div className="flex-1">
+ <label className="text-sm font-medium mb-2 block">
+ {t("common.labels.startDate")}
+ </label>
+ <Input
+ type="date"
+ value={startDate}
+ onChange={(e) => setStartDate(e.target.value)}
+ />
+ </div>
+
+ <div className="flex-1">
+ <label className="text-sm font-medium mb-2 block">
+ {t("common.labels.endDate")}
+ </label>
+ <Input
+ type="date"
+ value={endDate}
+ onChange={(e) => setEndDate(e.target.value)}
+ />
+ </div>
+
+ {/* Clear Filters Button */}
+ {(actionFilter !== "all" ||
+ severityFilter !== "all" ||
+ searchQuery ||
+ startDate ||
+ endDate) && (
+ <div className="flex items-end">
+ <Button variant="outline" onClick={clearFilters}>
+ <X className="h-4 w-4 mr-2" />
+ {t("common.filters.clearFilters")}
+ </Button>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Stats */}
+ <div className="flex items-center justify-between text-sm text-muted-foreground">
+ <p>
+ {t("admin.showingLogs", {
+ from: page * limit + 1,
+ to: Math.min(page * limit + logs.length, total),
+ total,
+ })}
+ </p>
+ </div>
+
+ {/* Bulk Actions Bar */}
+ {selectedLogIds.length > 0 && isSuperAdmin && (
+ <div className="flex items-center justify-between p-4 bg-muted rounded-lg border">
+ <div className="flex items-center gap-3">
+ <span className="text-sm font-medium">
+ {t("admin.selectedLogs", { count: selectedLogIds.length })}
+ </span>
+ <Button variant="ghost" size="sm" onClick={clearSelection}>
+ <X className="h-4 w-4 mr-2" />
+ {t("admin.clearSelection")}
+ </Button>
+ </div>
+ <Button
+ variant="destructive"
+ size="sm"
+ onClick={() => setShowDeleteDialog(true)}
+ >
+ <Trash2 className="h-4 w-4 mr-2" />
+ {t("common.deleteSelected")}
+ </Button>
+ </div>
+ )}
+
+ {/* Table */}
+ <div className="rounded-md border bg-card">
+ <div className={isPending ? "opacity-50 pointer-events-none" : ""}>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ {isSuperAdmin && (
+ <TableHead className="w-[50px]">
+ <Checkbox
+ checked={isAllSelected}
+ onCheckedChange={toggleSelectAll}
+ />
+ </TableHead>
+ )}
+ <TableHead className="w-[50px]"></TableHead>
+ <TableHead
+ className="cursor-pointer select-none"
+ onClick={() => handleSort("timestamp")}
+ >
+ <div className="flex items-center gap-2">
+ {t("admin.timestamp")}
+ {sortColumn === "timestamp" &&
+ (sortDirection === "asc" ? (
+ <ChevronUp className="h-4 w-4" />
+ ) : (
+ <ChevronDown className="h-4 w-4" />
+ ))}
+ </div>
+ </TableHead>
+ <TableHead
+ className="cursor-pointer select-none"
+ onClick={() => handleSort("action")}
+ >
+ <div className="flex items-center gap-2">
+ {t("common.labels.action")}
+ {sortColumn === "action" &&
+ (sortDirection === "asc" ? (
+ <ChevronUp className="h-4 w-4" />
+ ) : (
+ <ChevronDown className="h-4 w-4" />
+ ))}
+ </div>
+ </TableHead>
+ <TableHead
+ className="cursor-pointer select-none"
+ onClick={() => handleSort("user")}
+ >
+ <div className="flex items-center gap-2">
+ {t("common.labels.user")}
+ {sortColumn === "user" &&
+ (sortDirection === "asc" ? (
+ <ChevronUp className="h-4 w-4" />
+ ) : (
+ <ChevronDown className="h-4 w-4" />
+ ))}
+ </div>
+ </TableHead>
+ <TableHead
+ className="cursor-pointer select-none"
+ onClick={() => handleSort("severity")}
+ >
+ <div className="flex items-center gap-2">
+ {t("common.labels.severity")}
+ {sortColumn === "severity" &&
+ (sortDirection === "asc" ? (
+ <ChevronUp className="h-4 w-4" />
+ ) : (
+ <ChevronDown className="h-4 w-4" />
+ ))}
+ </div>
+ </TableHead>
+ <TableHead
+ className="cursor-pointer select-none"
+ onClick={() => handleSort("ipAddress")}
+ >
+ <div className="flex items-center gap-2">
+ {t("common.labels.ipAddress")}
+ {sortColumn === "ipAddress" &&
+ (sortDirection === "asc" ? (
+ <ChevronUp className="h-4 w-4" />
+ ) : (
+ <ChevronDown className="h-4 w-4" />
+ ))}
+ </div>
+ </TableHead>
+ <TableHead className="w-[100px]"></TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {logs.length === 0 ? (
+ <TableRow>
+ <TableCell
+ colSpan={isSuperAdmin ? 8 : 7}
+ className="text-center py-8 text-muted-foreground"
+ >
+ {isPending ? t("common.loading") : t("admin.noLogsFound")}
+ </TableCell>
+ </TableRow>
+ ) : (
+ logs.map((log) => (
+ <React.Fragment key={log.id}>
+ <TableRow
+ className="cursor-pointer hover:bg-muted/50"
+ onClick={() => toggleRow(log.id)}
+ >
+ {isSuperAdmin && (
+ <TableCell onClick={(e) => e.stopPropagation()}>
+ <Checkbox
+ checked={selectedLogIds.includes(log.id)}
+ onCheckedChange={() => toggleLogSelection(log.id)}
+ />
+ </TableCell>
+ )}
+ <TableCell>
+ {expandedRows.has(log.id) ? (
+ <ChevronDown className="h-4 w-4" />
+ ) : (
+ <ChevronRight className="h-4 w-4" />
+ )}
+ </TableCell>
+ <TableCell className="whitespace-nowrap">
+ {format(new Date(log.timestamp), "PPp", {
+ locale: dateLocale,
+ })}
+ </TableCell>
+ <TableCell>
+ <Badge
+ variant="outline"
+ className={getActionColor(log.action)}
+ >
+ {log.action}
+ </Badge>
+ </TableCell>
+ <TableCell>
+ {log.userId ? (
+ <div className="flex items-center gap-2">
+ <Avatar className="h-6 w-6">
+ {log.userImage && (
+ <AvatarImage
+ src={log.userImage}
+ alt={log.userName || ""}
+ />
+ )}
+ <AvatarFallback className="text-xs">
+ {getUserInitials(log.userName)}
+ </AvatarFallback>
+ </Avatar>
+ <span className="text-sm">
+ {log.userName ||
+ log.userEmail ||
+ t("admin.unknownUser")}
+ </span>
+ </div>
+ ) : (
+ <span className="text-sm text-muted-foreground">
+ {t("admin.systemAction")}
+ </span>
+ )}
+ </TableCell>
+ <TableCell>
+ <Badge
+ variant="outline"
+ className={getSeverityColor(log.severity)}
+ >
+ {log.severity}
+ </Badge>
+ </TableCell>
+ <TableCell className="text-sm text-muted-foreground">
+ {log.ipAddress || "—"}
+ </TableCell>
+ <TableCell>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={(e) => {
+ e.stopPropagation();
+ setSelectedLog(log);
+ setShowDetailsDialog(true);
+ }}
+ >
+ {t("common.viewDetails")}
+ </Button>
+ </TableCell>
+ </TableRow>
+ {expandedRows.has(log.id) && (
+ <TableRow>
+ <TableCell
+ colSpan={isSuperAdmin ? 8 : 7}
+ className="bg-muted/50"
+ >
+ <div className="p-4 space-y-2">
+ <div className="text-sm font-medium">
+ {t("admin.metadata")}:
+ </div>
+ <pre className="text-xs bg-background p-3 rounded border overflow-x-auto">
+ {JSON.stringify(log.metadata, null, 2)}
+ </pre>
+ {log.userAgent && (
+ <div className="text-xs text-muted-foreground">
+ <span className="font-medium">
+ {t("admin.userAgent")}:
+ </span>{" "}
+ {log.userAgent}
+ </div>
+ )}
+ </div>
+ </TableCell>
+ </TableRow>
+ )}
+ </React.Fragment>
+ ))
+ )}
+ </TableBody>
+ </Table>
+ </div>
+ </div>
+
+ {/* Pagination */}
+ {total > limit && (
+ <div className="flex items-center justify-between">
+ <div className="text-sm text-muted-foreground">
+ {t("admin.page")} {page + 1} {t("common.of")}{" "}
+ {Math.ceil(total / limit)}
+ </div>
+ <div className="flex items-center gap-2">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={goToPreviousPage}
+ disabled={page === 0}
+ >
+ <ChevronLeft className="h-4 w-4 mr-2" />
+ {t("common.previous")}
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={goToNextPage}
+ disabled={page * limit + logs.length >= total}
+ >
+ {t("common.next")}
+ <ChevronRight className="h-4 w-4 ml-2" />
+ </Button>
+ </div>
+ </div>
+ )}
+
+ {/* Dialogs */}
+ {selectedLog && (
+ <AuditLogDetailsDialog
+ open={showDetailsDialog}
+ onOpenChange={setShowDetailsDialog}
+ log={selectedLog}
+ />
+ )}
+
+ <AuditLogDeleteDialog
+ open={showDeleteDialog}
+ onOpenChange={setShowDeleteDialog}
+ selectedLogIds={selectedLogIds}
+ onSuccess={() => {
+ setPage(0);
+ clearSelection();
+ loadLogs();
+ }}
+ />
+ </div>
+ );
+}
diff --git a/app/admin/page.tsx b/app/admin/page.tsx
new file mode 100644
index 0000000..36225d2
--- /dev/null
+++ b/app/admin/page.tsx
@@ -0,0 +1,161 @@
+"use client";
+
+import { useTranslations } from "next-intl";
+import { useRouter } from "next/navigation";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { Button } from "@/components/ui/button";
+import { Separator } from "@/components/ui/separator";
+import { Badge } from "@/components/ui/badge";
+import { FullscreenLoader } from "@/components/fullscreen-loader";
+import { StatsCardsGrid } from "@/components/admin/stats-cards";
+import { useAdminStats } from "@/hooks/useAdminStats";
+import { FolderOpen, RefreshCw } from "lucide-react";
+import { formatDistanceToNow } from "date-fns";
+import { getDateLocale } from "@/lib/locales";
+import { useLocale } from "next-intl";
+
+/**
+ * Admin Dashboard Page
+ *
+ * Displays system statistics and quick actions.
+ * Implemented in Phase 9.3
+ */
+export default function AdminDashboardPage() {
+ const t = useTranslations();
+ const router = useRouter();
+ const locale = useLocale();
+ const dateLocale = getDateLocale(locale);
+
+ const { stats, isLoading, refetch } = useAdminStats();
+
+ if (isLoading && !stats) {
+ return <FullscreenLoader />;
+ }
+
+ const hasOrphanedCalendars = stats && stats.calendars.orphaned > 0;
+
+ return (
+ <div className="space-y-6">
+ {/* Welcome Message */}
+ <div className="flex items-center justify-between">
+ <div>
+ <h2 className="text-3xl font-bold tracking-tight">
+ {t("admin.dashboard")}
+ </h2>
+ <p className="text-muted-foreground mt-2">
+ {t("admin.dashboardDescription")}
+ </p>
+ </div>
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={() => refetch()}
+ disabled={isLoading}
+ >
+ <RefreshCw className={isLoading ? "animate-spin" : ""} />
+ </Button>
+ </div>
+
+ {/* Orphaned Calendars Warning */}
+ {hasOrphanedCalendars && (
+ <Card className="border-yellow-500 bg-yellow-50 dark:bg-yellow-950/20">
+ <CardHeader>
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-3">
+ <FolderOpen className="h-5 w-5 text-yellow-600 dark:text-yellow-400" />
+ <div>
+ <CardTitle className="text-yellow-900 dark:text-yellow-100">
+ {t("admin.orphanedCalendarsWarning")}
+ </CardTitle>
+ <CardDescription className="text-yellow-700 dark:text-yellow-300">
+ {t("admin.orphanedCalendarsWarningDescription", {
+ count: stats!.calendars.orphaned,
+ })}
+ </CardDescription>
+ </div>
+ </div>
+ <Button
+ variant="outline"
+ onClick={() => router.push("/admin/calendars")}
+ className="border-yellow-600 text-yellow-900 hover:bg-yellow-100 dark:text-yellow-100 dark:hover:bg-yellow-900/30"
+ >
+ {t("admin.manageOrphanedCalendars")}
+ </Button>
+ </div>
+ </CardHeader>
+ </Card>
+ )}
+
+ {/* Stats Cards */}
+ <StatsCardsGrid stats={stats} isLoading={isLoading} />
+
+ {/* Recent Activity Preview */}
+ {stats?.activity.logs && stats.activity.logs.length > 0 && (
+ <Card>
+ <CardHeader>
+ <div className="flex items-center justify-between">
+ <CardTitle>{t("admin.stats.recentActivity")}</CardTitle>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => router.push("/admin/logs")}
+ >
+ {t("common.viewAll")}
+ </Button>
+ </div>
+ <CardDescription>
+ {t("admin.recentActivityDescription")}
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="space-y-3">
+ {stats.activity.logs.map((log, index) => (
+ <div key={log.id}>
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-3">
+ <Badge
+ variant={
+ log.severity === "error"
+ ? "destructive"
+ : log.severity === "warning"
+ ? "outline"
+ : "secondary"
+ }
+ >
+ {log.severity}
+ </Badge>
+ <div className="text-sm">
+ <span className="font-medium">{log.action}</span>
+ {log.resourceType && (
+ <span className="text-muted-foreground">
+ {" "}
+ • {log.resourceType}
+ </span>
+ )}
+ </div>
+ </div>
+ <span className="text-xs text-muted-foreground">
+ {formatDistanceToNow(log.timestamp, {
+ addSuffix: true,
+ locale: dateLocale,
+ })}
+ </span>
+ </div>
+ {index < stats.activity.logs.length - 1 && (
+ <Separator className="mt-3" />
+ )}
+ </div>
+ ))}
+ </div>
+ </CardContent>
+ </Card>
+ )}
+ </div>
+ );
+}
diff --git a/app/admin/users/page.tsx b/app/admin/users/page.tsx
new file mode 100644
index 0000000..ce09821
--- /dev/null
+++ b/app/admin/users/page.tsx
@@ -0,0 +1,375 @@
+"use client";
+
+import { useState, useEffect } from "react";
+import { useTranslations } from "next-intl";
+import { Search, Filter, RefreshCw } from "lucide-react";
+import { Input } from "@/components/ui/input";
+import { Button } from "@/components/ui/button";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { FullscreenLoader } from "@/components/fullscreen-loader";
+import { UserTable } from "@/components/admin/user-table";
+import { UserEditSheet } from "@/components/admin/user-edit-sheet";
+import { UserDetailsSheet } from "@/components/admin/user-details-sheet";
+import { UserBanDialog } from "@/components/admin/user-ban-dialog";
+import { UserUnbanDialog } from "@/components/admin/user-unban-dialog";
+import { UserDeleteDialog } from "@/components/admin/user-delete-dialog";
+import { UserPasswordResetDialog } from "@/components/admin/user-password-reset-dialog";
+import {
+ useAdminUsers,
+ type AdminUser,
+ type UserFilters,
+ type UserSort,
+} from "@/hooks/useAdminUsers";
+
+export default function AdminUsersPage() {
+ const t = useTranslations();
+ const {
+ fetchUsers,
+ banUser,
+ unbanUser,
+ deleteUser,
+ resetPassword,
+ isLoading,
+ } = useAdminUsers();
+
+ // State
+ const [users, setUsers] = useState<AdminUser[]>([]);
+ const [totalUsers, setTotalUsers] = useState(0);
+
+ // Filters & Sort
+ const [searchQuery, setSearchQuery] = useState("");
+ const [roleFilter, setRoleFilter] = useState<
+ "all" | "superadmin" | "admin" | "user"
+ >("all");
+ const [statusFilter, setStatusFilter] = useState<"all" | "active" | "banned">(
+ "all"
+ );
+ const sortField = "createdAt" as const;
+ const sortDirection = "desc" as const;
+
+ // Dialogs & Sheets
+ const [selectedUser, setSelectedUser] = useState<AdminUser | null>(null);
+ const [showEditSheet, setShowEditSheet] = useState(false);
+ const [showDetailsSheet, setShowDetailsSheet] = useState(false);
+ const [showBanDialog, setShowBanDialog] = useState(false);
+ const [showUnbanDialog, setShowUnbanDialog] = useState(false);
+ const [showDeleteDialog, setShowDeleteDialog] = useState(false);
+ const [showPasswordDialog, setShowPasswordDialog] = useState(false);
+
+ // Load users
+ const loadUsers = async () => {
+ const filters: UserFilters = {
+ search: searchQuery || undefined,
+ role: roleFilter,
+ status: statusFilter,
+ };
+
+ const sort: UserSort = {
+ field: sortField,
+ direction: sortDirection,
+ };
+
+ const result = await fetchUsers(filters, sort, {
+ page: 1,
+ limit: 1000,
+ });
+
+ if (result) {
+ setUsers(result.users);
+ setTotalUsers(result.total);
+ }
+ };
+
+ // Initial load
+ useEffect(() => {
+ const filters: UserFilters = {
+ search: searchQuery || undefined,
+ role: roleFilter,
+ status: statusFilter,
+ };
+
+ const sort: UserSort = {
+ field: sortField,
+ direction: sortDirection,
+ };
+
+ const loadData = async () => {
+ const result = await fetchUsers(filters, sort, {
+ page: 1,
+ limit: 1000,
+ });
+
+ if (result) {
+ setUsers(result.users);
+ setTotalUsers(result.total);
+ }
+ };
+
+ loadData();
+ }, [
+ searchQuery,
+ roleFilter,
+ statusFilter,
+ sortField,
+ sortDirection,
+ fetchUsers,
+ ]);
+
+ // Handlers
+ const handleUserClick = (user: AdminUser) => {
+ setSelectedUser(user);
+ setShowDetailsSheet(true);
+ };
+
+ const handleEditUser = (user: AdminUser) => {
+ setSelectedUser(user);
+ setShowEditSheet(true);
+ };
+
+ const handleResetPassword = (user: AdminUser) => {
+ setSelectedUser(user);
+ setShowPasswordDialog(true);
+ };
+
+ const handleBanUser = (user: AdminUser) => {
+ setSelectedUser(user);
+ setShowBanDialog(true);
+ };
+
+ const handleUnbanUser = (user: AdminUser) => {
+ setSelectedUser(user);
+ setShowUnbanDialog(true);
+ };
+
+ const handleDeleteUser = (user: AdminUser) => {
+ setSelectedUser(user);
+ setShowDeleteDialog(true);
+ };
+
+ const handleBanConfirm = async (reason: string, expiresAt?: Date) => {
+ if (!selectedUser) return;
+ const success = await banUser(selectedUser.id, reason, expiresAt);
+ if (success) {
+ loadUsers();
+ setShowBanDialog(false);
+ }
+ };
+
+ const handleUnbanConfirm = async () => {
+ if (!selectedUser) return;
+ const success = await unbanUser(selectedUser.id);
+ if (success) {
+ loadUsers();
+ setShowUnbanDialog(false);
+ }
+ };
+
+ const handleDeleteConfirm = async () => {
+ if (!selectedUser) return;
+ const success = await deleteUser(selectedUser.id);
+ if (success) {
+ loadUsers();
+ setShowDeleteDialog(false);
+ }
+ };
+
+ const handlePasswordResetConfirm = async (newPassword: string) => {
+ if (!selectedUser) return;
+ const success = await resetPassword(selectedUser.id, newPassword);
+ if (success) {
+ setShowPasswordDialog(false);
+ }
+ };
+
+ const handleRefresh = () => {
+ loadUsers();
+ };
+
+ if (isLoading && users.length === 0) {
+ return <FullscreenLoader />;
+ }
+
+ return (
+ <>
+ <div className="space-y-6">
+ {/* Header */}
+ <div className="flex items-center justify-between">
+ <div>
+ <h2 className="text-3xl font-bold tracking-tight">
+ {t("admin.userManagement")}
+ </h2>
+ <p className="text-muted-foreground mt-2">
+ {t("admin.userManagementDescription")}
+ </p>
+ </div>
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={handleRefresh}
+ disabled={isLoading}
+ >
+ <RefreshCw className={isLoading ? "animate-spin" : ""} />
+ </Button>
+ </div>
+
+ {/* Filters */}
+ <div className="flex flex-col sm:flex-row gap-4">
+ {/* Search */}
+ <div className="relative flex-1">
+ <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
+ <Input
+ placeholder={t("admin.searchUsers")}
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ className="pl-10"
+ />
+ </div>
+
+ {/* Role Filter */}
+ <Select
+ value={roleFilter}
+ onValueChange={(value: "all" | "superadmin" | "admin" | "user") =>
+ setRoleFilter(value)
+ }
+ >
+ <SelectTrigger className="w-full sm:w-[180px]">
+ <Filter className="h-4 w-4 mr-2" />
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">{t("admin.allRoles")}</SelectItem>
+ <SelectItem value="superadmin">
+ {t("common.roles.superadmin")}
+ </SelectItem>
+ <SelectItem value="admin">{t("common.roles.admin")}</SelectItem>
+ <SelectItem value="user">{t("common.roles.user")}</SelectItem>
+ </SelectContent>
+ </Select>
+
+ {/* Status Filter */}
+ <Select
+ value={statusFilter}
+ onValueChange={(value: "all" | "active" | "banned") =>
+ setStatusFilter(value)
+ }
+ >
+ <SelectTrigger className="w-full sm:w-[180px]">
+ <Filter className="h-4 w-4 mr-2" />
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">{t("admin.allStatuses")}</SelectItem>
+ <SelectItem value="active">
+ {t("common.status.active")}
+ </SelectItem>
+ <SelectItem value="banned">{t("admin.banned")}</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
+ {/* Results Count */}
+ <div className="flex items-center justify-between text-sm text-muted-foreground">
+ <p>{t("admin.usersCount", { count: totalUsers })}</p>
+ </div>
+
+ {/* Table */}
+ <UserTable
+ users={users}
+ isLoading={isLoading}
+ onUserClick={handleUserClick}
+ onEditUser={handleEditUser}
+ onResetPassword={handleResetPassword}
+ onBanUser={handleBanUser}
+ onUnbanUser={handleUnbanUser}
+ onDeleteUser={handleDeleteUser}
+ />
+ </div>
+
+ {/* Edit Sheet */}
+ {selectedUser && (
+ <UserEditSheet
+ key={selectedUser.id}
+ open={showEditSheet}
+ onOpenChange={setShowEditSheet}
+ user={selectedUser}
+ onSuccess={loadUsers}
+ />
+ )}
+
+ {/* Details Sheet */}
+ {selectedUser && (
+ <UserDetailsSheet
+ open={showDetailsSheet}
+ onOpenChange={setShowDetailsSheet}
+ userId={selectedUser.id}
+ onEdit={() => {
+ setShowDetailsSheet(false);
+ setShowEditSheet(true);
+ }}
+ onResetPassword={() => {
+ setShowDetailsSheet(false);
+ setShowPasswordDialog(true);
+ }}
+ onBan={() => {
+ setShowDetailsSheet(false);
+ setShowBanDialog(true);
+ }}
+ onUnban={() => {
+ setShowDetailsSheet(false);
+ setShowUnbanDialog(true);
+ }}
+ onDelete={() => {
+ setShowDetailsSheet(false);
+ setShowDeleteDialog(true);
+ }}
+ />
+ )}
+
+ {/* Ban Dialog */}
+ {selectedUser && (
+ <UserBanDialog
+ open={showBanDialog}
+ onOpenChange={setShowBanDialog}
+ user={selectedUser}
+ onConfirm={handleBanConfirm}
+ />
+ )}
+
+ {/* Unban Dialog */}
+ {selectedUser && (
+ <UserUnbanDialog
+ open={showUnbanDialog}
+ onOpenChange={setShowUnbanDialog}
+ user={selectedUser}
+ onConfirm={handleUnbanConfirm}
+ />
+ )}
+
+ {/* Delete Dialog */}
+ {selectedUser && (
+ <UserDeleteDialog
+ open={showDeleteDialog}
+ onOpenChange={setShowDeleteDialog}
+ user={selectedUser}
+ onConfirm={handleDeleteConfirm}
+ />
+ )}
+
+ {/* Password Reset Dialog */}
+ {selectedUser && (
+ <UserPasswordResetDialog
+ open={showPasswordDialog}
+ onOpenChange={setShowPasswordDialog}
+ user={selectedUser}
+ onConfirm={handlePasswordResetConfirm}
+ />
+ )}
+ </>
+ );
+}
diff --git a/app/api/activity-logs/route.ts b/app/api/activity-logs/route.ts
new file mode 100644
index 0000000..089b6b9
--- /dev/null
+++ b/app/api/activity-logs/route.ts
@@ -0,0 +1,232 @@
+import { NextRequest, NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import { auditLogs, syncLogs } from "@/lib/db/schema";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { getUserAccessibleCalendars } from "@/lib/auth/permissions";
+import { eq, and, desc, gte, lte, inArray, sql } from "drizzle-orm";
+
+// Unified activity log format
+interface UnifiedActivityLog {
+ id: string;
+ type: "sync" | "auth" | "calendar" | "security";
+ action: string;
+ timestamp: Date;
+ severity: string;
+ metadata: object | null;
+ resourceType?: string;
+ resourceId?: string;
+}
+
+/**
+ * GET /api/activity-logs - List user's visible activity logs (merged from auditLogs + syncLogs)
+ *
+ * Query params:
+ * - type: Filter by action type prefix (security, calendar, sync, auth)
+ * - startDate: ISO date string (inclusive)
+ * - endDate: ISO date string (inclusive)
+ * - page: Page number (0-based, default: 0)
+ * - limit: Items per page (default: 50, max: 100)
+ */
+export async function GET(request: NextRequest) {
+ const user = await getSessionUser(request.headers);
+
+ // Require authentication to view activity logs
+ if (!user) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ const { searchParams } = new URL(request.url);
+ const type = searchParams.get("type"); // e.g., "auth", "calendar", "sync", "security"
+ const startDate = searchParams.get("startDate");
+ const endDate = searchParams.get("endDate");
+ const page = parseInt(searchParams.get("page") || "0", 10);
+ const limit = Math.min(parseInt(searchParams.get("limit") || "50", 10), 100);
+ const offset = page * limit;
+
+ try {
+ // Fetch all logs and merge them before pagination
+ const allLogs: UnifiedActivityLog[] = [];
+
+ // ============================================
+ // 1. Fetch auditLogs (if not filtering by sync type only)
+ // ============================================
+ if (!type || type !== "sync") {
+ const auditConditions = [
+ eq(auditLogs.isUserVisible, true),
+ eq(auditLogs.userId, user.id),
+ ];
+
+ // Filter by action type prefix (but exclude sync if type is specified)
+ if (type && type !== "sync") {
+ auditConditions.push(sql`${auditLogs.action} LIKE ${type + ".%"}`);
+ }
+
+ // Filter by date range
+ if (startDate) {
+ const start = new Date(startDate);
+ auditConditions.push(gte(auditLogs.timestamp, start));
+ }
+
+ if (endDate) {
+ const end = new Date(endDate);
+ auditConditions.push(lte(auditLogs.timestamp, end));
+ }
+
+ const auditLogsData = await db
+ .select()
+ .from(auditLogs)
+ .where(and(...auditConditions))
+ .orderBy(desc(auditLogs.timestamp));
+
+ // Convert auditLogs to unified format
+ for (const log of auditLogsData) {
+ const actionParts = log.action.split(".");
+ const logType =
+ actionParts[0] === "auth"
+ ? "auth"
+ : actionParts[0] === "security"
+ ? "security"
+ : "calendar";
+
+ allLogs.push({
+ id: log.id,
+ type: logType as "auth" | "security" | "calendar",
+ action: log.action,
+ timestamp: log.timestamp,
+ severity: log.severity,
+ metadata: log.metadata ? JSON.parse(log.metadata) : null,
+ resourceType: log.resourceType ?? undefined,
+ resourceId: log.resourceId ?? undefined,
+ });
+ }
+ }
+
+ // ============================================
+ // 2. Fetch syncLogs (if not filtering by non-sync types)
+ // ============================================
+ if (!type || type === "sync") {
+ // Get all calendars user has access to
+ const accessibleCalendars = await getUserAccessibleCalendars(user.id);
+ const calendarIds = accessibleCalendars.map((cal) => cal.id);
+
+ if (calendarIds.length > 0) {
+ const syncConditions = [inArray(syncLogs.calendarId, calendarIds)];
+
+ // Filter by date range
+ if (startDate) {
+ const start = new Date(startDate);
+ syncConditions.push(gte(syncLogs.syncedAt, start));
+ }
+
+ if (endDate) {
+ const end = new Date(endDate);
+ syncConditions.push(lte(syncLogs.syncedAt, end));
+ }
+
+ const syncLogsData = await db
+ .select()
+ .from(syncLogs)
+ .where(and(...syncConditions))
+ .orderBy(desc(syncLogs.syncedAt));
+
+ // Convert syncLogs to unified format
+ for (const log of syncLogsData) {
+ const action =
+ log.status === "success"
+ ? "sync.executed.success"
+ : "sync.executed.failed";
+
+ allLogs.push({
+ id: log.id,
+ type: "sync",
+ action,
+ timestamp: log.syncedAt,
+ severity: log.status === "success" ? "info" : "warning",
+ metadata: {
+ externalSyncId: log.externalSyncId,
+ externalSyncName: log.externalSyncName,
+ shiftsCreated: log.shiftsCreated,
+ shiftsUpdated: log.shiftsUpdated,
+ shiftsDeleted: log.shiftsDeleted,
+ syncType: log.syncType,
+ errorMessage: log.errorMessage ?? undefined,
+ },
+ resourceType: "sync",
+ resourceId: log.externalSyncId,
+ });
+ }
+ }
+ }
+
+ // ============================================
+ // 3. Sort merged logs by timestamp (descending)
+ // ============================================
+ allLogs.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());
+
+ // ============================================
+ // 4. Apply pagination to merged results
+ // ============================================
+ const paginatedLogs = allLogs.slice(offset, offset + limit);
+ const total = allLogs.length;
+
+ return NextResponse.json({
+ logs: paginatedLogs,
+ total,
+ page,
+ limit,
+ hasMore: offset + paginatedLogs.length < total,
+ });
+ } catch (error) {
+ console.error("Error fetching activity logs:", error);
+ return NextResponse.json(
+ { error: "Failed to fetch activity logs" },
+ { status: 500 }
+ );
+ }
+}
+
+/**
+ * DELETE /api/activity-logs - Clear user's activity logs
+ *
+ * Only deletes logs where:
+ * - userId = currentUser
+ * - isUserVisible = true
+ * Cannot delete admin/system logs.
+ */
+export async function DELETE(request: NextRequest) {
+ const user = await getSessionUser(request.headers);
+
+ if (!user) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ try {
+ // Delete user-visible audit logs
+ await db
+ .delete(auditLogs)
+ .where(
+ and(eq(auditLogs.userId, user.id), eq(auditLogs.isUserVisible, true))
+ );
+
+ // Delete sync logs for user's calendars
+ const accessibleCalendars = await getUserAccessibleCalendars(user.id);
+ const calendarIds = accessibleCalendars.map((cal) => cal.id);
+
+ if (calendarIds.length > 0) {
+ await db
+ .delete(syncLogs)
+ .where(inArray(syncLogs.calendarId, calendarIds));
+ }
+
+ return NextResponse.json({
+ success: true,
+ message: "Activity logs cleared",
+ });
+ } catch (error) {
+ console.error("Error clearing activity logs:", error);
+ return NextResponse.json(
+ { error: "Failed to clear activity logs" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/api/admin/audit-logs/route.ts b/app/api/admin/audit-logs/route.ts
new file mode 100644
index 0000000..6a646da
--- /dev/null
+++ b/app/api/admin/audit-logs/route.ts
@@ -0,0 +1,359 @@
+import { NextRequest, NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import { auditLogs, user } from "@/lib/db/schema";
+import { sql, eq, desc, and, or, lt } from "drizzle-orm";
+import { requireAdmin } from "@/lib/auth/admin";
+import {
+ getValidatedAdminUser,
+ isErrorResponse,
+} from "@/lib/auth/admin-helpers";
+import { logAdminAction } from "@/lib/audit-log";
+
+/**
+ * Admin Audit Logs API
+ *
+ * GET /api/admin/audit-logs
+ * View all audit logs with filtering, sorting, and pagination.
+ *
+ * Query Parameters:
+ * - action: Filter by action type (e.g., "admin.user.ban", "calendar.create")
+ * - userId: Filter by specific user ID
+ * - resourceType: Filter by resource type (e.g., "user", "calendar")
+ * - resourceId: Filter by specific resource ID
+ * - severity: Filter by severity (info, warning, error, critical)
+ * - search: Search in action, resourceType, or metadata (case-insensitive)
+ * - startDate: Filter logs after this date (ISO string)
+ * - endDate: Filter logs before this date (ISO string)
+ * - sortBy: Sort field (timestamp, action, severity)
+ * - sortOrder: Sort direction (asc, desc)
+ * - limit: Number of logs to return (default: 50, max: 500)
+ * - offset: Pagination offset
+ *
+ * Permission: Admin or Superadmin only
+ */
+export async function GET(request: NextRequest) {
+ try {
+ const currentUser = await getValidatedAdminUser(request);
+ if (isErrorResponse(currentUser)) return currentUser;
+
+ requireAdmin(currentUser);
+
+ // Parse query parameters
+ const { searchParams } = new URL(request.url);
+ const actionFilter = searchParams.get("action");
+ const userIdFilter = searchParams.get("userId");
+ const resourceTypeFilter = searchParams.get("resourceType");
+ const resourceIdFilter = searchParams.get("resourceId");
+ const severityFilter = searchParams.get("severity");
+ const searchQuery = searchParams.get("search");
+ const startDate = searchParams.get("startDate");
+ const endDate = searchParams.get("endDate");
+ const sortBy = searchParams.get("sortBy") || "timestamp";
+ const sortOrder = searchParams.get("sortOrder") || "desc";
+ const limit = Math.min(
+ parseInt(searchParams.get("limit") || "25", 10),
+ 500
+ );
+ const offset = parseInt(searchParams.get("offset") || "0", 10);
+
+ const conditions = [];
+
+ // Action filter (supports prefix matching)
+ if (actionFilter) {
+ if (actionFilter.endsWith(".")) {
+ // Prefix match (e.g., "admin." matches "admin.user.ban")
+ const searchPattern = `${actionFilter}%`;
+ conditions.push(sql`${auditLogs.action} LIKE ${searchPattern}`);
+ } else {
+ // Exact match
+ conditions.push(eq(auditLogs.action, actionFilter));
+ }
+ }
+
+ // User filter
+ if (userIdFilter) {
+ conditions.push(eq(auditLogs.userId, userIdFilter));
+ }
+
+ // Resource type filter
+ if (resourceTypeFilter) {
+ conditions.push(eq(auditLogs.resourceType, resourceTypeFilter));
+ }
+
+ // Resource ID filter
+ if (resourceIdFilter) {
+ conditions.push(eq(auditLogs.resourceId, resourceIdFilter));
+ }
+
+ // Severity filter
+ if (severityFilter) {
+ const validSeverities = ["info", "warning", "error", "critical"];
+ if (validSeverities.includes(severityFilter)) {
+ conditions.push(eq(auditLogs.severity, severityFilter));
+ }
+ }
+
+ // Search filter (action, resourceType, or metadata)
+ if (searchQuery) {
+ const searchPattern = `%${searchQuery.toLowerCase()}%`;
+ conditions.push(
+ or(
+ sql`LOWER(${auditLogs.action}) LIKE ${searchPattern}`,
+ sql`LOWER(${auditLogs.resourceType}) LIKE ${searchPattern}`,
+ sql`LOWER(${auditLogs.metadata}) LIKE ${searchPattern}`
+ )
+ );
+ }
+
+ // Date range filters
+ if (startDate) {
+ const startTimestamp = new Date(startDate);
+ if (!isNaN(startTimestamp.getTime())) {
+ // Set to start of day (00:00:00)
+ startTimestamp.setHours(0, 0, 0, 0);
+ // Convert to Unix timestamp (seconds)
+ const unixTimestamp = Math.floor(startTimestamp.getTime() / 1000);
+ conditions.push(sql`${auditLogs.timestamp} >= ${unixTimestamp}`);
+ }
+ }
+
+ if (endDate) {
+ const endTimestamp = new Date(endDate);
+ if (!isNaN(endTimestamp.getTime())) {
+ // Set to end of day (23:59:59)
+ endTimestamp.setHours(23, 59, 59, 999);
+ // Convert to Unix timestamp (seconds)
+ const unixTimestamp = Math.floor(endTimestamp.getTime() / 1000);
+ conditions.push(sql`${auditLogs.timestamp} <= ${unixTimestamp}`);
+ }
+ }
+
+ // Apply sorting
+ let orderByClause;
+
+ if (sortBy === "user") {
+ // Sort by user name, fallback to email, then null last
+ const userSortExpr = sql`COALESCE(${user.name}, ${user.email}, 'zzz')`;
+ orderByClause = sortOrder === "asc" ? userSortExpr : desc(userSortExpr);
+ } else if (sortBy === "ipAddress") {
+ // Sort by IP address, nulls last
+ const ipSortExpr = sql`COALESCE(${auditLogs.ipAddress}, 'zzz')`;
+ orderByClause = sortOrder === "asc" ? ipSortExpr : desc(ipSortExpr);
+ } else {
+ const sortField =
+ sortBy === "action"
+ ? auditLogs.action
+ : sortBy === "severity"
+ ? auditLogs.severity
+ : auditLogs.timestamp;
+ orderByClause = sortOrder === "asc" ? sortField : desc(sortField);
+ }
+
+ // Get total count (with filters)
+ const countQuery = db
+ .select({ count: sql<number>`COUNT(*)` })
+ .from(auditLogs);
+
+ const [countResult] =
+ conditions.length > 0
+ ? await countQuery.where(and(...conditions))
+ : await countQuery;
+
+ const total = Number(countResult?.count || 0);
+
+ // Get logs with user information
+ const logsQuery = db
+ .select({
+ id: auditLogs.id,
+ userId: auditLogs.userId,
+ action: auditLogs.action,
+ resourceType: auditLogs.resourceType,
+ resourceId: auditLogs.resourceId,
+ metadata: auditLogs.metadata,
+ ipAddress: auditLogs.ipAddress,
+ userAgent: auditLogs.userAgent,
+ severity: auditLogs.severity,
+ isUserVisible: auditLogs.isUserVisible,
+ timestamp: auditLogs.timestamp,
+ userName: user.name,
+ userEmail: user.email,
+ userImage: user.image,
+ })
+ .from(auditLogs)
+ .leftJoin(user, eq(auditLogs.userId, user.id))
+ .orderBy(orderByClause)
+ .limit(limit)
+ .offset(offset);
+
+ const logs =
+ conditions.length > 0
+ ? await logsQuery.where(and(...conditions))
+ : await logsQuery;
+
+ // Parse metadata JSON strings
+ const logsWithParsedMetadata = logs.map((log) => ({
+ ...log,
+ metadata: log.metadata ? tryParseJSON(log.metadata) : null,
+ timestamp: log.timestamp.toISOString(),
+ }));
+
+ return NextResponse.json({
+ logs: logsWithParsedMetadata,
+ pagination: {
+ total,
+ limit,
+ offset,
+ hasMore: offset + limit < total,
+ },
+ });
+ } catch (error) {
+ console.error("[Admin Audit Logs] Error fetching logs:", error);
+
+ if (error instanceof Error && "status" in error) {
+ return NextResponse.json(
+ { error: error.message },
+ { status: (error as { status: number }).status }
+ );
+ }
+
+ return NextResponse.json(
+ { error: "Failed to fetch audit logs" },
+ { status: 500 }
+ );
+ }
+}
+
+/**
+ * DELETE /api/admin/audit-logs
+ * Delete old audit logs (bulk operation).
+ *
+ * Delete Methods:
+ * 1. Query Parameter: ?before=2024-01-01 (delete logs older than date)
+ * 2. Request Body: { logIds: [...] } (delete specific logs by ID)
+ *
+ * Permission: Superadmin only
+ */
+export async function DELETE(request: NextRequest) {
+ try {
+ const currentUser = await getValidatedAdminUser(request);
+ if (isErrorResponse(currentUser)) return currentUser;
+
+ // Only superadmins can delete audit logs
+ if (currentUser.role !== "superadmin") {
+ return NextResponse.json(
+ { error: "Superadmin access required" },
+ { status: 403 }
+ );
+ }
+
+ const { searchParams } = new URL(request.url);
+ const beforeDate = searchParams.get("before");
+
+ let deletedCount = 0;
+
+ // Method 1: Delete by date (query parameter)
+ if (beforeDate) {
+ const beforeTimestamp = new Date(beforeDate);
+
+ if (isNaN(beforeTimestamp.getTime())) {
+ return NextResponse.json(
+ { error: "Invalid date format" },
+ { status: 400 }
+ );
+ }
+
+ const result = await db
+ .delete(auditLogs)
+ .where(lt(auditLogs.timestamp, beforeTimestamp))
+ .returning({ id: auditLogs.id });
+
+ deletedCount = result.length;
+
+ // Log admin action
+ await logAdminAction({
+ action: "admin.audit_log.delete_by_date",
+ userId: currentUser.id,
+ metadata: {
+ beforeDate: beforeTimestamp.toISOString(),
+ deletedCount,
+ deletedBy: currentUser.email,
+ },
+ request,
+ });
+
+ return NextResponse.json({
+ success: true,
+ deletedCount,
+ beforeDate: beforeTimestamp.toISOString(),
+ });
+ }
+
+ // Method 2: Delete by IDs (request body)
+ const body = await request.json().catch(() => ({}));
+ const { logIds } = body;
+
+ if (!logIds || !Array.isArray(logIds) || logIds.length === 0) {
+ return NextResponse.json(
+ {
+ error:
+ "Either 'before' query parameter or 'logIds' in body is required",
+ },
+ { status: 400 }
+ );
+ }
+
+ // Delete logs by IDs
+ const deletePromises = logIds.map((id) =>
+ db
+ .delete(auditLogs)
+ .where(eq(auditLogs.id, id))
+ .returning({ id: auditLogs.id })
+ );
+
+ const results = await Promise.all(deletePromises);
+ deletedCount = results.filter((r) => r.length > 0).length;
+
+ // Log admin action
+ await logAdminAction({
+ action: "admin.audit_log.delete_by_ids",
+ userId: currentUser.id,
+ metadata: {
+ logIds,
+ deletedCount,
+ deletedBy: currentUser.email,
+ },
+ request,
+ });
+
+ return NextResponse.json({
+ success: true,
+ deletedCount,
+ requestedCount: logIds.length,
+ });
+ } catch (error) {
+ console.error("[Admin Audit Logs] Error deleting logs:", error);
+
+ if (error instanceof Error && "status" in error) {
+ return NextResponse.json(
+ { error: error.message },
+ { status: (error as { status: number }).status }
+ );
+ }
+
+ return NextResponse.json(
+ { error: "Failed to delete audit logs" },
+ { status: 500 }
+ );
+ }
+}
+
+/**
+ * Helper function to safely parse JSON strings
+ */
+function tryParseJSON(jsonString: string): unknown {
+ try {
+ return JSON.parse(jsonString);
+ } catch {
+ return jsonString; // Return as string if parsing fails
+ }
+}
diff --git a/app/api/admin/calendars/[id]/route.ts b/app/api/admin/calendars/[id]/route.ts
new file mode 100644
index 0000000..93bbcac
--- /dev/null
+++ b/app/api/admin/calendars/[id]/route.ts
@@ -0,0 +1,515 @@
+import { NextRequest, NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import {
+ calendars as calendarsTable,
+ user as userTable,
+ shifts as shiftsTable,
+ calendarNotes as notesTable,
+ shiftPresets as presetsTable,
+ calendarShares as calendarSharesTable,
+ externalSyncs as externalSyncsTable,
+ syncLogs as syncLogsTable,
+ userCalendarSubscriptions as subscriptionsTable,
+ calendarAccessTokens as tokensTable,
+} from "@/lib/db/schema";
+import { eq, sql } from "drizzle-orm";
+import {
+ requireAdmin,
+ requireSuperAdmin,
+ canEditCalendar,
+ canDeleteCalendar,
+} from "@/lib/auth/admin";
+import { logAuditEvent } from "@/lib/audit-log";
+import { rateLimit } from "@/lib/rate-limiter";
+import {
+ getValidatedAdminUser,
+ isErrorResponse,
+} from "@/lib/auth/admin-helpers";
+import { eventEmitter } from "@/lib/event-emitter";
+
+/**
+ * Admin Calendar Detail API
+ *
+ * GET /api/admin/calendars/[id]
+ * Returns detailed information about a specific calendar.
+ *
+ * PATCH /api/admin/calendars/[id]
+ * Updates calendar information (name, color, guestPermission).
+ * - Admin & Superadmin: Can update calendars
+ * - Cannot change ownerId via PATCH (use transfer endpoint)
+ *
+ * DELETE /api/admin/calendars/[id]
+ * Deletes calendar and all associated data.
+ * - Superadmin only
+ *
+ * Permission: Admin or Superadmin (role-based restrictions apply)
+ */
+
+interface RouteParams {
+ params: Promise<{
+ id: string;
+ }>;
+}
+
+export async function GET(
+ request: NextRequest,
+ { params }: RouteParams
+): Promise<NextResponse> {
+ try {
+ const { id: calendarId } = await params;
+ const currentUser = await getValidatedAdminUser(request);
+ if (isErrorResponse(currentUser)) return currentUser;
+
+ requireAdmin(currentUser);
+
+ // Get calendar with owner info
+ const [calendar] = await db
+ .select({
+ id: calendarsTable.id,
+ name: calendarsTable.name,
+ color: calendarsTable.color,
+ ownerId: calendarsTable.ownerId,
+ guestPermission: calendarsTable.guestPermission,
+ createdAt: sql<string>`${calendarsTable.createdAt}`,
+ updatedAt: sql<string>`${calendarsTable.updatedAt}`,
+ ownerName: userTable.name,
+ ownerEmail: userTable.email,
+ ownerImage: userTable.image,
+ })
+ .from(calendarsTable)
+ .leftJoin(userTable, eq(calendarsTable.ownerId, userTable.id))
+ .where(eq(calendarsTable.id, calendarId));
+
+ if (!calendar) {
+ return NextResponse.json(
+ { error: "Calendar not found" },
+ { status: 404 }
+ );
+ }
+
+ // Get statistics
+ const [shiftCount] = await db
+ .select({ count: sql<number>`COUNT(*)` })
+ .from(shiftsTable)
+ .where(eq(shiftsTable.calendarId, calendarId));
+
+ const [noteCount] = await db
+ .select({ count: sql<number>`COUNT(*)` })
+ .from(notesTable)
+ .where(eq(notesTable.calendarId, calendarId));
+
+ const [presetCount] = await db
+ .select({ count: sql<number>`COUNT(*)` })
+ .from(presetsTable)
+ .where(eq(presetsTable.calendarId, calendarId));
+
+ const [shareCount] = await db
+ .select({ count: sql<number>`COUNT(*)` })
+ .from(calendarSharesTable)
+ .where(eq(calendarSharesTable.calendarId, calendarId));
+
+ // Get share list
+ const shares = await db
+ .select({
+ id: calendarSharesTable.id,
+ userId: calendarSharesTable.userId,
+ permission: calendarSharesTable.permission,
+ createdAt: calendarSharesTable.createdAt,
+ userName: userTable.name,
+ userEmail: userTable.email,
+ userImage: userTable.image,
+ })
+ .from(calendarSharesTable)
+ .leftJoin(userTable, eq(calendarSharesTable.userId, userTable.id))
+ .where(eq(calendarSharesTable.calendarId, calendarId));
+
+ // Get share tokens
+ const shareTokens = await db
+ .select({
+ id: tokensTable.id,
+ name: tokensTable.name,
+ permission: tokensTable.permission,
+ createdAt: sql<string>`${tokensTable.createdAt}`,
+ })
+ .from(tokensTable)
+ .where(eq(tokensTable.calendarId, calendarId));
+
+ // Get share token count
+ const [shareTokenCount] = await db
+ .select({ count: sql<number>`COUNT(*)` })
+ .from(tokensTable)
+ .where(eq(tokensTable.calendarId, calendarId));
+
+ // Get external syncs with last sync info
+ const externalSyncs = await db
+ .select({
+ id: externalSyncsTable.id,
+ name: externalSyncsTable.name,
+ syncType: externalSyncsTable.syncType,
+ url: externalSyncsTable.calendarUrl,
+ createdAt: sql<string>`${externalSyncsTable.createdAt}`,
+ })
+ .from(externalSyncsTable)
+ .where(eq(externalSyncsTable.calendarId, calendarId));
+
+ // Get last synced timestamp for each external sync
+ const externalSyncsWithLastSync = await Promise.all(
+ externalSyncs.map(async (sync) => {
+ const [lastSync] = await db
+ .select({ syncedAt: syncLogsTable.syncedAt })
+ .from(syncLogsTable)
+ .where(eq(syncLogsTable.externalSyncId, sync.id))
+ .orderBy(sql`${syncLogsTable.syncedAt} DESC`)
+ .limit(1);
+
+ return {
+ ...sync,
+ lastSyncedAt: lastSync?.syncedAt ? new Date(lastSync.syncedAt) : null,
+ };
+ })
+ );
+
+ // Get external syncs count
+ const [externalSyncCount] = await db
+ .select({ count: sql<number>`COUNT(*)` })
+ .from(externalSyncsTable)
+ .where(eq(externalSyncsTable.calendarId, calendarId));
+
+ return NextResponse.json({
+ id: calendar.id,
+ name: calendar.name,
+ color: calendar.color,
+ ownerId: calendar.ownerId,
+ owner: calendar.ownerId
+ ? {
+ name: calendar.ownerName,
+ email: calendar.ownerEmail,
+ image: calendar.ownerImage,
+ }
+ : null,
+ guestPermission: calendar.guestPermission,
+ createdAt: calendar.createdAt ? new Date(calendar.createdAt) : new Date(),
+ updatedAt: calendar.updatedAt ? new Date(calendar.updatedAt) : new Date(),
+ shiftsCount: Number(shiftCount?.count || 0),
+ notesCount: Number(noteCount?.count || 0),
+ presetsCount: Number(presetCount?.count || 0),
+ sharesCount:
+ Number(shareCount?.count || 0) + Number(shareTokenCount?.count || 0),
+ externalSyncsCount: Number(externalSyncCount?.count || 0),
+ shares: shares.map((s) => ({
+ userId: s.userId,
+ userName: s.userName || "",
+ userEmail: s.userEmail || "",
+ userImage: s.userImage,
+ permission: s.permission,
+ })),
+ shareTokens: shareTokens.map((t) => ({
+ id: t.id,
+ name: t.name,
+ permission: t.permission,
+ createdAt: t.createdAt ? new Date(t.createdAt) : new Date(),
+ })),
+ externalSyncs: externalSyncsWithLastSync,
+ });
+ } catch (error) {
+ console.error("[Admin Calendar Detail API] Error:", error);
+
+ if (error instanceof Error && error.message === "Admin access required") {
+ return NextResponse.json(
+ { error: "Admin access required" },
+ { status: 403 }
+ );
+ }
+
+ return NextResponse.json(
+ { error: "Failed to fetch calendar details" },
+ { status: 500 }
+ );
+ }
+}
+
+export async function PATCH(
+ request: NextRequest,
+ { params }: RouteParams
+): Promise<NextResponse> {
+ try {
+ const { id: calendarId } = await params;
+ const currentUser = await getValidatedAdminUser(request);
+ if (isErrorResponse(currentUser)) return currentUser;
+
+ requireAdmin(currentUser);
+
+ // Rate limiting: admin-calendar-mutations
+ const rateLimitResponse = rateLimit(
+ request,
+ currentUser.id,
+ "admin-calendar-mutations"
+ );
+ if (rateLimitResponse) return rateLimitResponse;
+
+ if (!canEditCalendar(currentUser)) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
+ }
+
+ // Get calendar before update
+ const [calendar] = await db
+ .select()
+ .from(calendarsTable)
+ .where(eq(calendarsTable.id, calendarId));
+
+ if (!calendar) {
+ return NextResponse.json(
+ { error: "Calendar not found" },
+ { status: 404 }
+ );
+ }
+
+ const body = await request.json();
+ const updates: {
+ name?: string;
+ color?: string;
+ guestPermission?: "none" | "read" | "write";
+ } = {};
+
+ // Validate and collect allowed updates
+ if (body.name !== undefined) {
+ if (typeof body.name !== "string" || body.name.trim().length === 0) {
+ return NextResponse.json(
+ { error: "Invalid calendar name" },
+ { status: 400 }
+ );
+ }
+ updates.name = body.name.trim();
+ }
+
+ if (body.color !== undefined) {
+ if (typeof body.color !== "string") {
+ return NextResponse.json(
+ { error: "Invalid color format" },
+ { status: 400 }
+ );
+ }
+ updates.color = body.color;
+ }
+
+ if (body.guestPermission !== undefined) {
+ if (!["none", "read", "write"].includes(body.guestPermission)) {
+ return NextResponse.json(
+ { error: "Invalid guest permission" },
+ { status: 400 }
+ );
+ }
+ updates.guestPermission = body.guestPermission;
+ }
+
+ // Don't allow ownerId changes via PATCH (use transfer endpoint)
+ if (body.ownerId !== undefined) {
+ return NextResponse.json(
+ { error: "Use /transfer endpoint to change ownership" },
+ { status: 400 }
+ );
+ }
+
+ if (Object.keys(updates).length === 0) {
+ return NextResponse.json(
+ { error: "No valid updates provided" },
+ { status: 400 }
+ );
+ }
+
+ // Update calendar
+ const [updatedCalendar] = await db
+ .update(calendarsTable)
+ .set(updates)
+ .where(eq(calendarsTable.id, calendarId))
+ .returning();
+
+ // Audit log
+ const changes = Object.keys(updates);
+ await logAuditEvent({
+ request,
+ action: "admin.calendar.update",
+ userId: currentUser.id,
+ severity: "warning",
+ metadata: {
+ calendarId,
+ calendarName: updatedCalendar.name,
+ changes,
+ oldValues: {
+ name: calendar.name,
+ color: calendar.color,
+ guestPermission: calendar.guestPermission,
+ },
+ newValues: updates,
+ updatedBy: currentUser.email,
+ },
+ });
+
+ // Emit SSE event
+ eventEmitter.emit("calendar-change", {
+ type: "calendar",
+ action: "update",
+ calendarId,
+ data: updatedCalendar,
+ });
+
+ return NextResponse.json(updatedCalendar);
+ } catch (error) {
+ console.error("[Admin Calendar Update API] Error:", error);
+
+ if (error instanceof Error) {
+ if (error.message === "Admin access required") {
+ return NextResponse.json(
+ { error: "Admin access required" },
+ { status: 403 }
+ );
+ }
+ if (error.message === "Insufficient permissions") {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
+ }
+ }
+
+ return NextResponse.json(
+ { error: "Failed to update calendar" },
+ { status: 500 }
+ );
+ }
+}
+
+export async function DELETE(
+ request: NextRequest,
+ { params }: RouteParams
+): Promise<NextResponse> {
+ try {
+ const { id: calendarId } = await params;
+ const currentUser = await getValidatedAdminUser(request);
+ if (isErrorResponse(currentUser)) return currentUser;
+
+ requireSuperAdmin(currentUser);
+
+ // Rate limiting: admin-calendar-mutations
+ const rateLimitResponse = rateLimit(
+ request,
+ currentUser.id,
+ "admin-calendar-mutations"
+ );
+ if (rateLimitResponse) return rateLimitResponse;
+
+ if (!canDeleteCalendar(currentUser)) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
+ }
+
+ // Get calendar info before deletion
+ const [calendar] = await db
+ .select()
+ .from(calendarsTable)
+ .where(eq(calendarsTable.id, calendarId));
+
+ if (!calendar) {
+ return NextResponse.json(
+ { error: "Calendar not found" },
+ { status: 404 }
+ );
+ }
+
+ // Get statistics for audit log
+ const [shiftCount] = await db
+ .select({ count: sql<number>`COUNT(*)` })
+ .from(shiftsTable)
+ .where(eq(shiftsTable.calendarId, calendarId));
+
+ const [noteCount] = await db
+ .select({ count: sql<number>`COUNT(*)` })
+ .from(notesTable)
+ .where(eq(notesTable.calendarId, calendarId));
+
+ const [presetCount] = await db
+ .select({ count: sql<number>`COUNT(*)` })
+ .from(presetsTable)
+ .where(eq(presetsTable.calendarId, calendarId));
+
+ // Delete all related data (cascade)
+ await db.delete(shiftsTable).where(eq(shiftsTable.calendarId, calendarId));
+ await db.delete(notesTable).where(eq(notesTable.calendarId, calendarId));
+ await db
+ .delete(presetsTable)
+ .where(eq(presetsTable.calendarId, calendarId));
+ await db
+ .delete(calendarSharesTable)
+ .where(eq(calendarSharesTable.calendarId, calendarId));
+ await db
+ .delete(subscriptionsTable)
+ .where(eq(subscriptionsTable.calendarId, calendarId));
+ await db.delete(tokensTable).where(eq(tokensTable.calendarId, calendarId));
+ await db
+ .delete(syncLogsTable)
+ .where(eq(syncLogsTable.calendarId, calendarId));
+ await db
+ .delete(externalSyncsTable)
+ .where(eq(externalSyncsTable.calendarId, calendarId));
+
+ // Delete calendar
+ await db.delete(calendarsTable).where(eq(calendarsTable.id, calendarId));
+
+ // Audit log
+ await logAuditEvent({
+ request,
+ action: "admin.calendar.delete",
+ userId: currentUser.id,
+ severity: "critical",
+ metadata: {
+ calendarId,
+ calendarName: calendar.name,
+ ownerId: calendar.ownerId,
+ shiftCount: Number(shiftCount?.count || 0),
+ noteCount: Number(noteCount?.count || 0),
+ presetCount: Number(presetCount?.count || 0),
+ deletedBy: currentUser.email,
+ },
+ });
+
+ // Emit SSE event
+ eventEmitter.emit("calendar-change", {
+ type: "calendar",
+ action: "delete",
+ calendarId,
+ data: { id: calendarId },
+ });
+
+ return NextResponse.json({
+ message: "Calendar deleted successfully",
+ calendarId,
+ });
+ } catch (error) {
+ console.error("[Admin Calendar Delete API] Error:", error);
+
+ if (error instanceof Error) {
+ if (error.message === "Superadmin access required") {
+ return NextResponse.json(
+ { error: "Superadmin access required" },
+ { status: 403 }
+ );
+ }
+ if (error.message === "Insufficient permissions") {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
+ }
+ }
+
+ return NextResponse.json(
+ { error: "Failed to delete calendar" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/api/admin/calendars/[id]/transfer/route.ts b/app/api/admin/calendars/[id]/transfer/route.ts
new file mode 100644
index 0000000..6505194
--- /dev/null
+++ b/app/api/admin/calendars/[id]/transfer/route.ts
@@ -0,0 +1,166 @@
+import { NextRequest, NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import {
+ calendars as calendarsTable,
+ user as userTable,
+} from "@/lib/db/schema";
+import { eq } from "drizzle-orm";
+import { requireAdmin, canTransferCalendar } from "@/lib/auth/admin";
+import { logAuditEvent } from "@/lib/audit-log";
+import { rateLimit } from "@/lib/rate-limiter";
+import {
+ getValidatedAdminUser,
+ isErrorResponse,
+} from "@/lib/auth/admin-helpers";
+import { eventEmitter } from "@/lib/event-emitter";
+
+/**
+ * Admin Calendar Transfer API
+ *
+ * POST /api/admin/calendars/[id]/transfer
+ * Transfers calendar ownership to a different user.
+ *
+ * Body:
+ * - newOwnerId: string - User ID to transfer to
+ * OR
+ * - assignToSelf: boolean - Transfer to current admin (for orphaned calendars)
+ *
+ * Permission: Admin or Superadmin
+ */
+
+interface RouteParams {
+ params: Promise<{
+ id: string;
+ }>;
+}
+
+export async function POST(
+ request: NextRequest,
+ { params }: RouteParams
+): Promise<NextResponse> {
+ try {
+ const { id: calendarId } = await params;
+ const currentUser = await getValidatedAdminUser(request);
+ if (isErrorResponse(currentUser)) return currentUser;
+
+ requireAdmin(currentUser);
+
+ // Rate limiting: admin-calendar-mutations
+ const rateLimitResponse = rateLimit(
+ request,
+ currentUser.id,
+ "admin-calendar-mutations"
+ );
+ if (rateLimitResponse) return rateLimitResponse;
+
+ if (!canTransferCalendar(currentUser)) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
+ }
+
+ const body = await request.json();
+ let newOwnerId: string;
+
+ // Determine new owner ID
+ if (body.assignToSelf === true) {
+ newOwnerId = currentUser.id;
+ } else if (body.newOwnerId) {
+ newOwnerId = body.newOwnerId;
+ } else {
+ return NextResponse.json(
+ { error: "Either newOwnerId or assignToSelf must be provided" },
+ { status: 400 }
+ );
+ }
+
+ // Validate new owner exists
+ const [newOwner] = await db
+ .select()
+ .from(userTable)
+ .where(eq(userTable.id, newOwnerId))
+ .limit(1);
+
+ if (!newOwner) {
+ return NextResponse.json(
+ { error: "Target user not found" },
+ { status: 404 }
+ );
+ }
+
+ // Get calendar info before transfer
+ const [calendar] = await db
+ .select()
+ .from(calendarsTable)
+ .where(eq(calendarsTable.id, calendarId));
+
+ if (!calendar) {
+ return NextResponse.json(
+ { error: "Calendar not found" },
+ { status: 404 }
+ );
+ }
+
+ const previousOwnerId = calendar.ownerId;
+
+ // Transfer ownership
+ const [updatedCalendar] = await db
+ .update(calendarsTable)
+ .set({ ownerId: newOwnerId })
+ .where(eq(calendarsTable.id, calendarId))
+ .returning();
+
+ // Audit log
+ await logAuditEvent({
+ request,
+ action: "admin.calendar.transfer",
+ userId: currentUser.id,
+ severity: "warning",
+ metadata: {
+ calendarId,
+ calendarName: updatedCalendar.name,
+ previousOwnerId,
+ newOwnerId,
+ newOwnerEmail: newOwner.email,
+ transferredBy: currentUser.email,
+ assignedToSelf: body.assignToSelf === true,
+ },
+ });
+
+ // Emit SSE event
+ eventEmitter.emit("calendar-change", {
+ type: "calendar",
+ action: "update",
+ calendarId,
+ data: updatedCalendar,
+ });
+
+ return NextResponse.json({
+ message: "Calendar ownership transferred successfully",
+ calendar: updatedCalendar,
+ });
+ } catch (error) {
+ console.error("[Admin Calendar Transfer API] Error:", error);
+
+ if (error instanceof Error) {
+ if (error.message === "Admin access required") {
+ return NextResponse.json(
+ { error: "Admin access required" },
+ { status: 403 }
+ );
+ }
+ if (error.message === "Insufficient permissions") {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
+ }
+ }
+
+ return NextResponse.json(
+ { error: "Failed to transfer calendar ownership" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/api/admin/calendars/bulk-delete/route.ts b/app/api/admin/calendars/bulk-delete/route.ts
new file mode 100644
index 0000000..7248c37
--- /dev/null
+++ b/app/api/admin/calendars/bulk-delete/route.ts
@@ -0,0 +1,177 @@
+import { NextRequest, NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import {
+ calendars as calendarsTable,
+ shifts as shiftsTable,
+ calendarNotes as notesTable,
+ shiftPresets as presetsTable,
+ calendarShares as calendarSharesTable,
+ externalSyncs as externalSyncsTable,
+ syncLogs as syncLogsTable,
+ userCalendarSubscriptions as subscriptionsTable,
+ calendarAccessTokens as tokensTable,
+} from "@/lib/db/schema";
+import { inArray, sql } from "drizzle-orm";
+import { requireSuperAdmin, canDeleteCalendar } from "@/lib/auth/admin";
+import { logAuditEvent } from "@/lib/audit-log";
+import { rateLimit } from "@/lib/rate-limiter";
+import {
+ getValidatedAdminUser,
+ isErrorResponse,
+} from "@/lib/auth/admin-helpers";
+import { eventEmitter } from "@/lib/event-emitter";
+
+/**
+ * Admin Calendar Bulk Delete API
+ *
+ * POST /api/admin/calendars/bulk-delete
+ * Deletes multiple calendars and all their associated data.
+ *
+ * Body:
+ * - calendarIds: string[] - Array of calendar IDs to delete
+ *
+ * Permission: Superadmin only
+ */
+
+export async function POST(request: NextRequest): Promise<NextResponse> {
+ try {
+ const currentUser = await getValidatedAdminUser(request);
+ if (isErrorResponse(currentUser)) return currentUser;
+
+ requireSuperAdmin(currentUser);
+
+ // Rate limiting: admin-bulk-operations (strictest limit)
+ const rateLimitResponse = rateLimit(
+ request,
+ currentUser.id,
+ "admin-bulk-operations"
+ );
+ if (rateLimitResponse) return rateLimitResponse;
+
+ if (!canDeleteCalendar(currentUser)) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
+ }
+
+ const body = await request.json();
+ const calendarIds: string[] = body.calendarIds;
+
+ if (!Array.isArray(calendarIds) || calendarIds.length === 0) {
+ return NextResponse.json(
+ { error: "calendarIds must be a non-empty array" },
+ { status: 400 }
+ );
+ }
+
+ // Get calendar info before deletion
+ const calendars = await db
+ .select()
+ .from(calendarsTable)
+ .where(inArray(calendarsTable.id, calendarIds));
+
+ if (calendars.length === 0) {
+ return NextResponse.json(
+ { error: "No calendars found with provided IDs" },
+ { status: 404 }
+ );
+ }
+
+ // Get total statistics for audit log
+ const [totalStats] = await db
+ .select({
+ shifts: sql<number>`(SELECT COUNT(*) FROM ${shiftsTable} WHERE ${shiftsTable.calendarId} IN ${calendarIds})`,
+ notes: sql<number>`(SELECT COUNT(*) FROM ${notesTable} WHERE ${notesTable.calendarId} IN ${calendarIds})`,
+ presets: sql<number>`(SELECT COUNT(*) FROM ${presetsTable} WHERE ${presetsTable.calendarId} IN ${calendarIds})`,
+ })
+ .from(calendarsTable)
+ .limit(1);
+
+ // Delete all related data for all calendars
+ await db
+ .delete(shiftsTable)
+ .where(inArray(shiftsTable.calendarId, calendarIds));
+ await db
+ .delete(notesTable)
+ .where(inArray(notesTable.calendarId, calendarIds));
+ await db
+ .delete(presetsTable)
+ .where(inArray(presetsTable.calendarId, calendarIds));
+ await db
+ .delete(calendarSharesTable)
+ .where(inArray(calendarSharesTable.calendarId, calendarIds));
+ await db
+ .delete(subscriptionsTable)
+ .where(inArray(subscriptionsTable.calendarId, calendarIds));
+ await db
+ .delete(tokensTable)
+ .where(inArray(tokensTable.calendarId, calendarIds));
+ await db
+ .delete(syncLogsTable)
+ .where(inArray(syncLogsTable.calendarId, calendarIds));
+ await db
+ .delete(externalSyncsTable)
+ .where(inArray(externalSyncsTable.calendarId, calendarIds));
+
+ // Delete all calendars
+ await db
+ .delete(calendarsTable)
+ .where(inArray(calendarsTable.id, calendarIds));
+
+ // Audit log
+ await logAuditEvent({
+ request,
+ action: "admin.calendar.bulk_delete",
+ userId: currentUser.id,
+ severity: "critical",
+ metadata: {
+ count: calendars.length,
+ calendarIds,
+ calendarNames: calendars.map((c) => c.name),
+ totalShifts: Number(totalStats?.shifts || 0),
+ totalNotes: Number(totalStats?.notes || 0),
+ totalPresets: Number(totalStats?.presets || 0),
+ deletedBy: currentUser.email,
+ },
+ });
+
+ // Emit SSE events for each deleted calendar
+ for (const calendarId of calendarIds) {
+ eventEmitter.emit("calendar-change", {
+ type: "calendar",
+ action: "delete",
+ calendarId,
+ data: { id: calendarId },
+ });
+ }
+
+ return NextResponse.json({
+ message: `${calendars.length} calendar(s) deleted successfully`,
+ deletedCount: calendars.length,
+ calendarIds,
+ });
+ } catch (error) {
+ console.error("[Admin Calendar Bulk Delete API] Error:", error);
+
+ if (error instanceof Error) {
+ if (error.message === "Superadmin access required") {
+ return NextResponse.json(
+ { error: "Superadmin access required" },
+ { status: 403 }
+ );
+ }
+ if (error.message === "Insufficient permissions") {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
+ }
+ }
+
+ return NextResponse.json(
+ { error: "Failed to delete calendars" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/api/admin/calendars/bulk-transfer/route.ts b/app/api/admin/calendars/bulk-transfer/route.ts
new file mode 100644
index 0000000..4ffd0a6
--- /dev/null
+++ b/app/api/admin/calendars/bulk-transfer/route.ts
@@ -0,0 +1,162 @@
+import { NextRequest, NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import {
+ calendars as calendarsTable,
+ user as userTable,
+} from "@/lib/db/schema";
+import { eq, inArray } from "drizzle-orm";
+import { requireAdmin, canTransferCalendar } from "@/lib/auth/admin";
+import { logAuditEvent } from "@/lib/audit-log";
+import { rateLimit } from "@/lib/rate-limiter";
+import {
+ getValidatedAdminUser,
+ isErrorResponse,
+} from "@/lib/auth/admin-helpers";
+import { eventEmitter } from "@/lib/event-emitter";
+
+/**
+ * Admin Calendar Bulk Transfer API
+ *
+ * POST /api/admin/calendars/bulk-transfer
+ * Transfers multiple calendars to a different user.
+ *
+ * Body:
+ * - calendarIds: string[] - Array of calendar IDs to transfer
+ * - newOwnerId: string - User ID to transfer to
+ *
+ * Permission: Admin or Superadmin
+ */
+
+export async function POST(request: NextRequest): Promise<NextResponse> {
+ try {
+ const currentUser = await getValidatedAdminUser(request);
+ if (isErrorResponse(currentUser)) return currentUser;
+
+ requireAdmin(currentUser);
+
+ // Rate limiting: admin-bulk-operations (strictest limit)
+ const rateLimitResponse = rateLimit(
+ request,
+ currentUser.id,
+ "admin-bulk-operations"
+ );
+ if (rateLimitResponse) return rateLimitResponse;
+
+ if (!canTransferCalendar(currentUser)) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
+ }
+
+ const body = await request.json();
+ const calendarIds: string[] = body.calendarIds;
+ const newOwnerId: string = body.newOwnerId;
+
+ if (!Array.isArray(calendarIds) || calendarIds.length === 0) {
+ return NextResponse.json(
+ { error: "calendarIds must be a non-empty array" },
+ { status: 400 }
+ );
+ }
+
+ if (!newOwnerId) {
+ return NextResponse.json(
+ { error: "newOwnerId is required" },
+ { status: 400 }
+ );
+ }
+
+ // Validate new owner exists
+ const [newOwner] = await db
+ .select()
+ .from(userTable)
+ .where(eq(userTable.id, newOwnerId))
+ .limit(1);
+
+ if (!newOwner) {
+ return NextResponse.json(
+ { error: "Target user not found" },
+ { status: 404 }
+ );
+ }
+
+ // Get calendar info before transfer
+ const calendars = await db
+ .select()
+ .from(calendarsTable)
+ .where(inArray(calendarsTable.id, calendarIds));
+
+ if (calendars.length === 0) {
+ return NextResponse.json(
+ { error: "No calendars found with provided IDs" },
+ { status: 404 }
+ );
+ }
+
+ // Transfer ownership for all calendars
+ await db
+ .update(calendarsTable)
+ .set({ ownerId: newOwnerId })
+ .where(inArray(calendarsTable.id, calendarIds));
+
+ // Audit log
+ await logAuditEvent({
+ request,
+ action: "admin.calendar.bulk_transfer",
+ userId: currentUser.id,
+ severity: "warning",
+ metadata: {
+ count: calendars.length,
+ calendarIds,
+ calendarNames: calendars.map((c) => c.name),
+ newOwnerId,
+ newOwnerEmail: newOwner.email,
+ transferredBy: currentUser.email,
+ previousOwners: calendars.map((c) => ({
+ calendarId: c.id,
+ previousOwnerId: c.ownerId,
+ })),
+ },
+ });
+
+ // Emit SSE events for each transferred calendar
+ for (const calendarId of calendarIds) {
+ eventEmitter.emit("calendar-change", {
+ type: "calendar",
+ action: "update",
+ calendarId,
+ data: { id: calendarId, ownerId: newOwnerId },
+ });
+ }
+
+ return NextResponse.json({
+ message: `${calendars.length} calendar(s) transferred successfully`,
+ transferredCount: calendars.length,
+ calendarIds,
+ newOwnerId,
+ });
+ } catch (error) {
+ console.error("[Admin Calendar Bulk Transfer API] Error:", error);
+
+ if (error instanceof Error) {
+ if (error.message === "Admin access required") {
+ return NextResponse.json(
+ { error: "Admin access required" },
+ { status: 403 }
+ );
+ }
+ if (error.message === "Insufficient permissions") {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
+ }
+ }
+
+ return NextResponse.json(
+ { error: "Failed to transfer calendars" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/api/admin/calendars/route.ts b/app/api/admin/calendars/route.ts
new file mode 100644
index 0000000..466d163
--- /dev/null
+++ b/app/api/admin/calendars/route.ts
@@ -0,0 +1,253 @@
+import { NextRequest, NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import {
+ calendars,
+ user,
+ shifts,
+ calendarNotes,
+ shiftPresets,
+ calendarShares,
+ calendarAccessTokens,
+ externalSyncs,
+} from "@/lib/db/schema";
+import { sql, eq, and, isNull } from "drizzle-orm";
+import { requireAdmin } from "@/lib/auth/admin";
+import {
+ getValidatedAdminUser,
+ isErrorResponse,
+} from "@/lib/auth/admin-helpers";
+
+/**
+ * Admin Calendar Management API
+ *
+ * GET /api/admin/calendars
+ * Lists all calendars with filtering, sorting, and pagination.
+ *
+ * Query Parameters:
+ * - status: Filter by status (all, orphaned, owned)
+ * - search: Search by calendar name (case-insensitive)
+ * - ownerId: Filter by specific owner ID
+ * - sortBy: Sort field (name, createdAt, ownerId, shiftCount)
+ * - sortOrder: Sort direction (asc, desc)
+ * - limit: Number of calendars to return (default: 1000)
+ * - offset: Pagination offset
+ *
+ * Permission: Admin or Superadmin only
+ */
+export async function GET(request: NextRequest) {
+ try {
+ const currentUser = await getValidatedAdminUser(request);
+ if (isErrorResponse(currentUser)) return currentUser;
+
+ requireAdmin(currentUser);
+
+ // Parse query parameters
+ const { searchParams } = new URL(request.url);
+ const statusFilter = searchParams.get("status") || "all";
+ const searchQuery = searchParams.get("search");
+ const ownerIdFilter = searchParams.get("ownerId");
+ const sortBy = searchParams.get("sortBy") || "createdAt";
+ const sortOrder = searchParams.get("sortOrder") || "desc";
+ const limit = parseInt(searchParams.get("limit") || "1000", 10);
+ const offset = parseInt(searchParams.get("offset") || "0", 10);
+
+ const conditions = [];
+
+ // Status filter
+ if (statusFilter === "orphaned") {
+ conditions.push(isNull(calendars.ownerId));
+ } else if (statusFilter === "with-owner") {
+ conditions.push(sql`${calendars.ownerId} IS NOT NULL`);
+ }
+
+ // Owner filter
+ if (ownerIdFilter) {
+ conditions.push(eq(calendars.ownerId, ownerIdFilter));
+ }
+
+ // Search filter
+ if (searchQuery) {
+ const searchPattern = `%${searchQuery.toLowerCase()}%`;
+ conditions.push(sql`LOWER(${calendars.name}) LIKE ${searchPattern}`);
+ }
+
+ // Base query with calendar data
+ const baseQuery = db
+ .select({
+ id: calendars.id,
+ name: calendars.name,
+ color: calendars.color,
+ ownerId: calendars.ownerId,
+ guestPermission: calendars.guestPermission,
+ createdAt: sql<string>`${calendars.createdAt}`,
+ updatedAt: sql<string>`${calendars.updatedAt}`,
+ ownerName: user.name,
+ ownerEmail: user.email,
+ ownerImage: user.image,
+ })
+ .from(calendars)
+ .leftJoin(user, eq(calendars.ownerId, user.id));
+
+ // Get total count
+ const countQuery = db
+ .select({ count: sql<number>`COUNT(*)` })
+ .from(calendars);
+
+ const [countResult] =
+ conditions.length > 0
+ ? await countQuery.where(and(...conditions))
+ : await countQuery;
+
+ const total = Number(countResult?.count || 0);
+
+ // Get calendars with owner info
+ const calendarsQuery =
+ conditions.length > 0 ? baseQuery.where(and(...conditions)) : baseQuery;
+
+ const calendarsData = await calendarsQuery.limit(limit).offset(offset);
+
+ // Get statistics for each calendar
+ const calendarIds = calendarsData.map((c) => c.id);
+
+ // Get shift counts
+ const shiftCounts = await db
+ .select({
+ calendarId: shifts.calendarId,
+ count: sql<number>`COUNT(*)`,
+ })
+ .from(shifts)
+ .where(sql`${shifts.calendarId} IN ${calendarIds}`)
+ .groupBy(shifts.calendarId);
+
+ // Get note counts
+ const noteCounts = await db
+ .select({
+ calendarId: calendarNotes.calendarId,
+ count: sql<number>`COUNT(*)`,
+ })
+ .from(calendarNotes)
+ .where(sql`${calendarNotes.calendarId} IN ${calendarIds}`)
+ .groupBy(calendarNotes.calendarId);
+
+ // Get preset counts
+ const presetCounts = await db
+ .select({
+ calendarId: shiftPresets.calendarId,
+ count: sql<number>`COUNT(*)`,
+ })
+ .from(shiftPresets)
+ .where(sql`${shiftPresets.calendarId} IN ${calendarIds}`)
+ .groupBy(shiftPresets.calendarId);
+
+ // Get share counts
+ const shareCounts = await db
+ .select({
+ calendarId: calendarShares.calendarId,
+ count: sql<number>`COUNT(*)`,
+ })
+ .from(calendarShares)
+ .where(sql`${calendarShares.calendarId} IN ${calendarIds}`)
+ .groupBy(calendarShares.calendarId);
+
+ // Get share token counts
+ const shareTokenCounts = await db
+ .select({
+ calendarId: calendarAccessTokens.calendarId,
+ count: sql<number>`COUNT(*)`,
+ })
+ .from(calendarAccessTokens)
+ .where(sql`${calendarAccessTokens.calendarId} IN ${calendarIds}`)
+ .groupBy(calendarAccessTokens.calendarId);
+
+ // Get external syncs counts
+ const externalSyncsCounts = await db
+ .select({
+ calendarId: externalSyncs.calendarId,
+ count: sql<number>`COUNT(*)`,
+ })
+ .from(externalSyncs)
+ .where(sql`${externalSyncs.calendarId} IN ${calendarIds}`)
+ .groupBy(externalSyncs.calendarId);
+
+ // Build result with statistics
+ const calendarsWithStats = calendarsData.map((calendar) => ({
+ id: calendar.id,
+ name: calendar.name,
+ color: calendar.color,
+ ownerId: calendar.ownerId,
+ owner: calendar.ownerId
+ ? {
+ name: calendar.ownerName,
+ email: calendar.ownerEmail,
+ image: calendar.ownerImage,
+ }
+ : null,
+ guestPermission: calendar.guestPermission,
+ createdAt: calendar.createdAt ? new Date(calendar.createdAt) : new Date(),
+ updatedAt: calendar.updatedAt ? new Date(calendar.updatedAt) : new Date(),
+ shiftsCount:
+ shiftCounts.find((s) => s.calendarId === calendar.id)?.count || 0,
+ notesCount:
+ noteCounts.find((n) => n.calendarId === calendar.id)?.count || 0,
+ presetsCount:
+ presetCounts.find((p) => p.calendarId === calendar.id)?.count || 0,
+ sharesCount:
+ (shareCounts.find((s) => s.calendarId === calendar.id)?.count || 0) +
+ (shareTokenCounts.find((t) => t.calendarId === calendar.id)?.count ||
+ 0),
+ externalSyncsCount:
+ externalSyncsCounts.find((e) => e.calendarId === calendar.id)?.count ||
+ 0,
+ }));
+
+ // Apply sorting
+ const sortedCalendars = calendarsWithStats.sort((a, b) => {
+ // Orphaned calendars always on top (when not filtering)
+ if (statusFilter === "all") {
+ const aOrphaned = !a.ownerId;
+ const bOrphaned = !b.ownerId;
+ if (aOrphaned !== bOrphaned) {
+ return aOrphaned ? -1 : 1;
+ }
+ }
+
+ // Then sort by specified field
+ let comparison = 0;
+ if (sortBy === "name") {
+ comparison = a.name.localeCompare(b.name);
+ } else if (sortBy === "createdAt") {
+ comparison =
+ new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
+ } else if (sortBy === "ownerId") {
+ const aOwner = a.owner?.name || a.owner?.email || "";
+ const bOwner = b.owner?.name || b.owner?.email || "";
+ comparison = aOwner.localeCompare(bOwner);
+ } else if (sortBy === "shiftCount") {
+ comparison = a.shiftsCount - b.shiftsCount;
+ }
+
+ return sortOrder === "asc" ? comparison : -comparison;
+ });
+
+ return NextResponse.json({
+ calendars: sortedCalendars,
+ total,
+ limit,
+ offset,
+ });
+ } catch (error) {
+ console.error("[Admin Calendars API] Error:", error);
+
+ if (error instanceof Error && error.message === "Admin access required") {
+ return NextResponse.json(
+ { error: "Admin access required" },
+ { status: 403 }
+ );
+ }
+
+ return NextResponse.json(
+ { error: "Failed to fetch calendars" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/api/admin/stats/route.ts b/app/api/admin/stats/route.ts
new file mode 100644
index 0000000..ff38a2a
--- /dev/null
+++ b/app/api/admin/stats/route.ts
@@ -0,0 +1,201 @@
+import { NextRequest, NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import {
+ user,
+ calendars,
+ calendarShares,
+ calendarAccessTokens,
+ shifts,
+ auditLogs,
+} from "@/lib/db/schema";
+import { sql, eq, and, gte, isNull } from "drizzle-orm";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { requireAdmin } from "@/lib/auth/admin";
+
+/**
+ * Admin System Statistics API
+ *
+ * GET /api/admin/stats
+ * Returns system-wide statistics for admin dashboard.
+ *
+ * Permission: Admin or Superadmin only
+ */
+export async function GET(request: NextRequest) {
+ try {
+ const sessionUser = await getSessionUser(request.headers);
+
+ if (!sessionUser) {
+ return NextResponse.json(
+ { error: "Authentication required" },
+ { status: 401 }
+ );
+ }
+
+ // Get full user from DB to check admin role
+ const [currentUser] = await db
+ .select()
+ .from(user)
+ .where(eq(user.id, sessionUser.id))
+ .limit(1);
+
+ if (!currentUser) {
+ return NextResponse.json({ error: "User not found" }, { status: 404 });
+ }
+
+ requireAdmin(currentUser);
+
+ // Calculate date for "recent activity" (last 7 days)
+ const sevenDaysAgo = new Date();
+ sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
+
+ // 1. Total users by role
+ const usersQuery = await db
+ .select({
+ role: user.role,
+ count: sql<number>`COUNT(*)`,
+ })
+ .from(user)
+ .groupBy(user.role);
+
+ const usersByRole = {
+ superadmin: 0,
+ admin: 0,
+ user: 0,
+ total: 0,
+ };
+
+ usersQuery.forEach((row) => {
+ const count = Number(row.count);
+ if (row.role === "superadmin") {
+ usersByRole.superadmin = count;
+ } else if (row.role === "admin") {
+ usersByRole.admin = count;
+ } else {
+ // null or "user" role
+ usersByRole.user = count;
+ }
+ usersByRole.total += count;
+ });
+
+ // 2. Total calendars (exclude orphaned)
+ const [totalCalendarsResult] = await db
+ .select({
+ count: sql<number>`COUNT(*)`,
+ })
+ .from(calendars)
+ .where(sql`${calendars.ownerId} IS NOT NULL`);
+
+ const totalCalendars = Number(totalCalendarsResult?.count || 0);
+
+ // 3. Orphaned calendars (ownerId = NULL)
+ const [orphanedCalendarsResult] = await db
+ .select({
+ count: sql<number>`COUNT(*)`,
+ })
+ .from(calendars)
+ .where(isNull(calendars.ownerId));
+
+ const orphanedCalendars = Number(orphanedCalendarsResult?.count || 0);
+
+ // 4. Active shares count (user shares)
+ const [activeSharesResult] = await db
+ .select({
+ count: sql<number>`COUNT(*)`,
+ })
+ .from(calendarShares);
+
+ const activeShares = Number(activeSharesResult?.count || 0);
+
+ // 4a. Active token shares count
+ const [activeTokenSharesResult] = await db
+ .select({
+ count: sql<number>`COUNT(*)`,
+ })
+ .from(calendarAccessTokens)
+ .where(eq(calendarAccessTokens.isActive, true));
+
+ const activeTokenShares = Number(activeTokenSharesResult?.count || 0);
+
+ // 5. Total shifts count
+ const [totalShiftsResult] = await db
+ .select({
+ count: sql<number>`COUNT(*)`,
+ })
+ .from(shifts);
+
+ const totalShifts = Number(totalShiftsResult?.count || 0);
+
+ // 6. Recent activity count (last 7 days) - user-visible audit logs only
+ const [recentActivityResult] = await db
+ .select({
+ count: sql<number>`COUNT(*)`,
+ })
+ .from(auditLogs)
+ .where(
+ and(
+ eq(auditLogs.isUserVisible, true),
+ gte(auditLogs.timestamp, sevenDaysAgo)
+ )
+ );
+
+ const recentActivity = Number(recentActivityResult?.count || 0);
+
+ // 7. Recent audit logs preview (last 5 entries, admin-only logs + security events)
+ const recentLogs = await db
+ .select({
+ id: auditLogs.id,
+ action: auditLogs.action,
+ resourceType: auditLogs.resourceType,
+ resourceId: auditLogs.resourceId,
+ userId: auditLogs.userId,
+ severity: auditLogs.severity,
+ timestamp: auditLogs.timestamp,
+ })
+ .from(auditLogs)
+ .where(
+ sql`(${auditLogs.action} LIKE 'admin.%' OR ${auditLogs.action} LIKE 'security.%')` // Admin actions + security events (rate limits, etc.) - both user-visible and admin-only
+ )
+ .orderBy(sql`${auditLogs.timestamp} DESC`)
+ .limit(5);
+
+ const stats = {
+ users: usersByRole,
+ calendars: {
+ total: totalCalendars,
+ orphaned: orphanedCalendars,
+ },
+ shares: {
+ user: activeShares,
+ token: activeTokenShares,
+ active: activeShares + activeTokenShares,
+ },
+ shifts: {
+ total: totalShifts,
+ },
+ activity: {
+ recent: recentActivity,
+ logs: recentLogs,
+ },
+ };
+
+ return NextResponse.json(stats, { status: 200 });
+ } catch (error) {
+ if (
+ error &&
+ typeof error === "object" &&
+ "status" in error &&
+ error.status === 403
+ ) {
+ return NextResponse.json(
+ { error: "Admin access required" },
+ { status: 403 }
+ );
+ }
+
+ console.error("Failed to fetch admin stats:", error);
+ return NextResponse.json(
+ { error: "Failed to fetch statistics" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/api/admin/users/[id]/ban/route.ts b/app/api/admin/users/[id]/ban/route.ts
new file mode 100644
index 0000000..42a3fd9
--- /dev/null
+++ b/app/api/admin/users/[id]/ban/route.ts
@@ -0,0 +1,125 @@
+import { NextRequest, NextResponse } from "next/server";
+import { requireSuperAdmin, canBanUser } from "@/lib/auth/admin";
+import { logAuditEvent } from "@/lib/audit-log";
+import { rateLimit } from "@/lib/rate-limiter";
+import { auth } from "@/lib/auth";
+import {
+ getValidatedAdminUser,
+ getValidatedTargetUser,
+ isErrorResponse,
+} from "@/lib/auth/admin-helpers";
+
+/**
+ * Admin User Ban API
+ *
+ * POST /api/admin/users/[id]/ban
+ * Bans a user from the system.
+ *
+ * Body:
+ * - reason: string (required) - Reason for ban
+ * - expiresAt: number | null (optional) - Ban expiration timestamp (ms), null for permanent ban
+ *
+ * Permission: Superadmin only
+ * Restrictions:
+ * - Cannot ban self
+ * - Cannot ban other superadmins
+ */
+
+interface RouteParams {
+ params: Promise<{
+ id: string;
+ }>;
+}
+
+export async function POST(
+ request: NextRequest,
+ { params }: RouteParams
+): Promise<NextResponse> {
+ try {
+ const { id: targetUserId } = await params;
+ const currentUser = await getValidatedAdminUser(request);
+ if (isErrorResponse(currentUser)) return currentUser;
+
+ requireSuperAdmin(currentUser);
+
+ // Rate limiting: admin-user-mutations
+ const rateLimitResponse = rateLimit(
+ request,
+ currentUser.id,
+ "admin-user-mutations"
+ );
+ if (rateLimitResponse) return rateLimitResponse;
+
+ const targetUser = await getValidatedTargetUser(targetUserId);
+ if (isErrorResponse(targetUser)) return targetUser;
+
+ if (!(await canBanUser(currentUser, targetUser))) {
+ return NextResponse.json(
+ { error: "Cannot ban this user" },
+ { status: 403 }
+ );
+ }
+
+ const body = await request.json();
+ const { reason, expiresAt } = body;
+
+ if (!reason || typeof reason !== "string" || reason.trim().length === 0) {
+ return NextResponse.json(
+ { error: "Ban reason is required" },
+ { status: 400 }
+ );
+ }
+
+ // Validate expiresAt if provided
+ let banExpiresIn: number | undefined = undefined;
+ if (expiresAt !== null && expiresAt !== undefined) {
+ const expiresDate = new Date(expiresAt);
+ if (isNaN(expiresDate.getTime()) || expiresDate <= new Date()) {
+ return NextResponse.json(
+ { error: "Invalid expiration date (must be in the future)" },
+ { status: 400 }
+ );
+ }
+ banExpiresIn = Math.floor((expiresDate.getTime() - Date.now()) / 1000);
+ }
+
+ await auth.api.banUser({
+ headers: request.headers,
+ body: {
+ userId: targetUserId,
+ banReason: reason,
+ banExpiresIn,
+ },
+ });
+
+ const banExpires = banExpiresIn
+ ? new Date(Date.now() + banExpiresIn * 1000)
+ : null;
+
+ // Audit log
+ await logAuditEvent({
+ action: "admin.user.ban",
+ userId: currentUser.id,
+ resourceType: "user",
+ resourceId: targetUserId,
+ metadata: {
+ targetUser: targetUser.email,
+ reason: reason,
+ expiresAt: banExpires ? banExpires.toISOString() : "permanent",
+ bannedBy: currentUser.email,
+ },
+ request,
+ severity: "warning",
+ isUserVisible: false,
+ });
+
+ return NextResponse.json({
+ success: true,
+ message: "User banned successfully",
+ expiresAt: banExpires,
+ });
+ } catch (error) {
+ console.error("Failed to ban user:", error);
+ return NextResponse.json({ error: "Failed to ban user" }, { status: 500 });
+ }
+}
diff --git a/app/api/admin/users/[id]/password/route.ts b/app/api/admin/users/[id]/password/route.ts
new file mode 100644
index 0000000..f9f090a
--- /dev/null
+++ b/app/api/admin/users/[id]/password/route.ts
@@ -0,0 +1,107 @@
+import { NextRequest, NextResponse } from "next/server";
+import { requireAdmin, canResetPassword } from "@/lib/auth/admin";
+import { logAuditEvent } from "@/lib/audit-log";
+import { rateLimit } from "@/lib/rate-limiter";
+import { auth } from "@/lib/auth";
+import {
+ getValidatedAdminUser,
+ getValidatedTargetUser,
+ isErrorResponse,
+} from "@/lib/auth/admin-helpers";
+
+/**
+ * Admin User Password Reset API
+ *
+ * POST /api/admin/users/[id]/password
+ * Resets a user's password using Better Auth Admin Plugin.
+ *
+ * Body:
+ * - password: string (required) - New password (plain text, will be hashed)
+ *
+ * Permission: Admin or Superadmin
+ * Restrictions:
+ * - Admin can reset regular user passwords only
+ * - Admin cannot reset superadmin passwords
+ * - Cannot reset own password via admin panel (use profile page)
+ */
+
+interface RouteParams {
+ params: Promise<{
+ id: string;
+ }>;
+}
+
+export async function POST(
+ request: NextRequest,
+ { params }: RouteParams
+): Promise<NextResponse> {
+ try {
+ const { id: targetUserId } = await params;
+ const currentUser = await getValidatedAdminUser(request);
+ if (isErrorResponse(currentUser)) return currentUser;
+
+ requireAdmin(currentUser);
+
+ // Rate limiting: admin-password-reset (stricter limit)
+ const rateLimitResponse = rateLimit(
+ request,
+ currentUser.id,
+ "admin-password-reset"
+ );
+ if (rateLimitResponse) return rateLimitResponse;
+
+ const targetUser = await getValidatedTargetUser(targetUserId);
+ if (isErrorResponse(targetUser)) return targetUser;
+
+ if (!(await canResetPassword(currentUser, targetUser))) {
+ return NextResponse.json(
+ { error: "Insufficient permissions to reset this user's password" },
+ { status: 403 }
+ );
+ }
+
+ const body = await request.json();
+ const { password } = body;
+
+ if (!password || typeof password !== "string" || password.length < 8) {
+ return NextResponse.json(
+ { error: "Password must be at least 8 characters long" },
+ { status: 400 }
+ );
+ }
+
+ await auth.api.setUserPassword({
+ headers: request.headers,
+ body: {
+ userId: targetUserId,
+ newPassword: password,
+ },
+ });
+
+ // Audit log
+ await logAuditEvent({
+ action: "admin.user.password_reset",
+ userId: currentUser.id,
+ resourceType: "user",
+ resourceId: targetUserId,
+ metadata: {
+ targetUser: targetUser.email,
+ resetBy: currentUser.email,
+ },
+ request,
+ severity: "warning",
+ isUserVisible: false,
+ });
+
+ return NextResponse.json({
+ success: true,
+ message: "Password reset successfully",
+ });
+ } catch (error) {
+ console.error("Failed to reset password:", error);
+ return NextResponse.json(
+ { error: "Failed to reset password" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/api/admin/users/[id]/route.ts b/app/api/admin/users/[id]/route.ts
new file mode 100644
index 0000000..86a7909
--- /dev/null
+++ b/app/api/admin/users/[id]/route.ts
@@ -0,0 +1,387 @@
+import { NextRequest, NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import {
+ user as userTable,
+ account as accountTable,
+ session as sessionTable,
+ calendars as calendarsTable,
+ calendarShares as calendarSharesTable,
+ userCalendarSubscriptions as userCalendarSubscriptionsTable,
+} from "@/lib/db/schema";
+import { eq, or, sql } from "drizzle-orm";
+import {
+ requireAdmin,
+ requireSuperAdmin,
+ canEditUser,
+ canDeleteUser,
+ canChangeUserRole,
+} from "@/lib/auth/admin";
+import { logAuditEvent } from "@/lib/audit-log";
+import { rateLimit } from "@/lib/rate-limiter";
+import { auth } from "@/lib/auth";
+import {
+ getValidatedAdminUser,
+ getValidatedTargetUser,
+ isErrorResponse,
+} from "@/lib/auth/admin-helpers";
+
+/**
+ * Admin User Detail API
+ *
+ * GET /api/admin/users/[id]
+ * Returns detailed information about a specific user.
+ *
+ * PATCH /api/admin/users/[id]
+ * Updates user information (name, email, role).
+ * - Superadmin: Can update any user (including role)
+ * - Admin: Can update regular users only (no role change)
+ *
+ * DELETE /api/admin/users/[id]
+ * Deletes user and all associated data.
+ * - Superadmin only
+ * - Cannot delete self
+ *
+ * Permission: Admin or Superadmin (role-based restrictions apply)
+ */
+
+interface RouteParams {
+ params: Promise<{
+ id: string;
+ }>;
+}
+
+export async function GET(
+ request: NextRequest,
+ { params }: RouteParams
+): Promise<NextResponse> {
+ try {
+ const { id: targetUserId } = await params;
+ const currentUser = await getValidatedAdminUser(request);
+ if (isErrorResponse(currentUser)) return currentUser;
+
+ requireAdmin(currentUser);
+
+ const targetUser = await getValidatedTargetUser(targetUserId);
+ if (isErrorResponse(targetUser)) return targetUser;
+
+ // Get owned calendars
+ const ownedCalendars = await db
+ .select({
+ id: calendarsTable.id,
+ name: calendarsTable.name,
+ color: calendarsTable.color,
+ createdAt: calendarsTable.createdAt,
+ })
+ .from(calendarsTable)
+ .where(eq(calendarsTable.ownerId, targetUserId));
+
+ // Get shared calendars (with calendar name and permission)
+ const sharedCalendars = await db
+ .select({
+ id: calendarSharesTable.id,
+ calendarId: calendarSharesTable.calendarId,
+ name: calendarsTable.name,
+ permission: calendarSharesTable.permission,
+ createdAt: calendarSharesTable.createdAt,
+ })
+ .from(calendarSharesTable)
+ .innerJoin(
+ calendarsTable,
+ eq(calendarSharesTable.calendarId, calendarsTable.id)
+ )
+ .where(eq(calendarSharesTable.userId, targetUserId));
+
+ const sharesCount = sharedCalendars.length;
+
+ // Get linked accounts
+ const accounts = await db
+ .select({
+ id: accountTable.id,
+ providerId: accountTable.providerId,
+ createdAt: accountTable.createdAt,
+ })
+ .from(accountTable)
+ .where(eq(accountTable.userId, targetUserId));
+
+ // Get active sessions count
+ const [sessionsCount] = await db
+ .select({
+ count: sql<number>`COUNT(*)`,
+ })
+ .from(sessionTable)
+ .where(eq(sessionTable.userId, targetUserId));
+
+ return NextResponse.json({
+ user: {
+ id: targetUser.id,
+ name: targetUser.name,
+ email: targetUser.email,
+ emailVerified: targetUser.emailVerified,
+ image: targetUser.image,
+ role: targetUser.role || "user",
+ banned: targetUser.banned || false,
+ banReason: targetUser.banReason,
+ banExpires: targetUser.banExpires,
+ createdAt: targetUser.createdAt,
+ updatedAt: targetUser.updatedAt,
+ },
+ calendars: ownedCalendars,
+ sharedCalendars: sharedCalendars.map((share) => ({
+ id: share.calendarId,
+ name: share.name,
+ permission: share.permission,
+ })),
+ sharesCount: sharesCount,
+ accounts,
+ sessionsCount: Number(sessionsCount?.count || 0),
+ });
+ } catch (error) {
+ console.error("Failed to fetch user details:", error);
+ return NextResponse.json(
+ { error: "Failed to fetch user details" },
+ { status: 500 }
+ );
+ }
+}
+
+// PATCH: Update user
+export async function PATCH(
+ request: NextRequest,
+ { params }: RouteParams
+): Promise<NextResponse> {
+ try {
+ const { id: targetUserId } = await params;
+ const currentUser = await getValidatedAdminUser(request);
+ if (isErrorResponse(currentUser)) return currentUser;
+
+ requireAdmin(currentUser);
+
+ // Rate limiting: admin-user-mutations
+ const rateLimitResponse = rateLimit(
+ request,
+ currentUser.id,
+ "admin-user-mutations"
+ );
+ if (rateLimitResponse) return rateLimitResponse;
+
+ const targetUser = await getValidatedTargetUser(targetUserId);
+ if (isErrorResponse(targetUser)) return targetUser;
+
+ if (!(await canEditUser(currentUser, targetUser))) {
+ return NextResponse.json(
+ { error: "Insufficient permissions to edit this user" },
+ { status: 403 }
+ );
+ }
+
+ const body = await request.json();
+ const { name, email, role } = body;
+
+ // Track changes for audit log
+ const changes: string[] = [];
+ const oldValues: Record<string, unknown> = {};
+ const newValues: Record<string, unknown> = {};
+
+ // Check what's changing
+ const hasNameChange = name !== undefined && name !== targetUser.name;
+ const hasEmailChange = email !== undefined && email !== targetUser.email;
+ const hasRoleChange =
+ role !== undefined && role !== (targetUser.role || "user");
+
+ if (hasRoleChange && !(await canChangeUserRole(currentUser, targetUser))) {
+ return NextResponse.json(
+ { error: "Insufficient permissions to change user role" },
+ { status: 403 }
+ );
+ }
+
+ // If no changes, return early
+ if (!hasNameChange && !hasEmailChange && !hasRoleChange) {
+ return NextResponse.json({
+ success: true,
+ message: "No changes to apply",
+ });
+ }
+
+ if (hasNameChange || hasEmailChange) {
+ const updateData: {
+ name?: string;
+ email?: string;
+ updatedAt: Date;
+ } = {
+ updatedAt: new Date(),
+ };
+
+ if (hasNameChange) {
+ updateData.name = name;
+ changes.push("name");
+ oldValues.name = targetUser.name;
+ newValues.name = name;
+ }
+
+ if (hasEmailChange) {
+ // Check if email is already taken
+ const [existingUser] = await db
+ .select()
+ .from(userTable)
+ .where(eq(userTable.email, email))
+ .limit(1);
+
+ if (existingUser && existingUser.id !== targetUserId) {
+ return NextResponse.json(
+ { error: "Email already in use" },
+ { status: 400 }
+ );
+ }
+
+ updateData.email = email;
+ changes.push("email");
+ oldValues.email = targetUser.email;
+ newValues.email = email;
+ }
+
+ await db
+ .update(userTable)
+ .set(updateData)
+ .where(eq(userTable.id, targetUserId));
+ }
+
+ if (hasRoleChange) {
+ await db
+ .update(userTable)
+ .set({
+ role: role,
+ updatedAt: new Date(),
+ })
+ .where(eq(userTable.id, targetUserId));
+
+ changes.push("role");
+ oldValues.role = targetUser.role || "user";
+ newValues.role = role;
+ }
+
+ // Audit log
+ await logAuditEvent({
+ action: "admin.user.update",
+ userId: currentUser.id,
+ resourceType: "user",
+ resourceId: targetUserId,
+ metadata: {
+ targetUser: targetUser.email,
+ changes,
+ oldValues,
+ newValues,
+ updatedBy: currentUser.email,
+ },
+ request,
+ severity: "info",
+ isUserVisible: false,
+ });
+
+ return NextResponse.json({
+ success: true,
+ message: "User updated successfully",
+ changes,
+ });
+ } catch (error) {
+ console.error("Failed to update user:", error);
+ return NextResponse.json(
+ { error: "Failed to update user" },
+ { status: 500 }
+ );
+ }
+}
+
+// DELETE: Delete user
+export async function DELETE(
+ request: NextRequest,
+ { params }: RouteParams
+): Promise<NextResponse> {
+ try {
+ const { id: targetUserId } = await params;
+ const currentUser = await getValidatedAdminUser(request);
+ if (isErrorResponse(currentUser)) return currentUser;
+
+ requireSuperAdmin(currentUser);
+
+ // Rate limiting: admin-user-mutations
+ const rateLimitResponse = rateLimit(
+ request,
+ currentUser.id,
+ "admin-user-mutations"
+ );
+ if (rateLimitResponse) return rateLimitResponse;
+
+ const targetUser = await getValidatedTargetUser(targetUserId);
+ if (isErrorResponse(targetUser)) return targetUser;
+
+ if (!(await canDeleteUser(currentUser, targetUser))) {
+ return NextResponse.json(
+ { error: "Cannot delete this user" },
+ { status: 403 }
+ );
+ }
+
+ // Count calendars before deletion (for audit log)
+ const [calendarCount] = await db
+ .select({
+ count: sql<number>`COUNT(*)`,
+ })
+ .from(calendarsTable)
+ .where(eq(calendarsTable.ownerId, targetUserId));
+
+ const calendarsDeleted = Number(calendarCount?.count || 0);
+
+ await db
+ .delete(calendarSharesTable)
+ .where(
+ or(
+ eq(calendarSharesTable.userId, targetUserId),
+ eq(calendarSharesTable.sharedBy, targetUserId)
+ )
+ );
+
+ await db
+ .delete(userCalendarSubscriptionsTable)
+ .where(eq(userCalendarSubscriptionsTable.userId, targetUserId));
+
+ await db
+ .delete(calendarsTable)
+ .where(eq(calendarsTable.ownerId, targetUserId));
+
+ // Audit log BEFORE deleting user
+ await logAuditEvent({
+ action: "admin.user.delete",
+ userId: currentUser.id,
+ resourceType: "user",
+ resourceId: targetUserId,
+ metadata: {
+ deletedUser: targetUser.email,
+ calendarsDeleted,
+ deletedBy: currentUser.email,
+ },
+ request,
+ severity: "critical",
+ isUserVisible: false,
+ });
+
+ await auth.api.removeUser({
+ headers: request.headers,
+ body: {
+ userId: targetUserId,
+ },
+ });
+
+ return NextResponse.json({
+ success: true,
+ message: "User deleted successfully",
+ calendarsDeleted,
+ });
+ } catch (error) {
+ console.error("Failed to delete user:", error);
+ return NextResponse.json(
+ { error: "Failed to delete user" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/api/admin/users/[id]/unban/route.ts b/app/api/admin/users/[id]/unban/route.ts
new file mode 100644
index 0000000..dbdfb7b
--- /dev/null
+++ b/app/api/admin/users/[id]/unban/route.ts
@@ -0,0 +1,97 @@
+import { NextRequest, NextResponse } from "next/server";
+import { requireSuperAdmin, canBanUser } from "@/lib/auth/admin";
+import { logAuditEvent } from "@/lib/audit-log";
+import { rateLimit } from "@/lib/rate-limiter";
+import { auth } from "@/lib/auth";
+import {
+ getValidatedAdminUser,
+ getValidatedTargetUser,
+ isErrorResponse,
+} from "@/lib/auth/admin-helpers";
+
+/**
+ * Admin User Unban API
+ *
+ * POST /api/admin/users/[id]/unban
+ * Unbans a user from the system.
+ *
+ * Permission: Superadmin only
+ */
+
+interface RouteParams {
+ params: Promise<{
+ id: string;
+ }>;
+}
+
+export async function POST(
+ request: NextRequest,
+ { params }: RouteParams
+): Promise<NextResponse> {
+ try {
+ const { id: targetUserId } = await params;
+ const currentUser = await getValidatedAdminUser(request);
+ if (isErrorResponse(currentUser)) return currentUser;
+
+ requireSuperAdmin(currentUser);
+
+ // Rate limiting: admin-user-mutations
+ const rateLimitResponse = rateLimit(
+ request,
+ currentUser.id,
+ "admin-user-mutations"
+ );
+ if (rateLimitResponse) return rateLimitResponse;
+
+ const targetUser = await getValidatedTargetUser(targetUserId);
+ if (isErrorResponse(targetUser)) return targetUser;
+
+ // Check if user is actually banned
+ if (!targetUser.banned) {
+ return NextResponse.json(
+ { error: "User is not banned" },
+ { status: 400 }
+ );
+ }
+
+ if (!(await canBanUser(currentUser, targetUser))) {
+ return NextResponse.json(
+ { error: "Cannot unban this user" },
+ { status: 403 }
+ );
+ }
+
+ await auth.api.unbanUser({
+ headers: request.headers,
+ body: {
+ userId: targetUserId,
+ },
+ });
+
+ // Audit log
+ await logAuditEvent({
+ action: "admin.user.unban",
+ userId: currentUser.id,
+ resourceType: "user",
+ resourceId: targetUserId,
+ metadata: {
+ targetUser: targetUser.email,
+ unbannedBy: currentUser.email,
+ },
+ request,
+ severity: "info",
+ isUserVisible: false,
+ });
+
+ return NextResponse.json({
+ success: true,
+ message: "User unbanned successfully",
+ });
+ } catch (error) {
+ console.error("Failed to unban user:", error);
+ return NextResponse.json(
+ { error: "Failed to unban user" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/api/admin/users/route.ts b/app/api/admin/users/route.ts
new file mode 100644
index 0000000..39bc2a9
--- /dev/null
+++ b/app/api/admin/users/route.ts
@@ -0,0 +1,156 @@
+import { NextRequest, NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import { user, calendars, session, calendarShares } from "@/lib/db/schema";
+import { sql, eq, desc, and, or } from "drizzle-orm";
+import { requireAdmin } from "@/lib/auth/admin";
+import {
+ getValidatedAdminUser,
+ isErrorResponse,
+} from "@/lib/auth/admin-helpers";
+
+/**
+ * Admin User Management API
+ *
+ * GET /api/admin/users
+ * Lists all users with filtering, sorting, and pagination.
+ *
+ * Query Parameters:
+ * - role: Filter by role (superadmin, admin, user)
+ * - banned: Filter by ban status (true, false)
+ * - search: Search by name or email (case-insensitive)
+ * - sortBy: Sort field (createdAt, name, email, role)
+ * - sortOrder: Sort direction (asc, desc)
+ * - limit: Number of users to return (default: 1000)
+ * - offset: Pagination offset
+ *
+ * Permission: Admin or Superadmin only
+ */
+export async function GET(request: NextRequest) {
+ try {
+ const currentUser = await getValidatedAdminUser(request);
+ if (isErrorResponse(currentUser)) return currentUser;
+
+ requireAdmin(currentUser);
+
+ // Parse query parameters
+ const { searchParams } = new URL(request.url);
+ const roleFilter = searchParams.get("role");
+ const bannedFilter = searchParams.get("banned");
+ const searchQuery = searchParams.get("search");
+ const sortBy = searchParams.get("sortBy") || "createdAt";
+ const sortOrder = searchParams.get("sortOrder") || "desc";
+ const limit = parseInt(searchParams.get("limit") || "1000", 10);
+ const offset = parseInt(searchParams.get("offset") || "0", 10);
+
+ const conditions = [];
+
+ if (roleFilter) {
+ conditions.push(eq(user.role, roleFilter));
+ }
+
+ if (bannedFilter !== null) {
+ const isBanned = bannedFilter === "true";
+ conditions.push(eq(user.banned, isBanned));
+ }
+
+ if (searchQuery) {
+ const searchPattern = `%${searchQuery.toLowerCase()}%`;
+ conditions.push(
+ or(
+ sql`LOWER(${user.email}) LIKE ${searchPattern}`,
+ sql`LOWER(${user.name}) LIKE ${searchPattern}`
+ )
+ );
+ }
+
+ // Apply sorting
+ const sortField =
+ sortBy === "createdAt"
+ ? user.createdAt
+ : sortBy === "name"
+ ? user.name
+ : sortBy === "email"
+ ? user.email
+ : sortBy === "role"
+ ? user.role
+ : user.createdAt;
+
+ const orderByClause = sortOrder === "asc" ? sortField : desc(sortField);
+
+ // Get total count (with filters)
+ const countQuery = db.select({ count: sql<number>`COUNT(*)` }).from(user);
+
+ const [countResult] =
+ conditions.length > 0
+ ? await countQuery.where(and(...conditions))
+ : await countQuery;
+
+ const total = Number(countResult?.count || 0);
+
+ // Get users (with filters, sorting, pagination)
+ const usersQuery = db
+ .select()
+ .from(user)
+ .orderBy(orderByClause)
+ .limit(limit)
+ .offset(offset);
+
+ const users =
+ conditions.length > 0
+ ? await usersQuery.where(and(...conditions))
+ : await usersQuery;
+
+ // Enrich users with calendar count and last activity
+ const enrichedUsers = await Promise.all(
+ users.map(async (u) => {
+ // Count owned calendars
+ const [calendarCount] = await db
+ .select({
+ count: sql<number>`COUNT(*)`,
+ })
+ .from(calendars)
+ .where(eq(calendars.ownerId, u.id));
+
+ // Count shared calendars (via calendarShares)
+ const [sharesCount] = await db
+ .select({
+ count: sql<number>`COUNT(*)`,
+ })
+ .from(calendarShares)
+ .where(eq(calendarShares.userId, u.id));
+
+ // Get last session (most recent activity)
+ const [lastSession] = await db
+ .select({
+ updatedAt: session.updatedAt,
+ })
+ .from(session)
+ .where(eq(session.userId, u.id))
+ .orderBy(desc(session.updatedAt))
+ .limit(1);
+
+ return {
+ ...u,
+ role: u.role || "user",
+ banned: u.banned || false,
+ calendarCount: Number(calendarCount?.count || 0),
+ sharesCount: Number(sharesCount?.count || 0),
+ lastActivity: lastSession?.updatedAt || null,
+ };
+ })
+ );
+
+ return NextResponse.json({
+ users: enrichedUsers,
+ total,
+ limit,
+ offset,
+ });
+ } catch (error) {
+ console.error("Failed to fetch users:", error);
+ return NextResponse.json(
+ { error: "Failed to fetch users" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/api/auth/[...all]/route.ts b/app/api/auth/[...all]/route.ts
new file mode 100644
index 0000000..370f5e6
--- /dev/null
+++ b/app/api/auth/[...all]/route.ts
@@ -0,0 +1,41 @@
+import { auth } from "@/lib/auth";
+import { toNextJsHandler } from "better-auth/next-js";
+import { NextRequest } from "next/server";
+import { rateLimit } from "@/lib/rate-limiter";
+
+/**
+ * Better Auth API route handler with rate limiting
+ *
+ * Note: Audit logging is handled by the auditLogPlugin in lib/auth/audit-plugin.ts
+ * Note: Registration restrictions are handled by Better Auth's disableSignUp config
+ */
+
+const handlers = toNextJsHandler(auth);
+
+// Wrap POST handler for rate limiting
+const originalPost = handlers.POST;
+
+export const POST = async (req: NextRequest) => {
+ const url = new URL(req.url);
+ const pathname = url.pathname;
+
+ // Rate limiting for auth endpoints
+ // Apply different limits for login vs registration
+ const isOAuthCallback =
+ pathname.includes("/callback/") || pathname.endsWith("/sign-in/social");
+ const isRegister =
+ pathname.endsWith("/sign-up/email") || pathname.includes("/register");
+
+ if (!isOAuthCallback) {
+ // Stricter rate limit for registration (3 per 10 min) vs login (5 per 1 min)
+ const rateLimitType = isRegister ? "register" : "auth";
+ const rateLimitResponse = rateLimit(req, null, rateLimitType);
+ if (rateLimitResponse) return rateLimitResponse;
+ }
+
+ // Call original Better Auth handler (audit logging handled by plugin)
+ return await originalPost(req);
+};
+
+// Export GET handler as-is
+export const GET = handlers.GET;
diff --git a/app/api/auth/ban-info/route.ts b/app/api/auth/ban-info/route.ts
new file mode 100644
index 0000000..9ac812c
--- /dev/null
+++ b/app/api/auth/ban-info/route.ts
@@ -0,0 +1,58 @@
+import { NextRequest, NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import { user as userTable } from "@/lib/db/schema";
+import { eq } from "drizzle-orm";
+
+/**
+ * Public API to get ban information for a banned user
+ *
+ * POST /api/auth/ban-info
+ * Body: { email: string }
+ *
+ * Returns ban details if user is banned, otherwise returns 404.
+ * This is a public endpoint to show ban info on login page.
+ */
+export async function POST(request: NextRequest): Promise<NextResponse> {
+ try {
+ const body = await request.json();
+ const { email } = body;
+
+ if (!email || typeof email !== "string") {
+ return NextResponse.json({ error: "Email is required" }, { status: 400 });
+ }
+
+ // Find user by email
+ const [user] = await db
+ .select({
+ banned: userTable.banned,
+ banReason: userTable.banReason,
+ banExpires: userTable.banExpires,
+ })
+ .from(userTable)
+ .where(eq(userTable.email, email))
+ .limit(1);
+
+ if (!user) {
+ return NextResponse.json({ error: "User not found" }, { status: 404 });
+ }
+
+ if (!user.banned) {
+ return NextResponse.json(
+ { error: "User is not banned" },
+ { status: 404 }
+ );
+ }
+
+ return NextResponse.json({
+ banned: true,
+ banReason: user.banReason,
+ banExpires: user.banExpires,
+ });
+ } catch (error) {
+ console.error("Failed to fetch ban info:", error);
+ return NextResponse.json(
+ { error: "Failed to fetch ban info" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/api/auth/change-password/route.ts b/app/api/auth/change-password/route.ts
new file mode 100644
index 0000000..33d64c3
--- /dev/null
+++ b/app/api/auth/change-password/route.ts
@@ -0,0 +1,136 @@
+import { NextRequest, NextResponse } from "next/server";
+import { auth } from "@/lib/auth";
+import { db } from "@/lib/db";
+import {
+ account as accountTable,
+ session as sessionTable,
+} from "@/lib/db/schema";
+import { eq, and, ne } from "drizzle-orm";
+import { hashPassword, verifyPassword } from "better-auth/crypto";
+import { rateLimit } from "@/lib/rate-limiter";
+import { logUserAction, type PasswordChangedMetadata } from "@/lib/audit-log";
+
+/**
+ * Change user password endpoint
+ *
+ * POST /api/auth/change-password
+ * Body: { currentPassword: string, newPassword: string }
+ */
+export async function POST(req: NextRequest) {
+ try {
+ // Get current session
+ const session = await auth.api.getSession({
+ headers: req.headers,
+ });
+
+ if (!session?.user) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ // Rate limiting check
+ const rateLimitResponse = rateLimit(
+ req,
+ session.user.id,
+ "password-change"
+ );
+ if (rateLimitResponse) return rateLimitResponse;
+
+ const body = await req.json();
+ const { currentPassword, newPassword } = body;
+
+ // Validation
+ if (!currentPassword || !newPassword) {
+ return NextResponse.json(
+ { error: "Current password and new password are required" },
+ { status: 400 }
+ );
+ }
+
+ if (newPassword.length < 8) {
+ return NextResponse.json(
+ { error: "New password must be at least 8 characters long" },
+ { status: 400 }
+ );
+ }
+
+ // Get user's current password from account table
+ const userAccounts = await db.query.account.findMany({
+ where: (accounts, { eq, and }) =>
+ and(
+ eq(accounts.userId, session.user.id),
+ eq(accounts.providerId, "credential")
+ ),
+ });
+
+ if (userAccounts.length === 0) {
+ return NextResponse.json(
+ { error: "No password set for this account" },
+ { status: 400 }
+ );
+ }
+
+ const account = userAccounts[0];
+
+ // Verify current password using Better Auth's password verification
+ const isPasswordValid = await verifyPassword({
+ password: currentPassword,
+ hash: account.password!,
+ });
+
+ if (!isPasswordValid) {
+ return NextResponse.json(
+ { error: "Current password is incorrect" },
+ { status: 400 }
+ );
+ }
+
+ // Hash new password using Better Auth's password hashing
+ const newPasswordHash = await hashPassword(newPassword);
+
+ // Update password in account table
+ await db
+ .update(accountTable)
+ .set({ password: newPasswordHash })
+ .where(
+ and(
+ eq(accountTable.userId, session.user.id),
+ eq(accountTable.providerId, "credential")
+ )
+ );
+
+ // Revoke all other sessions (keep current session active)
+ const revokedSessions = await db
+ .delete(sessionTable)
+ .where(
+ and(
+ eq(sessionTable.userId, session.user.id),
+ ne(sessionTable.token, session.session.token)
+ )
+ )
+ .returning();
+
+ // Log password change event
+ await logUserAction<PasswordChangedMetadata>({
+ action: "auth.password.changed",
+ userId: session.user.id,
+ resourceType: "user",
+ resourceId: session.user.id,
+ metadata: {
+ sessionsRevoked: revokedSessions.length,
+ },
+ request: req,
+ });
+
+ return NextResponse.json({
+ success: true,
+ message: "Password changed successfully",
+ sessionsRevoked: revokedSessions.length,
+ });
+ } catch (error) {
+ console.error("Error changing password:", error);
+ return NextResponse.json(
+ { error: "Failed to change password" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/api/auth/delete-account/route.ts b/app/api/auth/delete-account/route.ts
new file mode 100644
index 0000000..b46dd61
--- /dev/null
+++ b/app/api/auth/delete-account/route.ts
@@ -0,0 +1,137 @@
+import { NextRequest, NextResponse } from "next/server";
+import { auth } from "@/lib/auth";
+import { db } from "@/lib/db";
+import {
+ user as userTable,
+ account as accountTable,
+ session as sessionTable,
+ calendars as calendarsTable,
+ calendarShares as calendarSharesTable,
+ userCalendarSubscriptions as userCalendarSubscriptionsTable,
+} from "@/lib/db/schema";
+import { eq, or } from "drizzle-orm";
+import { verifyPassword } from "better-auth/crypto";
+import { rateLimit } from "@/lib/rate-limiter";
+import { logUserAction, type AccountDeletedMetadata } from "@/lib/audit-log";
+
+/**
+ * Delete user account endpoint
+ *
+ * DELETE /api/auth/delete-account
+ * Body: { password?: string } (required if user has password-based login)
+ *
+ * Deletes user account and all associated data in the correct order:
+ * 1. Calendar shares (where user is participant or sharer)
+ * 2. Calendar subscriptions
+ * 3. Owned calendars (cascade deletes shifts, presets, notes, external syncs)
+ * 4. Sessions
+ * 5. Linked accounts (OAuth, credential)
+ * 6. User record
+ */
+export async function DELETE(req: NextRequest) {
+ try {
+ // Get current session
+ const session = await auth.api.getSession({
+ headers: req.headers,
+ });
+
+ if (!session?.user) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ // Rate limiting check
+ const rateLimitResponse = rateLimit(req, session.user.id, "account-delete");
+ if (rateLimitResponse) return rateLimitResponse;
+
+ const userId = session.user.id;
+
+ // Check if user has password-based login
+ const credentialAccounts = await db.query.account.findMany({
+ where: (accounts, { eq, and }) =>
+ and(eq(accounts.userId, userId), eq(accounts.providerId, "credential")),
+ });
+
+ // If user has password, require password confirmation
+ if (credentialAccounts.length > 0) {
+ const body = await req.json();
+ const { password } = body;
+
+ if (!password) {
+ return NextResponse.json(
+ { error: "Password confirmation required" },
+ { status: 400 }
+ );
+ }
+
+ const account = credentialAccounts[0];
+
+ // Verify password using Better Auth's password verification
+ const isPasswordValid = await verifyPassword({
+ password: password,
+ hash: account.password!,
+ });
+
+ if (!isPasswordValid) {
+ return NextResponse.json(
+ { error: "Incorrect password" },
+ { status: 401 }
+ );
+ }
+ }
+
+ // Delete in the correct order to avoid foreign key constraint violations
+
+ // 1. Delete calendar shares where user is sharer OR shared with
+ await db
+ .delete(calendarSharesTable)
+ .where(
+ or(
+ eq(calendarSharesTable.userId, userId),
+ eq(calendarSharesTable.sharedBy, userId)
+ )
+ );
+
+ // 2. Delete user's calendar subscriptions
+ await db
+ .delete(userCalendarSubscriptionsTable)
+ .where(eq(userCalendarSubscriptionsTable.userId, userId));
+
+ // 3. Delete user's calendars (cascade will delete shifts, presets, notes, external syncs)
+ const deletedCalendars = await db
+ .delete(calendarsTable)
+ .where(eq(calendarsTable.ownerId, userId))
+ .returning();
+
+ // Log account deletion event BEFORE deleting the user
+ await logUserAction<AccountDeletedMetadata>({
+ action: "auth.account.deleted",
+ userId: userId,
+ resourceType: "user",
+ resourceId: userId,
+ metadata: {
+ calendarsDeleted: deletedCalendars.length,
+ },
+ request: req,
+ });
+
+ // 4. Delete user's sessions
+ await db.delete(sessionTable).where(eq(sessionTable.userId, userId));
+
+ // 5. Delete user's accounts (OAuth + credential)
+ await db.delete(accountTable).where(eq(accountTable.userId, userId));
+
+ // 6. Delete user record
+ await db.delete(userTable).where(eq(userTable.id, userId));
+
+ return NextResponse.json({
+ success: true,
+ message: "Account deleted successfully",
+ });
+ } catch (error) {
+ console.error("Error deleting account:", error);
+ return NextResponse.json(
+ { error: "Failed to delete account" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/api/auth/sessions/route.ts b/app/api/auth/sessions/route.ts
new file mode 100644
index 0000000..d0ef2a9
--- /dev/null
+++ b/app/api/auth/sessions/route.ts
@@ -0,0 +1,72 @@
+import { NextRequest, NextResponse } from "next/server";
+import { getUserSessions, revokeAllSessions } from "@/lib/auth/sessions";
+import { logAuditEvent } from "@/lib/audit-log";
+import { isAuthEnabled } from "@/lib/auth/feature-flags";
+import { auth } from "@/lib/auth";
+
+/**
+ * GET /api/auth/sessions
+ * List all active sessions for the current user
+ */
+export async function GET(request: NextRequest) {
+ if (!isAuthEnabled()) {
+ return NextResponse.json(
+ { error: "Authentication is disabled" },
+ { status: 403 }
+ );
+ }
+
+ // Get current session with Better Auth API
+ const sessionData = await auth.api.getSession({ headers: request.headers });
+ if (!sessionData?.user) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ const sessions = await getUserSessions(sessionData.user.id);
+
+ return NextResponse.json({ sessions });
+}
+
+/**
+ * DELETE /api/auth/sessions
+ * Revoke all sessions except the current one (logout from all devices)
+ */
+export async function DELETE(request: NextRequest) {
+ if (!isAuthEnabled()) {
+ return NextResponse.json(
+ { error: "Authentication is disabled" },
+ { status: 403 }
+ );
+ }
+
+ // Get current session with Better Auth API (includes session ID)
+ const sessionData = await auth.api.getSession({ headers: request.headers });
+ if (!sessionData?.user) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ const revokedCount = await revokeAllSessions(
+ sessionData.user.id,
+ sessionData.session.id
+ );
+
+ // Log audit event
+ await logAuditEvent({
+ action: "auth.session.revoked",
+ userId: sessionData.user.id,
+ resourceType: "session",
+ metadata: {
+ revokedBy: "user",
+ count: revokedCount,
+ },
+ request,
+ severity: "warning",
+ isUserVisible: true,
+ });
+
+ return NextResponse.json({
+ success: true,
+ revokedCount,
+ message: `Logged out from ${revokedCount} device(s)`,
+ });
+}
diff --git a/app/api/auth/upload-avatar/route.ts b/app/api/auth/upload-avatar/route.ts
new file mode 100644
index 0000000..788a054
--- /dev/null
+++ b/app/api/auth/upload-avatar/route.ts
@@ -0,0 +1,76 @@
+import { NextRequest, NextResponse } from "next/server";
+import { writeFile, mkdir } from "fs/promises";
+import { join } from "path";
+import { existsSync } from "fs";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { rateLimit } from "@/lib/rate-limiter";
+
+const UPLOAD_DIR = join(process.cwd(), "public", "uploads", "avatars");
+const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB
+const ALLOWED_TYPES = ["image/jpeg", "image/png", "image/gif", "image/webp"];
+
+export async function POST(request: NextRequest) {
+ try {
+ const user = await getSessionUser(request.headers);
+
+ if (!user) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ // Rate limiting check
+ const rateLimitResponse = rateLimit(request, user.id, "upload-avatar");
+ if (rateLimitResponse) return rateLimitResponse;
+
+ const formData = await request.formData();
+ const file = formData.get("file") as File;
+
+ if (!file) {
+ return NextResponse.json({ error: "No file provided" }, { status: 400 });
+ }
+
+ // Validate file type
+ if (!ALLOWED_TYPES.includes(file.type)) {
+ return NextResponse.json(
+ {
+ error:
+ "Invalid file type. Only JPEG, PNG, GIF, and WebP are allowed.",
+ },
+ { status: 400 }
+ );
+ }
+
+ // Validate file size
+ if (file.size > MAX_FILE_SIZE) {
+ return NextResponse.json(
+ { error: "File too large. Maximum size is 5MB." },
+ { status: 400 }
+ );
+ }
+
+ // Ensure upload directory exists
+ if (!existsSync(UPLOAD_DIR)) {
+ await mkdir(UPLOAD_DIR, { recursive: true });
+ }
+
+ // Generate unique filename
+ const fileExtension = file.name.split(".").pop();
+ const fileName = `${user.id}-${Date.now()}.${fileExtension}`;
+ const filePath = join(UPLOAD_DIR, fileName);
+
+ // Save file
+ const bytes = await file.arrayBuffer();
+ const buffer = Buffer.from(bytes);
+ await writeFile(filePath, buffer);
+
+ // Return public URL
+ const url = `/uploads/avatars/${fileName}`;
+
+ return NextResponse.json({ url }, { status: 200 });
+ } catch (error) {
+ console.error("Avatar upload error:", error);
+ return NextResponse.json(
+ { error: "Failed to upload avatar" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/api/calendars/[id]/export/ics/route.ts b/app/api/calendars/[id]/export/ics/route.ts
index 80f190c..02d8c4a 100644
--- a/app/api/calendars/[id]/export/ics/route.ts
+++ b/app/api/calendars/[id]/export/ics/route.ts
@@ -2,8 +2,9 @@ import { NextResponse } from "next/server";
import { db } from "@/lib/db";
import { calendars, shifts } from "@/lib/db/schema";
import { eq } from "drizzle-orm";
-import { verifyPassword } from "@/lib/password-utils";
import ICAL from "ical.js";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { canViewCalendar } from "@/lib/auth/permissions";
export async function GET(
request: Request,
@@ -11,8 +12,7 @@ export async function GET(
) {
try {
const { id } = await params;
- const { searchParams } = new URL(request.url);
- const password = searchParams.get("password");
+ const user = await getSessionUser(request.headers);
// Get calendar
const calendar = await db.query.calendars.findFirst({
@@ -26,14 +26,13 @@ export async function GET(
);
}
- // Check password protection
- if (calendar.passwordHash && calendar.isLocked) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check read permission (works for both authenticated users and guests)
+ const hasAccess = await canViewCalendar(user?.id, id);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
}
// Get all shifts for this calendar
diff --git a/app/api/calendars/[id]/export/pdf/route.ts b/app/api/calendars/[id]/export/pdf/route.ts
index b8508a6..bb8bf5c 100644
--- a/app/api/calendars/[id]/export/pdf/route.ts
+++ b/app/api/calendars/[id]/export/pdf/route.ts
@@ -1,18 +1,25 @@
-import { NextResponse } from "next/server";
+import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { calendars, shifts } from "@/lib/db/schema";
import { eq } from "drizzle-orm";
-import { verifyPassword } from "@/lib/password-utils";
import { jsPDF } from "jspdf";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { canViewCalendar } from "@/lib/auth/permissions";
+import { rateLimit } from "@/lib/rate-limiter";
export async function GET(
- request: Request,
+ request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params;
+ const user = await getSessionUser(request.headers);
+
+ // Rate limiting: 10 PDF exports per 10 minutes
+ const rateLimitResponse = rateLimit(request, user?.id, "export-pdf");
+ if (rateLimitResponse) return rateLimitResponse;
+
const { searchParams } = new URL(request.url);
- const password = searchParams.get("password");
const month = searchParams.get("month"); // Format: YYYY-MM
const year = searchParams.get("year"); // Format: YYYY
const locale = searchParams.get("locale") || "en"; // Default to English
@@ -29,14 +36,13 @@ export async function GET(
);
}
- // Check password protection
- if (calendar.passwordHash && calendar.isLocked) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check read permission (works for both authenticated users and guests)
+ const hasAccess = await canViewCalendar(user?.id, id);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
}
// Get all shifts for this calendar
diff --git a/app/api/calendars/[id]/route.ts b/app/api/calendars/[id]/route.ts
index 3cbe1a7..0ebf9f2 100644
--- a/app/api/calendars/[id]/route.ts
+++ b/app/api/calendars/[id]/route.ts
@@ -1,18 +1,33 @@
-import { NextResponse } from "next/server";
+import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
-import { calendars, shifts } from "@/lib/db/schema";
-import { eq } from "drizzle-orm";
-import { hashPassword, verifyPassword } from "@/lib/password-utils";
+import {
+ calendars,
+ shifts,
+ shiftPresets,
+ calendarNotes,
+} from "@/lib/db/schema";
+import { eq, sql } from "drizzle-orm";
+import { getSessionUser } from "@/lib/auth/sessions";
+import {
+ canViewCalendar,
+ canManageCalendar,
+ canDeleteCalendar,
+} from "@/lib/auth/permissions";
+import {
+ logUserAction,
+ type CalendarUpdatedMetadata,
+ type CalendarDeletedMetadata,
+ type CalendarGuestPermissionChangedMetadata,
+} from "@/lib/audit-log";
// GET single calendar
export async function GET(
- request: Request,
+ request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params;
- const { searchParams } = new URL(request.url);
- const password = searchParams.get("password");
+ const user = await getSessionUser(request.headers);
const [calendar] = await db
.select()
@@ -26,14 +41,13 @@ export async function GET(
);
}
- // Verify password if calendar is protected AND locked
- if (calendar.passwordHash && calendar.isLocked) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check read permission (works for both authenticated users and guests)
+ const hasAccess = await canViewCalendar(user?.id, id);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
}
const calendarShifts = await db
@@ -52,17 +66,18 @@ export async function GET(
}
}
-// PATCH update calendar
+// PATCH update calendar (requires admin permission)
export async function PATCH(
- request: Request,
+ request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params;
+ const user = await getSessionUser(request.headers);
const body = await request.json();
- const { name, color, password, currentPassword, isLocked } = body;
+ const { name, color, guestPermission } = body;
- // Fetch current calendar to check password
+ // Fetch current calendar
const [existingCalendar] = await db
.select()
.from(calendars)
@@ -75,38 +90,39 @@ export async function PATCH(
);
}
- // Always verify password if calendar is protected
- if (existingCalendar.passwordHash) {
- if (
- !currentPassword ||
- !verifyPassword(currentPassword, existingCalendar.passwordHash)
- ) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check admin permission (works for both authenticated users and guests)
+ const hasAccess = await canManageCalendar(user?.id, id);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions. Admin access required." },
+ { status: 403 }
+ );
}
const updateData: Partial<typeof calendars.$inferInsert> = {};
- if (name) updateData.name = name;
- if (color) updateData.color = color;
- if (password !== undefined) {
- updateData.passwordHash = password ? hashPassword(password) : null;
- // If removing password, also unlock calendar
- if (password === null) {
- updateData.isLocked = false;
- }
+ const changes: string[] = [];
+ let guestPermissionChanged = false;
+ let oldGuestPermission: string | undefined;
+
+ if (name && name !== existingCalendar.name) {
+ updateData.name = name;
+ changes.push("name");
+ }
+ if (color && color !== existingCalendar.color) {
+ updateData.color = color;
+ changes.push("color");
}
- if (isLocked !== undefined) {
- // Only allow locking if password exists or is being set
- if (isLocked && !existingCalendar.passwordHash && !password) {
- return NextResponse.json(
- { error: "Cannot lock calendar without password" },
- { status: 400 }
- );
+ if (
+ guestPermission !== undefined &&
+ guestPermission !== existingCalendar.guestPermission
+ ) {
+ // Validate guest permission value
+ if (["none", "read", "write"].includes(guestPermission)) {
+ updateData.guestPermission = guestPermission;
+ changes.push("guestPermission");
+ guestPermissionChanged = true;
+ oldGuestPermission = existingCalendar.guestPermission;
}
- updateData.isLocked = isLocked;
}
const [calendar] = await db
@@ -115,6 +131,43 @@ export async function PATCH(
.where(eq(calendars.id, id))
.returning();
+ // Log calendar update event if there were actual changes
+ if (user && changes.length > 0) {
+ await logUserAction<CalendarUpdatedMetadata>({
+ action: "calendar.updated",
+ userId: user.id,
+ resourceType: "calendar",
+ resourceId: calendar.id,
+ metadata: {
+ calendarName: calendar.name,
+ changes,
+ },
+ request,
+ });
+
+ // Log separate event for guest permission changes
+ if (guestPermissionChanged) {
+ await logUserAction<CalendarGuestPermissionChangedMetadata>({
+ action: "calendar.guest_permission.changed",
+ userId: user.id,
+ resourceType: "calendar",
+ resourceId: calendar.id,
+ metadata: {
+ calendarName: calendar.name,
+ oldPermission: (oldGuestPermission || "none") as
+ | "none"
+ | "read"
+ | "write",
+ newPermission: calendar.guestPermission as
+ | "none"
+ | "read"
+ | "write",
+ },
+ request,
+ });
+ }
+ }
+
return NextResponse.json(calendar);
} catch (error) {
console.error("Failed to update calendar:", error);
@@ -125,28 +178,16 @@ export async function PATCH(
}
}
-// DELETE calendar
+// DELETE calendar (requires owner permission)
export async function DELETE(
- request: Request,
+ request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params;
+ const user = await getSessionUser(request.headers);
- // Read password from request body
- let password: string | null = null;
- const contentType = request.headers.get("content-type");
-
- if (contentType?.includes("application/json")) {
- try {
- const body = await request.json();
- password = body.password || null;
- } catch {
- // If body parsing fails, continue with null password
- }
- }
-
- // Fetch calendar to check password
+ // Fetch calendar
const [calendar] = await db
.select()
.from(calendars)
@@ -159,18 +200,45 @@ export async function DELETE(
);
}
- // Verify password if calendar is protected
- if (calendar.passwordHash) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check owner permission (works for both authenticated users and guests)
+ const hasAccess = await canDeleteCalendar(user?.id, id);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions. Owner access required." },
+ { status: 403 }
+ );
}
+ // Count related records before deletion
+ const [{ shiftsCount, presetsCount, notesCount }] = await db
+ .select({
+ shiftsCount: sql<number>`(SELECT COUNT(*) FROM ${shifts} WHERE ${shifts.calendarId} = ${calendar.id})`,
+ presetsCount: sql<number>`(SELECT COUNT(*) FROM ${shiftPresets} WHERE ${shiftPresets.calendarId} = ${calendar.id})`,
+ notesCount: sql<number>`(SELECT COUNT(*) FROM ${calendarNotes} WHERE ${calendarNotes.calendarId} = ${calendar.id})`,
+ })
+ .from(calendars)
+ .where(eq(calendars.id, id));
+
+ // Delete calendar (cascade will delete related records)
await db.delete(calendars).where(eq(calendars.id, id));
+ // Log calendar deletion event
+ if (user) {
+ await logUserAction<CalendarDeletedMetadata>({
+ action: "calendar.deleted",
+ userId: user.id,
+ resourceType: "calendar",
+ resourceId: calendar.id,
+ metadata: {
+ calendarName: calendar.name,
+ shiftsDeleted: shiftsCount,
+ presetsDeleted: presetsCount,
+ notesDeleted: notesCount,
+ },
+ request,
+ });
+ }
+
return NextResponse.json({ success: true });
} catch (error) {
console.error("Failed to delete calendar:", error);
diff --git a/app/api/calendars/[id]/shares/[shareId]/route.ts b/app/api/calendars/[id]/shares/[shareId]/route.ts
new file mode 100644
index 0000000..d658bf0
--- /dev/null
+++ b/app/api/calendars/[id]/shares/[shareId]/route.ts
@@ -0,0 +1,236 @@
+import { NextRequest, NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import { calendarShares, calendars } from "@/lib/db/schema";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { checkPermission } from "@/lib/auth/permissions";
+import { eq, and } from "drizzle-orm";
+import { logAuditEvent } from "@/lib/audit-log";
+
+export async function PUT(
+ request: NextRequest,
+ { params }: { params: Promise<{ id: string; shareId: string }> }
+) {
+ try {
+ const { id: calendarId, shareId } = await params;
+ const user = await getSessionUser(request.headers);
+
+ if (!user) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ // Check if user has admin/owner permission
+ const hasPermission = await checkPermission(user.id, calendarId, "admin");
+ if (!hasPermission) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
+ }
+
+ const body = await request.json();
+ const { permission } = body;
+
+ // Validate permission value
+ const validPermissions = ["owner", "admin", "write", "read"];
+ if (!validPermissions.includes(permission)) {
+ return NextResponse.json(
+ { error: "Invalid permission value" },
+ { status: 400 }
+ );
+ }
+
+ // Only owner can set/change admin permissions
+ if (permission === "admin") {
+ const isOwner = await checkPermission(user.id, calendarId, "owner");
+ if (!isOwner) {
+ return NextResponse.json(
+ { error: "Only the owner can grant admin permissions" },
+ { status: 403 }
+ );
+ }
+ }
+
+ // Fetch existing share
+ const existingShare = await db.query.calendarShares.findFirst({
+ where: and(
+ eq(calendarShares.id, shareId),
+ eq(calendarShares.calendarId, calendarId)
+ ),
+ with: {
+ user: {
+ columns: {
+ email: true,
+ name: true,
+ },
+ },
+ },
+ });
+
+ if (!existingShare) {
+ return NextResponse.json({ error: "Share not found" }, { status: 404 });
+ }
+
+ // Only owner can modify admin permissions
+ if (existingShare.permission === "admin") {
+ const isOwner = await checkPermission(user.id, calendarId, "owner");
+ if (!isOwner) {
+ return NextResponse.json(
+ { error: "Only the owner can modify admin permissions" },
+ { status: 403 }
+ );
+ }
+ }
+
+ // Store old permission for audit log
+ const oldPermission = existingShare.permission;
+
+ // Update share permission
+ await db
+ .update(calendarShares)
+ .set({ permission })
+ .where(eq(calendarShares.id, shareId));
+
+ // Fetch calendar name for audit log
+ const calendar = await db.query.calendars.findFirst({
+ where: eq(calendars.id, calendarId),
+ columns: { name: true },
+ });
+
+ // Log audit event
+ await logAuditEvent({
+ userId: user.id,
+ action: "calendar.permission.changed",
+ severity: "info",
+ request,
+ metadata: {
+ calendarId,
+ calendarName: calendar?.name || "Unknown",
+ user:
+ existingShare.user.email ||
+ existingShare.user.name ||
+ existingShare.userId,
+ oldPermission,
+ newPermission: permission,
+ },
+ });
+
+ // Fetch updated share with relations
+ const shareWithUser = await db.query.calendarShares.findFirst({
+ where: eq(calendarShares.id, shareId),
+ with: {
+ user: {
+ columns: {
+ id: true,
+ name: true,
+ email: true,
+ image: true,
+ },
+ },
+ sharedByUser: {
+ columns: {
+ id: true,
+ name: true,
+ email: true,
+ },
+ },
+ },
+ });
+
+ return NextResponse.json(shareWithUser);
+ } catch (error) {
+ console.error("Failed to update calendar share:", error);
+ return NextResponse.json(
+ { error: "Failed to update share" },
+ { status: 500 }
+ );
+ }
+}
+
+export async function DELETE(
+ request: NextRequest,
+ { params }: { params: Promise<{ id: string; shareId: string }> }
+) {
+ try {
+ const { id: calendarId, shareId } = await params;
+ const user = await getSessionUser(request.headers);
+
+ if (!user) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ // Fetch the share first
+ const share = await db.query.calendarShares.findFirst({
+ where: and(
+ eq(calendarShares.id, shareId),
+ eq(calendarShares.calendarId, calendarId)
+ ),
+ with: {
+ user: {
+ columns: {
+ email: true,
+ name: true,
+ },
+ },
+ },
+ });
+
+ if (!share) {
+ return NextResponse.json({ error: "Share not found" }, { status: 404 });
+ }
+
+ // Check permissions: owner can remove any share, admin can remove non-admin shares, users can remove their own
+ const hasAdminPermission = await checkPermission(
+ user.id,
+ calendarId,
+ "admin"
+ );
+ const isOwner = await checkPermission(user.id, calendarId, "owner");
+ const isSelf = share.userId === user.id;
+
+ // Only owner can remove admin shares
+ if (share.permission === "admin" && !isOwner) {
+ return NextResponse.json(
+ { error: "Only the owner can remove admin shares" },
+ { status: 403 }
+ );
+ }
+
+ if (!hasAdminPermission && !isSelf) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
+ }
+
+ // Fetch calendar name for audit log
+ const calendar = await db.query.calendars.findFirst({
+ where: eq(calendars.id, calendarId),
+ columns: { name: true },
+ });
+
+ // Delete share
+ await db.delete(calendarShares).where(eq(calendarShares.id, shareId));
+
+ // Log audit event
+ await logAuditEvent({
+ userId: user.id,
+ action: "calendar.share.removed",
+ severity: "info",
+ request,
+ metadata: {
+ calendarId,
+ calendarName: calendar?.name || "Unknown",
+ removedUser: share.user.email || share.user.name || share.userId,
+ removedBy: isSelf ? "self" : hasAdminPermission ? "admin" : "owner",
+ },
+ });
+
+ return NextResponse.json({ success: true });
+ } catch (error) {
+ console.error("Failed to delete calendar share:", error);
+ return NextResponse.json(
+ { error: "Failed to delete share" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/api/calendars/[id]/shares/route.ts b/app/api/calendars/[id]/shares/route.ts
new file mode 100644
index 0000000..d4c1b9a
--- /dev/null
+++ b/app/api/calendars/[id]/shares/route.ts
@@ -0,0 +1,223 @@
+import { NextRequest, NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import {
+ calendarShares,
+ calendars,
+ userCalendarSubscriptions,
+} from "@/lib/db/schema";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { checkPermission } from "@/lib/auth/permissions";
+import { eq, and } from "drizzle-orm";
+import { logAuditEvent } from "@/lib/audit-log";
+
+export async function GET(
+ request: NextRequest,
+ { params }: { params: Promise<{ id: string }> }
+) {
+ try {
+ const { id: calendarId } = await params;
+ const user = await getSessionUser(request.headers);
+
+ // Check if user has admin/owner permission
+ const hasPermission = await checkPermission(user?.id, calendarId, "admin");
+ if (!hasPermission) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
+ }
+
+ // Fetch all shares for this calendar
+ const shares = await db.query.calendarShares.findMany({
+ where: eq(calendarShares.calendarId, calendarId),
+ with: {
+ user: {
+ columns: {
+ id: true,
+ name: true,
+ email: true,
+ image: true,
+ },
+ },
+ sharedByUser: {
+ columns: {
+ id: true,
+ name: true,
+ email: true,
+ },
+ },
+ },
+ orderBy: (shares, { desc }) => [desc(shares.createdAt)],
+ });
+
+ return NextResponse.json(shares);
+ } catch (error) {
+ console.error("Failed to fetch calendar shares:", error);
+ return NextResponse.json(
+ { error: "Failed to fetch shares" },
+ { status: 500 }
+ );
+ }
+}
+
+export async function POST(
+ request: NextRequest,
+ { params }: { params: Promise<{ id: string }> }
+) {
+ try {
+ const { id: calendarId } = await params;
+ const user = await getSessionUser(request.headers);
+
+ if (!user) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ // Check if user has admin/owner permission
+ const hasPermission = await checkPermission(user.id, calendarId, "admin");
+ if (!hasPermission) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
+ }
+
+ const body = await request.json();
+ const { userId: targetUserId, permission } = body;
+
+ // Validate permission value
+ const validPermissions = ["owner", "admin", "write", "read"];
+ if (!validPermissions.includes(permission)) {
+ return NextResponse.json(
+ { error: "Invalid permission value" },
+ { status: 400 }
+ );
+ }
+
+ // Only owner can grant admin permissions
+ if (permission === "admin") {
+ const isOwner = await checkPermission(user.id, calendarId, "owner");
+ if (!isOwner) {
+ return NextResponse.json(
+ { error: "Only the owner can grant admin permissions" },
+ { status: 403 }
+ );
+ }
+ }
+
+ // Check if share already exists
+ const existingShare = await db.query.calendarShares.findFirst({
+ where: and(
+ eq(calendarShares.calendarId, calendarId),
+ eq(calendarShares.userId, targetUserId)
+ ),
+ });
+
+ if (existingShare) {
+ return NextResponse.json(
+ { error: "Calendar already shared with this user" },
+ { status: 409 }
+ );
+ }
+
+ // Fetch calendar name for audit log
+ const calendar = await db.query.calendars.findFirst({
+ where: eq(calendars.id, calendarId),
+ columns: { name: true },
+ });
+
+ // Fetch target user info for audit log
+ const targetUser = await db.query.user.findFirst({
+ where: (users, { eq }) => eq(users.id, targetUserId),
+ columns: { email: true, name: true },
+ });
+
+ // Check if user has an existing subscription (guest or dismissed)
+ const existingSub = await db.query.userCalendarSubscriptions.findFirst({
+ where: and(
+ eq(userCalendarSubscriptions.userId, targetUserId),
+ eq(userCalendarSubscriptions.calendarId, calendarId)
+ ),
+ });
+
+ // If subscription exists, update it to "shared" source and "subscribed" status
+ if (existingSub) {
+ await db
+ .update(userCalendarSubscriptions)
+ .set({
+ source: "shared",
+ status: "subscribed",
+ })
+ .where(
+ and(
+ eq(userCalendarSubscriptions.userId, targetUserId),
+ eq(userCalendarSubscriptions.calendarId, calendarId)
+ )
+ );
+ } else {
+ // Create new subscription entry
+ await db.insert(userCalendarSubscriptions).values({
+ userId: targetUserId,
+ calendarId,
+ source: "shared",
+ status: "subscribed",
+ });
+ }
+
+ // Create share
+ const [newShare] = await db
+ .insert(calendarShares)
+ .values({
+ id: crypto.randomUUID(),
+ calendarId,
+ userId: targetUserId,
+ permission,
+ sharedBy: user.id,
+ createdAt: new Date(),
+ })
+ .returning();
+
+ // Log audit event
+ await logAuditEvent({
+ userId: user.id,
+ action: "calendar.shared",
+ severity: "info",
+ request,
+ metadata: {
+ calendarId,
+ calendarName: calendar?.name || "Unknown",
+ sharedWith: targetUser?.email || targetUser?.name || targetUserId,
+ permission,
+ },
+ });
+
+ // Fetch full share data with relations
+ const shareWithUser = await db.query.calendarShares.findFirst({
+ where: eq(calendarShares.id, newShare.id),
+ with: {
+ user: {
+ columns: {
+ id: true,
+ name: true,
+ email: true,
+ image: true,
+ },
+ },
+ sharedByUser: {
+ columns: {
+ id: true,
+ name: true,
+ email: true,
+ },
+ },
+ },
+ });
+
+ return NextResponse.json(shareWithUser, { status: 201 });
+ } catch (error) {
+ console.error("Failed to create calendar share:", error);
+ return NextResponse.json(
+ { error: "Failed to create share" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/api/calendars/[id]/tokens/[tokenId]/route.ts b/app/api/calendars/[id]/tokens/[tokenId]/route.ts
new file mode 100644
index 0000000..1e5027a
--- /dev/null
+++ b/app/api/calendars/[id]/tokens/[tokenId]/route.ts
@@ -0,0 +1,246 @@
+import { NextRequest, NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import { calendarAccessTokens, calendars } from "@/lib/db/schema";
+import { eq, and } from "drizzle-orm";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { checkPermission } from "@/lib/auth/permissions";
+import { logAuditEvent } from "@/lib/audit-log";
+
+/**
+ * PATCH /api/calendars/[id]/tokens/[tokenId]
+ * Update an access token
+ * Only owner/admin can update tokens
+ * Cannot change the token itself
+ */
+export async function PATCH(
+ request: NextRequest,
+ { params }: { params: Promise<{ id: string; tokenId: string }> }
+) {
+ try {
+ const { id: calendarId, tokenId } = await params;
+ const user = await getSessionUser(request.headers);
+
+ if (!user) {
+ return NextResponse.json(
+ { error: "Authentication required" },
+ { status: 401 }
+ );
+ }
+
+ // Check permissions (admin or owner only)
+ const canManage =
+ (await checkPermission(user.id, calendarId, "admin")) ||
+ (await checkPermission(user.id, calendarId, "owner"));
+
+ if (!canManage) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
+ }
+
+ // Get existing token
+ const [existingToken] = await db
+ .select()
+ .from(calendarAccessTokens)
+ .where(
+ and(
+ eq(calendarAccessTokens.id, tokenId),
+ eq(calendarAccessTokens.calendarId, calendarId)
+ )
+ )
+ .limit(1);
+
+ if (!existingToken) {
+ return NextResponse.json({ error: "Token not found" }, { status: 404 });
+ }
+
+ const body = await request.json();
+ const {
+ name,
+ permission,
+ expiresAt,
+ isActive,
+ }: {
+ name?: string;
+ permission?: "read" | "write";
+ expiresAt?: string | null;
+ isActive?: boolean;
+ } = body;
+
+ // Validate permission if provided
+ if (permission && permission !== "read" && permission !== "write") {
+ return NextResponse.json(
+ { error: "Permission must be 'read' or 'write'" },
+ { status: 400 }
+ );
+ }
+
+ // Validate expiration date if provided
+ let expiresAtDate: Date | null | undefined = undefined;
+ if (expiresAt !== undefined) {
+ if (expiresAt === null) {
+ expiresAtDate = null; // Remove expiration
+ } else {
+ expiresAtDate = new Date(expiresAt);
+ if (isNaN(expiresAtDate.getTime())) {
+ return NextResponse.json(
+ { error: "Invalid expiration date" },
+ { status: 400 }
+ );
+ }
+ if (expiresAtDate <= new Date()) {
+ return NextResponse.json(
+ { error: "Expiration date must be in the future" },
+ { status: 400 }
+ );
+ }
+ }
+ }
+
+ // Build update object
+ const updates: Partial<typeof calendarAccessTokens.$inferInsert> = {};
+ if (name !== undefined) updates.name = name;
+ if (permission !== undefined) updates.permission = permission;
+ if (expiresAtDate !== undefined) updates.expiresAt = expiresAtDate;
+ if (isActive !== undefined) updates.isActive = isActive;
+
+ // Update token
+ const [updatedToken] = await db
+ .update(calendarAccessTokens)
+ .set(updates)
+ .where(eq(calendarAccessTokens.id, tokenId))
+ .returning();
+
+ // Get calendar name for audit log
+ const [calendar] = await db
+ .select({ name: calendars.name })
+ .from(calendars)
+ .where(eq(calendars.id, calendarId))
+ .limit(1);
+
+ // Audit log
+ void logAuditEvent({
+ userId: user.id,
+ action: "calendar_token_updated",
+ resourceType: "calendar",
+ resourceId: calendarId,
+ metadata: {
+ tokenId,
+ tokenName: updatedToken.name || "Unnamed",
+ calendarName: calendar?.name || "Unknown",
+ changes: updates,
+ },
+ request,
+ severity: "info",
+ isUserVisible: true,
+ });
+
+ // Return sanitized token (no full token)
+ return NextResponse.json({
+ ...updatedToken,
+ tokenPreview: `${updatedToken.token.slice(0, 6)}...`,
+ token: undefined,
+ });
+ } catch (error) {
+ console.error(
+ "[API] PATCH /api/calendars/[id]/tokens/[tokenId] error:",
+ error
+ );
+ return NextResponse.json(
+ { error: "Failed to update access token" },
+ { status: 500 }
+ );
+ }
+}
+
+/**
+ * DELETE /api/calendars/[id]/tokens/[tokenId]
+ * Delete (revoke) an access token
+ * Only owner/admin can delete tokens
+ */
+export async function DELETE(
+ request: NextRequest,
+ { params }: { params: Promise<{ id: string; tokenId: string }> }
+) {
+ try {
+ const { id: calendarId, tokenId } = await params;
+ const user = await getSessionUser(request.headers);
+
+ if (!user) {
+ return NextResponse.json(
+ { error: "Authentication required" },
+ { status: 401 }
+ );
+ }
+
+ // Check permissions (admin or owner only)
+ const canManage =
+ (await checkPermission(user.id, calendarId, "admin")) ||
+ (await checkPermission(user.id, calendarId, "owner"));
+
+ if (!canManage) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
+ }
+
+ // Get token details before deletion
+ const [token] = await db
+ .select()
+ .from(calendarAccessTokens)
+ .where(
+ and(
+ eq(calendarAccessTokens.id, tokenId),
+ eq(calendarAccessTokens.calendarId, calendarId)
+ )
+ )
+ .limit(1);
+
+ if (!token) {
+ return NextResponse.json({ error: "Token not found" }, { status: 404 });
+ }
+
+ // Get calendar name for audit log
+ const [calendar] = await db
+ .select({ name: calendars.name })
+ .from(calendars)
+ .where(eq(calendars.id, calendarId))
+ .limit(1);
+
+ // Delete token
+ await db
+ .delete(calendarAccessTokens)
+ .where(eq(calendarAccessTokens.id, tokenId));
+
+ // Audit log
+ void logAuditEvent({
+ userId: user.id,
+ action: "calendar_token_revoked",
+ resourceType: "calendar",
+ resourceId: calendarId,
+ metadata: {
+ tokenId,
+ tokenName: token.name || "Unnamed",
+ calendarName: calendar?.name || "Unknown",
+ permission: token.permission,
+ usageCount: token.usageCount,
+ },
+ request,
+ severity: "info",
+ isUserVisible: true,
+ });
+
+ return NextResponse.json({ success: true });
+ } catch (error) {
+ console.error(
+ "[API] DELETE /api/calendars/[id]/tokens/[tokenId] error:",
+ error
+ );
+ return NextResponse.json(
+ { error: "Failed to delete access token" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/api/calendars/[id]/tokens/route.ts b/app/api/calendars/[id]/tokens/route.ts
new file mode 100644
index 0000000..c1f43a3
--- /dev/null
+++ b/app/api/calendars/[id]/tokens/route.ts
@@ -0,0 +1,206 @@
+import { NextRequest, NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import { calendarAccessTokens, calendars } from "@/lib/db/schema";
+import { eq, desc } from "drizzle-orm";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { checkPermission } from "@/lib/auth/permissions";
+import { generateAccessToken } from "@/lib/auth/token-auth";
+import { logAuditEvent } from "@/lib/audit-log";
+import { rateLimit } from "@/lib/rate-limiter";
+
+/**
+ * GET /api/calendars/[id]/tokens
+ * List all access tokens for a calendar
+ * Only owner/admin can view tokens
+ */
+export async function GET(
+ request: NextRequest,
+ { params }: { params: Promise<{ id: string }> }
+) {
+ try {
+ const { id: calendarId } = await params;
+ const user = await getSessionUser(request.headers);
+
+ // Check permissions (admin or owner only)
+ const canManage =
+ (await checkPermission(user?.id, calendarId, "admin")) ||
+ (await checkPermission(user?.id, calendarId, "owner"));
+
+ if (!canManage) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
+ }
+
+ // Fetch all tokens for this calendar
+ const tokens = await db
+ .select({
+ id: calendarAccessTokens.id,
+ token: calendarAccessTokens.token,
+ name: calendarAccessTokens.name,
+ permission: calendarAccessTokens.permission,
+ expiresAt: calendarAccessTokens.expiresAt,
+ createdBy: calendarAccessTokens.createdBy,
+ createdAt: calendarAccessTokens.createdAt,
+ lastUsedAt: calendarAccessTokens.lastUsedAt,
+ usageCount: calendarAccessTokens.usageCount,
+ isActive: calendarAccessTokens.isActive,
+ })
+ .from(calendarAccessTokens)
+ .where(eq(calendarAccessTokens.calendarId, calendarId))
+ .orderBy(desc(calendarAccessTokens.createdAt));
+
+ // Return partial tokens (first 6 chars) for security
+ const sanitizedTokens = tokens.map((token) => ({
+ ...token,
+ tokenPreview: `${token.token.slice(0, 6)}...`,
+ token: undefined, // Remove full token from response
+ }));
+
+ return NextResponse.json(sanitizedTokens);
+ } catch (error) {
+ console.error("[API] GET /api/calendars/[id]/tokens error:", error);
+ return NextResponse.json(
+ { error: "Failed to fetch access tokens" },
+ { status: 500 }
+ );
+ }
+}
+
+/**
+ * POST /api/calendars/[id]/tokens
+ * Create a new access token
+ * Only owner/admin can create tokens
+ */
+export async function POST(
+ request: NextRequest,
+ { params }: { params: Promise<{ id: string }> }
+) {
+ try {
+ const { id: calendarId } = await params;
+ const user = await getSessionUser(request.headers);
+
+ if (!user) {
+ return NextResponse.json(
+ { error: "Authentication required" },
+ { status: 401 }
+ );
+ }
+
+ // Rate limit: 10 tokens per hour per calendar
+ const rateLimitResponse = rateLimit(
+ request,
+ user.id,
+ "token-creation",
+ calendarId
+ );
+ if (rateLimitResponse) return rateLimitResponse;
+
+ // Check permissions (admin or owner only)
+ const canManage =
+ (await checkPermission(user.id, calendarId, "admin")) ||
+ (await checkPermission(user.id, calendarId, "owner"));
+
+ if (!canManage) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
+ }
+
+ const body = await request.json();
+ const {
+ name,
+ permission = "read",
+ expiresAt,
+ }: {
+ name?: string;
+ permission?: "read" | "write";
+ expiresAt?: string | null;
+ } = body;
+
+ // Validate permission
+ if (permission !== "read" && permission !== "write") {
+ return NextResponse.json(
+ { error: "Permission must be 'read' or 'write'" },
+ { status: 400 }
+ );
+ }
+
+ // Validate expiration date (if provided)
+ let expiresAtDate: Date | null = null;
+ if (expiresAt) {
+ expiresAtDate = new Date(expiresAt);
+ if (isNaN(expiresAtDate.getTime())) {
+ return NextResponse.json(
+ { error: "Invalid expiration date" },
+ { status: 400 }
+ );
+ }
+ if (expiresAtDate <= new Date()) {
+ return NextResponse.json(
+ { error: "Expiration date must be in the future" },
+ { status: 400 }
+ );
+ }
+ }
+
+ // Generate secure token
+ const token = generateAccessToken();
+
+ // Get calendar name for audit log
+ const [calendar] = await db
+ .select({ name: calendars.name })
+ .from(calendars)
+ .where(eq(calendars.id, calendarId))
+ .limit(1);
+
+ // Create token
+ const [newToken] = await db
+ .insert(calendarAccessTokens)
+ .values({
+ calendarId,
+ token,
+ name: name || null,
+ permission,
+ expiresAt: expiresAtDate,
+ createdBy: user.id,
+ })
+ .returning();
+
+ // Audit log
+ void logAuditEvent({
+ userId: user.id,
+ action: "calendar_token_created",
+ resourceType: "calendar",
+ resourceId: calendarId,
+ metadata: {
+ tokenId: newToken.id,
+ tokenName: name || "Unnamed",
+ calendarName: calendar?.name || "Unknown",
+ permission,
+ expiresAt: expiresAt || null,
+ },
+ request,
+ severity: "info",
+ isUserVisible: true,
+ });
+
+ // Return full token (only time it's shown!)
+ return NextResponse.json(
+ {
+ ...newToken,
+ token, // Full token returned ONLY on creation
+ tokenPreview: `${token.slice(0, 6)}...`,
+ },
+ { status: 201 }
+ );
+ } catch (error) {
+ console.error("[API] POST /api/calendars/[id]/tokens error:", error);
+ return NextResponse.json(
+ { error: "Failed to create access token" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/api/calendars/[id]/verify-password/route.ts b/app/api/calendars/[id]/verify-password/route.ts
deleted file mode 100644
index 0b7dc1c..0000000
--- a/app/api/calendars/[id]/verify-password/route.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { NextResponse } from "next/server";
-import { db } from "@/lib/db";
-import { calendars } from "@/lib/db/schema";
-import { eq } from "drizzle-orm";
-import { verifyPassword } from "@/lib/password-utils";
-
-// POST verify calendar password
-export async function POST(
- request: Request,
- { params }: { params: Promise<{ id: string }> }
-) {
- try {
- const { id } = await params;
- const body = await request.json();
- const { password } = body;
-
- // Fetch calendar
- const [calendar] = await db
- .select()
- .from(calendars)
- .where(eq(calendars.id, id));
-
- if (!calendar) {
- return NextResponse.json(
- { error: "Calendar not found" },
- { status: 404 }
- );
- }
-
- // Check if calendar has a password
- if (!calendar.passwordHash) {
- return NextResponse.json({ valid: true, protected: false });
- }
-
- // If no password provided in request but calendar is protected
- if (!password) {
- return NextResponse.json({ valid: false, protected: true });
- }
-
- // Verify password
- const isValid = verifyPassword(password, calendar.passwordHash);
-
- return NextResponse.json({ valid: isValid, protected: true });
- } catch (error) {
- console.error("Failed to verify password:", error);
- return NextResponse.json(
- { error: "Failed to verify password" },
- { status: 500 }
- );
- }
-}
diff --git a/app/api/calendars/route.ts b/app/api/calendars/route.ts
index 945659d..b5a4b9c 100644
--- a/app/api/calendars/route.ts
+++ b/app/api/calendars/route.ts
@@ -1,19 +1,43 @@
-import { NextResponse } from "next/server";
+import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
-import { calendars, shifts } from "@/lib/db/schema";
-import { sql } from "drizzle-orm";
-import { hashPassword } from "@/lib/password-utils";
+import {
+ calendars,
+ shifts,
+ calendarShares,
+ userCalendarSubscriptions,
+} from "@/lib/db/schema";
+import { sql, eq, or, and } from "drizzle-orm";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { getUserAccessibleCalendars } from "@/lib/auth/permissions";
+import { isAuthEnabled } from "@/lib/auth/feature-flags";
+import { rateLimit } from "@/lib/rate-limiter";
+import { logUserAction, type CalendarCreatedMetadata } from "@/lib/audit-log";
+import {
+ getTokensFromCookie,
+ validateAccessToken,
+} from "@/lib/auth/token-auth";
-// GET all calendars
-export async function GET() {
+// GET all calendars (only those accessible to the user)
+export async function GET(request: Request) {
try {
- const allCalendars = await db
+ const user = await getSessionUser(request.headers);
+
+ // Get accessible calendar IDs with permissions
+ const accessible = await getUserAccessibleCalendars(user?.id);
+ const accessibleIds = accessible.map((a) => a.id);
+
+ if (accessibleIds.length === 0) {
+ return NextResponse.json([]);
+ }
+
+ // Fetch calendars with counts
+ const userCalendars = await db
.select({
id: calendars.id,
name: calendars.name,
color: calendars.color,
- passwordHash: calendars.passwordHash,
- isLocked: calendars.isLocked,
+ ownerId: calendars.ownerId,
+ guestPermission: calendars.guestPermission,
createdAt: calendars.createdAt,
updatedAt: calendars.updatedAt,
_count:
@@ -22,9 +46,70 @@ export async function GET() {
),
})
.from(calendars)
+ .where(or(...accessibleIds.map((id) => eq(calendars.id, id))))
.orderBy(calendars.createdAt);
- return NextResponse.json(allCalendars);
+ // If user is authenticated, fetch additional metadata
+ let subscriptions: Map<string, { status: string; source: string }> =
+ new Map();
+ let shares: Map<string, string> = new Map();
+ const tokens: Map<string, "read" | "write"> = new Map();
+
+ // Get token permissions (works for both guests and authenticated users)
+ const userTokens = await getTokensFromCookie();
+ for (const tokenData of userTokens) {
+ // Validate token is still valid
+ const validation = await validateAccessToken(tokenData.token);
+ if (validation && validation.calendarId === tokenData.calendarId) {
+ tokens.set(tokenData.calendarId, tokenData.permission);
+ }
+ }
+
+ if (user) {
+ // Get subscriptions
+ const userSubs = await db.query.userCalendarSubscriptions.findMany({
+ where: and(
+ eq(sql`${userCalendarSubscriptions.userId}`, user.id),
+ eq(sql`${userCalendarSubscriptions.status}`, "subscribed")
+ ),
+ });
+ subscriptions = new Map(
+ userSubs.map((s) => [
+ s.calendarId,
+ { status: s.status, source: s.source },
+ ])
+ );
+
+ // Get shares
+ const userShares = await db.query.calendarShares.findMany({
+ where: eq(sql`${calendarShares.userId}`, user.id),
+ });
+ shares = new Map(userShares.map((s) => [s.calendarId, s.permission]));
+ }
+
+ // Enrich calendars with permission metadata
+ const enrichedCalendars = userCalendars.map((cal) => {
+ const share = shares.get(cal.id);
+ const subscription = subscriptions.get(cal.id);
+ const token = tokens.get(cal.id);
+
+ // Determine subscription source
+ let subscriptionSource: "guest" | "shared" | "token" | undefined =
+ subscription?.source as "guest" | "shared" | undefined;
+ if (token && !share && !subscription) {
+ subscriptionSource = "token";
+ }
+
+ return {
+ ...cal,
+ sharePermission: share || undefined,
+ tokenPermission: token || undefined,
+ isSubscribed: !!subscription || !!token,
+ subscriptionSource,
+ };
+ });
+
+ return NextResponse.json(enrichedCalendars);
} catch (error) {
console.error("Failed to fetch calendars:", error);
return NextResponse.json(
@@ -34,23 +119,29 @@ export async function GET() {
}
}
-// POST create new calendar
-export async function POST(request: Request) {
+// POST create new calendar (sets current user as owner)
+export async function POST(request: NextRequest) {
try {
- const body = await request.json();
- const { name, color, password, isLocked } = body;
+ const user = await getSessionUser(request.headers);
- if (!name) {
+ // Rate limiting: 10 calendars per hour
+ const rateLimitResponse = rateLimit(request, user?.id, "calendar-create");
+ if (rateLimitResponse) return rateLimitResponse;
+
+ // If auth is enabled, require authentication to create calendars
+ if (isAuthEnabled() && !user) {
return NextResponse.json(
- { error: "Calendar name is required" },
- { status: 400 }
+ { error: "Authentication required to create calendars" },
+ { status: 401 }
);
}
- // Can't lock without password
- if (isLocked && !password) {
+ const body = await request.json();
+ const { name, color, guestPermission } = body;
+
+ if (!name) {
return NextResponse.json(
- { error: "Cannot lock calendar without password" },
+ { error: "Calendar name is required" },
{ status: 400 }
);
}
@@ -60,11 +151,26 @@ export async function POST(request: Request) {
.values({
name,
color: color || "#3b82f6",
- passwordHash: password ? hashPassword(password) : null,
- isLocked: isLocked || false,
+ ownerId: user?.id || null, // Set current user as owner (or null if auth disabled)
+ guestPermission: guestPermission || "none",
})
.returning();
+ // Log calendar creation event
+ if (user) {
+ await logUserAction<CalendarCreatedMetadata>({
+ action: "calendar.created",
+ userId: user.id,
+ resourceType: "calendar",
+ resourceId: calendar.id,
+ metadata: {
+ calendarName: calendar.name,
+ color: calendar.color,
+ },
+ request,
+ });
+ }
+
return NextResponse.json(calendar, { status: 201 });
} catch (error) {
console.error("Failed to create calendar:", error);
diff --git a/app/api/calendars/subscriptions/[calendarId]/route.ts b/app/api/calendars/subscriptions/[calendarId]/route.ts
new file mode 100644
index 0000000..38239c6
--- /dev/null
+++ b/app/api/calendars/subscriptions/[calendarId]/route.ts
@@ -0,0 +1,44 @@
+import { NextRequest, NextResponse } from "next/server";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { dismissCalendar } from "@/lib/auth/permissions";
+import { eventEmitter } from "@/lib/event-emitter";
+
+/**
+ * DELETE /api/calendars/subscriptions/[calendarId]
+ * Dismiss/unsubscribe from a calendar
+ * - For shared calendars: creates dismissal entry
+ * - For subscribed calendars: removes subscription
+ * - Cannot dismiss owned calendars
+ */
+export async function DELETE(
+ request: NextRequest,
+ { params }: { params: Promise<{ calendarId: string }> }
+) {
+ const user = await getSessionUser(request.headers);
+
+ if (!user) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ try {
+ const { calendarId } = await params;
+
+ // Use the helper function to handle dismissal/unsubscribe
+ await dismissCalendar(user.id, calendarId);
+
+ // Emit SSE event to trigger calendar list refresh
+ eventEmitter.emit("calendar-change", {
+ type: "calendar",
+ action: "update",
+ calendarId,
+ data: { dismissed: true },
+ });
+
+ return NextResponse.json({ success: true }, { status: 200 });
+ } catch (error) {
+ console.error("Error dismissing calendar:", error);
+ const message =
+ error instanceof Error ? error.message : "Failed to dismiss calendar";
+ return NextResponse.json({ error: message }, { status: 400 });
+ }
+}
diff --git a/app/api/calendars/subscriptions/route.ts b/app/api/calendars/subscriptions/route.ts
new file mode 100644
index 0000000..652acf7
--- /dev/null
+++ b/app/api/calendars/subscriptions/route.ts
@@ -0,0 +1,223 @@
+import { NextRequest, NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import {
+ calendars,
+ calendarShares,
+ userCalendarSubscriptions,
+} from "@/lib/db/schema";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { eq, and, or, ne, isNull } from "drizzle-orm";
+import { undismissCalendar } from "@/lib/auth/permissions";
+import { eventEmitter } from "@/lib/event-emitter";
+
+/**
+ * GET /api/calendars/subscriptions
+ * List all available calendars for discovery
+ * Returns two lists:
+ * - available: Calendars user can browse (public calendars, showing subscription status)
+ * - dismissed: Calendars user has dismissed (both shared and guest-subscribed)
+ */
+export async function GET(request: NextRequest) {
+ const user = await getSessionUser(request.headers);
+
+ if (!user) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ try {
+ // Get all public calendars (guestPermission != "none", not owned by user)
+ const allPublicCalendars = await db.query.calendars.findMany({
+ where: and(
+ ne(calendars.guestPermission, "none"),
+ or(isNull(calendars.ownerId), ne(calendars.ownerId, user.id))
+ ),
+ with: {
+ owner: {
+ columns: {
+ id: true,
+ name: true,
+ email: true,
+ },
+ },
+ },
+ });
+
+ // Get all user's subscriptions (both subscribed and dismissed)
+ const userSubscriptions = await db.query.userCalendarSubscriptions.findMany(
+ {
+ where: eq(userCalendarSubscriptions.userId, user.id),
+ }
+ );
+
+ const subscribedIds = new Set(
+ userSubscriptions
+ .filter((sub) => sub.status === "subscribed")
+ .map((sub) => sub.calendarId)
+ );
+
+ const dismissedSubs = userSubscriptions.filter(
+ (sub) => sub.status === "dismissed"
+ );
+
+ // Get user's explicit shares (not dismissed)
+ const userShares = await db.query.calendarShares.findMany({
+ where: eq(calendarShares.userId, user.id),
+ with: {
+ calendar: {
+ with: {
+ owner: {
+ columns: {
+ id: true,
+ name: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ const dismissedIds = new Set(dismissedSubs.map((sub) => sub.calendarId));
+
+ // Filter out dismissed shares from userShares before building sharedIds
+ const activeShares = userShares.filter(
+ (share) => !dismissedIds.has(share.calendarId)
+ );
+ const sharedIds = new Set(activeShares.map((share) => share.calendarId));
+
+ // Build available calendars list (public calendars, excluding ones with active shares or dismissed)
+ const publicCalendars = allPublicCalendars
+ .filter(
+ (cal) =>
+ !sharedIds.has(cal.id) && // Exclude if user has active share
+ !dismissedIds.has(cal.id) // Exclude if user has dismissed this calendar
+ )
+ .map((cal) => ({
+ id: cal.id,
+ name: cal.name,
+ color: cal.color,
+ guestPermission: cal.guestPermission,
+ owner: cal.owner
+ ? {
+ id: cal.owner.id,
+ name: cal.owner.name,
+ }
+ : null,
+ isSubscribed: subscribedIds.has(cal.id),
+ source: "guest" as const,
+ }));
+
+ // Add shared calendars to available list (already filtered for dismissed in activeShares)
+ const sharedCalendars = activeShares.map((share) => ({
+ id: share.calendar.id,
+ name: share.calendar.name,
+ color: share.calendar.color,
+ permission: share.permission, // User's share permission level
+ guestPermission: share.calendar.guestPermission, // Calendar's guest permission (for reference)
+ owner: share.calendar.owner
+ ? {
+ id: share.calendar.owner.id,
+ name: share.calendar.owner.name,
+ }
+ : null,
+ isSubscribed: subscribedIds.has(share.calendarId),
+ source: "shared" as const,
+ }));
+
+ const availableCalendars = [...publicCalendars, ...sharedCalendars];
+
+ // Build dismissed calendars list (both shared and guest-subscribed)
+ const dismissedCalendars = await Promise.all(
+ dismissedSubs.map(async (sub) => {
+ const calendar = await db.query.calendars.findFirst({
+ where: eq(calendars.id, sub.calendarId),
+ with: {
+ owner: {
+ columns: {
+ id: true,
+ name: true,
+ },
+ },
+ },
+ });
+
+ if (!calendar) return null;
+
+ // Check if it's also a shared calendar
+ const share = userShares.find((s) => s.calendarId === sub.calendarId);
+
+ return {
+ id: calendar.id,
+ name: calendar.name,
+ color: calendar.color,
+ permission: share ? share.permission : calendar.guestPermission,
+ owner: calendar.owner
+ ? {
+ id: calendar.owner.id,
+ name: calendar.owner.name,
+ }
+ : null,
+ source: sub.source,
+ };
+ })
+ );
+
+ // Filter out nulls
+ const validDismissedCalendars = dismissedCalendars.filter(
+ (cal): cal is NonNullable<typeof cal> => cal !== null
+ );
+
+ return NextResponse.json({
+ available: availableCalendars,
+ dismissed: validDismissedCalendars,
+ });
+ } catch (error) {
+ console.error("Error fetching subscription calendars:", error);
+ return NextResponse.json(
+ { error: "Failed to fetch calendars" },
+ { status: 500 }
+ );
+ }
+}
+
+/**
+ * POST /api/calendars/subscriptions
+ * Subscribe to a calendar or re-subscribe to a dismissed calendar
+ * Body: { calendarId: string }
+ */
+export async function POST(request: NextRequest) {
+ const user = await getSessionUser(request.headers);
+
+ if (!user) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ try {
+ const body = await request.json();
+ const { calendarId } = body;
+
+ if (!calendarId) {
+ return NextResponse.json(
+ { error: "Calendar ID is required" },
+ { status: 400 }
+ );
+ }
+
+ // Use the helper function to handle both scenarios
+ await undismissCalendar(user.id, calendarId);
+
+ // Emit SSE event to trigger calendar list refresh
+ eventEmitter.emit("calendar-change", {
+ type: "calendar",
+ action: "update",
+ calendarId,
+ data: { subscribed: true },
+ });
+
+ return NextResponse.json({ success: true }, { status: 200 });
+ } catch (error) {
+ console.error("Error subscribing to calendar:", error);
+ const message =
+ error instanceof Error ? error.message : "Failed to subscribe";
+ return NextResponse.json({ error: message }, { status: 400 });
+ }
+}
diff --git a/app/api/events/stream/route.ts b/app/api/events/stream/route.ts
index 7b694ac..bb5db48 100644
--- a/app/api/events/stream/route.ts
+++ b/app/api/events/stream/route.ts
@@ -1,5 +1,8 @@
import { NextRequest } from "next/server";
import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { canViewCalendar } from "@/lib/auth/permissions";
+import { rateLimit } from "@/lib/rate-limiter";
// Disable default body parsing
export const dynamic = "force-dynamic";
@@ -15,6 +18,20 @@ export async function GET(request: NextRequest) {
});
}
+ // Check read permission for calendar (works for both authenticated users and guests)
+ const user = await getSessionUser(request.headers);
+ const hasAccess = await canViewCalendar(user?.id, calendarId);
+ if (!hasAccess) {
+ return new Response(JSON.stringify({ error: "Insufficient permissions" }), {
+ status: 403,
+ headers: { "Content-Type": "application/json" },
+ });
+ }
+
+ // Rate limiting check for SSE connections (1 per user per minute)
+ const rateLimitResponse = rateLimit(request, user?.id, "sse");
+ if (rateLimitResponse) return rateLimitResponse;
+
// Create a readable stream for SSE
const encoder = new TextEncoder();
const stream = new ReadableStream({
diff --git a/app/api/external-syncs/[id]/route.ts b/app/api/external-syncs/[id]/route.ts
index a1f7cc7..aae291b 100644
--- a/app/api/external-syncs/[id]/route.ts
+++ b/app/api/external-syncs/[id]/route.ts
@@ -1,23 +1,23 @@
-import { NextResponse } from "next/server";
+import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { externalSyncs, shifts, calendars } from "@/lib/db/schema";
import { eq } from "drizzle-orm";
-import { verifyPassword } from "@/lib/password-utils";
import { eventEmitter } from "@/lib/event-emitter";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";
import {
isValidCalendarUrl,
type CalendarSyncType,
} from "@/lib/external-calendar-utils";
+import { logUserAction, type SyncDeletedMetadata } from "@/lib/audit-log";
// GET single external sync
export async function GET(
- request: Request,
+ request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params;
- const { searchParams } = new URL(request.url);
- const password = searchParams.get("password");
const [externalSync] = await db
.select()
@@ -32,7 +32,7 @@ export async function GET(
);
}
- // Fetch calendar to check password
+ // Fetch calendar to verify it exists
const [calendar] = await db
.select()
.from(calendars)
@@ -45,14 +45,14 @@ export async function GET(
);
}
- // Verify password if calendar is protected AND locked
- if (calendar.passwordHash && calendar.isLocked) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check view permissions (works for both authenticated users and guests)
+ const user = await getSessionUser(request.headers);
+ const hasAccess = await canViewCalendar(user?.id, externalSync.calendarId);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions. Read access required." },
+ { status: 403 }
+ );
}
return NextResponse.json(externalSync);
@@ -67,7 +67,7 @@ export async function GET(
// PATCH update external sync
export async function PATCH(
- request: Request,
+ request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
@@ -97,7 +97,7 @@ export async function PATCH(
);
}
- // Fetch calendar to check password
+ // Fetch calendar to verify it exists
const [calendar] = await db
.select()
.from(calendars)
@@ -110,15 +110,14 @@ export async function PATCH(
);
}
- // Verify password if calendar is protected
- if (calendar.passwordHash) {
- const { password } = body;
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check edit permissions (works for both authenticated users and guests)
+ const user = await getSessionUser(request.headers);
+ const hasAccess = await canEditCalendar(user?.id, existingSync.calendarId);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions. Write access required." },
+ { status: 403 }
+ );
}
// Validate calendar URL if provided
@@ -223,25 +222,12 @@ export async function PATCH(
// DELETE external sync and all associated shifts
export async function DELETE(
- request: Request,
+ request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params;
- // Read password from request body
- let password: string | null = null;
- const contentType = request.headers.get("content-type");
-
- if (contentType?.includes("application/json")) {
- try {
- const body = await request.json();
- password = body.password || null;
- } catch {
- // If body parsing fails, continue with null password
- }
- }
-
// Fetch external sync to get calendar ID
const [existingSync] = await db
.select()
@@ -255,7 +241,7 @@ export async function DELETE(
);
}
- // Fetch calendar to check password
+ // Fetch calendar to verify it exists
const [calendar] = await db
.select()
.from(calendars)
@@ -268,18 +254,36 @@ export async function DELETE(
);
}
- // Verify password if calendar is protected
- if (calendar.passwordHash) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check edit permissions (works for both authenticated users and guests)
+ const user = await getSessionUser(request.headers);
+ const hasAccess = await canEditCalendar(user?.id, existingSync.calendarId);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions. Write access required." },
+ { status: 403 }
+ );
}
await db.delete(externalSyncs).where(eq(externalSyncs.id, id));
+ // Log external sync deletion event
+ if (user) {
+ await logUserAction<SyncDeletedMetadata>({
+ action: "sync.deleted",
+ userId: user.id,
+ resourceType: "sync",
+ resourceId: id,
+ metadata: {
+ calendarName: calendar.name,
+ syncUrl: existingSync.isOneTimeImport
+ ? "file-upload"
+ : existingSync.calendarUrl,
+ syncName: existingSync.name,
+ },
+ request,
+ });
+ }
+
return NextResponse.json({ success: true });
} catch (error) {
console.error("Failed to delete external sync:", error);
diff --git a/app/api/external-syncs/[id]/sync/route.ts b/app/api/external-syncs/[id]/sync/route.ts
index 05f69d9..e5b5d9f 100644
--- a/app/api/external-syncs/[id]/sync/route.ts
+++ b/app/api/external-syncs/[id]/sync/route.ts
@@ -1,9 +1,10 @@
-import { NextResponse } from "next/server";
+import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { externalSyncs, shifts, syncLogs, calendars } from "@/lib/db/schema";
import { eq, inArray } from "drizzle-orm";
-import { verifyPassword } from "@/lib/password-utils";
import ICAL from "ical.js";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { canEditCalendar } from "@/lib/auth/permissions";
import {
expandRecurringEvents,
splitMultiDayEvent,
@@ -11,15 +12,25 @@ import {
needsUpdate,
} from "@/lib/external-calendar-utils";
import { eventEmitter } from "@/lib/event-emitter";
+import { rateLimit } from "@/lib/rate-limiter";
+import {
+ logUserAction,
+ logSystemEvent,
+ type SyncExecutedMetadata,
+} from "@/lib/audit-log";
/**
* Core sync logic extracted for reuse by both API route and auto-sync service
* @param syncId - The external sync ID
* @param syncType - Whether this is "auto" or "manual" sync
+ * @param userId - Optional user ID for audit logging (null for auto-sync)
+ * @param request - Optional request object for audit logging
*/
export async function syncExternalCalendar(
syncId: string,
- syncType: "auto" | "manual" = "manual"
+ syncType: "auto" | "manual" = "manual",
+ userId?: string | null,
+ request?: NextRequest
) {
// Get the external sync configuration
const [externalSync] = await db
@@ -300,6 +311,24 @@ export async function syncExternalCalendar(
stats = transactionResult;
+ // Log successful sync event to audit logs
+ const logFunction = syncType === "auto" ? logSystemEvent : logUserAction;
+ await logFunction<SyncExecutedMetadata>({
+ action: "sync.executed",
+ userId: userId || null,
+ resourceType: "sync",
+ resourceId: syncId,
+ metadata: {
+ calendarName: externalSync.calendarId, // Will be enriched with actual name in UI
+ syncName: externalSync.name,
+ shiftsAdded: stats.created,
+ shiftsUpdated: stats.updated,
+ shiftsDeleted: stats.deleted,
+ success: true,
+ },
+ request,
+ });
+
// Emit event for sync log creation after successful transaction
eventEmitter.emit("calendar-change", {
type: "sync-log",
@@ -325,6 +354,25 @@ export async function syncExternalCalendar(
syncedAt: new Date(),
});
+ // Log failed sync event to audit logs
+ const logFunction = syncType === "auto" ? logSystemEvent : logUserAction;
+ await logFunction<SyncExecutedMetadata>({
+ action: "sync.executed",
+ userId: userId || null,
+ resourceType: "sync",
+ resourceId: syncId,
+ metadata: {
+ calendarName: externalSync.calendarId,
+ syncName: externalSync.name,
+ shiftsAdded: 0,
+ shiftsUpdated: 0,
+ shiftsDeleted: 0,
+ success: false,
+ error: errorMessage,
+ },
+ request,
+ });
+
// Emit event for sync log creation
eventEmitter.emit("calendar-change", {
type: "sync-log",
@@ -339,26 +387,13 @@ export async function syncExternalCalendar(
}
export async function POST(
- request: Request,
+ request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id: syncId } = await params;
- // Read password from request body
- let password: string | null = null;
- const contentType = request.headers.get("content-type");
-
- if (contentType?.includes("application/json")) {
- try {
- const body = await request.json();
- password = body.password || null;
- } catch {
- // If body parsing fails, continue with null password
- }
- }
-
- // Fetch external sync to get calendar ID
+ // Fetch external sync to get calendar ID for rate limiting and permission checks
const [externalSync] = await db
.select()
.from(externalSyncs)
@@ -371,7 +406,20 @@ export async function POST(
);
}
- // Fetch calendar to check password
+ // Get user for audit logging and rate limiting
+ const user = await getSessionUser(request.headers);
+
+ // Rate limiting: 5 syncs per 5 minutes PER CALENDAR
+ // Use calendarId as identifier to prevent spamming one calendar
+ const rateLimitResponse = rateLimit(
+ request,
+ user?.id || null,
+ "external-sync",
+ externalSync.calendarId
+ );
+ if (rateLimitResponse) return rateLimitResponse;
+
+ // Fetch calendar to verify it exists
const [calendar] = await db
.select()
.from(calendars)
@@ -384,17 +432,21 @@ export async function POST(
);
}
- // Verify password if calendar is protected
- if (calendar.passwordHash) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check edit permissions (works for both authenticated users and guests)
+ const hasAccess = await canEditCalendar(user?.id, externalSync.calendarId);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions. Write access required." },
+ { status: 403 }
+ );
}
- const stats = await syncExternalCalendar(syncId, "manual");
+ const stats = await syncExternalCalendar(
+ syncId,
+ "manual",
+ user?.id,
+ request
+ );
return NextResponse.json({
success: true,
diff --git a/app/api/external-syncs/route.ts b/app/api/external-syncs/route.ts
index 072a1ff..102a4dc 100644
--- a/app/api/external-syncs/route.ts
+++ b/app/api/external-syncs/route.ts
@@ -1,17 +1,19 @@
-import { NextResponse } from "next/server";
+import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { externalSyncs, calendars } from "@/lib/db/schema";
import { eq, desc } from "drizzle-orm";
-import { verifyPassword } from "@/lib/password-utils";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";
import {
isValidCalendarUrl,
detectCalendarSyncType,
isValidICSContent,
type CalendarSyncType,
} from "@/lib/external-calendar-utils";
+import { logUserAction, type SyncCreatedMetadata } from "@/lib/audit-log";
// GET all external syncs for a calendar
-export async function GET(request: Request) {
+export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const calendarId = searchParams.get("calendarId");
@@ -23,9 +25,7 @@ export async function GET(request: Request) {
);
}
- const password = searchParams.get("password");
-
- // Fetch calendar to check password
+ // Fetch calendar to verify it exists
const [calendar] = await db
.select()
.from(calendars)
@@ -38,14 +38,14 @@ export async function GET(request: Request) {
);
}
- // Verify password if calendar is protected AND locked
- if (calendar.passwordHash && calendar.isLocked) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check view permissions (works for both authenticated users and guests)
+ const user = await getSessionUser(request.headers);
+ const hasAccess = await canViewCalendar(user?.id, calendarId);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions. Read access required." },
+ { status: 403 }
+ );
}
const syncs = await db
@@ -65,7 +65,7 @@ export async function GET(request: Request) {
}
// POST create new external sync
-export async function POST(request: Request) {
+export async function POST(request: NextRequest) {
try {
const body = await request.json();
const {
@@ -89,7 +89,7 @@ export async function POST(request: Request) {
);
}
- // Fetch calendar to check password
+ // Fetch calendar to verify it exists
const [calendar] = await db
.select()
.from(calendars)
@@ -102,15 +102,14 @@ export async function POST(request: Request) {
);
}
- // Verify password if calendar is protected
- if (calendar.passwordHash) {
- const { password } = body;
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check edit permissions (works for both authenticated users and guests)
+ const user = await getSessionUser(request.headers);
+ const hasAccess = await canEditCalendar(user?.id, calendarId);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions. Write access required." },
+ { status: 403 }
+ );
}
let finalCalendarUrl;
@@ -198,6 +197,22 @@ export async function POST(request: Request) {
})
.returning();
+ // Log external sync creation event
+ if (user) {
+ await logUserAction<SyncCreatedMetadata>({
+ action: "sync.created",
+ userId: user.id,
+ resourceType: "sync",
+ resourceId: externalSync.id,
+ metadata: {
+ calendarName: calendar.name,
+ syncUrl: isOneTimeImport ? "file-upload" : finalCalendarUrl,
+ syncName: externalSync.name,
+ },
+ request,
+ });
+ }
+
return NextResponse.json(externalSync, { status: 201 });
} catch (error) {
console.error("Failed to create external sync:", error);
diff --git a/app/api/notes/[id]/route.ts b/app/api/notes/[id]/route.ts
index 6452a6d..1c0725e 100644
--- a/app/api/notes/[id]/route.ts
+++ b/app/api/notes/[id]/route.ts
@@ -3,7 +3,8 @@ import { db } from "@/lib/db";
import { calendarNotes, calendars } from "@/lib/db/schema";
import { eq } from "drizzle-orm";
import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";
-import { verifyPassword } from "@/lib/password-utils";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";
// GET single calendar note
export async function GET(
@@ -12,8 +13,6 @@ export async function GET(
) {
try {
const { id } = await params;
- const { searchParams } = new URL(request.url);
- const password = searchParams.get("password");
const result = await db
.select()
@@ -27,7 +26,7 @@ export async function GET(
);
}
- // Fetch calendar to check password
+ // Fetch calendar
const [calendar] = await db
.select()
.from(calendars)
@@ -40,14 +39,14 @@ export async function GET(
);
}
- // Verify password if calendar is protected AND locked
- if (calendar.passwordHash && calendar.isLocked) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check permissions (works for both authenticated users and guests)
+ const user = await getSessionUser(request.headers);
+ const hasAccess = await canViewCalendar(user?.id, calendar.id);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
}
return NextResponse.json(result[0]);
@@ -68,8 +67,7 @@ export async function PUT(
try {
const { id } = await params;
const body = await request.json();
- const { note, type, color, recurringPattern, recurringInterval, password } =
- body;
+ const { note, type, color, recurringPattern, recurringInterval } = body;
if (!note) {
return NextResponse.json({ error: "Note is required" }, { status: 400 });
@@ -88,7 +86,7 @@ export async function PUT(
);
}
- // Fetch calendar to check password
+ // Fetch calendar
const [calendar] = await db
.select()
.from(calendars)
@@ -101,14 +99,13 @@ export async function PUT(
);
}
- // Verify password if calendar is protected
- if (calendar.passwordHash) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check permissions
+ const user = await getSessionUser(request.headers);
+ if (user && !(await canEditCalendar(user.id, calendar.id))) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
}
// Determine the final type value
@@ -176,19 +173,6 @@ export async function DELETE(
try {
const { id } = await params;
- // Read password from request body
- let password: string | null = null;
- const contentType = request.headers.get("content-type");
-
- if (contentType?.includes("application/json")) {
- try {
- const body = await request.json();
- password = body.password || null;
- } catch {
- // If body parsing fails, continue with null password
- }
- }
-
// Fetch existing note to get calendar ID
const [existingNote] = await db
.select()
@@ -202,7 +186,7 @@ export async function DELETE(
);
}
- // Fetch calendar to check password
+ // Fetch calendar
const [calendar] = await db
.select()
.from(calendars)
@@ -215,14 +199,14 @@ export async function DELETE(
);
}
- // Verify password if calendar is protected
- if (calendar.passwordHash) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check permissions (works for both authenticated users and guests)
+ const user = await getSessionUser(request.headers);
+ const hasAccess = await canEditCalendar(user?.id, calendar.id);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
}
const result = await db
diff --git a/app/api/notes/route.ts b/app/api/notes/route.ts
index 5a88dfb..e0edf80 100644
--- a/app/api/notes/route.ts
+++ b/app/api/notes/route.ts
@@ -3,7 +3,8 @@ import { db } from "@/lib/db";
import { calendarNotes, calendars } from "@/lib/db/schema";
import { eq, and, gte, lte } from "drizzle-orm";
import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";
-import { verifyPassword } from "@/lib/password-utils";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";
// GET calendar notes for a calendar (with optional date filter)
export async function GET(request: Request) {
@@ -19,9 +20,7 @@ export async function GET(request: Request) {
);
}
- const password = searchParams.get("password");
-
- // Fetch calendar to check password
+ // Fetch calendar
const [calendar] = await db
.select()
.from(calendars)
@@ -34,14 +33,14 @@ export async function GET(request: Request) {
);
}
- // Verify password if calendar is protected AND locked
- if (calendar.passwordHash && calendar.isLocked) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check permissions (works for both authenticated users and guests)
+ const user = await getSessionUser(request.headers);
+ const hasAccess = await canViewCalendar(user?.id, calendar.id);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
}
const query = db
@@ -90,7 +89,6 @@ export async function POST(request: Request) {
color,
recurringPattern,
recurringInterval,
- password,
} = body;
if (!calendarId || !date || !note) {
@@ -108,7 +106,7 @@ export async function POST(request: Request) {
);
}
- // Fetch calendar to check password
+ // Fetch calendar
const [calendar] = await db
.select()
.from(calendars)
@@ -121,14 +119,14 @@ export async function POST(request: Request) {
);
}
- // Verify password if calendar is protected
- if (calendar.passwordHash) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check permissions (works for both authenticated users and guests)
+ const user = await getSessionUser(request.headers);
+ const hasAccess = await canEditCalendar(user?.id, calendar.id);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
}
const [calendarNote] = await db
diff --git a/app/api/presets/[id]/route.ts b/app/api/presets/[id]/route.ts
index c5d3c89..5d74a0a 100644
--- a/app/api/presets/[id]/route.ts
+++ b/app/api/presets/[id]/route.ts
@@ -2,8 +2,9 @@ import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { shiftPresets, shifts, calendars } from "@/lib/db/schema";
import { eq } from "drizzle-orm";
-import { verifyPassword } from "@/lib/password-utils";
import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";
// GET single preset
export async function GET(
@@ -12,8 +13,7 @@ export async function GET(
) {
try {
const { id } = await params;
- const { searchParams } = new URL(request.url);
- const password = searchParams.get("password");
+ const user = await getSessionUser(request.headers);
const [preset] = await db
.select()
@@ -24,7 +24,7 @@ export async function GET(
return NextResponse.json({ error: "Preset not found" }, { status: 404 });
}
- // Fetch calendar to check password
+ // Fetch calendar
const [calendar] = await db
.select()
.from(calendars)
@@ -37,14 +37,13 @@ export async function GET(
);
}
- // Verify password if calendar is protected AND locked
- if (calendar.passwordHash && calendar.isLocked) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check read permission (works for both authenticated users and guests)
+ const hasAccess = await canViewCalendar(user?.id, preset.calendarId);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
}
return NextResponse.json(preset);
@@ -74,9 +73,10 @@ export async function PATCH(
isSecondary,
isAllDay,
hideFromStats,
- password,
} = body;
+ const user = await getSessionUser(request.headers);
+
// Fetch preset to get calendar ID
const [existingPreset] = await db
.select()
@@ -87,7 +87,7 @@ export async function PATCH(
return NextResponse.json({ error: "Preset not found" }, { status: 404 });
}
- // Fetch calendar to check password
+ // Fetch calendar
const [calendar] = await db
.select()
.from(calendars)
@@ -100,14 +100,16 @@ export async function PATCH(
);
}
- // Verify password if calendar is protected
- if (calendar.passwordHash) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check edit permission (works for both authenticated users and guests)
+ const hasAccess = await canEditCalendar(
+ user?.id,
+ existingPreset.calendarId
+ );
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
}
const [updatedPreset] = await db
@@ -165,19 +167,7 @@ export async function DELETE(
) {
try {
const { id } = await params;
-
- // Read password from request body
- let password: string | null = null;
- const contentType = request.headers.get("content-type");
-
- if (contentType?.includes("application/json")) {
- try {
- const body = await request.json();
- password = body.password || null;
- } catch {
- // If body parsing fails, continue with null password
- }
- }
+ const user = await getSessionUser(request.headers);
// Fetch preset to get calendar ID
const [preset] = await db
@@ -189,7 +179,7 @@ export async function DELETE(
return NextResponse.json({ error: "Preset not found" }, { status: 404 });
}
- // Fetch calendar to check password
+ // Fetch calendar
const [calendar] = await db
.select()
.from(calendars)
@@ -202,14 +192,13 @@ export async function DELETE(
);
}
- // Verify password if calendar is protected
- if (calendar.passwordHash) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check edit permission (works for both authenticated users and guests)
+ const hasAccess = await canEditCalendar(user?.id, preset.calendarId);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
}
// Delete all shifts that were created from this preset
diff --git a/app/api/presets/reorder/route.ts b/app/api/presets/reorder/route.ts
index b49ce30..eeec2a2 100644
--- a/app/api/presets/reorder/route.ts
+++ b/app/api/presets/reorder/route.ts
@@ -2,14 +2,15 @@ import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { shiftPresets, calendars } from "@/lib/db/schema";
import { eq } from "drizzle-orm";
-import { verifyPassword } from "@/lib/password-utils";
import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { canEditCalendar } from "@/lib/auth/permissions";
// PATCH reorder presets
export async function PATCH(request: NextRequest) {
try {
const body = await request.json();
- const { calendarId, presetOrders, password } = body;
+ const { calendarId, presetOrders } = body;
if (!calendarId || !presetOrders || !Array.isArray(presetOrders)) {
return NextResponse.json(
@@ -34,7 +35,9 @@ export async function PATCH(request: NextRequest) {
);
}
- // Fetch calendar to check password
+ const user = await getSessionUser(request.headers);
+
+ // Fetch calendar
const [calendar] = await db
.select()
.from(calendars)
@@ -47,14 +50,13 @@ export async function PATCH(request: NextRequest) {
);
}
- // Verify password if calendar is protected
- if (calendar.passwordHash) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check edit permission (works for both authenticated users and guests)
+ const hasAccess = await canEditCalendar(user?.id, calendarId);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
}
// Verify all preset IDs belong to the specified calendarId
diff --git a/app/api/presets/route.ts b/app/api/presets/route.ts
index 79a51e2..ae994c3 100644
--- a/app/api/presets/route.ts
+++ b/app/api/presets/route.ts
@@ -2,8 +2,9 @@ import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { shiftPresets, calendars } from "@/lib/db/schema";
import { eq, asc } from "drizzle-orm";
-import { verifyPassword } from "@/lib/password-utils";
import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";
// GET all presets for a calendar
export async function GET(request: NextRequest) {
@@ -18,9 +19,9 @@ export async function GET(request: NextRequest) {
);
}
- const password = searchParams.get("password");
+ const user = await getSessionUser(request.headers);
- // Fetch calendar to check password
+ // Fetch calendar
const [calendar] = await db
.select()
.from(calendars)
@@ -33,14 +34,13 @@ export async function GET(request: NextRequest) {
);
}
- // Verify password if calendar is protected AND locked
- if (calendar.passwordHash && calendar.isLocked) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check read permission (works for both authenticated users and guests)
+ const hasAccess = await canViewCalendar(user?.id, calendarId);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
}
const presets = await db
@@ -72,7 +72,6 @@ export async function POST(request: NextRequest) {
isSecondary,
isAllDay,
hideFromStats,
- password,
} = body;
if (!calendarId || !title) {
@@ -82,7 +81,9 @@ export async function POST(request: NextRequest) {
);
}
- // Fetch calendar to check password
+ const user = await getSessionUser(request.headers);
+
+ // Fetch calendar
const [calendar] = await db
.select()
.from(calendars)
@@ -95,14 +96,13 @@ export async function POST(request: NextRequest) {
);
}
- // Verify password if calendar is protected
- if (calendar.passwordHash) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check edit permission (works for both authenticated users and guests)
+ const hasAccess = await canEditCalendar(user?.id, calendarId);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
}
// Get the max order value for this calendar to append new preset at the end
diff --git a/app/api/shifts/[id]/route.ts b/app/api/shifts/[id]/route.ts
index 3df15d4..56f484d 100644
--- a/app/api/shifts/[id]/route.ts
+++ b/app/api/shifts/[id]/route.ts
@@ -2,8 +2,9 @@ import { NextResponse } from "next/server";
import { db } from "@/lib/db";
import { calendars, shifts } from "@/lib/db/schema";
import { eq } from "drizzle-orm";
-import { verifyPassword } from "@/lib/password-utils";
import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";
// GET single shift
export async function GET(
@@ -12,8 +13,7 @@ export async function GET(
) {
try {
const { id } = await params;
- const { searchParams } = new URL(request.url);
- const password = searchParams.get("password");
+ const user = await getSessionUser(request.headers);
const result = await db
.select({
@@ -43,29 +43,15 @@ export async function GET(
return NextResponse.json({ error: "Shift not found" }, { status: 404 });
}
- // Fetch calendar to check password
- const [calendar] = await db
- .select()
- .from(calendars)
- .where(eq(calendars.id, result[0].calendarId));
-
- if (!calendar) {
+ // Check read permission (works for both authenticated users and guests)
+ const hasAccess = await canViewCalendar(user?.id, result[0].calendarId);
+ if (!hasAccess) {
return NextResponse.json(
- { error: "Calendar not found" },
- { status: 404 }
+ { error: "Insufficient permissions" },
+ { status: 403 }
);
}
- // Verify password if calendar is protected AND locked
- if (calendar.passwordHash && calendar.isLocked) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
- }
-
return NextResponse.json(result[0]);
} catch (error) {
console.error("Failed to fetch shift:", error);
@@ -76,7 +62,7 @@ export async function GET(
}
}
-// PATCH update shift
+// PATCH update shift (requires write permission)
export async function PATCH(
request: Request,
{ params }: { params: Promise<{ id: string }> }
@@ -93,9 +79,10 @@ export async function PATCH(
notes,
isAllDay,
isSecondary,
- password,
} = body;
+ const user = await getSessionUser(request.headers);
+
// Fetch shift to get calendar ID
const [existingShift] = await db
.select()
@@ -106,7 +93,7 @@ export async function PATCH(
return NextResponse.json({ error: "Shift not found" }, { status: 404 });
}
- // Fetch calendar to check password
+ // Fetch calendar
const [calendar] = await db
.select()
.from(calendars)
@@ -119,14 +106,13 @@ export async function PATCH(
);
}
- // Verify password if calendar is protected
- if (calendar.passwordHash) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check write permission (works for both authenticated users and guests)
+ const hasAccess = await canEditCalendar(user?.id, existingShift.calendarId);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions. Write access required." },
+ { status: 403 }
+ );
}
const updateData: Partial<typeof shifts.$inferInsert> = {};
@@ -163,26 +149,14 @@ export async function PATCH(
}
}
-// DELETE shift
+// DELETE shift (requires write permission)
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params;
-
- // Read password from request body
- let password: string | null = null;
- const contentType = request.headers.get("content-type");
-
- if (contentType?.includes("application/json")) {
- try {
- const body = await request.json();
- password = body.password || null;
- } catch {
- // If body parsing fails, continue with null password
- }
- }
+ const user = await getSessionUser(request.headers);
// Fetch shift to get calendar ID
const [shift] = await db.select().from(shifts).where(eq(shifts.id, id));
@@ -191,29 +165,15 @@ export async function DELETE(
return NextResponse.json({ error: "Shift not found" }, { status: 404 });
}
- // Fetch calendar to check password
- const [calendar] = await db
- .select()
- .from(calendars)
- .where(eq(calendars.id, shift.calendarId));
-
- if (!calendar) {
+ // Check write permission (works for both authenticated users and guests)
+ const hasAccess = await canEditCalendar(user?.id, shift.calendarId);
+ if (!hasAccess) {
return NextResponse.json(
- { error: "Calendar not found" },
- { status: 404 }
+ { error: "Insufficient permissions. Write access required." },
+ { status: 403 }
);
}
- // Verify password if calendar is protected
- if (calendar.passwordHash) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
- }
-
await db.delete(shifts).where(eq(shifts.id, id));
// Emit event for SSE
diff --git a/app/api/shifts/route.ts b/app/api/shifts/route.ts
index 9b1e54a..68f2f12 100644
--- a/app/api/shifts/route.ts
+++ b/app/api/shifts/route.ts
@@ -2,8 +2,9 @@ import { NextResponse } from "next/server";
import { db } from "@/lib/db";
import { calendars, shifts, externalSyncs } from "@/lib/db/schema";
import { eq, and, gte, lte, or, isNull } from "drizzle-orm";
-import { verifyPassword } from "@/lib/password-utils";
import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";
// GET shifts for a calendar (with optional date filter)
export async function GET(request: Request) {
@@ -19,9 +20,9 @@ export async function GET(request: Request) {
);
}
- const password = searchParams.get("password");
+ const user = await getSessionUser(request.headers);
- // Fetch calendar to check password
+ // Fetch calendar
const [calendar] = await db
.select()
.from(calendars)
@@ -34,14 +35,13 @@ export async function GET(request: Request) {
);
}
- // Verify password if calendar is protected AND locked
- if (calendar.passwordHash && calendar.isLocked) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check read permission (works for both authenticated users and guests)
+ const hasAccess = await canViewCalendar(user?.id, calendarId);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
}
const query = db
@@ -104,7 +104,7 @@ export async function GET(request: Request) {
}
}
-// POST create new shift
+// POST create new shift (requires write permission)
export async function POST(request: Request) {
try {
const body = await request.json();
@@ -119,7 +119,6 @@ export async function POST(request: Request) {
presetId,
isAllDay,
isSecondary,
- password,
} = body;
if (!calendarId || !date || !title) {
@@ -129,7 +128,9 @@ export async function POST(request: Request) {
);
}
- // Fetch calendar to check password
+ const user = await getSessionUser(request.headers);
+
+ // Fetch calendar
const [calendar] = await db
.select()
.from(calendars)
@@ -142,14 +143,13 @@ export async function POST(request: Request) {
);
}
- // Verify password if calendar is protected
- if (calendar.passwordHash) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check write permission (works for both authenticated users and guests)
+ const hasAccess = await canEditCalendar(user?.id, calendarId);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions. Write access required." },
+ { status: 403 }
+ );
}
const [shift] = await db
diff --git a/app/api/shifts/stats/route.ts b/app/api/shifts/stats/route.ts
index 3e8def0..a06d0f3 100644
--- a/app/api/shifts/stats/route.ts
+++ b/app/api/shifts/stats/route.ts
@@ -7,7 +7,8 @@ import {
calendars,
} from "@/lib/db/schema";
import { eq, and, gte, lte, or, isNull } from "drizzle-orm";
-import { verifyPassword } from "@/lib/password-utils";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { canViewCalendar } from "@/lib/auth/permissions";
import { calculateShiftDuration } from "@/lib/date-utils";
import {
startOfWeek,
@@ -33,9 +34,9 @@ export async function GET(request: Request) {
);
}
- const password = searchParams.get("password");
+ const user = await getSessionUser(request.headers);
- // Fetch calendar to check password
+ // Fetch calendar
const [calendar] = await db
.select()
.from(calendars)
@@ -48,14 +49,13 @@ export async function GET(request: Request) {
);
}
- // Verify password if calendar is protected AND locked
- if (calendar.passwordHash && calendar.isLocked) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check read permission (works for both authenticated users and guests)
+ const hasAccess = await canViewCalendar(user?.id, calendarId);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
}
const referenceDate = date ? new Date(date) : new Date();
diff --git a/app/api/sync-logs/route.ts b/app/api/sync-logs/route.ts
index 27a68bb..f401277 100644
--- a/app/api/sync-logs/route.ts
+++ b/app/api/sync-logs/route.ts
@@ -2,13 +2,13 @@ import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { syncLogs, calendars } from "@/lib/db/schema";
import { eq, desc, and } from "drizzle-orm";
-import { verifyPassword } from "@/lib/password-utils";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";
export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
const calendarId = searchParams.get("calendarId");
const limit = parseInt(searchParams.get("limit") || "50");
- const password = searchParams.get("password");
if (!calendarId) {
return NextResponse.json(
@@ -18,7 +18,9 @@ export async function GET(request: NextRequest) {
}
try {
- // Fetch calendar to check password
+ const user = await getSessionUser(request.headers);
+
+ // Fetch calendar
const [calendar] = await db
.select()
.from(calendars)
@@ -31,14 +33,13 @@ export async function GET(request: NextRequest) {
);
}
- // Verify password if calendar is protected AND locked
- if (calendar.passwordHash && calendar.isLocked) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check read permission (works for both authenticated users and guests)
+ const hasAccess = await canViewCalendar(user?.id, calendarId);
+ if (!hasAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions" },
+ { status: 403 }
+ );
}
const logs = await db
@@ -71,20 +72,9 @@ export async function PATCH(request: NextRequest) {
}
try {
- // Read password from request body
- let password: string | null = null;
- const contentType = request.headers.get("content-type");
-
- if (contentType?.includes("application/json")) {
- try {
- const body = await request.json();
- password = body.password || null;
- } catch {
- // If body parsing fails, continue with null password
- }
- }
+ const user = await getSessionUser(request.headers);
- // Fetch calendar to check password
+ // Fetch calendar
const [calendar] = await db
.select()
.from(calendars)
@@ -97,14 +87,12 @@ export async function PATCH(request: NextRequest) {
);
}
- // Verify password if calendar is protected
- if (calendar.passwordHash) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check write permission (if auth is enabled)
+ if (user && !(await canEditCalendar(user.id, calendarId))) {
+ return NextResponse.json(
+ { error: "Insufficient permissions. Write access required." },
+ { status: 403 }
+ );
}
if (action === "markErrorsAsRead") {
@@ -141,20 +129,9 @@ export async function DELETE(request: NextRequest) {
}
try {
- // Read password from request body
- let password: string | null = null;
- const contentType = request.headers.get("content-type");
-
- if (contentType?.includes("application/json")) {
- try {
- const body = await request.json();
- password = body.password || null;
- } catch {
- // If body parsing fails, continue with null password
- }
- }
+ const user = await getSessionUser(request.headers);
- // Fetch calendar to check password
+ // Fetch calendar
const [calendar] = await db
.select()
.from(calendars)
@@ -167,14 +144,13 @@ export async function DELETE(request: NextRequest) {
);
}
- // Verify password if calendar is protected
- if (calendar.passwordHash) {
- if (!password || !verifyPassword(password, calendar.passwordHash)) {
- return NextResponse.json(
- { error: "Invalid password" },
- { status: 401 }
- );
- }
+ // Check write permission (works for both authenticated users and guests)
+ const hasWriteAccess = await canEditCalendar(user?.id, calendarId);
+ if (!hasWriteAccess) {
+ return NextResponse.json(
+ { error: "Insufficient permissions. Write access required." },
+ { status: 403 }
+ );
}
await db.delete(syncLogs).where(eq(syncLogs.calendarId, calendarId));
diff --git a/app/api/users/search/route.ts b/app/api/users/search/route.ts
new file mode 100644
index 0000000..a8250c9
--- /dev/null
+++ b/app/api/users/search/route.ts
@@ -0,0 +1,63 @@
+import { NextRequest, NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { like, or, and, ne } from "drizzle-orm";
+import { user as userTable } from "@/lib/db/schema";
+
+export async function GET(request: NextRequest) {
+ try {
+ const currentUser = await getSessionUser(request.headers);
+
+ if (!currentUser) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ const { searchParams } = new URL(request.url);
+ const query = searchParams.get("q") || "";
+ const calendarId = searchParams.get("calendarId");
+
+ if (!calendarId) {
+ return NextResponse.json(
+ { error: "calendarId is required" },
+ { status: 400 }
+ );
+ }
+
+ // Search users by name or email (case-insensitive)
+ let users = await db.query.user.findMany({
+ where: and(
+ or(
+ like(userTable.name, `%${query}%`),
+ like(userTable.email, `%${query}%`)
+ ),
+ ne(userTable.id, currentUser.id) // Exclude current user
+ ),
+ columns: {
+ id: true,
+ name: true,
+ email: true,
+ image: true,
+ },
+ limit: 10,
+ });
+
+ // Exclude users who already have access to this calendar
+ const existingShares = await db.query.calendarShares.findMany({
+ where: (shares, { eq }) => eq(shares.calendarId, calendarId),
+ columns: {
+ userId: true,
+ },
+ });
+
+ const sharedUserIds = new Set(existingShares.map((s) => s.userId));
+ users = users.filter((u) => !sharedUserIds.has(u.id));
+
+ return NextResponse.json(users);
+ } catch (error) {
+ console.error("Failed to search users:", error);
+ return NextResponse.json(
+ { error: "Failed to search users" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/layout.tsx b/app/layout.tsx
index 8c0ca95..b2d7054 100644
--- a/app/layout.tsx
+++ b/app/layout.tsx
@@ -4,6 +4,9 @@ import { NextIntlClientProvider } from "next-intl";
import { getMessages, getLocale } from "next-intl/server";
import { ThemeProvider } from "@/components/theme-provider";
import { ThemedToaster } from "@/components/themed-toaster";
+import { AuthProvider } from "@/components/auth-provider";
+import { PublicConfigProvider } from "@/components/public-config-provider";
+import { getPublicConfig } from "@/lib/public-config";
import "./globals.css";
const geistSans = Geist({
@@ -62,9 +65,18 @@ export default async function RootLayout({
}>) {
const locale = await getLocale();
const messages = await getMessages();
+ const publicConfig = getPublicConfig();
return (
<html lang={locale} suppressHydrationWarning>
+ <head>
+ {/* Inject public config for immediate client-side access (zero latency) */}
+ <script
+ dangerouslySetInnerHTML={{
+ __html: `window.__PUBLIC_CONFIG__=${JSON.stringify(publicConfig)};`,
+ }}
+ />
+ </head>
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased bg-background text-foreground`}
>
@@ -75,7 +87,9 @@ export default async function RootLayout({
disableTransitionOnChange={false}
>
<NextIntlClientProvider messages={messages} locale={locale}>
- {children}
+ <PublicConfigProvider initialConfig={publicConfig}>
+ <AuthProvider>{children}</AuthProvider>
+ </PublicConfigProvider>
<ThemedToaster />
</NextIntlClientProvider>
</ThemeProvider>
diff --git a/app/login/page.tsx b/app/login/page.tsx
new file mode 100644
index 0000000..be55220
--- /dev/null
+++ b/app/login/page.tsx
@@ -0,0 +1,441 @@
+"use client";
+
+import { useState, useEffect } from "react";
+import { useRouter, useSearchParams } from "next/navigation";
+import { useTranslations } from "next-intl";
+import { useLocale } from "next-intl";
+import Link from "next/link";
+import { signIn } from "@/lib/auth/client";
+import { useAuth } from "@/hooks/useAuth";
+import { useAuthFeatures } from "@/hooks/useAuthFeatures";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { toast } from "sonner";
+import { FullscreenLoader } from "@/components/fullscreen-loader";
+import { AuthHeader } from "@/components/auth-header";
+import { AppFooter } from "@/components/app-footer";
+import { useVersionInfo } from "@/hooks/useVersionInfo";
+import { AlertTriangle, X } from "lucide-react";
+import { format } from "date-fns";
+import { getDateLocale } from "@/lib/locales";
+import {
+ isRateLimitError,
+ handleRateLimitError,
+} from "@/lib/rate-limit-client";
+
+/**
+ * Login page with email/password and OIDC providers
+ *
+ * Features:
+ * - Email/Password authentication
+ * - Social login (Google, GitHub, Discord)
+ * - Custom OIDC provider
+ * - "Continue as Guest" for auth-disabled mode
+ * - Dynamic provider list based on env config
+ */
+export default function LoginPage() {
+ const t = useTranslations();
+ const locale = useLocale();
+ const dateLocale = getDateLocale(locale);
+ const router = useRouter();
+ const searchParams = useSearchParams();
+ const { isAuthenticated } = useAuth();
+ const { isAuthEnabled, allowRegistration, allowGuest, providers, oidc } =
+ useAuthFeatures();
+ const [email, setEmail] = useState("");
+ const [password, setPassword] = useState("");
+ const [isLoading, setIsLoading] = useState(false);
+ const [mounted, setMounted] = useState(false);
+ const [banInfo, setBanInfo] = useState<{
+ reason?: string;
+ expiresAt?: string;
+ } | null>(null);
+ const versionInfo = useVersionInfo();
+
+ useEffect(() => {
+ setMounted(true);
+ }, []);
+
+ // Redirect authenticated users to home or returnUrl
+ useEffect(() => {
+ if (mounted && isAuthenticated) {
+ const returnUrl = searchParams.get("returnUrl");
+ router.replace(returnUrl || "/");
+ }
+ }, [mounted, isAuthenticated, searchParams, router]);
+
+ // If auth is disabled, redirect to home
+ useEffect(() => {
+ if (!isAuthEnabled) {
+ router.replace("/");
+ }
+ }, [isAuthEnabled, router]);
+
+ if (!isAuthEnabled) {
+ return null;
+ }
+
+ // Prevent hydration mismatch by showing loader until mounted
+ if (!mounted) {
+ return <FullscreenLoader />;
+ }
+
+ const handleEmailLogin = async (e: React.FormEvent) => {
+ e.preventDefault();
+
+ if (!email || !password) {
+ toast.error(t("auth.emailRequired"));
+ return;
+ }
+
+ setIsLoading(true);
+
+ try {
+ const result = await signIn.email({
+ email,
+ password,
+ });
+
+ if (result.error) {
+ // Check if user is banned (Better Auth returns BANNED_USER code)
+ if (
+ result.error.code === "BANNED_USER" ||
+ result.error.message?.toLowerCase().includes("banned")
+ ) {
+ // Fetch ban details from our API
+ try {
+ const banResponse = await fetch("/api/auth/ban-info", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ email }),
+ });
+
+ if (banResponse.ok) {
+ const banData = await banResponse.json();
+ setBanInfo({
+ reason: banData.banReason,
+ expiresAt: banData.banExpires,
+ });
+ } else {
+ // Fallback if API fails
+ setBanInfo({
+ reason: result.error.message || t("auth.accountBanned"),
+ });
+ }
+ } catch {
+ // Fallback if fetch fails
+ setBanInfo({
+ reason: result.error.message || t("auth.accountBanned"),
+ });
+ }
+ return;
+ }
+
+ // Check if the error indicates rate limiting (Better Auth wraps 429 errors)
+ // The error might contain the fetch response status
+ if (result.error.status === 429) {
+ // Make a test request to get proper rate limit headers for user-friendly message
+ try {
+ const testResponse = await fetch("/api/auth/sign-in/email", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ email, password }),
+ });
+
+ if (isRateLimitError(testResponse)) {
+ await handleRateLimitError(testResponse, t);
+ return;
+ }
+ } catch {
+ // If test request fails, show generic rate limit message
+ toast.error(t("rateLimit.title"), {
+ description: t("rateLimit.fallback"),
+ });
+ return;
+ }
+ }
+
+ toast.error(t("auth.loginError"));
+ return;
+ }
+
+ toast.success(t("auth.loginSuccess"));
+ // Redirect will be handled by useEffect when isAuthenticated updates
+ } catch (error) {
+ console.error("Login error:", error);
+ toast.error(t("auth.loginError"));
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const handleSocialLogin = async (
+ provider: "google" | "github" | "discord"
+ ) => {
+ setIsLoading(true);
+
+ try {
+ // Get returnUrl from query params for OAuth callback
+ const returnUrl = searchParams.get("returnUrl") || "/";
+ await signIn.social({
+ provider,
+ callbackURL: returnUrl,
+ });
+ } catch (error) {
+ console.error(`${provider} login error:`, error);
+ toast.error(t("auth.loginError"));
+ setIsLoading(false);
+ }
+ };
+
+ const handleCustomOidcLogin = async () => {
+ setIsLoading(true);
+
+ try {
+ // Get returnUrl from query params for OAuth callback
+ const returnUrl = searchParams.get("returnUrl") || "/";
+ await signIn.oauth2({
+ providerId: "custom-oidc",
+ callbackURL: returnUrl,
+ });
+ } catch (error) {
+ console.error("Custom OIDC login error:", error);
+ toast.error(t("auth.loginError"));
+ setIsLoading(false);
+ }
+ };
+
+ if (!isAuthEnabled) {
+ return null;
+ }
+
+ // Prevent hydration mismatch by showing loader until mounted
+ if (!mounted) {
+ return <FullscreenLoader />;
+ }
+
+ return (
+ <div className="flex flex-col min-h-screen">
+ <AuthHeader />
+
+ <div className="flex flex-1 items-center justify-center bg-gradient-to-br from-background via-background to-primary/5 px-4 py-8">
+ <div className="w-full max-w-md space-y-8">
+ {/* Ban Warning Banner */}
+ {banInfo && (
+ <div className="relative rounded-lg border-2 border-destructive bg-destructive/5 p-4 shadow-lg animate-in fade-in slide-in-from-top-4 duration-500">
+ <button
+ onClick={() => setBanInfo(null)}
+ className="absolute top-2 right-2 p-1 rounded-md hover:bg-destructive/10 transition-colors"
+ >
+ <X className="h-4 w-4 text-destructive" />
+ </button>
+ <div className="flex gap-3 pr-6">
+ <AlertTriangle className="h-6 w-6 text-destructive flex-shrink-0 mt-0.5" />
+ <div className="space-y-1">
+ <h3 className="font-semibold text-destructive text-lg">
+ {t("auth.accountBanned")}
+ </h3>
+ {banInfo.reason && (
+ <p className="text-sm text-foreground">{banInfo.reason}</p>
+ )}
+ {banInfo.expiresAt ? (
+ <p className="text-xs text-muted-foreground mt-2">
+ {t("admin.bannedUntil", {
+ date: format(new Date(banInfo.expiresAt), "PPP", {
+ locale: dateLocale,
+ }),
+ })}
+ </p>
+ ) : (
+ <p className="text-xs text-muted-foreground mt-2">
+ {t("admin.bannedPermanently")}
+ </p>
+ )}
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Registration Disabled Info Banner */}
+ {!allowRegistration && (
+ <div className="rounded-lg border border-primary/30 bg-primary/5 p-4 shadow-sm animate-in fade-in slide-in-from-top-4 duration-500">
+ <div className="flex gap-3">
+ <AlertTriangle className="h-5 w-5 text-primary flex-shrink-0 mt-0.5" />
+ <div className="space-y-1">
+ <h3 className="font-semibold text-foreground">
+ {t("auth.registrationDisabled")}
+ </h3>
+ <p className="text-sm text-muted-foreground">
+ {t("auth.registrationDisabledDescription")}
+ </p>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Header */}
+ <div className="text-center space-y-2">
+ <h1 className="text-4xl font-bold tracking-tight bg-gradient-to-r from-foreground via-foreground to-foreground/70 bg-clip-text text-transparent">
+ {t("auth.loginTitle")}
+ </h1>
+ <p className="text-sm text-muted-foreground">
+ {t("auth.loginDescription")}
+ </p>
+ </div>
+
+ {/* Login Form */}
+ <div className="rounded-xl border border-border/50 bg-gradient-to-br from-card/95 via-card to-card/80 p-8 shadow-lg backdrop-blur-sm">
+ <form onSubmit={handleEmailLogin} className="space-y-6">
+ {/* Email */}
+ <div className="space-y-2">
+ <Label htmlFor="email">{t("common.labels.email")}</Label>
+ <Input
+ id="email"
+ type="email"
+ placeholder={t("auth.emailPlaceholder")}
+ value={email}
+ onChange={(e) => setEmail(e.target.value)}
+ disabled={isLoading}
+ required
+ />
+ </div>
+
+ {/* Password */}
+ <div className="space-y-2">
+ <Label htmlFor="password">{t("common.labels.password")}</Label>
+ <Input
+ id="password"
+ type="password"
+ placeholder={t("auth.passwordPlaceholder")}
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ disabled={isLoading}
+ required
+ />
+ </div>
+
+ {/* Submit Button */}
+ <Button type="submit" className="w-full" disabled={isLoading}>
+ {isLoading ? t("common.loading") : t("auth.login")}
+ </Button>
+ </form>
+
+ {/* OAuth Providers */}
+ {(providers.hasAny || oidc.enabled) && (
+ <>
+ <div className="relative my-6">
+ <div className="absolute inset-0 flex items-center">
+ <span className="w-full border-t border-border/50" />
+ </div>
+ <div className="relative flex justify-center text-xs uppercase">
+ <span className="bg-card px-2 text-muted-foreground">
+ {t("common.or")}
+ </span>
+ </div>
+ </div>
+
+ <div className="space-y-3">
+ {providers.google && (
+ <Button
+ variant="outline"
+ className="w-full"
+ onClick={() => handleSocialLogin("google")}
+ disabled={isLoading}
+ >
+ {t("auth.continueWith", {
+ provider: t("auth.provider.google"),
+ })}
+ </Button>
+ )}
+
+ {providers.github && (
+ <Button
+ variant="outline"
+ className="w-full"
+ onClick={() => handleSocialLogin("github")}
+ disabled={isLoading}
+ >
+ {t("auth.continueWith", {
+ provider: t("auth.provider.github"),
+ })}
+ </Button>
+ )}
+
+ {providers.discord && (
+ <Button
+ variant="outline"
+ className="w-full"
+ onClick={() => handleSocialLogin("discord")}
+ disabled={isLoading}
+ >
+ {t("auth.continueWith", {
+ provider: t("auth.provider.discord"),
+ })}
+ </Button>
+ )}
+
+ {oidc.enabled && (
+ <Button
+ variant="outline"
+ className="w-full"
+ onClick={handleCustomOidcLogin}
+ disabled={isLoading}
+ >
+ {t("auth.continueWith", {
+ provider: oidc.name || t("auth.provider.customOidc"),
+ })}
+ </Button>
+ )}
+ </div>
+ </>
+ )}
+
+ {/* Continue as Guest */}
+ {allowGuest && (
+ <>
+ <div className="relative my-6">
+ <div className="absolute inset-0 flex items-center">
+ <span className="w-full border-t border-border/50" />
+ </div>
+ <div className="relative flex justify-center text-xs uppercase">
+ <span className="bg-card px-2 text-muted-foreground">
+ {t("common.or")}
+ </span>
+ </div>
+ </div>
+ <Button
+ variant="ghost"
+ className="w-full border-2 border-dashed border-border/50 hover:border-primary/50 hover:bg-primary/5"
+ onClick={() => {
+ const returnUrl = searchParams.get("returnUrl") || "/";
+ // Use replace instead of push to avoid login redirect loop
+ router.replace(returnUrl);
+ }}
+ disabled={isLoading}
+ >
+ {t("auth.continueAsGuest")}
+ </Button>
+ </>
+ )}
+
+ {/* Register Link */}
+ {allowRegistration && (
+ <p className="mt-6 text-center text-sm text-muted-foreground">
+ {t("auth.noAccountYet")}{" "}
+ <Link
+ href="/register"
+ className="font-medium text-primary hover:underline"
+ >
+ {t("auth.register")}
+ </Link>
+ </p>
+ )}
+ </div>
+ </div>
+ </div>
+
+ <AppFooter versionInfo={versionInfo} />
+ </div>
+ );
+}
diff --git a/app/page.tsx b/app/page.tsx
index ac8b9e6..1b66402 100644
--- a/app/page.tsx
+++ b/app/page.tsx
@@ -20,19 +20,16 @@ import { useShifts } from "@/hooks/useShifts";
import { usePresets } from "@/hooks/usePresets";
import { useNotes } from "@/hooks/useNotes";
import { useSSEConnection } from "@/hooks/useSSEConnection";
-import { usePasswordManagement } from "@/hooks/usePasswordManagement";
import { useViewSettings } from "@/hooks/useViewSettings";
import { useShiftActions } from "@/hooks/useShiftActions";
import { useNoteActions } from "@/hooks/useNoteActions";
import { useExternalSync } from "@/hooks/useExternalSync";
import { useDialogStates } from "@/hooks/useDialogStates";
import { useVersionInfo } from "@/hooks/useVersionInfo";
+import { useAuth } from "@/hooks/useAuth";
import { EmptyCalendarState } from "@/components/empty-calendar-state";
-import { LockedCalendarView } from "@/components/locked-calendar-view";
-import { CalendarSkeleton } from "@/components/calendar-skeleton";
-import { CalendarContentSkeleton } from "@/components/calendar-content-skeleton";
-import { LockedCalendarSkeleton } from "@/components/locked-calendar-skeleton";
-import { CalendarCompareSkeleton } from "@/components/calendar-compare-skeleton";
+import { GuestEmptyState } from "@/components/guest-empty-state";
+import { FullscreenLoader } from "@/components/fullscreen-loader";
import { CalendarContent } from "@/components/calendar-content";
import { CalendarCompareSheet } from "@/components/calendar-compare-sheet";
import { CalendarCompareView } from "@/components/calendar-compare-view";
@@ -40,10 +37,6 @@ import { AppFooter } from "@/components/app-footer";
import { AppHeader } from "@/components/app-header";
import { DialogManager } from "@/components/dialog-manager";
import { getCalendarDays } from "@/lib/calendar-utils";
-import {
- getCachedPassword,
- verifyAndCachePassword,
-} from "@/lib/password-cache";
import { formatDateToLocal } from "@/lib/date-utils";
import { findNotesForDate } from "@/lib/event-utils";
import { toast } from "sonner";
@@ -56,12 +49,16 @@ function HomeContent() {
const dateLocale = getDateLocale(locale);
const t = useTranslations();
+ // Auth hook
+ const { isGuest } = useAuth();
+
// Data hooks
const {
calendars,
selectedCalendar,
setSelectedCalendar,
loading,
+ hasLoadedOnce,
createCalendar: createCalendarHook,
deleteCalendar: deleteCalendarHook,
refetchCalendars,
@@ -71,6 +68,7 @@ function HomeContent() {
shifts,
setShifts,
loading: shiftsLoading,
+ hasLoadedOnce: shiftsLoadedOnce,
createShift: createShiftHook,
updateShift: updateShiftHook,
deleteShift: deleteShiftHook,
@@ -80,6 +78,7 @@ function HomeContent() {
const {
presets,
loading: presetsLoading,
+ hasLoadedOnce: presetsLoadedOnce,
refetchPresets,
} = usePresets(selectedCalendar);
@@ -117,18 +116,6 @@ function HomeContent() {
fetchSyncErrorStatus,
} = useExternalSync(selectedCalendar || null);
- // Password management
- const {
- pendingAction,
- setPendingAction,
- isCalendarUnlocked,
- setIsCalendarUnlocked,
- isVerifyingCalendarPassword,
- shouldHideUIElements,
- handlePasswordSuccess: baseHandlePasswordSuccess,
- verifyPasswordForAction,
- } = usePasswordManagement(selectedCalendar || null, calendars);
-
// View settings
const viewSettings = useViewSettings();
@@ -140,10 +127,6 @@ function HomeContent() {
createNote: createNoteHook,
updateNote: updateNoteHook,
deleteNote: deleteNoteHook,
- onPasswordRequired: (action) => {
- setPendingAction({ type: "edit", action });
- dialogStates.setShowPasswordDialog(true);
- },
});
// Wrapper for note submit that reloads compare data
@@ -164,11 +147,9 @@ function HomeContent() {
// Reload notes for the specific calendar in compare mode
if (isCompareMode && compareNoteCalendarId) {
- const password = getCachedPassword(compareNoteCalendarId);
- const passwordParam = password ? `&password=${password}` : "";
try {
const notesRes = await fetch(
- `/api/notes?calendarId=${compareNoteCalendarId}${passwordParam}`
+ `/api/notes?calendarId=${compareNoteCalendarId}`
);
const notesData = notesRes.ok ? await notesRes.json() : [];
setCompareCalendarData((prev) => {
@@ -191,11 +172,9 @@ function HomeContent() {
// Reload notes for the specific calendar in compare mode
if (isCompareMode && compareNoteCalendarId) {
- const password = getCachedPassword(compareNoteCalendarId);
- const passwordParam = password ? `&password=${password}` : "";
try {
const notesRes = await fetch(
- `/api/notes?calendarId=${compareNoteCalendarId}${passwordParam}`
+ `/api/notes?calendarId=${compareNoteCalendarId}`
);
const notesData = notesRes.ok ? await notesRes.json() : [];
setCompareCalendarData((prev) => {
@@ -222,9 +201,7 @@ function HomeContent() {
};
const handleDeleteNoteFromList = async (noteId: string) => {
- const success = await deleteNoteHook(noteId, () => {
- dialogStates.setShowPasswordDialog(true);
- });
+ const success = await deleteNoteHook(noteId);
if (success) {
// Update the notes list in the dialog
@@ -240,11 +217,9 @@ function HomeContent() {
// Reload compare mode data if needed
if (isCompareMode && compareNoteCalendarId) {
- const password = getCachedPassword(compareNoteCalendarId);
- const passwordParam = password ? `&password=${password}` : "";
try {
const notesRes = await fetch(
- `/api/notes?calendarId=${compareNoteCalendarId}${passwordParam}`
+ `/api/notes?calendarId=${compareNoteCalendarId}`
);
const notesData = notesRes.ok ? await notesRes.json() : [];
setCompareCalendarData((prev) => {
@@ -286,7 +261,6 @@ function HomeContent() {
// Shift actions
const shiftActions = useShiftActions({
- selectedCalendar: selectedCalendar || null,
shifts,
setShifts,
presets,
@@ -294,10 +268,6 @@ function HomeContent() {
updateShift: updateShiftHook,
deleteShift: deleteShiftHook,
onStatsRefresh: () => setStatsRefreshTrigger((prev) => prev + 1),
- onPasswordRequired: (action) => {
- setPendingAction({ type: "edit", action });
- dialogStates.setShowPasswordDialog(true);
- },
});
// SSE Connection
@@ -306,6 +276,7 @@ function HomeContent() {
onShiftUpdate: refetchShifts,
onPresetUpdate: refetchPresets,
onNoteUpdate: refetchNotes,
+ onCalendarUpdate: refetchCalendars,
onStatsRefresh: () => setStatsRefreshTrigger((prev) => prev + 1),
onSyncLogUpdate: () => {
fetchSyncErrorStatus();
@@ -327,18 +298,13 @@ function HomeContent() {
await Promise.all(
selectedCompareIds.map(async (calendarId) => {
try {
- const password = getCachedPassword(calendarId);
- const passwordParam = password ? `&password=${password}` : "";
-
// Fetch all data for this calendar in parallel
const [shiftsRes, notesRes, syncsRes, presetsRes] =
await Promise.all([
- fetch(`/api/shifts?calendarId=${calendarId}${passwordParam}`),
- fetch(`/api/notes?calendarId=${calendarId}${passwordParam}`),
- fetch(
- `/api/external-syncs?calendarId=${calendarId}${passwordParam}`
- ),
- fetch(`/api/presets?calendarId=${calendarId}${passwordParam}`),
+ fetch(`/api/shifts?calendarId=${calendarId}`),
+ fetch(`/api/notes?calendarId=${calendarId}`),
+ fetch(`/api/external-syncs?calendarId=${calendarId}`),
+ fetch(`/api/presets?calendarId=${calendarId}`),
]);
const [shiftsData, notesData, syncsData, presetsData] =
@@ -416,72 +382,18 @@ function HomeContent() {
}
}, [selectedCalendar, isCompareMode, selectedCompareIds, router]);
- // Old URL update effect removed - now handled above
-
- // Handle password success with data refresh
- const handlePasswordSuccess = async () => {
- if (isCompareMode && compareNoteCalendarId) {
- // In compare mode, reload notes for the specific calendar
- await refetchNotes();
- const password = getCachedPassword(compareNoteCalendarId);
- const passwordParam = password ? `&password=${password}` : "";
- const notesRes = await fetch(
- `/api/notes?calendarId=${compareNoteCalendarId}${passwordParam}`
- );
- const notesData = notesRes.ok ? await notesRes.json() : [];
- setCompareCalendarData((prev) => {
- const updated = new Map(prev);
- const data = updated.get(compareNoteCalendarId);
- if (data) {
- updated.set(compareNoteCalendarId, { ...data, notes: notesData });
- }
- return updated;
- });
- } else {
- await Promise.all([
- refetchShifts(),
- refetchPresets(),
- refetchNotes(),
- fetchExternalSyncs(),
- fetchSyncErrorStatus(),
- ]);
- setStatsRefreshTrigger((prev) => prev + 1);
- }
- baseHandlePasswordSuccess();
-
- // Execute pending action if exists
- if (pendingAction?.action) {
- await pendingAction.action();
- setPendingAction(null);
- }
- };
-
// Calendar operations
- const handleDeleteCalendar = async (password?: string) => {
+ const handleDeleteCalendar = async () => {
if (!selectedCalendar) return;
- const success = await deleteCalendarHook(selectedCalendar, password);
+ const success = await deleteCalendarHook(selectedCalendar);
if (success) {
dialogStates.setShowCalendarSettingsDialog(false);
}
};
// External sync operations
- const handleExternalSyncClick = async () => {
- const executed = await verifyPasswordForAction(async () => {
- dialogStates.setShowExternalSyncDialog(true);
- });
- if (!executed) {
- dialogStates.setShowPasswordDialog(true);
- }
- };
-
- const handleSyncNotifications = async () => {
- const executed = await verifyPasswordForAction(async () => {
- dialogStates.setShowSyncNotificationDialog(true);
- });
- if (!executed) {
- dialogStates.setShowPasswordDialog(true);
- }
+ const handleSyncNotifications = () => {
+ dialogStates.setShowSyncNotificationDialog(true);
};
const handleSyncComplete = () => {
@@ -493,14 +405,9 @@ function HomeContent() {
};
// Manual shift creation
- const handleManualShiftCreation = async () => {
- const executed = await verifyPasswordForAction(async () => {
- setSelectedDate(new Date());
- dialogStates.setShowShiftDialog(true);
- });
- if (!executed) {
- dialogStates.setShowPasswordDialog(true);
- }
+ const handleManualShiftCreation = () => {
+ setSelectedDate(new Date());
+ dialogStates.setShowShiftDialog(true);
};
// Day interaction handlers
@@ -651,36 +558,6 @@ function HomeContent() {
});
try {
- const password = getCachedPassword(calendarId);
-
- // Check password if needed
- const result = await verifyAndCachePassword(calendarId, password);
- if (result.protected && !result.valid) {
- // Clear toggling state before showing password dialog
- setCompareCalendarData((prev) => {
- const updated = new Map(prev);
- const data = updated.get(calendarId);
- if (data) {
- const newTogglingDates = new Set(data.togglingDates);
- newTogglingDates.delete(dateKey);
- updated.set(calendarId, {
- ...data,
- togglingDates: newTogglingDates,
- });
- }
- return updated;
- });
- setPendingAction({
- type: "edit",
- calendarId: calendarId,
- action: async () => {
- await handleCompareDayClick(calendarId, targetDate);
- },
- });
- dialogStates.setShowPasswordDialog(true);
- return;
- }
-
// Check if shift already exists
const existingShift = calendarData.shifts.find(
(shift) =>
@@ -696,7 +573,6 @@ function HomeContent() {
const response = await fetch(`/api/shifts/${existingShift.id}`, {
method: "DELETE",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ password }),
});
if (!response.ok) {
@@ -704,11 +580,7 @@ function HomeContent() {
} else {
toast.success(t("common.deleted", { item: t("shift.shift_one") }));
// Reload shifts for this calendar
- const shiftsRes = await fetch(
- `/api/shifts?calendarId=${calendarId}${
- password ? `&password=${password}` : ""
- }`
- );
+ const shiftsRes = await fetch(`/api/shifts?calendarId=${calendarId}`);
const shiftsData = shiftsRes.ok ? await shiftsRes.json() : [];
setCompareCalendarData((prev) => {
const updated = new Map(prev);
@@ -732,7 +604,6 @@ function HomeContent() {
notes: preset.notes || "",
presetId: preset.id,
isAllDay: preset.isAllDay || false,
- password,
};
const response = await fetch("/api/shifts", {
@@ -746,11 +617,7 @@ function HomeContent() {
} else {
toast.success(t("common.created", { item: t("shift.shift_one") }));
// Reload shifts for this calendar
- const shiftsRes = await fetch(
- `/api/shifts?calendarId=${calendarId}${
- password ? `&password=${password}` : ""
- }`
- );
+ const shiftsRes = await fetch(`/api/shifts?calendarId=${calendarId}`);
const shiftsData = shiftsRes.ok ? await shiftsRes.json() : [];
setCompareCalendarData((prev) => {
const updated = new Map(prev);
@@ -871,25 +738,24 @@ function HomeContent() {
dialogStates.setShowSyncedShiftsDialog(true);
};
+ // Show fullscreen loader only on first load (prevents spinner on navigation)
+ // Only show if at least one data source hasn't loaded yet
+ if (
+ (!hasLoadedOnce && loading) ||
+ (!shiftsLoadedOnce && shiftsLoading) ||
+ (!presetsLoadedOnce && presetsLoading)
+ ) {
+ return <FullscreenLoader message={t("common.loading")} />;
+ }
+
// Calendar grid calculations
const calendarDays = getCalendarDays(currentDate);
- // Check if selected calendar is locked and has no cached password
- const isSelectedCalendarLocked =
- selectedCalendar &&
- calendars.find((c) => c.id === selectedCalendar)?.isLocked &&
- !getCachedPassword(selectedCalendar);
-
// If in compare mode, render compare view
if (isCompareMode) {
- // Show skeleton while loading
+ // Show loader while loading compare data
if (compareDataLoading) {
- return (
- <CalendarCompareSkeleton
- count={selectedCompareIds.length}
- hidePresetHeader={viewSettings.hidePresetHeader}
- />
- );
+ return <FullscreenLoader message={t("common.loading")} />;
}
return (
@@ -976,13 +842,10 @@ function HomeContent() {
onHidePresetHeaderChange={viewSettings.handleHidePresetHeaderChange}
onPresetsChange={async (calendarId: string) => {
// Reload presets and shifts for specific calendar
- const password = getCachedPassword(calendarId);
- const passwordParam = password ? `&password=${password}` : "";
-
try {
const [presetsRes, shiftsRes] = await Promise.all([
- fetch(`/api/presets?calendarId=${calendarId}${passwordParam}`),
- fetch(`/api/shifts?calendarId=${calendarId}${passwordParam}`),
+ fetch(`/api/presets?calendarId=${calendarId}`),
+ fetch(`/api/shifts?calendarId=${calendarId}`),
]);
const [presetsData, shiftsData] = await Promise.all([
@@ -1018,12 +881,8 @@ function HomeContent() {
await Promise.all(
selectedCompareIds.map(async (calendarId) => {
try {
- const password = getCachedPassword(calendarId);
- const passwordParam = password
- ? `&password=${password}`
- : "";
const shiftsRes = await fetch(
- `/api/shifts?calendarId=${calendarId}${passwordParam}`
+ `/api/shifts?calendarId=${calendarId}`
);
const shiftsData = shiftsRes.ok
? await shiftsRes.json()
@@ -1055,62 +914,6 @@ function HomeContent() {
loadShifts();
}}
onStatsRefresh={() => setStatsRefreshTrigger((prev) => prev + 1)}
- onPasswordRequired={(calendarId, action) => {
- setPendingAction({ type: "edit", calendarId, action });
- dialogStates.setShowPasswordDialog(true);
- }}
- onUnlockCalendar={(calendarId) => {
- // Reload data for unlocked calendar
- const loadCalendarData = async () => {
- try {
- const password = getCachedPassword(calendarId);
- const passwordParam = password ? `&password=${password}` : "";
-
- const [shiftsRes, notesRes, syncsRes, presetsRes] =
- await Promise.all([
- fetch(
- `/api/shifts?calendarId=${calendarId}${passwordParam}`
- ),
- fetch(
- `/api/notes?calendarId=${calendarId}${passwordParam}`
- ),
- fetch(
- `/api/external-syncs?calendarId=${calendarId}${passwordParam}`
- ),
- fetch(
- `/api/presets?calendarId=${calendarId}${passwordParam}`
- ),
- ]);
-
- const [shiftsData, notesData, syncsData, presetsData] =
- await Promise.all([
- shiftsRes.ok ? shiftsRes.json() : [],
- notesRes.ok ? notesRes.json() : [],
- syncsRes.ok ? syncsRes.json() : [],
- presetsRes.ok ? presetsRes.json() : [],
- ]);
-
- setCompareCalendarData((prev) => {
- const updated = new Map(prev);
- updated.set(calendarId, {
- shifts: shiftsData,
- notes: notesData,
- externalSyncs: syncsData,
- presets: presetsData,
- togglingDates:
- prev.get(calendarId)?.togglingDates || new Set<string>(),
- });
- return updated;
- });
- } catch (error) {
- console.error(
- `Error loading data for calendar ${calendarId}:`,
- error
- );
- }
- };
- loadCalendarData();
- }}
/>
{/* Dialogs still work in compare mode */}
@@ -1122,20 +925,18 @@ function HomeContent() {
onShiftDialogChange={dialogStates.setShowShiftDialog}
onShiftSubmit={shiftActions.handleShiftSubmit}
selectedDate={selectedDate}
- selectedCalendar={
- pendingAction?.calendarId || selectedCalendar || null
- }
+ selectedCalendar={selectedCalendar || null}
onPresetsChange={refetchPresets}
- showPasswordDialog={dialogStates.showPasswordDialog}
- onPasswordDialogChange={dialogStates.setShowPasswordDialog}
calendars={calendars}
- onPasswordSuccess={handlePasswordSuccess}
showCalendarSettingsDialog={dialogStates.showCalendarSettingsDialog}
onCalendarSettingsDialogChange={
dialogStates.setShowCalendarSettingsDialog
}
onCalendarSettingsSuccess={refetchCalendars}
onDeleteCalendar={handleDeleteCalendar}
+ onExternalSyncFromSettings={() =>
+ dialogStates.setShowExternalSyncDialog(true)
+ }
showExternalSyncDialog={dialogStates.showExternalSyncDialog}
onExternalSyncDialogChange={dialogStates.setShowExternalSyncDialog}
syncErrorRefreshTrigger={syncLogRefreshTrigger}
@@ -1193,17 +994,19 @@ function HomeContent() {
);
}
- // Loading state
- if (loading) {
- return <CalendarSkeleton />;
- }
-
// Empty state
if (calendars.length === 0) {
+ // If user is guest, show guest empty state (no create calendar option)
+ if (isGuest) {
+ return <GuestEmptyState />;
+ }
+
+ // Otherwise, show normal empty state with create calendar option
return (
<>
<EmptyCalendarState
onCreateCalendar={() => dialogStates.setShowCalendarDialog(true)}
+ showUserMenu={true}
/>
<DialogManager
showCalendarDialog={dialogStates.showCalendarDialog}
@@ -1215,16 +1018,16 @@ function HomeContent() {
selectedDate={selectedDate}
selectedCalendar={selectedCalendar || null}
onPresetsChange={refetchPresets}
- showPasswordDialog={dialogStates.showPasswordDialog}
- onPasswordDialogChange={dialogStates.setShowPasswordDialog}
calendars={calendars}
- onPasswordSuccess={handlePasswordSuccess}
showCalendarSettingsDialog={dialogStates.showCalendarSettingsDialog}
onCalendarSettingsDialogChange={
dialogStates.setShowCalendarSettingsDialog
}
onCalendarSettingsSuccess={refetchCalendars}
onDeleteCalendar={handleDeleteCalendar}
+ onExternalSyncFromSettings={() =>
+ dialogStates.setShowExternalSyncDialog(true)
+ }
showExternalSyncDialog={dialogStates.showExternalSyncDialog}
onExternalSyncDialogChange={dialogStates.setShowExternalSyncDialog}
syncErrorRefreshTrigger={syncLogRefreshTrigger}
@@ -1309,90 +1112,62 @@ function HomeContent() {
onSelectCalendar={setSelectedCalendar}
onSelectPreset={setSelectedPresetId}
onCreateCalendar={() => dialogStates.setShowCalendarDialog(true)}
- onManagePassword={() =>
- dialogStates.setShowCalendarSettingsDialog(true)
- }
- onExternalSync={handleExternalSyncClick}
+ onSettings={() => dialogStates.setShowCalendarSettingsDialog(true)}
onSyncNotifications={handleSyncNotifications}
onCompare={handleCompareClick}
onPresetsChange={refetchPresets}
onShiftsChange={refetchShifts}
onStatsRefresh={() => setStatsRefreshTrigger((prev) => prev + 1)}
- onPasswordRequired={(action) => {
- setPendingAction({ type: "edit", presetAction: action });
- dialogStates.setShowPasswordDialog(true);
- }}
onManualShiftCreation={handleManualShiftCreation}
onMobileCalendarDialogChange={dialogStates.setShowMobileCalendarDialog}
onViewSettingsClick={() => dialogStates.setShowViewSettingsDialog(true)}
- presetsLoading={presetsLoading && !isSelectedCalendarLocked}
+ presetsLoading={presetsLoading}
hidePresetHeader={viewSettings.hidePresetHeader}
onHidePresetHeaderChange={viewSettings.handleHidePresetHeaderChange}
/>
<div className="container max-w-4xl mx-auto px-1 py-3 sm:p-4 flex-1">
- {isVerifyingCalendarPassword || shiftsLoading ? (
- isSelectedCalendarLocked ? (
- <LockedCalendarSkeleton />
- ) : (
- <CalendarContentSkeleton daysCount={calendarDays.length} />
- )
- ) : selectedCalendar && !isCalendarUnlocked ? (
- <LockedCalendarView
- calendarId={selectedCalendar}
- onUnlock={() => {
- setIsCalendarUnlocked(true);
- handlePasswordSuccess();
- }}
- />
- ) : (
- <CalendarContent
- calendarDays={calendarDays}
- currentDate={currentDate}
- onDateChange={setCurrentDate}
- shifts={shifts}
- notes={notes}
- selectedPresetId={selectedPresetId}
- togglingDates={shiftActions.togglingDates}
- externalSyncs={externalSyncs}
- maxShiftsToShow={
- viewSettings.shiftsPerDay === null
- ? undefined
- : viewSettings.shiftsPerDay
- }
- maxExternalShiftsToShow={
- viewSettings.externalShiftsPerDay === null
- ? undefined
- : viewSettings.externalShiftsPerDay
- }
- showShiftNotes={viewSettings.showShiftNotes}
- showFullTitles={viewSettings.showFullTitles}
- shiftSortType={viewSettings.shiftSortType}
- shiftSortOrder={viewSettings.shiftSortOrder}
- combinedSortMode={viewSettings.combinedSortMode}
- highlightedWeekdays={viewSettings.highlightedWeekdays}
- highlightColor={viewSettings.highlightColor}
- selectedCalendar={selectedCalendar || null}
- statsRefreshTrigger={statsRefreshTrigger}
- shouldHideUIElements={shouldHideUIElements}
- locale={dateLocale}
- onDayClick={handleDayClick}
- onDayRightClick={
- shouldHideUIElements ? undefined : handleDayRightClick
- }
- onNoteIconClick={
- shouldHideUIElements ? undefined : handleNoteIconClick
- }
- onLongPress={shouldHideUIElements ? undefined : handleLongPressDay}
- onShowAllShifts={handleShowAllShifts}
- onShowSyncedShifts={handleShowSyncedShifts}
- onDeleteShift={shiftActions.handleDeleteShift}
- />
- )}
+ <CalendarContent
+ calendarDays={calendarDays}
+ currentDate={currentDate}
+ onDateChange={setCurrentDate}
+ shifts={shifts}
+ notes={notes}
+ selectedPresetId={selectedPresetId}
+ togglingDates={shiftActions.togglingDates}
+ externalSyncs={externalSyncs}
+ maxShiftsToShow={
+ viewSettings.shiftsPerDay === null
+ ? undefined
+ : viewSettings.shiftsPerDay
+ }
+ maxExternalShiftsToShow={
+ viewSettings.externalShiftsPerDay === null
+ ? undefined
+ : viewSettings.externalShiftsPerDay
+ }
+ showShiftNotes={viewSettings.showShiftNotes}
+ showFullTitles={viewSettings.showFullTitles}
+ shiftSortType={viewSettings.shiftSortType}
+ shiftSortOrder={viewSettings.shiftSortOrder}
+ combinedSortMode={viewSettings.combinedSortMode}
+ highlightedWeekdays={viewSettings.highlightedWeekdays}
+ highlightColor={viewSettings.highlightColor}
+ selectedCalendar={selectedCalendar || null}
+ statsRefreshTrigger={statsRefreshTrigger}
+ locale={dateLocale}
+ onDayClick={handleDayClick}
+ onDayRightClick={handleDayRightClick}
+ onNoteIconClick={handleNoteIconClick}
+ onLongPress={handleLongPressDay}
+ onShowAllShifts={handleShowAllShifts}
+ onShowSyncedShifts={handleShowSyncedShifts}
+ onDeleteShift={shiftActions.handleDeleteShift}
+ />
</div>
{/* Floating Action Button */}
- {selectedCalendar && !shouldHideUIElements && (
+ {selectedCalendar && (
<motion.div
className="hidden sm:block fixed bottom-6 right-6 z-50"
initial={{ scale: 0, opacity: 0 }}
@@ -1420,16 +1195,16 @@ function HomeContent() {
selectedDate={selectedDate}
selectedCalendar={selectedCalendar || null}
onPresetsChange={refetchPresets}
- showPasswordDialog={dialogStates.showPasswordDialog}
- onPasswordDialogChange={dialogStates.setShowPasswordDialog}
calendars={calendars}
- onPasswordSuccess={handlePasswordSuccess}
showCalendarSettingsDialog={dialogStates.showCalendarSettingsDialog}
onCalendarSettingsDialogChange={
dialogStates.setShowCalendarSettingsDialog
}
onCalendarSettingsSuccess={refetchCalendars}
onDeleteCalendar={handleDeleteCalendar}
+ onExternalSyncFromSettings={() =>
+ dialogStates.setShowExternalSyncDialog(true)
+ }
showExternalSyncDialog={dialogStates.showExternalSyncDialog}
onExternalSyncDialogChange={dialogStates.setShowExternalSyncDialog}
syncErrorRefreshTrigger={syncLogRefreshTrigger}
diff --git a/app/profile/activity/page.tsx b/app/profile/activity/page.tsx
new file mode 100644
index 0000000..cfeacdf
--- /dev/null
+++ b/app/profile/activity/page.tsx
@@ -0,0 +1,590 @@
+"use client";
+
+import React, { useState, useEffect } from "react";
+import { useRouter } from "next/navigation";
+import { useTranslations, useLocale } from "next-intl";
+import { useAuth } from "@/hooks/useAuth";
+import { useActivityLogs } from "@/hooks/useActivityLogs";
+import { useVersionInfo } from "@/hooks/useVersionInfo";
+import { FullscreenLoader } from "@/components/fullscreen-loader";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Badge } from "@/components/ui/badge";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
+import { AuthHeader } from "@/components/auth-header";
+import { AppFooter } from "@/components/app-footer";
+import {
+ ChevronLeft,
+ ChevronRight,
+ RefreshCw,
+ Trash2,
+ Search,
+ ChevronDown,
+ ChevronUp,
+} from "lucide-react";
+import { format } from "date-fns";
+import { getDateLocale } from "@/lib/locales";
+import { cn } from "@/lib/utils";
+import { toast } from "sonner";
+
+/**
+ * Activity Log Page - Full-screen table view for user activity logs
+ *
+ * Features:
+ * - Merged view of auditLogs + syncLogs
+ * - Advanced filters (type, date range, severity, search)
+ * - Sortable columns
+ * - Expandable rows for metadata
+ * - Pagination
+ * - Actions: Clear all, Mark all as read, Refresh
+ * - Responsive design
+ */
+export default function ActivityLogPage() {
+ const t = useTranslations();
+ const locale = useLocale();
+ const dateLocale = getDateLocale(locale);
+ const router = useRouter();
+ const { isLoading: authLoading, isAuthenticated } = useAuth();
+ const versionInfo = useVersionInfo();
+ const {
+ logs,
+ total,
+ page,
+ limit,
+ hasMore,
+ loading,
+ error,
+ filters,
+ updateFilters,
+ clearFilters,
+ fetchLogs,
+ clearLogs,
+ goToNextPage,
+ goToPreviousPage,
+ } = useActivityLogs();
+
+ // UI State (must be defined before any early returns)
+ const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set());
+ const [sortColumn, setSortColumn] = useState<
+ "timestamp" | "type" | "severity" | null
+ >("timestamp");
+ const [sortDirection, setSortDirection] = useState<"asc" | "desc">("desc");
+ const [clearDialogOpen, setClearDialogOpen] = useState(false);
+ const [startDate, setStartDate] = useState<string>("");
+ const [endDate, setEndDate] = useState<string>("");
+
+ // Redirect to login if not authenticated
+ useEffect(() => {
+ if (!authLoading && !isAuthenticated) {
+ router.replace("/login");
+ }
+ }, [authLoading, isAuthenticated, router]);
+
+ // Show fullscreen loader during initial data fetch
+ if (authLoading || loading) {
+ return <FullscreenLoader />;
+ }
+
+ // Toggle row expansion
+ const toggleRow = (logId: string) => {
+ setExpandedRows((prev) => {
+ const newSet = new Set(prev);
+ if (newSet.has(logId)) {
+ newSet.delete(logId);
+ } else {
+ newSet.add(logId);
+ }
+ return newSet;
+ });
+ };
+
+ // Sort logs
+ const sortedLogs = [...logs].sort((a, b) => {
+ if (!sortColumn) return 0;
+
+ let comparison = 0;
+
+ switch (sortColumn) {
+ case "timestamp":
+ comparison = a.timestamp.getTime() - b.timestamp.getTime();
+ break;
+ case "type":
+ comparison = a.type.localeCompare(b.type);
+ break;
+ case "severity":
+ const severityOrder = { info: 0, warning: 1, error: 2, critical: 3 };
+ comparison =
+ (severityOrder[a.severity as keyof typeof severityOrder] ?? 0) -
+ (severityOrder[b.severity as keyof typeof severityOrder] ?? 0);
+ break;
+ }
+
+ return sortDirection === "asc" ? comparison : -comparison;
+ });
+
+ // Handle sort column click
+ const handleSort = (column: "timestamp" | "type" | "severity") => {
+ if (sortColumn === column) {
+ setSortDirection((prev) => (prev === "asc" ? "desc" : "asc"));
+ } else {
+ setSortColumn(column);
+ setSortDirection("desc");
+ }
+ };
+
+ // Severity badge color
+ const getSeverityColor = (severity: string) => {
+ switch (severity) {
+ case "info":
+ return "bg-blue-500/10 text-blue-500 border-blue-500/20";
+ case "warning":
+ return "bg-yellow-500/10 text-yellow-500 border-yellow-500/20";
+ case "error":
+ return "bg-orange-500/10 text-orange-500 border-orange-500/20";
+ case "critical":
+ return "bg-red-500/10 text-red-500 border-red-500/20";
+ default:
+ return "bg-gray-500/10 text-gray-500 border-gray-500/20";
+ }
+ };
+
+ // Type badge color
+ const getTypeColor = (type: string) => {
+ switch (type) {
+ case "auth":
+ return "bg-purple-500/10 text-purple-500 border-purple-500/20";
+ case "calendar":
+ return "bg-green-500/10 text-green-500 border-green-500/20";
+ case "sync":
+ return "bg-cyan-500/10 text-cyan-500 border-cyan-500/20";
+ case "security":
+ return "bg-red-500/10 text-red-500 border-red-500/20";
+ default:
+ return "bg-gray-500/10 text-gray-500 border-gray-500/20";
+ }
+ };
+
+ // Handle date changes
+ const handleStartDateChange = (value: string) => {
+ setStartDate(value);
+ updateFilters({
+ startDate: value ? new Date(value) : undefined,
+ endDate: endDate ? new Date(endDate) : undefined,
+ });
+ };
+
+ const handleEndDateChange = (value: string) => {
+ setEndDate(value);
+ updateFilters({
+ startDate: startDate ? new Date(startDate) : undefined,
+ endDate: value ? new Date(value) : undefined,
+ });
+ };
+
+ // Clear all logs with confirmation
+ const handleClearAll = async () => {
+ setClearDialogOpen(false);
+ await clearLogs();
+ };
+
+ return (
+ <div className="flex min-h-screen flex-col">
+ <AuthHeader showUserMenu />
+
+ <div className="flex-1 bg-gradient-to-br from-background via-background to-primary/5">
+ <main className="container py-4 sm:py-8 max-w-full sm:max-w-6xl mx-auto px-2 sm:px-4">
+ {/* Header */}
+ <div className="mb-6 sm:mb-8">
+ <h1 className="text-2xl sm:text-4xl font-bold tracking-tight bg-gradient-to-r from-foreground via-foreground to-foreground/70 bg-clip-text text-transparent mb-2">
+ {t("activityLog.title")}
+ </h1>
+ <p className="text-sm text-muted-foreground">
+ {t("activityLog.description")}
+ </p>
+ </div>
+
+ {/* Filters Bar */}
+ <div className="mb-6 space-y-4">
+ <div className="flex flex-col sm:flex-row gap-4">
+ {/* Type Filter */}
+ <Select
+ value={filters.type || "all"}
+ onValueChange={(value) =>
+ updateFilters({
+ type:
+ value === "all"
+ ? undefined
+ : (value as "auth" | "calendar" | "sync" | "security"),
+ })
+ }
+ >
+ <SelectTrigger className="w-full sm:w-[200px]">
+ <SelectValue placeholder={t("activityLog.allTypes")} />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">
+ {t("activityLog.allTypes")}
+ </SelectItem>
+ <SelectItem value="auth">{t("activityLog.auth")}</SelectItem>
+ <SelectItem value="calendar">
+ {t("common.labels.calendar")}
+ </SelectItem>
+ <SelectItem value="sync">{t("activityLog.sync")}</SelectItem>
+ <SelectItem value="security">
+ {t("activityLog.security")}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+
+ {/* Severity Filter */}
+ <Select
+ value={filters.severity || "all"}
+ onValueChange={(value) =>
+ updateFilters({
+ severity:
+ value === "all"
+ ? undefined
+ : (value as "info" | "warning" | "error" | "critical"),
+ })
+ }
+ >
+ <SelectTrigger className="w-full sm:w-[200px]">
+ <SelectValue
+ placeholder={t("common.filters.allSeverities")}
+ />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">
+ {t("common.filters.allSeverities")}
+ </SelectItem>
+ <SelectItem value="info">
+ {t("common.severity.info")}
+ </SelectItem>
+ <SelectItem value="warning">
+ {t("common.severity.warning")}
+ </SelectItem>
+ <SelectItem value="error">
+ {t("common.severity.error")}
+ </SelectItem>
+ <SelectItem value="critical">
+ {t("common.severity.critical")}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+
+ {/* Date Range - Start Date */}
+ <div className="flex flex-col sm:flex-row gap-2 w-full sm:w-auto">
+ <Input
+ type="date"
+ value={startDate}
+ onChange={(e) => handleStartDateChange(e.target.value)}
+ placeholder={t("common.labels.startDate")}
+ className="w-full sm:w-[150px]"
+ />
+ <Input
+ type="date"
+ value={endDate}
+ onChange={(e) => handleEndDateChange(e.target.value)}
+ placeholder={t("common.labels.endDate")}
+ className="w-full sm:w-[150px]"
+ />
+ </div>
+
+ {/* Search */}
+ <div className="relative flex-1">
+ <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
+ <Input
+ placeholder={t("activityLog.searchPlaceholder")}
+ value={filters.search || ""}
+ onChange={(e) => updateFilters({ search: e.target.value })}
+ className="pl-9"
+ />
+ </div>
+
+ {/* Clear Filters */}
+ {(filters.type ||
+ filters.severity ||
+ startDate ||
+ endDate ||
+ filters.search) && (
+ <Button
+ variant="outline"
+ onClick={() => {
+ clearFilters();
+ setStartDate("");
+ setEndDate("");
+ }}
+ >
+ {t("common.filters.clearFilters")}
+ </Button>
+ )}
+ </div>
+
+ {/* Actions Row */}
+ <div className="flex items-center justify-between">
+ <div className="text-sm text-muted-foreground">
+ {t("activityLog.totalLogs", { count: total })}
+ </div>
+
+ <div className="flex gap-2 flex-wrap">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={async () => {
+ await fetchLogs();
+ toast.success(t("activityLog.refreshed"));
+ }}
+ >
+ <RefreshCw className="h-4 w-4 mr-1" />
+ <span className="hidden sm:inline">
+ {t("activityLog.refresh")}
+ </span>
+ </Button>
+
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setClearDialogOpen(true)}
+ disabled={total === 0}
+ >
+ <Trash2 className="h-4 w-4 mr-1" />
+ <span className="hidden sm:inline">
+ {t("activityLog.clearAll")}
+ </span>
+ </Button>
+ </div>
+ </div>
+ </div>
+
+ {/* Table */}
+ {loading && logs.length === 0 ? (
+ <div className="text-center py-12 text-muted-foreground">
+ {t("common.loading")}
+ </div>
+ ) : error ? (
+ <div className="text-center py-12 text-red-500">
+ {t("common.error")}: {error}
+ </div>
+ ) : logs.length === 0 ? (
+ <div className="text-center py-12 text-muted-foreground">
+ {t("activityLog.noLogs")}
+ </div>
+ ) : (
+ <div className="border border-border/50 bg-gradient-to-br from-card/95 via-card to-card/80 backdrop-blur-sm rounded-lg overflow-hidden shadow-sm">
+ <Table>
+ <TableHeader className="bg-muted/50">
+ <TableRow>
+ <TableHead className="w-8"></TableHead>
+ <TableHead
+ className="cursor-pointer hover:bg-muted/80 transition-colors"
+ onClick={() => handleSort("timestamp")}
+ >
+ <div className="flex items-center gap-2">
+ {t("common.labels.time")}
+ {sortColumn === "timestamp" &&
+ (sortDirection === "asc" ? (
+ <ChevronUp className="h-4 w-4" />
+ ) : (
+ <ChevronDown className="h-4 w-4" />
+ ))}
+ </div>
+ </TableHead>
+ <TableHead
+ className="cursor-pointer hover:bg-muted/80 transition-colors"
+ onClick={() => handleSort("type")}
+ >
+ <div className="flex items-center gap-2">
+ {t("activityLog.eventType")}
+ {sortColumn === "type" &&
+ (sortDirection === "asc" ? (
+ <ChevronUp className="h-4 w-4" />
+ ) : (
+ <ChevronDown className="h-4 w-4" />
+ ))}
+ </div>
+ </TableHead>
+ <TableHead>{t("common.labels.action")}</TableHead>
+ <TableHead>{t("activityLog.resource")}</TableHead>
+ <TableHead
+ className="cursor-pointer hover:bg-muted/80 transition-colors"
+ onClick={() => handleSort("severity")}
+ >
+ <div className="flex items-center gap-2">
+ {t("common.labels.severity")}
+ {sortColumn === "severity" &&
+ (sortDirection === "asc" ? (
+ <ChevronUp className="h-4 w-4" />
+ ) : (
+ <ChevronDown className="h-4 w-4" />
+ ))}
+ </div>
+ </TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {sortedLogs.map((log) => (
+ <React.Fragment key={log.id}>
+ <TableRow
+ className="cursor-pointer"
+ onClick={() => toggleRow(log.id)}
+ >
+ <TableCell className="text-center">
+ {expandedRows.has(log.id) ? (
+ <ChevronUp className="h-4 w-4 text-muted-foreground" />
+ ) : (
+ <ChevronDown className="h-4 w-4 text-muted-foreground" />
+ )}
+ </TableCell>
+ <TableCell className="text-sm">
+ {log.timestamp &&
+ log.timestamp instanceof Date &&
+ !isNaN(log.timestamp.getTime()) ? (
+ <>
+ {format(log.timestamp, "MMM dd, yyyy", {
+ locale: dateLocale,
+ })}
+ <br />
+ <span className="text-xs text-muted-foreground">
+ {format(log.timestamp, "HH:mm:ss", {
+ locale: dateLocale,
+ })}
+ </span>
+ </>
+ ) : (
+ <span className="text-xs text-muted-foreground">
+ Invalid date
+ </span>
+ )}
+ </TableCell>
+ <TableCell>
+ <Badge
+ variant="outline"
+ className={cn("text-xs", getTypeColor(log.type))}
+ >
+ {t(`activityLog.${log.type}`)}
+ </Badge>
+ </TableCell>
+ <TableCell className="text-sm font-mono text-xs">
+ {log.action}
+ </TableCell>
+ <TableCell className="text-sm text-muted-foreground">
+ {log.resourceType ? (
+ <span>
+ {log.resourceType}
+ {log.resourceId && (
+ <span className="text-xs block truncate max-w-[150px]">
+ {log.resourceId}
+ </span>
+ )}
+ </span>
+ ) : (
+ "-"
+ )}
+ </TableCell>
+ <TableCell>
+ <Badge
+ variant="outline"
+ className={cn(
+ "text-xs",
+ getSeverityColor(log.severity)
+ )}
+ >
+ {t(`common.severity.${log.severity}`)}
+ </Badge>
+ </TableCell>
+ </TableRow>
+
+ {/* Expanded Row - Metadata */}
+ {expandedRows.has(log.id) && (
+ <TableRow className="bg-muted/20">
+ <TableCell colSpan={6} className="p-4">
+ <div className="space-y-2">
+ <div className="text-sm font-semibold">
+ {t("activityLog.details")}:
+ </div>
+ {log.metadata ? (
+ <pre className="text-xs bg-background p-3 rounded border whitespace-pre-wrap break-words overflow-auto max-w-full">
+ {JSON.stringify(log.metadata, null, 2)}
+ </pre>
+ ) : (
+ <p className="text-sm text-muted-foreground">
+ {t("activityLog.noMetadata")}
+ </p>
+ )}
+ </div>
+ </TableCell>
+ </TableRow>
+ )}
+ </React.Fragment>
+ ))}
+ </TableBody>
+ </Table>
+
+ {/* Pagination */}
+ <div className="flex items-center justify-between p-4 border-t bg-muted/20">
+ <div className="text-sm text-muted-foreground">
+ {t("activityLog.showingResults", {
+ start: page * limit + 1,
+ end: Math.min((page + 1) * limit, total),
+ total,
+ })}
+ </div>
+
+ <div className="flex gap-2">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={goToPreviousPage}
+ disabled={page === 0}
+ >
+ <ChevronLeft className="h-4 w-4 mr-1" />
+ {t("common.previous")}
+ </Button>
+
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={goToNextPage}
+ disabled={!hasMore}
+ >
+ {t("common.next")}
+ <ChevronRight className="h-4 w-4 ml-1" />
+ </Button>
+ </div>
+ </div>
+ </div>
+ )}
+ </main>
+ </div>
+
+ <AppFooter versionInfo={versionInfo} />
+
+ {/* Clear All Confirmation Dialog */}
+ <ConfirmationDialog
+ open={clearDialogOpen}
+ onOpenChange={setClearDialogOpen}
+ onConfirm={handleClearAll}
+ title={t("activityLog.clearAll")}
+ description={t("activityLog.confirmClear")}
+ confirmText={t("common.delete")}
+ cancelText={t("common.cancel")}
+ confirmVariant="destructive"
+ />
+ </div>
+ );
+}
diff --git a/app/profile/page.tsx b/app/profile/page.tsx
new file mode 100644
index 0000000..e740b31
--- /dev/null
+++ b/app/profile/page.tsx
@@ -0,0 +1,833 @@
+"use client";
+
+import { useState, useEffect } from "react";
+import { useRouter } from "next/navigation";
+import { useTranslations } from "next-intl";
+import { useAuth } from "@/hooks/useAuth";
+import { useAuthFeatures } from "@/hooks/useAuthFeatures";
+import { useConnectedAccounts } from "@/hooks/useConnectedAccounts";
+import { useSessions } from "@/hooks/useSessions";
+import { signOut } from "@/lib/auth/client";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { UAParser } from "ua-parser-js";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { Separator } from "@/components/ui/separator";
+import { toast } from "sonner";
+import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
+import { AuthHeader } from "@/components/auth-header";
+import { Smartphone, Monitor, Tablet, HelpCircle, LogOut } from "lucide-react";
+import { AppFooter } from "@/components/app-footer";
+import { FullscreenLoader } from "@/components/fullscreen-loader";
+import { useVersionInfo } from "@/hooks/useVersionInfo";
+import {
+ isRateLimitError,
+ handleRateLimitError,
+} from "@/lib/rate-limit-client";
+
+/**
+ * User profile page
+ *
+ * Features:
+ * - Display user info
+ * - Change password
+ * - Change email
+ * - Connected OAuth accounts
+ * - Delete account
+ */
+export default function ProfilePage() {
+ const t = useTranslations();
+ const router = useRouter();
+ const { user, isLoading, refetch } = useAuth();
+ const { isAuthEnabled } = useAuthFeatures();
+ const { accounts, isLoading: accountsLoading } = useConnectedAccounts();
+ const {
+ sessions,
+ isLoading: sessionsLoading,
+ revokeAllSessions,
+ } = useSessions();
+ const [currentPassword, setCurrentPassword] = useState("");
+ const [newPassword, setNewPassword] = useState("");
+ const [confirmNewPassword, setConfirmNewPassword] = useState("");
+ const [isChangingPassword, setIsChangingPassword] = useState(false);
+ const [showDeleteDialog, setShowDeleteDialog] = useState(false);
+ const [deletePassword, setDeletePassword] = useState("");
+ const [isDeleting, setIsDeleting] = useState(false);
+ const [mounted, setMounted] = useState(false);
+ const versionInfo = useVersionInfo();
+
+ // Profile editing state
+ const [editName, setEditName] = useState("");
+ const [editEmail, setEditEmail] = useState("");
+ const [isUpdatingProfile, setIsUpdatingProfile] = useState(false);
+ const [avatarFile, setAvatarFile] = useState<File | null>(null);
+ const [avatarPreview, setAvatarPreview] = useState<string>("");
+ const [isUploadingAvatar, setIsUploadingAvatar] = useState(false);
+
+ // Check if user has password-based authentication
+ const hasPasswordAuth = accounts.some(
+ (account) => account.provider === "credential"
+ );
+
+ // Prevent hydration mismatch
+ useEffect(() => {
+ setMounted(true);
+ }, []);
+
+ // Initialize edit fields when user loads
+ useEffect(() => {
+ if (user) {
+ setEditName(user.name || "");
+ setEditEmail(user.email || "");
+ setAvatarPreview(user.image || "");
+ }
+ }, [user]);
+
+ // Redirect if auth disabled or not logged in
+ useEffect(() => {
+ if (!isAuthEnabled) {
+ router.replace("/");
+ } else if (!isLoading && !user) {
+ router.replace("/login");
+ }
+ }, [isAuthEnabled, isLoading, user, router]);
+
+ // Show fullscreen loader during initial data fetch
+ if (isLoading || accountsLoading || sessionsLoading) {
+ return <FullscreenLoader />;
+ }
+
+ if (!isAuthEnabled || !user) {
+ return null;
+ }
+
+ // Don't render until mounted (prevent hydration issues)
+ if (!mounted) {
+ return null;
+ }
+
+ const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ if (!file) return;
+
+ // Validate file type
+ if (!file.type.startsWith("image/")) {
+ toast.error(t("auth.invalidImageType"));
+ return;
+ }
+
+ // Validate file size (max 5MB)
+ if (file.size > 5 * 1024 * 1024) {
+ toast.error(t("auth.imageTooLarge"));
+ return;
+ }
+
+ setAvatarFile(file);
+
+ // Create preview
+ const reader = new FileReader();
+ reader.onloadend = () => {
+ setAvatarPreview(reader.result as string);
+ };
+ reader.readAsDataURL(file);
+ };
+
+ const handleUpdateProfile = async (e: React.FormEvent) => {
+ e.preventDefault();
+
+ if (!editName.trim()) {
+ toast.error(t("auth.nameRequired"));
+ return;
+ }
+
+ if (!editEmail.trim()) {
+ toast.error(t("auth.emailRequired"));
+ return;
+ }
+
+ setIsUpdatingProfile(true);
+
+ try {
+ // Upload avatar first if changed
+ let imageUrl = user?.image;
+ if (avatarFile) {
+ setIsUploadingAvatar(true);
+ const formData = new FormData();
+ formData.append("file", avatarFile);
+
+ const uploadResponse = await fetch("/api/auth/upload-avatar", {
+ method: "POST",
+ body: formData,
+ });
+
+ // Check for rate limit error
+ if (isRateLimitError(uploadResponse)) {
+ await handleRateLimitError(uploadResponse, t);
+ return;
+ }
+
+ if (!uploadResponse.ok) {
+ toast.error(t("auth.avatarUploadFailed"));
+ return;
+ }
+
+ const uploadData = await uploadResponse.json();
+ imageUrl = uploadData.url;
+ setIsUploadingAvatar(false);
+ }
+
+ // Update name and image via Better Auth API
+ const updateResponse = await fetch("/api/auth/update-user", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ name: editName,
+ image: imageUrl,
+ }),
+ });
+
+ if (isRateLimitError(updateResponse)) {
+ await handleRateLimitError(updateResponse, t);
+ return;
+ }
+
+ if (!updateResponse.ok) {
+ const updateData = await updateResponse.json();
+ toast.error(updateData.error || t("common.error"));
+ return;
+ }
+
+ // Update email if changed (without verification)
+ if (editEmail !== user?.email) {
+ const emailResponse = await fetch("/api/auth/change-email", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ newEmail: editEmail,
+ }),
+ });
+
+ if (isRateLimitError(emailResponse)) {
+ await handleRateLimitError(emailResponse, t);
+ return;
+ }
+
+ if (!emailResponse.ok) {
+ const emailData = await emailResponse.json();
+ toast.error(emailData.error || t("common.error"));
+ return;
+ }
+ }
+
+ toast.success(t("auth.profileUpdated"));
+ setAvatarFile(null);
+
+ // Reload user data without page refresh
+ await refetch();
+ } catch (error) {
+ console.error("Profile update error:", error);
+ toast.error(t("common.error"));
+ } finally {
+ setIsUpdatingProfile(false);
+ setIsUploadingAvatar(false);
+ }
+ };
+
+ const handleChangePassword = async (e: React.FormEvent) => {
+ e.preventDefault();
+
+ if (!currentPassword || !newPassword) {
+ toast.error(t("validation.passwordRequired"));
+ return;
+ }
+
+ if (newPassword.length < 8) {
+ toast.error(t("validation.passwordTooShort"));
+ return;
+ }
+
+ if (newPassword !== confirmNewPassword) {
+ toast.error(t("validation.passwordsNoMatch"));
+ return;
+ }
+
+ setIsChangingPassword(true);
+
+ try {
+ // Check for rate limiting first
+ const response = await fetch("/api/auth/change-password", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ newPassword,
+ currentPassword,
+ revokeOtherSessions: false,
+ }),
+ });
+
+ if (isRateLimitError(response)) {
+ await handleRateLimitError(response, t);
+ return;
+ }
+
+ const result = await response.json();
+
+ if (!response.ok) {
+ toast.error(result.error || t("common.error"));
+ return;
+ }
+
+ toast.success(t("auth.passwordChanged"));
+ setCurrentPassword("");
+ setNewPassword("");
+ setConfirmNewPassword("");
+ } catch (error) {
+ console.error("Password change error:", error);
+ toast.error(t("common.error"));
+ } finally {
+ setIsChangingPassword(false);
+ }
+ };
+
+ const handleDeleteAccount = async () => {
+ setIsDeleting(true);
+ try {
+ // Use our custom delete endpoint to properly handle foreign key constraints
+ const response = await fetch("/api/auth/delete-account", {
+ method: "DELETE",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: hasPasswordAuth
+ ? JSON.stringify({ password: deletePassword })
+ : undefined,
+ });
+
+ // Check for rate limit error
+ if (isRateLimitError(response)) {
+ await handleRateLimitError(response, t);
+ return;
+ }
+
+ const data = await response.json();
+
+ if (!response.ok) {
+ toast.error(data.error || t("common.error"));
+ return;
+ }
+
+ toast.success(t("auth.accountDeleted"));
+ setShowDeleteDialog(false);
+ setDeletePassword("");
+
+ // Sign out and redirect
+ await signOut();
+ router.replace("/");
+ } catch (error) {
+ console.error("Account deletion error:", error);
+ toast.error(t("common.error"));
+ } finally {
+ setIsDeleting(false);
+ }
+ };
+
+ const handleSignOut = async () => {
+ try {
+ await signOut({
+ fetchOptions: {
+ onSuccess: () => {
+ toast.success(t("auth.logoutSuccess"));
+ router.replace("/login");
+ },
+ },
+ });
+ } catch (error) {
+ console.error("Sign out error:", error);
+ toast.error(t("common.error"));
+ }
+ };
+
+ const handleRevokeAllSessions = async () => {
+ const result = await revokeAllSessions();
+
+ if (result.success) {
+ toast.success(
+ t("auth.sessionsRevokedCount", { count: result.revokedCount || 0 })
+ );
+ } else {
+ toast.error(result.error || t("common.error"));
+ }
+ };
+
+ // Parse user agent to get device info
+ const parseUserAgent = (userAgent: string | null | undefined) => {
+ if (!userAgent) {
+ return {
+ browser: "Unknown Browser",
+ os: "Unknown OS",
+ deviceType: "unknown" as const,
+ deviceName: "Unknown Device",
+ };
+ }
+
+ const parser = new UAParser(userAgent);
+ const result = parser.getResult();
+
+ const browser = result.browser.name
+ ? `${result.browser.name}${
+ result.browser.version ? ` ${result.browser.version}` : ""
+ }`
+ : "Unknown Browser";
+ const os = result.os.name
+ ? `${result.os.name}${result.os.version ? ` ${result.os.version}` : ""}`
+ : "Unknown OS";
+
+ let deviceType: "desktop" | "mobile" | "tablet" | "unknown" = "unknown";
+ if (result.device.type === "mobile") {
+ deviceType = "mobile";
+ } else if (result.device.type === "tablet") {
+ deviceType = "tablet";
+ } else if (result.device.type === undefined && result.os.name) {
+ // Desktop devices typically don't have a device.type
+ deviceType = "desktop";
+ }
+
+ return {
+ browser,
+ os,
+ deviceType,
+ deviceName: `${result.browser.name || "Unknown"} on ${
+ result.os.name || "Unknown"
+ }`,
+ };
+ };
+
+ const getDeviceIcon = (deviceType: string) => {
+ switch (deviceType) {
+ case "mobile":
+ return <Smartphone className="h-5 w-5" />;
+ case "tablet":
+ return <Tablet className="h-5 w-5" />;
+ case "desktop":
+ return <Monitor className="h-5 w-5" />;
+ default:
+ return <HelpCircle className="h-5 w-5" />;
+ }
+ };
+
+ return (
+ <div className="flex flex-col min-h-screen">
+ <AuthHeader showUserMenu />
+
+ <div className="flex-1 bg-gradient-to-br from-background via-background to-primary/5">
+ <div className="container mx-auto max-w-4xl px-4 py-8">
+ {/* Header */}
+ <div className="mb-8 space-y-2">
+ <h1 className="text-4xl font-bold tracking-tight bg-gradient-to-r from-foreground via-foreground to-foreground/70 bg-clip-text text-transparent">
+ {t("auth.profileTitle")}
+ </h1>
+ <p className="text-muted-foreground">
+ {t("auth.profileDescription")}
+ </p>
+ </div>
+
+ <div className="space-y-6">
+ {/* User Info */}
+ <Card className="border-border/50 bg-gradient-to-br from-card/95 via-card to-card/80 backdrop-blur-sm">
+ <CardHeader>
+ <CardTitle className="bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text text-transparent">
+ {t("auth.profile")}
+ </CardTitle>
+ <CardDescription>
+ {t("auth.profileBasicInfoDescription")}
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ <div className="flex items-center gap-4">
+ {user?.image && (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img
+ src={user.image}
+ alt={user.name || "User"}
+ className="w-16 h-16 rounded-full object-cover border-2 border-border"
+ />
+ )}
+ <div className="flex-1">
+ <div className="mb-3">
+ <Label>{t("common.labels.name")}</Label>
+ <p className="mt-1 text-sm">{user?.name || "—"}</p>
+ </div>
+ <div>
+ <Label>{t("common.labels.email")}</Label>
+ <p className="mt-1 text-sm">{user?.email || "—"}</p>
+ </div>
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+
+ {/* Edit Profile - Only for email/password users */}
+ {hasPasswordAuth && (
+ <Card className="border-border/50 bg-gradient-to-br from-card/95 via-card to-card/80 backdrop-blur-sm">
+ <CardHeader>
+ <CardTitle className="bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text text-transparent">
+ {t("auth.editProfile")}
+ </CardTitle>
+ <CardDescription>
+ {t("auth.editProfileDescription")}
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <form onSubmit={handleUpdateProfile} className="space-y-4">
+ {/* Avatar Upload */}
+ <div className="space-y-2">
+ <Label htmlFor="avatar">{t("auth.profilePicture")}</Label>
+ <div className="flex items-center gap-4">
+ {avatarPreview && (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img
+ src={avatarPreview}
+ alt="Avatar preview"
+ className="w-20 h-20 rounded-full object-cover border-2 border-border"
+ />
+ )}
+ <div className="flex-1">
+ <Input
+ id="avatar"
+ type="file"
+ accept="image/*"
+ onChange={handleAvatarChange}
+ disabled={isUpdatingProfile || isUploadingAvatar}
+ />
+ <p className="text-xs text-muted-foreground mt-1">
+ {t("auth.avatarHint")}
+ </p>
+ </div>
+ </div>
+ </div>
+
+ {/* Name */}
+ <div className="space-y-2">
+ <Label htmlFor="editName">
+ {t("common.labels.name")}
+ </Label>
+ <Input
+ id="editName"
+ type="text"
+ value={editName}
+ onChange={(e) => setEditName(e.target.value)}
+ disabled={isUpdatingProfile || isUploadingAvatar}
+ required
+ />
+ </div>
+
+ {/* Email */}
+ <div className="space-y-2">
+ <Label htmlFor="editEmail">
+ {t("common.labels.email")}
+ </Label>
+ <Input
+ id="editEmail"
+ type="email"
+ value={editEmail}
+ onChange={(e) => setEditEmail(e.target.value)}
+ disabled={isUpdatingProfile || isUploadingAvatar}
+ required
+ />
+ </div>
+
+ <Button
+ type="submit"
+ disabled={isUpdatingProfile || isUploadingAvatar}
+ >
+ {isUploadingAvatar
+ ? t("auth.uploadingImage")
+ : isUpdatingProfile
+ ? t("common.saving")
+ : t("common.save")}
+ </Button>
+ </form>
+ </CardContent>
+ </Card>
+ )}
+
+ {/* Change Password - Only for email/password users */}
+ {hasPasswordAuth && (
+ <Card className="border-border/50 bg-gradient-to-br from-card/95 via-card to-card/80 backdrop-blur-sm">
+ <CardHeader>
+ <CardTitle className="bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text text-transparent">
+ {t("auth.changePassword")}
+ </CardTitle>
+ <CardDescription>
+ {t("auth.changePasswordDescription")}
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <form onSubmit={handleChangePassword} className="space-y-4">
+ <div className="space-y-2">
+ <Label htmlFor="currentPassword">
+ {t("auth.currentPassword")}
+ </Label>
+ <Input
+ id="currentPassword"
+ type="password"
+ value={currentPassword}
+ onChange={(e) => setCurrentPassword(e.target.value)}
+ disabled={isChangingPassword}
+ />
+ </div>
+
+ <div className="space-y-2">
+ <Label htmlFor="newPassword">
+ {t("common.labels.newPassword")}
+ </Label>
+ <Input
+ id="newPassword"
+ type="password"
+ value={newPassword}
+ onChange={(e) => setNewPassword(e.target.value)}
+ disabled={isChangingPassword}
+ minLength={8}
+ />
+ </div>
+
+ <div className="space-y-2">
+ <Label htmlFor="confirmNewPassword">
+ {t("common.labels.confirmPassword")}
+ </Label>
+ <Input
+ id="confirmNewPassword"
+ type="password"
+ value={confirmNewPassword}
+ onChange={(e) => setConfirmNewPassword(e.target.value)}
+ disabled={isChangingPassword}
+ minLength={8}
+ />
+ </div>
+
+ <Button type="submit" disabled={isChangingPassword}>
+ {isChangingPassword
+ ? t("common.saving")
+ : t("auth.changePassword")}
+ </Button>
+ </form>
+ </CardContent>
+ </Card>
+ )}
+
+ {/* Connected Accounts */}
+ <Card className="border-border/50 bg-gradient-to-br from-card/95 via-card to-card/80 backdrop-blur-sm">
+ <CardHeader>
+ <CardTitle className="bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text text-transparent">
+ {t("common.auth.connectedAccounts")}
+ </CardTitle>
+ <CardDescription>
+ {t("auth.connectedAccountsDescription")}
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ {accountsLoading ? (
+ <p className="text-sm text-muted-foreground">
+ {t("common.loading")}
+ </p>
+ ) : accounts.length === 0 ? (
+ <p className="text-sm text-muted-foreground">
+ {t("auth.noConnectedAccounts")}
+ </p>
+ ) : (
+ <div className="space-y-3">
+ {accounts.map((account) => (
+ <div
+ key={account.id}
+ className="flex items-center justify-between rounded-lg border border-border/50 p-3"
+ >
+ <div>
+ <p className="font-medium capitalize">
+ {account.provider === "credential"
+ ? t("auth.emailPasswordAuth")
+ : account.provider}
+ </p>
+ <p className="text-sm text-muted-foreground">
+ {account.accountId || "—"}
+ </p>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </CardContent>
+ </Card>
+
+ {/* Active Sessions */}
+ <Card className="border-border/50 bg-gradient-to-br from-card/95 via-card to-card/80 backdrop-blur-sm">
+ <CardHeader>
+ <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
+ <div>
+ <CardTitle className="bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text text-transparent">
+ {t("common.auth.activeSessions")}
+ </CardTitle>
+ <CardDescription>
+ {t("auth.activeSessionsDescription")}
+ </CardDescription>
+ </div>
+ {sessions.length > 1 && !sessionsLoading && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handleRevokeAllSessions}
+ className="text-destructive hover:text-destructive"
+ >
+ <LogOut className="h-4 w-4 mr-2" />
+ {t("auth.logoutAllDevices")}
+ </Button>
+ )}
+ </div>
+ </CardHeader>
+ <CardContent>
+ {sessionsLoading ? (
+ <p className="text-sm text-muted-foreground">
+ {t("common.loading")}
+ </p>
+ ) : sessions.length === 0 ? (
+ <p className="text-sm text-muted-foreground">
+ {t("auth.noActiveSessions")}
+ </p>
+ ) : (
+ <div className="space-y-3">
+ {sessions.map((session) => {
+ const deviceInfo = parseUserAgent(session.userAgent);
+
+ return (
+ <div
+ key={session.id}
+ className="flex items-start gap-3 rounded-lg border border-border/50 p-3 transition-colors"
+ >
+ <div className="mt-0.5 text-muted-foreground">
+ {getDeviceIcon(deviceInfo.deviceType)}
+ </div>
+ <div className="flex-1 min-w-0 space-y-1">
+ <div className="flex items-center gap-2 flex-wrap">
+ <p className="font-medium truncate">
+ {deviceInfo.deviceName}
+ </p>
+ </div>
+ <div className="text-xs text-muted-foreground space-y-0.5">
+ <p className="truncate">
+ {t("auth.browser")}: {deviceInfo.browser}
+ </p>
+ <p className="truncate">
+ {t("auth.operatingSystem")}: {deviceInfo.os}
+ </p>
+ {session.ipAddress && (
+ <p className="truncate">
+ {t("common.labels.ipAddress")}:{" "}
+ {session.ipAddress}
+ </p>
+ )}
+ <p>
+ {t("common.time.lastActive")}:{" "}
+ {new Intl.DateTimeFormat(undefined, {
+ dateStyle: "medium",
+ timeStyle: "short",
+ }).format(new Date(session.updatedAt))}
+ </p>
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </CardContent>
+ </Card>
+
+ <Separator />
+
+ {/* Danger Zone */}
+ <Card className="border-destructive/30 bg-gradient-to-br from-card/95 via-card to-card/80 backdrop-blur-sm">
+ <CardHeader>
+ <CardTitle className="bg-gradient-to-r from-destructive to-destructive/70 bg-clip-text text-transparent">
+ {t("auth.dangerZone")}
+ </CardTitle>
+ <CardDescription>
+ {t("auth.dangerZoneDescription")}
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div>
+ <p className="font-medium">{t("auth.logout")}</p>
+ <p className="text-sm text-muted-foreground">
+ {t("auth.logoutDescription")}
+ </p>
+ </div>
+ <Button variant="outline" onClick={handleSignOut}>
+ {t("auth.logout")}
+ </Button>
+ </div>
+
+ <Separator />
+
+ <div className="flex items-center justify-between">
+ <div>
+ <p className="font-medium">{t("auth.deleteAccount")}</p>
+ <p className="text-sm text-muted-foreground">
+ {t("auth.deleteAccountDescription")}
+ </p>
+ </div>
+ <Button
+ variant="destructive"
+ onClick={() => setShowDeleteDialog(true)}
+ >
+ {t("auth.deleteAccount")}
+ </Button>
+ </div>
+ </CardContent>
+ </Card>
+ </div>
+
+ {/* Delete Confirmation Dialog */}
+ <ConfirmationDialog
+ open={showDeleteDialog}
+ onOpenChange={(open) => {
+ setShowDeleteDialog(open);
+ if (!open) setDeletePassword("");
+ }}
+ onConfirm={handleDeleteAccount}
+ title={t("auth.deleteAccount")}
+ description={t("auth.deleteAccountConfirm")}
+ confirmText={
+ isDeleting ? t("common.loading") : t("auth.deleteAccount")
+ }
+ confirmDisabled={isDeleting || (hasPasswordAuth && !deletePassword)}
+ >
+ {hasPasswordAuth && (
+ <div className="space-y-2 pt-4">
+ <Label htmlFor="deletePassword">
+ {t("auth.confirmPasswordLabel")}
+ </Label>
+ <Input
+ id="deletePassword"
+ type="password"
+ value={deletePassword}
+ onChange={(e) => setDeletePassword(e.target.value)}
+ disabled={isDeleting}
+ placeholder={t("auth.enterPassword")}
+ />
+ </div>
+ )}
+ </ConfirmationDialog>
+ </div>
+ </div>
+
+ <AppFooter versionInfo={versionInfo} />
+ </div>
+ );
+}
diff --git a/app/register/page.tsx b/app/register/page.tsx
new file mode 100644
index 0000000..70758c2
--- /dev/null
+++ b/app/register/page.tsx
@@ -0,0 +1,265 @@
+"use client";
+
+import { useState, useEffect } from "react";
+import { useRouter } from "next/navigation";
+import { useTranslations } from "next-intl";
+import Link from "next/link";
+import { signUp } from "@/lib/auth/client";
+import { useAuth } from "@/hooks/useAuth";
+import { useAuthFeatures } from "@/hooks/useAuthFeatures";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { toast } from "sonner";
+import { FullscreenLoader } from "@/components/fullscreen-loader";
+import { AuthHeader } from "@/components/auth-header";
+import { AppFooter } from "@/components/app-footer";
+import { useVersionInfo } from "@/hooks/useVersionInfo";
+import {
+ isRateLimitError,
+ handleRateLimitError,
+} from "@/lib/rate-limit-client";
+
+/**
+ * Registration page for new users
+ *
+ * Features:
+ * - Email/Password registration
+ * - Name field
+ * - Password confirmation
+ * - Validation
+ * - Redirect to dashboard after success
+ */
+export default function RegisterPage() {
+ const t = useTranslations();
+ const router = useRouter();
+ const { isAuthenticated } = useAuth();
+ const { isAuthEnabled, allowRegistration } = useAuthFeatures();
+ const [name, setName] = useState("");
+ const [email, setEmail] = useState("");
+ const [password, setPassword] = useState("");
+ const [confirmPassword, setConfirmPassword] = useState("");
+ const [isLoading, setIsLoading] = useState(false);
+ const [mounted, setMounted] = useState(false);
+ const versionInfo = useVersionInfo();
+
+ const handleRegister = async (e: React.FormEvent) => {
+ e.preventDefault();
+
+ // Validation
+ if (!name) {
+ toast.error(t("auth.nameRequired"));
+ return;
+ }
+
+ if (!email) {
+ toast.error(t("auth.emailRequired"));
+ return;
+ }
+
+ if (!password) {
+ toast.error(t("validation.passwordRequired"));
+ return;
+ }
+
+ if (password.length < 8) {
+ toast.error(t("validation.passwordTooShort"));
+ return;
+ }
+
+ if (password !== confirmPassword) {
+ toast.error(t("validation.passwordsNoMatch"));
+ return;
+ }
+
+ setIsLoading(true);
+
+ try {
+ const result = await signUp.email({
+ email,
+ password,
+ name,
+ });
+
+ if (result.error) {
+ // Check if the error indicates rate limiting
+ if (result.error.status === 429) {
+ // Make a test request to get proper rate limit headers
+ try {
+ const testResponse = await fetch("/api/auth/sign-up/email", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ email, password, name }),
+ });
+
+ if (isRateLimitError(testResponse)) {
+ await handleRateLimitError(testResponse, t);
+ return;
+ }
+ } catch {
+ // If test request fails, show generic rate limit message
+ toast.error(t("rateLimit.title"), {
+ description: t("rateLimit.fallback"),
+ });
+ return;
+ }
+ }
+
+ console.error("Registration error:", result.error);
+ const errorMessage = result.error.message || "";
+ if (errorMessage.includes("email")) {
+ toast.error(t("auth.emailAlreadyExists"));
+ } else {
+ toast.error(t("auth.registerError"));
+ }
+ return;
+ }
+
+ // Better Auth automatically signs in the user after signup
+ toast.success(t("auth.registerSuccess"));
+ // Session update triggers automatic navigation via AuthProvider
+ } catch (error) {
+ console.error("Registration error:", error);
+ toast.error(t("auth.registerError"));
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ // Prevent hydration mismatch
+ useEffect(() => {
+ setMounted(true);
+ }, []);
+
+ // Redirect authenticated users to home
+ useEffect(() => {
+ if (mounted && isAuthenticated) {
+ router.replace("/");
+ }
+ }, [mounted, isAuthenticated, router]);
+
+ // Redirect if auth disabled or registration not allowed
+ useEffect(() => {
+ if (!isAuthEnabled) {
+ router.replace("/");
+ } else if (!allowRegistration) {
+ router.replace("/login");
+ }
+ }, [isAuthEnabled, allowRegistration, router]);
+
+ if (!isAuthEnabled || !allowRegistration) {
+ return null;
+ }
+
+ // Prevent hydration mismatch by showing loader until mounted
+ // Also show loader while redirecting authenticated users
+ if (!mounted || isAuthenticated) {
+ return <FullscreenLoader />;
+ }
+
+ return (
+ <div className="flex flex-col min-h-screen">
+ <AuthHeader />
+
+ <div className="flex flex-1 items-center justify-center bg-gradient-to-br from-background via-background to-primary/5 px-4 py-8">
+ <div className="w-full max-w-md space-y-8">
+ {/* Header */}
+ <div className="text-center space-y-2">
+ <h1 className="text-4xl font-bold tracking-tight bg-gradient-to-r from-foreground via-foreground to-foreground/70 bg-clip-text text-transparent">
+ {t("auth.registerTitle")}
+ </h1>
+ <p className="text-sm text-muted-foreground">
+ {t("auth.registerDescription")}
+ </p>
+ </div>
+
+ {/* Registration Form */}
+ <div className="rounded-xl border border-border/50 bg-gradient-to-br from-card/95 via-card to-card/80 p-8 shadow-lg backdrop-blur-sm">
+ <form onSubmit={handleRegister} className="space-y-6">
+ {/* Name */}
+ <div className="space-y-2">
+ <Label htmlFor="name">{t("common.labels.name")}</Label>
+ <Input
+ id="name"
+ type="text"
+ placeholder={t("auth.namePlaceholder")}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ disabled={isLoading}
+ required
+ />
+ </div>
+
+ {/* Email */}
+ <div className="space-y-2">
+ <Label htmlFor="email">{t("common.labels.email")}</Label>
+ <Input
+ id="email"
+ type="email"
+ placeholder={t("auth.emailPlaceholder")}
+ value={email}
+ onChange={(e) => setEmail(e.target.value)}
+ disabled={isLoading}
+ required
+ />
+ </div>
+
+ {/* Password */}
+ <div className="space-y-2">
+ <Label htmlFor="password">{t("common.labels.password")}</Label>
+ <Input
+ id="password"
+ type="password"
+ placeholder={t("auth.passwordPlaceholder")}
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ disabled={isLoading}
+ required
+ minLength={8}
+ />
+ <p className="text-xs text-muted-foreground">
+ {t("validation.passwordTooShort")}
+ </p>
+ </div>
+
+ {/* Confirm Password */}
+ <div className="space-y-2">
+ <Label htmlFor="confirmPassword">
+ {t("common.labels.confirmPassword")}
+ </Label>
+ <Input
+ id="confirmPassword"
+ type="password"
+ placeholder={t("common.labels.confirmPassword")}
+ value={confirmPassword}
+ onChange={(e) => setConfirmPassword(e.target.value)}
+ disabled={isLoading}
+ required
+ minLength={8}
+ />
+ </div>
+
+ {/* Submit Button */}
+ <Button type="submit" className="w-full" disabled={isLoading}>
+ {isLoading ? t("common.loading") : t("auth.register")}
+ </Button>
+ </form>
+
+ {/* Login Link */}
+ <p className="mt-6 text-center text-sm text-muted-foreground">
+ {t("auth.alreadyHaveAccount")}{" "}
+ <Link
+ href="/login"
+ className="font-medium text-primary hover:underline"
+ >
+ {t("auth.login")}
+ </Link>
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <AppFooter versionInfo={versionInfo} />
+ </div>
+ );
+}
diff --git a/components/admin/admin-header.tsx b/components/admin/admin-header.tsx
new file mode 100644
index 0000000..ea83801
--- /dev/null
+++ b/components/admin/admin-header.tsx
@@ -0,0 +1,136 @@
+"use client";
+
+import { useTranslations } from "next-intl";
+import Link from "next/link";
+import { usePathname } from "next/navigation";
+import { Menu } from "lucide-react";
+import {
+ Breadcrumb,
+ BreadcrumbItem,
+ BreadcrumbLink,
+ BreadcrumbList,
+ BreadcrumbPage,
+ BreadcrumbSeparator,
+} from "@/components/ui/breadcrumb";
+import { Button } from "@/components/ui/button";
+import { ThemeSwitcher } from "@/components/theme-switcher";
+import { LanguageSwitcher } from "@/components/language-switcher";
+
+interface BreadcrumbSegment {
+ label: string;
+ href?: string;
+}
+
+interface AdminHeaderProps {
+ onMenuClick?: () => void;
+}
+
+/**
+ * Admin Panel Header
+ *
+ * Features:
+ * - Automatic breadcrumb navigation from URL
+ * - Theme + Language switchers
+ * - Mobile menu toggle
+ */
+export function AdminHeader({ onMenuClick }: AdminHeaderProps) {
+ const t = useTranslations();
+ const pathname = usePathname();
+
+ // Generate breadcrumbs from pathname
+ const generateBreadcrumbs = (): BreadcrumbSegment[] => {
+ const segments: BreadcrumbSegment[] = [
+ { label: t("admin.title"), href: "/admin" },
+ ];
+
+ // Parse pathname segments
+ const pathParts = pathname.split("/").filter(Boolean);
+
+ // Remove "admin" prefix (already in first segment)
+ const adminIndex = pathParts.indexOf("admin");
+ if (adminIndex !== -1) {
+ pathParts.splice(adminIndex, 1);
+ }
+
+ // Map path segments to breadcrumb items
+ let currentPath = "/admin";
+ for (let i = 0; i < pathParts.length; i++) {
+ const part = pathParts[i];
+ currentPath += `/${part}`;
+
+ // Check if it's the last segment (current page - no link)
+ const isLast = i === pathParts.length - 1;
+
+ // Map known segments to translations
+ let label = part;
+ if (part === "users") {
+ label = t("admin.usersMenu");
+ } else if (part === "calendars") {
+ label = t("admin.calendarsMenu");
+ } else if (part === "orphaned") {
+ label = t("admin.orphanedCalendars");
+ } else if (part === "logs") {
+ label = t("admin.auditLogs");
+ }
+
+ segments.push({
+ label,
+ href: isLast ? undefined : currentPath,
+ });
+ }
+
+ return segments;
+ };
+
+ const breadcrumbs = generateBreadcrumbs();
+
+ return (
+ <header className="sticky top-0 z-20 bg-background/80 backdrop-blur-xl border-b border-border/50 shadow-sm">
+ <div className="p-4 space-y-3">
+ {/* Top row: Breadcrumbs + Controls */}
+ <div className="flex items-center justify-between gap-4">
+ {/* Mobile Menu Button */}
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={onMenuClick}
+ className="lg:hidden flex-shrink-0"
+ aria-label="Toggle menu"
+ >
+ <Menu className="h-5 w-5" />
+ </Button>
+
+ {/* Breadcrumbs */}
+ <Breadcrumb className="flex-1 min-w-0">
+ <BreadcrumbList>
+ {breadcrumbs.map((segment, index) => {
+ const isLast = index === breadcrumbs.length - 1;
+
+ return (
+ <div key={segment.href || segment.label} className="contents">
+ <BreadcrumbItem>
+ {segment.href ? (
+ <BreadcrumbLink asChild>
+ <Link href={segment.href}>{segment.label}</Link>
+ </BreadcrumbLink>
+ ) : (
+ <BreadcrumbPage>{segment.label}</BreadcrumbPage>
+ )}
+ </BreadcrumbItem>
+ {!isLast && <BreadcrumbSeparator />}
+ </div>
+ );
+ })}
+ </BreadcrumbList>
+ </Breadcrumb>
+
+ {/* Controls: Theme + Language */}
+ <div className="flex items-center gap-2">
+ <LanguageSwitcher />
+ <ThemeSwitcher />
+ </div>
+ </div>
+ </div>
+ </header>
+ );
+}
diff --git a/components/admin/admin-sidebar.tsx b/components/admin/admin-sidebar.tsx
new file mode 100644
index 0000000..b3190cc
--- /dev/null
+++ b/components/admin/admin-sidebar.tsx
@@ -0,0 +1,284 @@
+"use client";
+
+import { useState, useEffect } from "react";
+import { usePathname, useRouter } from "next/navigation";
+import { useTranslations } from "next-intl";
+import { motion, AnimatePresence } from "motion/react";
+import { cn } from "@/lib/utils";
+import { Button } from "@/components/ui/button";
+import { Badge } from "@/components/ui/badge";
+import { Separator } from "@/components/ui/separator";
+import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
+import {
+ LayoutDashboard,
+ Users,
+ FolderOpen,
+ ScrollText,
+ ChevronLeft,
+ ChevronRight,
+ ArrowLeft,
+ Crown,
+} from "lucide-react";
+import { useAdminLevel } from "@/hooks/useAdminAccess";
+import { useAuth } from "@/hooks/useAuth";
+
+interface NavItem {
+ label: string;
+ href: string;
+ icon: React.ElementType;
+ adminOnly?: boolean; // Only visible for superadmin
+}
+
+interface AdminSidebarProps {
+ onWidthChange?: (width: number) => void;
+ isMobileOpen?: boolean;
+ onMobileClose?: () => void;
+}
+
+/**
+ * Admin Panel Sidebar Navigation
+ *
+ * Features:
+ * - Collapsible (Icons only ↔ Icons + Text)
+ * - Active route highlighting
+ * - Role-based menu items (superadmin badge)
+ * - Mobile responsive
+ * - "Back to App" link at bottom
+ */
+export function AdminSidebar({
+ onWidthChange,
+ isMobileOpen,
+ onMobileClose,
+}: AdminSidebarProps) {
+ const t = useTranslations();
+ const router = useRouter();
+ const pathname = usePathname();
+ const { user } = useAuth();
+ const adminLevel = useAdminLevel();
+ const [isCollapsed, setIsCollapsed] = useState(false);
+
+ const isSuperAdmin = adminLevel === "superadmin";
+ // Notify parent of width changes
+ useEffect(() => {
+ onWidthChange?.(isCollapsed ? 80 : 280);
+ }, [isCollapsed, onWidthChange]);
+ // Navigation items
+ const navItems: NavItem[] = [
+ {
+ label: t("admin.dashboard"),
+ href: "/admin",
+ icon: LayoutDashboard,
+ },
+ {
+ label: t("admin.usersMenu"),
+ href: "/admin/users",
+ icon: Users,
+ },
+ {
+ label: t("admin.calendarsMenu"),
+ href: "/admin/calendars",
+ icon: FolderOpen,
+ },
+ {
+ label: t("admin.auditLogs"),
+ href: "/admin/logs",
+ icon: ScrollText,
+ },
+ ];
+
+ const handleNavigation = (href: string) => {
+ router.push(href);
+ // Close mobile menu after navigation
+ if (typeof window !== "undefined" && window.innerWidth < 1024) {
+ onMobileClose?.();
+ }
+ };
+
+ const handleBackToApp = () => {
+ router.push("/");
+ // Close mobile menu after navigation
+ if (typeof window !== "undefined" && window.innerWidth < 1024) {
+ onMobileClose?.();
+ }
+ };
+
+ // Get user initials for avatar
+ const getInitials = (name: string | undefined | null) => {
+ if (!name) return "?";
+ return name
+ .split(" ")
+ .map((n) => n[0])
+ .join("")
+ .toUpperCase()
+ .slice(0, 2);
+ };
+
+ return (
+ <>
+ {/* Backdrop for mobile */}
+ {isMobileOpen && (
+ <div
+ className="fixed inset-0 bg-black/50 z-40 lg:hidden"
+ onClick={onMobileClose}
+ />
+ )}
+
+ {/* Sidebar */}
+ <motion.aside
+ initial={false}
+ animate={{
+ width: isCollapsed ? "80px" : "280px",
+ }}
+ style={{
+ x:
+ typeof window !== "undefined" && window.innerWidth < 1024
+ ? isMobileOpen
+ ? 0
+ : -280
+ : 0,
+ }}
+ transition={{ duration: 0.3, ease: "easeInOut" }}
+ className={cn(
+ "fixed left-0 top-0 h-screen",
+ "border-r border-border bg-background",
+ "flex flex-col",
+ "z-50 lg:z-30"
+ )}
+ >
+ {/* Header: User Info + Collapse Toggle */}
+ <div className="p-4 flex items-center justify-between gap-2 min-h-[72px]">
+ <AnimatePresence mode="wait">
+ {!isCollapsed && (
+ <motion.div
+ initial={{ opacity: 0, x: -10 }}
+ animate={{ opacity: 1, x: 0 }}
+ exit={{ opacity: 0, x: -10 }}
+ transition={{ duration: 0.2 }}
+ className="flex items-center gap-3 min-w-0 flex-1"
+ >
+ {/* User Avatar */}
+ <Avatar className="h-10 w-10 flex-shrink-0">
+ <AvatarImage
+ src={user?.image || undefined}
+ alt={user?.name || ""}
+ />
+ <AvatarFallback className="bg-primary/10 text-primary text-sm font-semibold">
+ {getInitials(user?.name)}
+ </AvatarFallback>
+ </Avatar>
+ {/* User Info */}
+ <div className="min-w-0 flex-1">
+ <p className="text-sm font-medium truncate">{user?.name}</p>
+ {isSuperAdmin && (
+ <Badge
+ variant="default"
+ className="text-xs mt-1 bg-amber-500 hover:bg-amber-600"
+ >
+ <Crown className="w-3 h-3 mr-1" />
+ {t("admin.superadminBadge")}
+ </Badge>
+ )}
+ {!isSuperAdmin && (
+ <Badge
+ variant="secondary"
+ className="text-xs mt-1 bg-orange-500/10 text-orange-500 border-orange-500/20"
+ >
+ {t("common.roles.admin")}
+ </Badge>
+ )}
+ </div>
+ </motion.div>
+ )}
+ </AnimatePresence>
+
+ {/* Collapse Toggle Button */}
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={() => setIsCollapsed(!isCollapsed)}
+ className="flex-shrink-0"
+ aria-label={
+ isCollapsed
+ ? t("admin.expandSidebar")
+ : t("admin.collapseSidebar")
+ }
+ >
+ {isCollapsed ? (
+ <ChevronRight className="h-4 w-4" />
+ ) : (
+ <ChevronLeft className="h-4 w-4" />
+ )}
+ </Button>
+ </div>
+
+ <Separator />
+
+ {/* Navigation Items */}
+ <nav className="flex-1 p-2 space-y-1 overflow-y-auto">
+ {navItems.map((item) => {
+ const Icon = item.icon;
+ const isActive = pathname === item.href;
+
+ return (
+ <Button
+ key={item.href}
+ variant={isActive ? "secondary" : "ghost"}
+ className={cn(
+ "w-full justify-start gap-3",
+ isCollapsed && "justify-center px-0"
+ )}
+ onClick={() => handleNavigation(item.href)}
+ title={isCollapsed ? item.label : undefined}
+ >
+ <Icon className="h-5 w-5 flex-shrink-0" />
+ <AnimatePresence mode="wait">
+ {!isCollapsed && (
+ <motion.span
+ initial={{ opacity: 0, x: -10 }}
+ animate={{ opacity: 1, x: 0 }}
+ exit={{ opacity: 0, x: -10 }}
+ transition={{ duration: 0.2 }}
+ className="truncate"
+ >
+ {item.label}
+ </motion.span>
+ )}
+ </AnimatePresence>
+ </Button>
+ );
+ })}
+ </nav>
+
+ <Separator />
+
+ {/* Back to App Link */}
+ <div className="p-2">
+ <Button
+ variant="ghost"
+ className={cn(
+ "w-full justify-start gap-3",
+ isCollapsed && "justify-center px-0"
+ )}
+ onClick={handleBackToApp}
+ title={isCollapsed ? t("admin.backToApp") : undefined}
+ >
+ <ArrowLeft className="h-5 w-5 flex-shrink-0" />
+ <AnimatePresence mode="wait">
+ {!isCollapsed && (
+ <motion.span
+ initial={{ opacity: 0, x: -10 }}
+ animate={{ opacity: 1, x: 0 }}
+ exit={{ opacity: 0, x: -10 }}
+ transition={{ duration: 0.2 }}
+ className="truncate"
+ >
+ {t("admin.backToApp")}
+ </motion.span>
+ )}
+ </AnimatePresence>
+ </Button>
+ </div>
+ </motion.aside>
+ </>
+ );
+}
diff --git a/components/admin/audit-log-delete-dialog.tsx b/components/admin/audit-log-delete-dialog.tsx
new file mode 100644
index 0000000..5a34b4f
--- /dev/null
+++ b/components/admin/audit-log-delete-dialog.tsx
@@ -0,0 +1,192 @@
+"use client";
+
+import { useState } from "react";
+import { useTranslations } from "next-intl";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogDescription,
+ DialogFooter,
+} from "@/components/ui/dialog";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Checkbox } from "@/components/ui/checkbox";
+import { AlertTriangle, Trash2, X } from "lucide-react";
+import { useAuditLogs } from "@/hooks/useAuditLogs";
+import { toast } from "sonner";
+
+interface AuditLogDeleteDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ selectedLogIds?: string[];
+ onSuccess?: () => void;
+}
+
+export function AuditLogDeleteDialog({
+ open,
+ onOpenChange,
+ selectedLogIds = [],
+ onSuccess,
+}: AuditLogDeleteDialogProps) {
+ const t = useTranslations();
+ const { deleteLogsByDate, deleteLogsByIds, isLoading } = useAuditLogs();
+
+ const [beforeDate, setBeforeDate] = useState("");
+ const [confirmed, setConfirmed] = useState(false);
+
+ // Determine mode: by IDs (if provided) or by date
+ const deleteByIds = selectedLogIds.length > 0;
+
+ const handleDelete = async () => {
+ if (!confirmed) {
+ toast.error(t("admin.pleaseConfirmDeletion"));
+ return;
+ }
+
+ let success = false;
+
+ if (deleteByIds) {
+ // Delete by IDs
+ success = await deleteLogsByIds(selectedLogIds);
+ } else {
+ // Delete by date
+ if (!beforeDate) {
+ toast.error(t("admin.pleaseSelectDate"));
+ return;
+ }
+ success = await deleteLogsByDate(beforeDate);
+ }
+
+ if (success) {
+ onOpenChange(false);
+ setBeforeDate("");
+ setConfirmed(false);
+ onSuccess?.();
+ }
+ };
+
+ const handleClose = () => {
+ if (!isLoading) {
+ onOpenChange(false);
+ setBeforeDate("");
+ setConfirmed(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={handleClose}>
+ <DialogContent className="max-w-md">
+ <DialogHeader>
+ <div className="flex items-center gap-2 text-destructive">
+ <AlertTriangle className="h-5 w-5" />
+ <DialogTitle>
+ {deleteByIds
+ ? t("common.deleteSelected")
+ : t("admin.deleteOldLogs")}
+ </DialogTitle>
+ </div>
+ <DialogDescription className="pt-2">
+ {deleteByIds
+ ? t("admin.deleteSelectedLogsDescription", {
+ count: selectedLogIds.length,
+ })
+ : t("admin.deleteLogsDescription")}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-4">
+ {!deleteByIds && (
+ <>
+ {/* Date Picker */}
+ <div>
+ <label className="text-sm font-medium mb-2 block">
+ {t("admin.deleteLogsBefore")}
+ </label>
+ <Input
+ type="date"
+ value={beforeDate}
+ onChange={(e) => setBeforeDate(e.target.value)}
+ max={new Date().toISOString().split("T")[0]}
+ disabled={isLoading}
+ />
+ <p className="text-xs text-muted-foreground mt-1">
+ {t("admin.deleteLogsBeforeHint")}
+ </p>
+ </div>
+
+ {/* Preview */}
+ {beforeDate && (
+ <div className="p-3 bg-muted rounded-lg text-sm">
+ <div className="font-medium mb-1">{t("admin.preview")}:</div>
+ <div className="text-muted-foreground">
+ {t("admin.willDeleteLogsOlderThan", {
+ date: new Date(beforeDate).toLocaleDateString(),
+ })}
+ </div>
+ </div>
+ )}
+ </>
+ )}
+
+ {deleteByIds && (
+ <div className="p-3 bg-muted rounded-lg text-sm">
+ <div className="font-medium mb-1">{t("admin.preview")}:</div>
+ <div className="text-muted-foreground">
+ {t("admin.willDeleteSelectedLogs", {
+ count: selectedLogIds.length,
+ })}
+ </div>
+ </div>
+ )}
+
+ {/* Warning */}
+ <div className="bg-destructive/10 border border-destructive/20 rounded-lg p-3">
+ <div className="flex gap-2">
+ <AlertTriangle className="h-4 w-4 text-destructive shrink-0 mt-0.5" />
+ <div className="text-sm text-destructive">
+ {t("admin.deleteLogsWarning")}
+ </div>
+ </div>
+ </div>
+
+ {/* Confirmation Checkbox */}
+ <div className="flex items-start gap-3">
+ <Checkbox
+ id="confirm-delete"
+ checked={confirmed}
+ onCheckedChange={(checked) => setConfirmed(checked === true)}
+ disabled={isLoading}
+ />
+ <label
+ htmlFor="confirm-delete"
+ className="text-sm leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
+ >
+ {t("admin.confirmPermanentDeletion")}
+ </label>
+ </div>
+ </div>
+
+ <DialogFooter>
+ <Button variant="outline" onClick={handleClose} disabled={isLoading}>
+ <X className="h-4 w-4 mr-2" />
+ {t("common.cancel")}
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={handleDelete}
+ disabled={isLoading || (!deleteByIds && !beforeDate) || !confirmed}
+ >
+ <Trash2 className="h-4 w-4 mr-2" />
+ {isLoading
+ ? t("common.loading")
+ : deleteByIds
+ ? t("common.deleteSelected")
+ : t("admin.deleteOldLogs")}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/components/admin/audit-log-details-dialog.tsx b/components/admin/audit-log-details-dialog.tsx
new file mode 100644
index 0000000..267d0a8
--- /dev/null
+++ b/components/admin/audit-log-details-dialog.tsx
@@ -0,0 +1,266 @@
+"use client";
+
+import { useTranslations, useLocale } from "next-intl";
+import { format } from "date-fns";
+import { getDateLocale } from "@/lib/locales";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogFooter,
+} from "@/components/ui/dialog";
+import { Button } from "@/components/ui/button";
+import { Badge } from "@/components/ui/badge";
+import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
+import { Copy, X } from "lucide-react";
+import { toast } from "sonner";
+import type { AuditLog } from "@/hooks/useAuditLogs";
+
+interface AuditLogDetailsDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ log: AuditLog;
+}
+
+export function AuditLogDetailsDialog({
+ open,
+ onOpenChange,
+ log,
+}: AuditLogDetailsDialogProps) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const dateLocale = getDateLocale(locale);
+
+ // Get user initials
+ const getUserInitials = (name: string | null) => {
+ if (!name) return "?";
+ return name
+ .split(" ")
+ .map((n) => n[0])
+ .join("")
+ .toUpperCase()
+ .slice(0, 2);
+ };
+
+ // Severity badge color
+ const getSeverityColor = (severity: string) => {
+ switch (severity) {
+ case "info":
+ return "bg-blue-500/10 text-blue-500 border-blue-500/20";
+ case "warning":
+ return "bg-yellow-500/10 text-yellow-500 border-yellow-500/20";
+ case "error":
+ return "bg-orange-500/10 text-orange-500 border-orange-500/20";
+ case "critical":
+ return "bg-red-500/10 text-red-500 border-red-500/20";
+ default:
+ return "bg-gray-500/10 text-gray-500 border-gray-500/20";
+ }
+ };
+
+ // Action category badge color
+ const getActionColor = (action: string) => {
+ if (action.startsWith("admin.")) {
+ return "bg-red-500/10 text-red-500 border-red-500/20";
+ }
+ if (action.startsWith("calendar")) {
+ return "bg-blue-500/10 text-blue-500 border-blue-500/20";
+ }
+ if (action.startsWith("auth")) {
+ return "bg-green-500/10 text-green-500 border-green-500/20";
+ }
+ if (action.startsWith("security")) {
+ return "bg-orange-500/10 text-orange-500 border-orange-500/20";
+ }
+ return "bg-gray-500/10 text-gray-500 border-gray-500/20";
+ };
+
+ // Copy JSON to clipboard
+ const copyToClipboard = () => {
+ const jsonString = JSON.stringify(
+ {
+ id: log.id,
+ action: log.action,
+ timestamp: log.timestamp,
+ severity: log.severity,
+ userId: log.userId,
+ userName: log.userName,
+ userEmail: log.userEmail,
+ resourceType: log.resourceType,
+ resourceId: log.resourceId,
+ metadata: log.metadata,
+ ipAddress: log.ipAddress,
+ userAgent: log.userAgent,
+ isUserVisible: log.isUserVisible,
+ },
+ null,
+ 2
+ );
+
+ navigator.clipboard.writeText(jsonString);
+ toast.success(t("common.copied", { item: t("admin.metadata") }));
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
+ <DialogHeader>
+ <DialogTitle>{t("admin.auditLogDetails")}</DialogTitle>
+ </DialogHeader>
+
+ <div className="space-y-6">
+ {/* Action & Severity */}
+ <div className="grid grid-cols-2 gap-4">
+ <div>
+ <div className="text-sm font-medium text-muted-foreground mb-2">
+ {t("common.labels.action")}
+ </div>
+ <Badge variant="outline" className={getActionColor(log.action)}>
+ {log.action}
+ </Badge>
+ </div>
+ <div>
+ <div className="text-sm font-medium text-muted-foreground mb-2">
+ {t("common.labels.severity")}
+ </div>
+ <Badge
+ variant="outline"
+ className={getSeverityColor(log.severity)}
+ >
+ {log.severity}
+ </Badge>
+ </div>
+ </div>
+
+ {/* Timestamp */}
+ <div>
+ <div className="text-sm font-medium text-muted-foreground mb-2">
+ {t("admin.timestamp")}
+ </div>
+ <div className="text-sm">
+ {format(new Date(log.timestamp), "PPpp", { locale: dateLocale })}
+ </div>
+ </div>
+
+ {/* User Details */}
+ {log.userId != null && (
+ <div>
+ <div className="text-sm font-medium text-muted-foreground mb-2">
+ {t("common.labels.user")}
+ </div>
+ <div className="flex items-center gap-3 p-3 border rounded-lg">
+ <Avatar className="h-10 w-10">
+ {log.userImage && (
+ <AvatarImage src={log.userImage} alt={log.userName || ""} />
+ )}
+ <AvatarFallback>
+ {getUserInitials(log.userName)}
+ </AvatarFallback>
+ </Avatar>
+ <div>
+ <div className="text-sm font-medium">
+ {log.userName || t("admin.unknownUser")}
+ </div>
+ <div className="text-xs text-muted-foreground">
+ {log.userEmail || "—"}
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Resource */}
+ {log.resourceType != null && (
+ <div className="grid grid-cols-2 gap-4">
+ <div>
+ <div className="text-sm font-medium text-muted-foreground mb-2">
+ {t("admin.resourceType")}
+ </div>
+ <div className="text-sm">{log.resourceType}</div>
+ </div>
+ <div>
+ <div className="text-sm font-medium text-muted-foreground mb-2">
+ {t("admin.resourceId")}
+ </div>
+ <div className="text-sm font-mono text-xs">
+ {log.resourceId || "—"}
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* IP Address */}
+ {log.ipAddress != null && (
+ <div>
+ <div className="text-sm font-medium text-muted-foreground mb-2">
+ {t("common.labels.ipAddress")}
+ </div>
+ <div className="text-sm font-mono">{log.ipAddress}</div>
+ </div>
+ )}
+
+ {/* User Agent */}
+ {log.userAgent != null && (
+ <div>
+ <div className="text-sm font-medium text-muted-foreground mb-2">
+ {t("admin.userAgent")}
+ </div>
+ <div className="text-xs text-muted-foreground break-all">
+ {log.userAgent}
+ </div>
+ </div>
+ )}
+
+ {/* Metadata */}
+ {log.metadata != null && (
+ <div>
+ <div className="flex items-center justify-between mb-2">
+ <div className="text-sm font-medium text-muted-foreground">
+ {t("admin.metadata")}
+ </div>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={copyToClipboard}
+ className="h-7"
+ >
+ <Copy className="h-3 w-3 mr-1" />
+ {t("common.copy")}
+ </Button>
+ </div>
+ <pre className="text-xs bg-muted p-4 rounded-lg border overflow-x-auto">
+ {JSON.stringify(log.metadata, null, 2)}
+ </pre>
+ </div>
+ )}
+
+ {/* Additional Info */}
+ <div className="grid grid-cols-2 gap-4 pt-4 border-t">
+ <div>
+ <div className="text-sm font-medium text-muted-foreground mb-2">
+ {t("admin.logId")}
+ </div>
+ <div className="text-xs font-mono">{log.id}</div>
+ </div>
+ <div>
+ <div className="text-sm font-medium text-muted-foreground mb-2">
+ {t("admin.userVisible")}
+ </div>
+ <div className="text-sm">
+ {log.isUserVisible ? t("common.yes") : t("common.no")}
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <DialogFooter>
+ <Button variant="outline" onClick={() => onOpenChange(false)}>
+ <X className="h-4 w-4 mr-2" />
+ {t("common.close")}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/components/admin/calendar-bulk-delete-dialog.tsx b/components/admin/calendar-bulk-delete-dialog.tsx
new file mode 100644
index 0000000..38ca147
--- /dev/null
+++ b/components/admin/calendar-bulk-delete-dialog.tsx
@@ -0,0 +1,140 @@
+"use client";
+
+import { useState } from "react";
+import { useTranslations } from "next-intl";
+import { AlertTriangle } from "lucide-react";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Label } from "@/components/ui/label";
+import type { AdminCalendar } from "@/hooks/useAdminCalendars";
+
+interface CalendarBulkDeleteDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ calendars: AdminCalendar[];
+ onConfirm: () => Promise<void>;
+}
+
+export function CalendarBulkDeleteDialog({
+ open,
+ onOpenChange,
+ calendars,
+ onConfirm,
+}: CalendarBulkDeleteDialogProps) {
+ const t = useTranslations();
+ const [understood, setUnderstood] = useState(false);
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ const handleConfirm = async () => {
+ if (!understood) return;
+
+ setIsSubmitting(true);
+ try {
+ await onConfirm();
+ // Reset form
+ setUnderstood(false);
+ onOpenChange(false);
+ } finally {
+ setIsSubmitting(false);
+ }
+ };
+
+ const handleCancel = () => {
+ // Reset form
+ setUnderstood(false);
+ onOpenChange(false);
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-[500px]">
+ <DialogHeader>
+ <DialogTitle>{t("common.deleteSelected")}</DialogTitle>
+ <DialogDescription>
+ {t("admin.calendars.bulkDeleteConfirm", {
+ count: calendars.length,
+ })}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-4 py-4">
+ {/* Warning */}
+ <div className="flex gap-3 p-3 rounded-lg bg-red-50 dark:bg-red-950/20 border border-red-200 dark:border-red-900">
+ <AlertTriangle className="h-5 w-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5" />
+ <p className="text-sm text-red-800 dark:text-red-200">
+ {t("admin.calendars.bulkDeleteWarning")}
+ </p>
+ </div>
+
+ {/* Calendar List (max 5 shown) */}
+ <div className="space-y-2">
+ <Label>{t("admin.calendars.calendarsToDelete")}:</Label>
+ <div className="p-3 rounded-lg border bg-muted/20 max-h-[150px] overflow-y-auto">
+ <ul className="space-y-1 text-sm">
+ {calendars.slice(0, 5).map((calendar) => (
+ <li key={calendar.id} className="flex items-center gap-2">
+ <div
+ className="w-3 h-3 rounded-full shrink-0"
+ style={{ backgroundColor: calendar.color }}
+ />
+ <span className="truncate">{calendar.name}</span>
+ </li>
+ ))}
+ {calendars.length > 5 && (
+ <li className="text-muted-foreground italic">
+ {t("admin.calendars.andMore", {
+ count: calendars.length - 5,
+ })}
+ </li>
+ )}
+ </ul>
+ </div>
+ </div>
+
+ {/* Checkbox Confirmation */}
+ <div className="flex items-start space-x-3">
+ <Checkbox
+ id="understood"
+ checked={understood}
+ onCheckedChange={(checked) => setUnderstood(checked === true)}
+ className="mt-1"
+ />
+ <Label
+ htmlFor="understood"
+ className="text-sm font-medium leading-normal cursor-pointer"
+ >
+ {t("admin.calendars.deleteUnderstood")}
+ </Label>
+ </div>
+ </div>
+
+ <DialogFooter>
+ <Button
+ variant="outline"
+ onClick={handleCancel}
+ disabled={isSubmitting}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={handleConfirm}
+ disabled={!understood || isSubmitting}
+ >
+ {isSubmitting
+ ? t("common.saving")
+ : t("admin.calendars.confirmDelete")}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/components/admin/calendar-delete-dialog.tsx b/components/admin/calendar-delete-dialog.tsx
new file mode 100644
index 0000000..513e1a3
--- /dev/null
+++ b/components/admin/calendar-delete-dialog.tsx
@@ -0,0 +1,138 @@
+"use client";
+
+import { useState } from "react";
+import { useTranslations } from "next-intl";
+import { AlertTriangle } from "lucide-react";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Button } from "@/components/ui/button";
+import { Label } from "@/components/ui/label";
+import { Input } from "@/components/ui/input";
+import { Checkbox } from "@/components/ui/checkbox";
+import type { AdminCalendar } from "@/hooks/useAdminCalendars";
+
+interface CalendarDeleteDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ calendar: AdminCalendar;
+ onConfirm: () => Promise<void>;
+}
+
+export function CalendarDeleteDialog({
+ open,
+ onOpenChange,
+ calendar,
+ onConfirm,
+}: CalendarDeleteDialogProps) {
+ const t = useTranslations();
+ const [confirmation, setConfirmation] = useState("");
+ const [understood, setUnderstood] = useState(false);
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ const isConfirmed = confirmation === calendar.name && understood;
+
+ const handleConfirm = async () => {
+ if (!isConfirmed) return;
+
+ setIsSubmitting(true);
+ try {
+ await onConfirm();
+ // Reset form
+ setConfirmation("");
+ setUnderstood(false);
+ onOpenChange(false);
+ } finally {
+ setIsSubmitting(false);
+ }
+ };
+
+ const handleCancel = () => {
+ // Reset form
+ setConfirmation("");
+ setUnderstood(false);
+ onOpenChange(false);
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-[500px]">
+ <DialogHeader>
+ <DialogTitle>{t("admin.calendars.deleteCalendar")}</DialogTitle>
+ <DialogDescription>
+ {t("admin.calendars.deleteCalendarConfirm", {
+ name: calendar.name,
+ })}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-4 py-4">
+ {/* Warning */}
+ <div className="flex gap-3 p-3 rounded-lg bg-red-50 dark:bg-red-950/20 border border-red-200 dark:border-red-900">
+ <AlertTriangle className="h-5 w-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5" />
+ <p className="text-sm text-red-800 dark:text-red-200">
+ {t("admin.calendars.deleteWarning")}
+ </p>
+ </div>
+
+ {/* Checkbox Confirmation */}
+ <div className="flex items-start space-x-3">
+ <Checkbox
+ id="understood"
+ checked={understood}
+ onCheckedChange={(checked) => setUnderstood(checked === true)}
+ className="mt-1"
+ />
+ <Label
+ htmlFor="understood"
+ className="text-sm font-medium leading-normal cursor-pointer"
+ >
+ {t("admin.calendars.deleteUnderstood")}
+ </Label>
+ </div>
+
+ {/* Name Confirmation */}
+ <div className="space-y-2">
+ <Label htmlFor="confirmation">
+ {t("admin.calendars.deleteConfirmation", { name: calendar.name })}
+ </Label>
+ <Input
+ id="confirmation"
+ value={confirmation}
+ onChange={(e) => setConfirmation(e.target.value)}
+ placeholder={calendar.name}
+ className="font-mono"
+ />
+ <p className="text-xs text-muted-foreground">
+ {t("admin.calendars.deleteConfirmationHint")}
+ </p>
+ </div>
+ </div>
+
+ <DialogFooter>
+ <Button
+ variant="outline"
+ onClick={handleCancel}
+ disabled={isSubmitting}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={handleConfirm}
+ disabled={!isConfirmed || isSubmitting}
+ >
+ {isSubmitting
+ ? t("common.saving")
+ : t("admin.calendars.confirmDelete")}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/components/admin/calendar-details-sheet.tsx b/components/admin/calendar-details-sheet.tsx
new file mode 100644
index 0000000..93ed362
--- /dev/null
+++ b/components/admin/calendar-details-sheet.tsx
@@ -0,0 +1,439 @@
+"use client";
+
+import { useState, useEffect } from "react";
+import { useTranslations } from "next-intl";
+import { useLocale } from "next-intl";
+import { format } from "date-fns";
+import {
+ Edit,
+ Send,
+ Trash2,
+ Calendar,
+ StickyNote,
+ Bookmark,
+ Share2,
+ CloudDownload,
+ Link,
+} from "lucide-react";
+import { BaseSheet } from "@/components/ui/base-sheet";
+import { Button } from "@/components/ui/button";
+import { Badge } from "@/components/ui/badge";
+import { Separator } from "@/components/ui/separator";
+import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
+import {
+ useAdminCalendars,
+ type CalendarDetails,
+} from "@/hooks/useAdminCalendars";
+import {
+ useCanEditCalendar,
+ useCanDeleteCalendar,
+ useCanTransferCalendar,
+} from "@/hooks/useAdminAccess";
+import { getDateLocale } from "@/lib/locales";
+
+interface CalendarDetailsSheetProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ calendarId: string;
+ onEdit: () => void;
+ onTransfer: () => void;
+ onDelete: () => void;
+}
+
+export function CalendarDetailsSheet({
+ open,
+ onOpenChange,
+ calendarId,
+ onEdit,
+ onTransfer,
+ onDelete,
+}: CalendarDetailsSheetProps) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const dateLocale = getDateLocale(locale);
+ const { fetchCalendarDetails, isLoading } = useAdminCalendars();
+ const [calendarDetails, setCalendarDetails] =
+ useState<CalendarDetails | null>(null);
+
+ const canEdit = useCanEditCalendar();
+ const canDelete = useCanDeleteCalendar();
+ const canTransfer = useCanTransferCalendar();
+
+ useEffect(() => {
+ if (!open) return;
+
+ const loadDetails = async () => {
+ const details = await fetchCalendarDetails(calendarId);
+ if (details) {
+ setCalendarDetails(details);
+ }
+ };
+
+ loadDetails();
+ }, [open, calendarId, fetchCalendarDetails]);
+
+ const isOrphaned = !calendarDetails?.ownerId || !calendarDetails?.owner;
+
+ const getOwnerInitials = () => {
+ if (!calendarDetails?.owner) return "?";
+ const name = calendarDetails.owner.name;
+ if (!name) return "?";
+ return name
+ .split(" ")
+ .map((n) => n[0])
+ .join("")
+ .toUpperCase()
+ .slice(0, 2);
+ };
+
+ const getUserInitials = (name: string, email: string) => {
+ if (name) {
+ return name
+ .split(" ")
+ .map((n) => n[0])
+ .join("")
+ .toUpperCase()
+ .slice(0, 2);
+ }
+ return email.slice(0, 2).toUpperCase();
+ };
+
+ const getGuestPermissionBadge = () => {
+ if (!calendarDetails) return null;
+
+ const permission = calendarDetails.guestPermission;
+ if (permission === "none") {
+ return (
+ <Badge variant="secondary" className="text-xs">
+ {t("common.labels.permissions.none")}
+ </Badge>
+ );
+ } else if (permission === "read") {
+ return (
+ <Badge variant="outline" className="text-xs">
+ {t("common.labels.permissions.read")}
+ </Badge>
+ );
+ } else {
+ return (
+ <Badge variant="default" className="text-xs">
+ {t("common.labels.permissions.write")}
+ </Badge>
+ );
+ }
+ };
+
+ return (
+ <BaseSheet
+ open={open}
+ onOpenChange={onOpenChange}
+ title={t("admin.calendars.calendarDetails")}
+ description={t("admin.calendars.calendarDetailsDescription")}
+ maxWidth="lg"
+ >
+ {isLoading && !calendarDetails ? (
+ <div className="text-center py-12 text-muted-foreground">
+ {t("common.loading")}
+ </div>
+ ) : calendarDetails ? (
+ <div className="space-y-6">
+ {/* Calendar Info & Owner Cards */}
+ <div className="flex items-stretch gap-4">
+ {/* Calendar Name Card */}
+ <div className="flex-1 p-4 rounded-lg border bg-muted/30">
+ <h3 className="text-lg font-semibold mb-2 truncate">
+ {calendarDetails.name}
+ </h3>
+ <div className="flex flex-wrap gap-2 mb-3">
+ {isOrphaned && (
+ <Badge
+ variant="outline"
+ className="bg-red-500/10 text-red-500 border-red-500/20"
+ >
+ {t("admin.calendars.orphaned")}
+ </Badge>
+ )}
+ {getGuestPermissionBadge()}
+ </div>
+ <div className="space-y-1 text-xs text-muted-foreground">
+ <p>
+ {t("common.stats.created")}{" "}
+ {format(calendarDetails.createdAt, "PP", {
+ locale: dateLocale,
+ })}
+ </p>
+ <p>
+ {t("admin.calendars.updated")}{" "}
+ {format(calendarDetails.updatedAt, "PP", {
+ locale: dateLocale,
+ })}
+ </p>
+ </div>
+ </div>
+
+ {/* Separator */}
+ <div className="w-px bg-border self-stretch" />
+
+ {/* Owner Info Card */}
+ <div className="flex-1 p-4 rounded-lg border bg-muted/30">
+ <h4 className="text-sm font-medium mb-3">
+ {t("admin.calendars.owner")}
+ </h4>
+ {isOrphaned ? (
+ <div className="flex items-center justify-center h-20">
+ <p className="text-sm text-red-600 dark:text-red-400">
+ {t("admin.calendars.noOwner")}
+ </p>
+ </div>
+ ) : (
+ <div className="flex items-center gap-3">
+ <Avatar className="h-12 w-12">
+ {calendarDetails.owner?.image && (
+ <AvatarImage src={calendarDetails.owner.image} />
+ )}
+ <AvatarFallback className="text-sm">
+ {getOwnerInitials()}
+ </AvatarFallback>
+ </Avatar>
+ <div className="flex-1 min-w-0">
+ <p className="text-sm font-medium truncate">
+ {calendarDetails.owner?.name}
+ </p>
+ <p className="text-xs text-muted-foreground truncate">
+ {calendarDetails.owner?.email}
+ </p>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+
+ <Separator />
+
+ {/* Statistics */}
+ <div>
+ <h4 className="text-sm font-medium mb-3">
+ {t("common.stats.statistics")}
+ </h4>
+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
+ <div className="p-3 rounded-lg border bg-muted/20">
+ <div className="flex items-center gap-2 mb-1">
+ <Calendar className="h-4 w-4 text-muted-foreground" />
+ <span className="text-xs text-muted-foreground">
+ {t("common.labels.shifts")}
+ </span>
+ </div>
+ <p className="text-xl font-semibold">
+ {calendarDetails.shiftsCount}
+ </p>
+ </div>
+ <div className="p-3 rounded-lg border bg-muted/20">
+ <div className="flex items-center gap-2 mb-1">
+ <StickyNote className="h-4 w-4 text-muted-foreground" />
+ <span className="text-xs text-muted-foreground">
+ {t("common.labels.notes")}
+ </span>
+ </div>
+ <p className="text-xl font-semibold">
+ {calendarDetails.notesCount}
+ </p>
+ </div>
+ <div className="p-3 rounded-lg border bg-muted/20">
+ <div className="flex items-center gap-2 mb-1">
+ <Bookmark className="h-4 w-4 text-muted-foreground" />
+ <span className="text-xs text-muted-foreground">
+ {t("common.labels.presets")}
+ </span>
+ </div>
+ <p className="text-xl font-semibold">
+ {calendarDetails.presetsCount}
+ </p>
+ </div>
+ <div className="p-3 rounded-lg border bg-muted/20">
+ <div className="flex items-center gap-2 mb-1">
+ <Share2 className="h-4 w-4 text-muted-foreground" />
+ <span className="text-xs text-muted-foreground">
+ {t("common.labels.shares")}
+ </span>
+ </div>
+ <p className="text-xl font-semibold">
+ {calendarDetails.sharesCount}
+ </p>
+ <p className="text-xs text-muted-foreground mt-1">
+ {calendarDetails.shares.length}{" "}
+ {t("admin.calendars.userShares")},{" "}
+ {calendarDetails.shareTokens?.length || 0}{" "}
+ {t("admin.calendars.tokenShares")}
+ </p>
+ </div>
+ </div>
+ </div>
+
+ {/* User Shares List */}
+ {calendarDetails.shares.length > 0 && (
+ <>
+ <Separator />
+ <div>
+ <h4 className="text-sm font-medium flex items-center gap-2 mb-3">
+ <Share2 className="h-4 w-4" />
+ {t("admin.calendars.userSharesList")} (
+ {calendarDetails.shares.length})
+ </h4>
+ <div className="space-y-2 max-h-64 overflow-y-auto">
+ {calendarDetails.shares.map((share) => (
+ <div
+ key={share.userId}
+ className="flex items-center gap-3 p-2 rounded-lg border bg-muted/20"
+ >
+ <Avatar className="h-8 w-8">
+ {share.userImage && (
+ <AvatarImage src={share.userImage} />
+ )}
+ <AvatarFallback className="text-xs">
+ {getUserInitials(share.userName, share.userEmail)}
+ </AvatarFallback>
+ </Avatar>
+ <div className="flex-1 min-w-0">
+ <p className="text-sm font-medium truncate">
+ {share.userName}
+ </p>
+ <p className="text-xs text-muted-foreground truncate">
+ {share.userEmail}
+ </p>
+ </div>
+ <Badge variant="secondary" className="text-xs">
+ {t(`common.labels.permissions.${share.permission}`)}
+ </Badge>
+ </div>
+ ))}
+ </div>
+ </div>
+ </>
+ )}
+
+ {/* Share Tokens */}
+ {calendarDetails.shareTokens &&
+ calendarDetails.shareTokens.length > 0 && (
+ <>
+ <Separator />
+ <div>
+ <h4 className="text-sm font-medium flex items-center gap-2 mb-3">
+ <Link className="h-4 w-4" />
+ {t("admin.calendars.tokenSharesList")} (
+ {calendarDetails.shareTokens.length})
+ </h4>
+ <div className="space-y-2 max-h-64 overflow-y-auto">
+ {calendarDetails.shareTokens.map((token) => (
+ <div
+ key={token.id}
+ className="flex items-center gap-3 p-2 rounded-lg border bg-muted/20"
+ >
+ <div className="flex-1 min-w-0">
+ <p className="text-sm font-medium truncate">
+ {token.name}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {t("common.stats.created")}{" "}
+ {format(token.createdAt, "PP", {
+ locale: dateLocale,
+ })}
+ </p>
+ </div>
+ <Badge variant="secondary" className="text-xs">
+ {t(`common.labels.permissions.${token.permission}`)}
+ </Badge>
+ </div>
+ ))}
+ </div>
+ </div>
+ </>
+ )}
+
+ {/* External Syncs */}
+ {calendarDetails.externalSyncs &&
+ calendarDetails.externalSyncs.length > 0 && (
+ <>
+ {(calendarDetails.shares.length > 0 ||
+ (calendarDetails.shareTokens &&
+ calendarDetails.shareTokens.length > 0)) && <Separator />}
+ <div>
+ <h4 className="text-sm font-medium flex items-center gap-2 mb-3">
+ <CloudDownload className="h-4 w-4" />
+ {t("admin.calendars.externalSyncs")} (
+ {calendarDetails.externalSyncs.length})
+ </h4>
+ <div className="space-y-2 max-h-48 overflow-y-auto">
+ {calendarDetails.externalSyncs.map((sync) => (
+ <div
+ key={sync.id}
+ className="p-2 rounded-lg border bg-muted/20"
+ >
+ <p className="text-sm font-medium truncate">
+ {sync.name}
+ </p>
+ <p className="text-xs text-muted-foreground truncate">
+ {sync.url}
+ </p>
+ {sync.lastSyncedAt && (
+ <p className="text-xs text-muted-foreground mt-1">
+ {t("admin.calendars.lastSynced")}{" "}
+ {format(sync.lastSyncedAt, "PP", {
+ locale: dateLocale,
+ })}
+ </p>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ </>
+ )}
+
+ {/* Quick Actions */}
+ {(canEdit || canTransfer || canDelete) && (
+ <>
+ <Separator />
+ <div>
+ <h4 className="text-sm font-medium mb-3">
+ {t("admin.calendars.quickActions")}
+ </h4>
+ <div className="flex flex-col sm:flex-row gap-2">
+ {canEdit && (
+ <Button
+ variant="outline"
+ className="flex-1"
+ onClick={onEdit}
+ >
+ <Edit className="h-4 w-4 mr-2" />
+ {t("admin.calendars.editCalendar")}
+ </Button>
+ )}
+ {canTransfer && (
+ <Button
+ variant="outline"
+ className="flex-1"
+ onClick={onTransfer}
+ >
+ <Send className="h-4 w-4 mr-2" />
+ {t("admin.calendars.transferOwnership")}
+ </Button>
+ )}
+ {canDelete && (
+ <Button
+ variant="outline"
+ className="flex-1 text-destructive hover:text-destructive"
+ onClick={onDelete}
+ >
+ <Trash2 className="h-4 w-4 mr-2" />
+ {t("admin.calendars.deleteCalendar")}
+ </Button>
+ )}
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ ) : null}
+ </BaseSheet>
+ );
+}
diff --git a/components/admin/calendar-edit-sheet.tsx b/components/admin/calendar-edit-sheet.tsx
new file mode 100644
index 0000000..88d2010
--- /dev/null
+++ b/components/admin/calendar-edit-sheet.tsx
@@ -0,0 +1,174 @@
+"use client";
+
+import { useState, useEffect } from "react";
+import { useTranslations } from "next-intl";
+import { BaseSheet } from "@/components/ui/base-sheet";
+import { Label } from "@/components/ui/label";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { ColorPicker } from "@/components/ui/color-picker";
+import { PRESET_COLORS } from "@/lib/constants";
+import {
+ useAdminCalendars,
+ type AdminCalendar,
+} from "@/hooks/useAdminCalendars";
+import { useCanEditCalendar } from "@/hooks/useAdminAccess";
+
+interface CalendarEditSheetProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ calendar: AdminCalendar;
+ onSuccess: () => void;
+}
+
+export function CalendarEditSheet({
+ open,
+ onOpenChange,
+ calendar,
+ onSuccess,
+}: CalendarEditSheetProps) {
+ const t = useTranslations();
+ const { updateCalendar, isLoading } = useAdminCalendars();
+ const canEdit = useCanEditCalendar();
+
+ const [name, setName] = useState(calendar.name);
+ const [color, setColor] = useState(calendar.color);
+ const [guestPermission, setGuestPermission] = useState(
+ calendar.guestPermission
+ );
+
+ // Reset state when calendar changes
+ useEffect(() => {
+ setName(calendar.name);
+ setColor(calendar.color);
+ setGuestPermission(calendar.guestPermission);
+ }, [calendar]);
+
+ // Track if form has changes
+ const hasChanges =
+ name !== calendar.name ||
+ color !== calendar.color ||
+ guestPermission !== calendar.guestPermission;
+
+ if (!canEdit) {
+ return null;
+ }
+
+ const handleOpenChange = (newOpen: boolean) => {
+ onOpenChange(newOpen);
+ };
+
+ const handleSave = async () => {
+ const updates: {
+ name?: string;
+ color?: string;
+ guestPermission?: string;
+ } = {};
+
+ if (name !== calendar.name) updates.name = name;
+ if (color !== calendar.color) updates.color = color;
+ if (guestPermission !== calendar.guestPermission)
+ updates.guestPermission = guestPermission;
+
+ const success = await updateCalendar(calendar.id, updates);
+ if (success) {
+ onSuccess();
+ handleOpenChange(false);
+ }
+ };
+
+ return (
+ <BaseSheet
+ open={open}
+ onOpenChange={handleOpenChange}
+ title={t("admin.calendars.editCalendar")}
+ description={t("admin.calendars.editCalendarDescription")}
+ showSaveButton
+ onSave={handleSave}
+ isSaving={isLoading}
+ saveDisabled={!hasChanges || !name.trim()}
+ hasUnsavedChanges={hasChanges}
+ maxWidth="md"
+ >
+ <div className="space-y-6">
+ {/* Calendar Name */}
+ <div className="space-y-2">
+ <Label htmlFor="name">
+ {t("common.labels.name")}{" "}
+ <span className="text-destructive">*</span>
+ </Label>
+ <Input
+ id="name"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder={t("admin.calendars.namePlaceholder")}
+ />
+ </div>
+
+ {/* Calendar Color */}
+ <ColorPicker
+ color={color}
+ onChange={setColor}
+ label={t("form.colorLabel")}
+ presetColors={PRESET_COLORS}
+ />
+
+ {/* Guest Permission */}
+ <div className="space-y-2">
+ <Label htmlFor="guestPermission">
+ {t("admin.calendars.guestPermission")}
+ </Label>
+ <Select
+ value={guestPermission}
+ onValueChange={(value) =>
+ setGuestPermission(value as "none" | "read" | "write")
+ }
+ >
+ <SelectTrigger id="guestPermission">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="none">
+ {t("common.labels.permissions.none")}
+ </SelectItem>
+ <SelectItem value="read">
+ {t("common.labels.permissions.read")}
+ </SelectItem>
+ <SelectItem value="write">
+ {t("common.labels.permissions.write")}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ <p className="text-xs text-muted-foreground">
+ {t("admin.calendars.guestPermissionHint")}
+ </p>
+ </div>
+
+ {/* Current Owner */}
+ <div className="space-y-2">
+ <Label>{t("admin.calendars.currentOwner")}</Label>
+ <div className="p-3 rounded-lg border bg-muted/20">
+ {calendar.ownerId ? (
+ <div className="flex flex-col gap-1">
+ <p className="text-sm font-medium">{calendar.owner!.name}</p>
+ <p className="text-xs text-muted-foreground">
+ {calendar.owner!.email}
+ </p>
+ </div>
+ ) : (
+ <p className="text-sm text-muted-foreground">
+ {t("admin.calendars.noOwner")}
+ </p>
+ )}
+ </div>
+ </div>
+ </div>
+ </BaseSheet>
+ );
+}
diff --git a/components/admin/calendar-table.tsx b/components/admin/calendar-table.tsx
new file mode 100644
index 0000000..663b030
--- /dev/null
+++ b/components/admin/calendar-table.tsx
@@ -0,0 +1,454 @@
+"use client";
+
+import { useState } from "react";
+import { useTranslations } from "next-intl";
+import { useLocale } from "next-intl";
+import { format } from "date-fns";
+import {
+ MoreVertical,
+ Edit,
+ Trash2,
+ Eye,
+ Send,
+ ChevronUp,
+ ChevronDown,
+} from "lucide-react";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { getDateLocale } from "@/lib/locales";
+import type { AdminCalendar } from "@/hooks/useAdminCalendars";
+import {
+ useCanEditCalendar,
+ useCanDeleteCalendar,
+ useCanTransferCalendar,
+} from "@/hooks/useAdminAccess";
+
+interface CalendarTableProps {
+ calendars: AdminCalendar[];
+ selectedIds: string[];
+ onToggleSelect: (calendarId: string) => void;
+ onToggleSelectAll: () => void;
+ isAllSelected: boolean;
+ onCalendarClick: (calendar: AdminCalendar) => void;
+ onEditCalendar: (calendar: AdminCalendar) => void;
+ onTransferCalendar: (calendar: AdminCalendar) => void;
+ onDeleteCalendar: (calendar: AdminCalendar) => void;
+}
+
+type SortColumn =
+ | "name"
+ | "createdAt"
+ | "owner"
+ | "shiftsCount"
+ | "sharesCount"
+ | "externalSyncsCount"
+ | "guestPermission";
+type SortDirection = "asc" | "desc";
+
+function CalendarTableRow({
+ calendar,
+ isSelected,
+ onToggleSelect,
+ onCalendarClick,
+ onEditCalendar,
+ onTransferCalendar,
+ onDeleteCalendar,
+}: {
+ calendar: AdminCalendar;
+ isSelected: boolean;
+ onToggleSelect: (calendarId: string) => void;
+ onCalendarClick: (calendar: AdminCalendar) => void;
+ onEditCalendar: (calendar: AdminCalendar) => void;
+ onTransferCalendar: (calendar: AdminCalendar) => void;
+ onDeleteCalendar: (calendar: AdminCalendar) => void;
+}) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const dateLocale = getDateLocale(locale);
+
+ const canEdit = useCanEditCalendar();
+ const canDelete = useCanDeleteCalendar();
+ const canTransfer = useCanTransferCalendar();
+
+ const isOrphaned = !calendar.ownerId || !calendar.owner;
+ const hasActions = canEdit || canTransfer || canDelete;
+
+ return (
+ <TableRow
+ className="cursor-pointer"
+ onClick={() => onCalendarClick(calendar)}
+ >
+ {/* Checkbox */}
+ <TableCell onClick={(e) => e.stopPropagation()}>
+ <Checkbox
+ checked={isSelected}
+ onCheckedChange={() => onToggleSelect(calendar.id)}
+ />
+ </TableCell>
+
+ {/* Calendar Name + Color */}
+ <TableCell>
+ <div className="flex items-center gap-3">
+ <div
+ className="w-4 h-4 rounded-full shrink-0 ring-2 ring-background"
+ style={{ backgroundColor: calendar.color }}
+ />
+ <div className="min-w-0">
+ <p className="text-sm font-medium truncate">{calendar.name}</p>
+ </div>
+ </div>
+ </TableCell>
+
+ {/* Owner */}
+ <TableCell>
+ {isOrphaned ? (
+ <Badge
+ variant="outline"
+ className="bg-red-500/10 text-red-500 border-red-500/20"
+ >
+ {t("admin.calendars.orphaned")}
+ </Badge>
+ ) : (
+ <div className="flex items-center gap-3">
+ <Avatar className="h-8 w-8">
+ {calendar.owner?.image && (
+ <AvatarImage src={calendar.owner.image} />
+ )}
+ <AvatarFallback className="text-xs">
+ {calendar.owner?.name
+ ? calendar.owner.name
+ .split(" ")
+ .map((n) => n[0])
+ .join("")
+ .toUpperCase()
+ .slice(0, 2)
+ : (calendar.owner?.email || "").slice(0, 2).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ <div className="min-w-0">
+ <p className="text-sm truncate">{calendar.owner?.name}</p>
+ <p className="text-xs text-muted-foreground truncate">
+ {calendar.owner?.email}
+ </p>
+ </div>
+ </div>
+ )}
+ </TableCell>
+
+ {/* Created */}
+ <TableCell>
+ <span className="text-sm text-muted-foreground">
+ {format(calendar.createdAt, "PP", { locale: dateLocale })}
+ </span>
+ </TableCell>
+
+ {/* Shifts Count */}
+ <TableCell>
+ <span className="text-sm">{calendar.shiftsCount}</span>
+ </TableCell>
+
+ {/* Shares Count */}
+ <TableCell>
+ <span className="text-sm">{calendar.sharesCount}</span>
+ </TableCell>
+
+ {/* External Syncs Count */}
+ <TableCell>
+ <span className="text-sm">{calendar.externalSyncsCount || 0}</span>
+ </TableCell>
+
+ {/* Guest Permission */}
+ <TableCell>
+ {calendar.guestPermission === "none" ? (
+ <Badge variant="secondary" className="text-xs">
+ {t("common.labels.permissions.none")}
+ </Badge>
+ ) : calendar.guestPermission === "read" ? (
+ <Badge variant="outline" className="text-xs">
+ {t("common.labels.permissions.read")}
+ </Badge>
+ ) : (
+ <Badge variant="default" className="text-xs">
+ {t("common.labels.permissions.write")}
+ </Badge>
+ )}
+ </TableCell>
+
+ {/* Actions */}
+ <TableCell onClick={(e) => e.stopPropagation()}>
+ {hasActions && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="sm">
+ <MoreVertical className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => onCalendarClick(calendar)}>
+ <Eye className="h-4 w-4 mr-2" />
+ {t("common.viewDetails")}
+ </DropdownMenuItem>
+ {canEdit && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={() => onEditCalendar(calendar)}>
+ <Edit className="h-4 w-4 mr-2" />
+ {t("admin.calendars.editCalendar")}
+ </DropdownMenuItem>
+ </>
+ )}
+ {canTransfer && (
+ <DropdownMenuItem onClick={() => onTransferCalendar(calendar)}>
+ <Send className="h-4 w-4 mr-2" />
+ {t("admin.calendars.transferOwnership")}
+ </DropdownMenuItem>
+ )}
+ {canDelete && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={() => onDeleteCalendar(calendar)}
+ className="text-destructive"
+ >
+ <Trash2 className="h-4 w-4 mr-2" />
+ {t("admin.calendars.deleteCalendar")}
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </TableCell>
+ </TableRow>
+ );
+}
+
+export function CalendarTable({
+ calendars,
+ selectedIds,
+ onToggleSelect,
+ onToggleSelectAll,
+ isAllSelected,
+ onCalendarClick,
+ onEditCalendar,
+ onTransferCalendar,
+ onDeleteCalendar,
+}: CalendarTableProps) {
+ const t = useTranslations();
+ const [sortColumn, setSortColumn] = useState<SortColumn | null>("createdAt");
+ const [sortDirection, setSortDirection] = useState<SortDirection>("desc");
+
+ // Sort calendars (orphaned always first, then by selected column)
+ const sortedCalendars = [...calendars].sort((a, b) => {
+ // Orphaned calendars always on top
+ const aOrphaned = !a.ownerId;
+ const bOrphaned = !b.ownerId;
+
+ if (aOrphaned !== bOrphaned) {
+ return aOrphaned ? -1 : 1;
+ }
+
+ // Then sort by selected column
+ if (!sortColumn) return 0;
+
+ let comparison = 0;
+
+ switch (sortColumn) {
+ case "name":
+ comparison = a.name.localeCompare(b.name);
+ break;
+ case "createdAt":
+ comparison = a.createdAt.getTime() - b.createdAt.getTime();
+ break;
+ case "owner":
+ const aOwner = a.owner?.name || "";
+ const bOwner = b.owner?.name || "";
+ comparison = aOwner.localeCompare(bOwner);
+ break;
+ case "shiftsCount":
+ comparison = a.shiftsCount - b.shiftsCount;
+ break;
+ case "sharesCount":
+ comparison = a.sharesCount - b.sharesCount;
+ break;
+ case "externalSyncsCount":
+ comparison = (a.externalSyncsCount || 0) - (b.externalSyncsCount || 0);
+ break;
+ case "guestPermission":
+ const permissionOrder = { none: 0, read: 1, write: 2 };
+ comparison =
+ permissionOrder[a.guestPermission] -
+ permissionOrder[b.guestPermission];
+ break;
+ }
+
+ return sortDirection === "asc" ? comparison : -comparison;
+ });
+
+ // Handle sort column click
+ const handleSort = (column: SortColumn) => {
+ if (sortColumn === column) {
+ setSortDirection((prev) => (prev === "asc" ? "desc" : "asc"));
+ } else {
+ setSortColumn(column);
+ setSortDirection("desc");
+ }
+ };
+
+ return (
+ <div className="border border-border/50 bg-gradient-to-br from-card/95 via-card to-card/80 backdrop-blur-sm rounded-lg overflow-hidden shadow-sm">
+ <Table>
+ <TableHeader className="bg-muted/50">
+ <TableRow>
+ <TableHead className="w-[50px]">
+ <Checkbox
+ checked={isAllSelected}
+ onCheckedChange={onToggleSelectAll}
+ />
+ </TableHead>
+ <TableHead
+ className="cursor-pointer hover:bg-muted/80 transition-colors"
+ onClick={() => handleSort("name")}
+ >
+ <div className="flex items-center gap-2">
+ {t("common.labels.name")}
+ {sortColumn === "name" &&
+ (sortDirection === "asc" ? (
+ <ChevronUp className="h-4 w-4" />
+ ) : (
+ <ChevronDown className="h-4 w-4" />
+ ))}
+ </div>
+ </TableHead>
+ <TableHead
+ className="cursor-pointer hover:bg-muted/80 transition-colors"
+ onClick={() => handleSort("owner")}
+ >
+ <div className="flex items-center gap-2">
+ {t("admin.calendars.owner")}
+ {sortColumn === "owner" &&
+ (sortDirection === "asc" ? (
+ <ChevronUp className="h-4 w-4" />
+ ) : (
+ <ChevronDown className="h-4 w-4" />
+ ))}
+ </div>
+ </TableHead>
+ <TableHead
+ className="cursor-pointer hover:bg-muted/80 transition-colors"
+ onClick={() => handleSort("createdAt")}
+ >
+ <div className="flex items-center gap-2">
+ {t("common.stats.created")}
+ {sortColumn === "createdAt" &&
+ (sortDirection === "asc" ? (
+ <ChevronUp className="h-4 w-4" />
+ ) : (
+ <ChevronDown className="h-4 w-4" />
+ ))}
+ </div>
+ </TableHead>
+ <TableHead
+ className="cursor-pointer hover:bg-muted/80 transition-colors"
+ onClick={() => handleSort("shiftsCount")}
+ >
+ <div className="flex items-center gap-2">
+ {t("common.labels.shifts")}
+ {sortColumn === "shiftsCount" &&
+ (sortDirection === "asc" ? (
+ <ChevronUp className="h-4 w-4" />
+ ) : (
+ <ChevronDown className="h-4 w-4" />
+ ))}
+ </div>
+ </TableHead>
+ <TableHead
+ className="cursor-pointer hover:bg-muted/80 transition-colors"
+ onClick={() => handleSort("sharesCount")}
+ >
+ <div className="flex items-center gap-2">
+ {t("common.labels.shares")}
+ {sortColumn === "sharesCount" &&
+ (sortDirection === "asc" ? (
+ <ChevronUp className="h-4 w-4" />
+ ) : (
+ <ChevronDown className="h-4 w-4" />
+ ))}
+ </div>
+ </TableHead>
+ <TableHead
+ className="cursor-pointer hover:bg-muted/80 transition-colors"
+ onClick={() => handleSort("externalSyncsCount")}
+ >
+ <div className="flex items-center gap-2">
+ {t("admin.calendars.externalSyncsShort")}
+ {sortColumn === "externalSyncsCount" &&
+ (sortDirection === "asc" ? (
+ <ChevronUp className="h-4 w-4" />
+ ) : (
+ <ChevronDown className="h-4 w-4" />
+ ))}
+ </div>
+ </TableHead>
+ <TableHead
+ className="cursor-pointer hover:bg-muted/80 transition-colors"
+ onClick={() => handleSort("guestPermission")}
+ >
+ <div className="flex items-center gap-2">
+ {t("admin.calendars.guestPermission")}
+ {sortColumn === "guestPermission" &&
+ (sortDirection === "asc" ? (
+ <ChevronUp className="h-4 w-4" />
+ ) : (
+ <ChevronDown className="h-4 w-4" />
+ ))}
+ </div>
+ </TableHead>
+ <TableHead className="w-[50px]"></TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {sortedCalendars.length === 0 ? (
+ <TableRow>
+ <TableCell colSpan={9} className="text-center py-8">
+ <p className="text-muted-foreground">
+ {t("admin.calendars.noCalendarsFound")}
+ </p>
+ </TableCell>
+ </TableRow>
+ ) : (
+ sortedCalendars.map((calendar) => (
+ <CalendarTableRow
+ key={calendar.id}
+ calendar={calendar}
+ isSelected={selectedIds.includes(calendar.id)}
+ onToggleSelect={onToggleSelect}
+ onCalendarClick={onCalendarClick}
+ onEditCalendar={onEditCalendar}
+ onTransferCalendar={onTransferCalendar}
+ onDeleteCalendar={onDeleteCalendar}
+ />
+ ))
+ )}
+ </TableBody>
+ </Table>
+ </div>
+ );
+}
diff --git a/components/admin/calendar-transfer-sheet.tsx b/components/admin/calendar-transfer-sheet.tsx
new file mode 100644
index 0000000..95c53e0
--- /dev/null
+++ b/components/admin/calendar-transfer-sheet.tsx
@@ -0,0 +1,336 @@
+"use client";
+
+import { useState, useCallback, useMemo } from "react";
+import { useTranslations } from "next-intl";
+import { Search, X } from "lucide-react";
+import { BaseSheet } from "@/components/ui/base-sheet";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
+import { Badge } from "@/components/ui/badge";
+import {
+ useAdminCalendars,
+ type AdminCalendar,
+} from "@/hooks/useAdminCalendars";
+import { useAdminUsers, type AdminUser } from "@/hooks/useAdminUsers";
+import { useCanTransferCalendar } from "@/hooks/useAdminAccess";
+
+interface CalendarTransferSheetProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ calendars: AdminCalendar[]; // Single calendar or multiple for bulk
+ onSuccess: () => void;
+}
+
+interface SearchUser {
+ id: string;
+ name: string;
+ email: string;
+ image: string | null;
+ role: string;
+}
+
+export function CalendarTransferSheet({
+ open,
+ onOpenChange,
+ calendars,
+ onSuccess,
+}: CalendarTransferSheetProps) {
+ const t = useTranslations();
+ const { transferCalendar, bulkTransferCalendars, isLoading } =
+ useAdminCalendars();
+ const { fetchUsers } = useAdminUsers();
+ const canTransfer = useCanTransferCalendar();
+
+ const [query, setQuery] = useState("");
+ const [selectedUser, setSelectedUser] = useState<SearchUser | null>(null);
+ const [searchResults, setSearchResults] = useState<SearchUser[]>([]);
+ const [searchLoading, setSearchLoading] = useState(false);
+
+ const isBulk = calendars.length > 1;
+
+ // Debounced search
+ const handleSearch = useCallback(
+ (value: string) => {
+ setQuery(value);
+ setSelectedUser(null);
+
+ if (value.length < 2) {
+ setSearchResults([]);
+ return;
+ }
+
+ setSearchLoading(true);
+
+ // Debounce search
+ const timeoutId = setTimeout(async () => {
+ const result = await fetchUsers(
+ { search: value, status: "active" },
+ { field: "name", direction: "asc" },
+ { page: 1, limit: 50 }
+ );
+
+ if (result) {
+ setSearchResults(
+ result.users.map((user: AdminUser) => ({
+ id: user.id,
+ name: user.name,
+ email: user.email,
+ image: user.image || null,
+ role: user.role || "user",
+ }))
+ );
+ }
+ setSearchLoading(false);
+ }, 300);
+
+ return () => clearTimeout(timeoutId);
+ },
+ [fetchUsers]
+ );
+
+ const handleSelectUser = (user: SearchUser) => {
+ setSelectedUser(user);
+ setQuery(user.name || user.email);
+ };
+
+ const handleTransfer = async () => {
+ if (!selectedUser) return;
+
+ let success = false;
+
+ if (isBulk) {
+ // Bulk transfer
+ const calendarIds = calendars.map((cal) => cal.id);
+ success = await bulkTransferCalendars(calendarIds, selectedUser.id);
+ } else {
+ // Single transfer
+ success = await transferCalendar(calendars[0].id, selectedUser.id);
+ }
+
+ if (success) {
+ handleClose();
+ onSuccess();
+ }
+ };
+
+ const handleClose = () => {
+ setQuery("");
+ setSelectedUser(null);
+ setSearchResults([]);
+ onOpenChange(false);
+ };
+
+ const getUserInitials = (user: SearchUser) => {
+ if (user.name) {
+ return user.name
+ .split(" ")
+ .map((n) => n[0])
+ .join("")
+ .toUpperCase()
+ .slice(0, 2);
+ }
+ return user.email.slice(0, 2).toUpperCase();
+ };
+
+ const getRoleBadgeClass = (role: string) => {
+ switch (role) {
+ case "superadmin":
+ return "bg-red-500/10 text-red-500 border-red-500/20";
+ case "admin":
+ return "bg-orange-500/10 text-orange-500 border-orange-500/20";
+ default:
+ return "bg-blue-500/10 text-blue-500 border-blue-500/20";
+ }
+ };
+
+ const showResults = useMemo(
+ () => query.length >= 2 && !selectedUser && searchResults.length > 0,
+ [query, selectedUser, searchResults]
+ );
+
+ if (!canTransfer) {
+ return null;
+ }
+
+ return (
+ <BaseSheet
+ open={open}
+ onOpenChange={handleClose}
+ title={t("admin.calendars.transferOwnership")}
+ description={
+ isBulk
+ ? t("admin.calendars.transferMultipleDescription", {
+ count: calendars.length,
+ })
+ : t("admin.calendars.transferSingleDescription", {
+ name: calendars[0]?.name,
+ })
+ }
+ showSaveButton
+ onSave={handleTransfer}
+ isSaving={isLoading}
+ saveDisabled={!selectedUser}
+ saveLabel={t("admin.calendars.transferButton")}
+ maxWidth="md"
+ >
+ <div className="space-y-6">
+ {/* Calendar(s) Preview */}
+ <div className="space-y-2">
+ <Label>
+ {isBulk
+ ? t("admin.calendars.calendarsToTransfer")
+ : t("admin.calendars.calendarToTransfer")}
+ </Label>
+ <div className="space-y-2 max-h-48 overflow-y-auto border rounded-lg p-3 bg-muted/20">
+ {calendars.map((calendar) => (
+ <div
+ key={calendar.id}
+ className="flex items-center gap-3 p-2 rounded-md bg-background"
+ >
+ <div
+ className="w-3 h-3 rounded-full shrink-0"
+ style={{ backgroundColor: calendar.color }}
+ />
+ <div className="flex-1 min-w-0">
+ <p className="text-sm font-medium truncate">
+ {calendar.name}
+ </p>
+ {calendar.ownerId ? (
+ <p className="text-xs text-muted-foreground truncate">
+ {t("admin.calendars.currentOwner")}:{" "}
+ {calendar.owner!.name}
+ </p>
+ ) : (
+ <Badge
+ variant="outline"
+ className="bg-red-500/10 text-red-500 border-red-500/20 text-xs"
+ >
+ {t("admin.calendars.orphaned")}
+ </Badge>
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* User Search */}
+ <div className="space-y-2">
+ <Label htmlFor="user-search">
+ {t("admin.calendars.selectNewOwner")}{" "}
+ <span className="text-destructive">*</span>
+ </Label>
+ <div className="relative">
+ <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
+ <Input
+ id="user-search"
+ type="text"
+ value={query}
+ onChange={(e) => handleSearch(e.target.value)}
+ placeholder={t("admin.calendars.searchUserPlaceholder")}
+ className="pl-10 pr-10"
+ autoComplete="off"
+ />
+ {query && (
+ <button
+ type="button"
+ onClick={() => {
+ setQuery("");
+ setSelectedUser(null);
+ }}
+ className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
+ >
+ <X className="h-4 w-4" />
+ </button>
+ )}
+ </div>
+
+ {/* Search Results */}
+ {showResults && (
+ <div className="border rounded-lg divide-y max-h-64 overflow-y-auto bg-card">
+ {searchResults.map((user) => (
+ <button
+ key={user.id}
+ type="button"
+ onClick={() => handleSelectUser(user)}
+ className="w-full flex items-center gap-3 p-3 hover:bg-muted/50 transition-colors text-left"
+ >
+ <Avatar className="h-8 w-8">
+ {user.image && <AvatarImage src={user.image} />}
+ <AvatarFallback className="text-xs">
+ {getUserInitials(user)}
+ </AvatarFallback>
+ </Avatar>
+ <div className="flex-1 min-w-0">
+ <p className="text-sm font-medium truncate">{user.name}</p>
+ <p className="text-xs text-muted-foreground truncate">
+ {user.email}
+ </p>
+ </div>
+ <Badge
+ variant="outline"
+ className={getRoleBadgeClass(user.role)}
+ >
+ {t(`common.roles.${user.role}`)}
+ </Badge>
+ </button>
+ ))}
+ </div>
+ )}
+
+ {/* No Results */}
+ {query.length >= 2 &&
+ !selectedUser &&
+ searchResults.length === 0 &&
+ !searchLoading && (
+ <p className="text-sm text-muted-foreground text-center py-4">
+ {t("common.empty.noUsersFound")}
+ </p>
+ )}
+
+ {/* Loading */}
+ {searchLoading && (
+ <p className="text-sm text-muted-foreground text-center py-4">
+ {t("common.loading")}
+ </p>
+ )}
+
+ {/* Hint */}
+ {query.length < 2 && (
+ <p className="text-xs text-muted-foreground">
+ {t("admin.calendars.searchUserHint")}
+ </p>
+ )}
+ </div>
+
+ {/* Selected User Preview */}
+ {selectedUser && (
+ <div className="space-y-2">
+ <Label>{t("admin.calendars.newOwner")}</Label>
+ <div className="flex items-center gap-3 p-3 rounded-lg border bg-muted/20">
+ <Avatar className="h-10 w-10">
+ {selectedUser.image && <AvatarImage src={selectedUser.image} />}
+ <AvatarFallback>{getUserInitials(selectedUser)}</AvatarFallback>
+ </Avatar>
+ <div className="flex-1 min-w-0">
+ <p className="text-sm font-medium truncate">
+ {selectedUser.name}
+ </p>
+ <p className="text-xs text-muted-foreground truncate">
+ {selectedUser.email}
+ </p>
+ </div>
+ <Badge
+ variant="outline"
+ className={getRoleBadgeClass(selectedUser.role)}
+ >
+ {t(`common.roles.${selectedUser.role}`)}
+ </Badge>
+ </div>
+ </div>
+ )}
+ </div>
+ </BaseSheet>
+ );
+}
diff --git a/components/admin/stats-cards.tsx b/components/admin/stats-cards.tsx
new file mode 100644
index 0000000..40e2056
--- /dev/null
+++ b/components/admin/stats-cards.tsx
@@ -0,0 +1,214 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useTranslations } from "next-intl";
+import {
+ Users,
+ Calendar,
+ Share2,
+ FolderOpen,
+ Clock,
+ Activity,
+ LucideIcon,
+} from "lucide-react";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Badge } from "@/components/ui/badge";
+import { cn } from "@/lib/utils";
+import type { AdminStats } from "@/hooks/useAdminStats";
+
+interface StatsCardProps {
+ title: string;
+ value: number | string;
+ description?: string;
+ icon: LucideIcon;
+ variant?: "default" | "warning" | "success" | "info";
+ href?: string;
+ badge?: {
+ text: string;
+ variant: "default" | "secondary" | "destructive" | "outline";
+ };
+ isLoading?: boolean;
+}
+
+/**
+ * Individual Stats Card Component
+ *
+ * Displays a single statistic with optional click navigation.
+ */
+function StatsCard({
+ title,
+ value,
+ description,
+ icon: Icon,
+ variant = "default",
+ href,
+ badge,
+ isLoading = false,
+}: StatsCardProps) {
+ const router = useRouter();
+
+ const variantColors = {
+ default: "text-blue-600 dark:text-blue-400",
+ warning: "text-yellow-600 dark:text-yellow-400",
+ success: "text-green-600 dark:text-green-400",
+ info: "text-cyan-600 dark:text-cyan-400",
+ };
+
+ const handleClick = () => {
+ if (href) {
+ router.push(href);
+ }
+ };
+
+ return (
+ <Card
+ className={cn(
+ "transition-all",
+ href && "cursor-pointer hover:shadow-md hover:scale-[1.02]"
+ )}
+ onClick={handleClick}
+ >
+ <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
+ <CardTitle className="text-sm font-medium">{title}</CardTitle>
+ <Icon className={cn("h-4 w-4", variantColors[variant])} />
+ </CardHeader>
+ <CardContent>
+ {isLoading ? (
+ <div className="text-muted-foreground">-</div>
+ ) : (
+ <>
+ <div className="flex items-center gap-2">
+ <div className="text-2xl font-bold">{value}</div>
+ {badge && (
+ <Badge variant={badge.variant} className="text-xs">
+ {badge.text}
+ </Badge>
+ )}
+ </div>
+ {description && (
+ <p className="text-xs text-muted-foreground mt-1">
+ {description}
+ </p>
+ )}
+ </>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
+
+interface StatsCardsGridProps {
+ stats: AdminStats | null;
+ isLoading: boolean;
+}
+
+/**
+ * Admin Stats Cards Grid
+ *
+ * Displays system statistics in a responsive grid layout.
+ *
+ * Features:
+ * - Responsive layout (1 col mobile, 2-3 cols desktop)
+ * - Color-coded by importance/type
+ * - Clickable cards navigate to relevant pages
+ * - Loading skeleton states
+ * - Warning indicators (e.g., orphaned calendars)
+ */
+export function StatsCardsGrid({ stats, isLoading }: StatsCardsGridProps) {
+ const t = useTranslations();
+
+ return (
+ <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
+ {/* Total Users */}
+ <StatsCard
+ title={t("admin.stats.totalUsers")}
+ value={isLoading ? "-" : stats?.users.total || 0}
+ description={
+ isLoading
+ ? undefined
+ : t("admin.stats.usersByRole", {
+ superadmin: stats?.users.superadmin || 0,
+ admin: stats?.users.admin || 0,
+ user: stats?.users.user || 0,
+ })
+ }
+ icon={Users}
+ variant="info"
+ href="/admin/users"
+ isLoading={isLoading}
+ />
+
+ {/* Total Calendars */}
+ <StatsCard
+ title={t("admin.stats.totalCalendars")}
+ value={isLoading ? "-" : stats?.calendars.total || 0}
+ description={t("admin.stats.calendarsDescription")}
+ icon={Calendar}
+ variant="default"
+ href="/admin/calendars"
+ isLoading={isLoading}
+ />
+
+ {/* Active Shares */}
+ <StatsCard
+ title={t("admin.stats.activeShares")}
+ value={isLoading ? "-" : stats?.shares.active || 0}
+ description={
+ isLoading
+ ? undefined
+ : t("admin.stats.sharesDescription", {
+ user: stats?.shares.user || 0,
+ token: stats?.shares.token || 0,
+ })
+ }
+ icon={Share2}
+ variant="success"
+ isLoading={isLoading}
+ />
+
+ {/* Orphaned Calendars */}
+ <StatsCard
+ title={t("admin.stats.orphanedCalendars")}
+ value={isLoading ? "-" : stats?.calendars.orphaned || 0}
+ description={t("admin.stats.orphanedDescription")}
+ icon={FolderOpen}
+ variant={
+ !isLoading && stats && stats.calendars.orphaned > 0
+ ? "warning"
+ : "default"
+ }
+ href="/admin/calendars"
+ badge={
+ !isLoading && stats && stats.calendars.orphaned > 0
+ ? {
+ text: t("admin.stats.needsAttention"),
+ variant: "destructive",
+ }
+ : undefined
+ }
+ isLoading={isLoading}
+ />
+
+ {/* Total Shifts */}
+ <StatsCard
+ title={t("admin.stats.totalShifts")}
+ value={isLoading ? "-" : stats?.shifts.total || 0}
+ description={t("admin.stats.shiftsDescription")}
+ icon={Clock}
+ variant="default"
+ isLoading={isLoading}
+ />
+
+ {/* Recent Activity */}
+ <StatsCard
+ title={t("admin.stats.recentActivity")}
+ value={isLoading ? "-" : stats?.activity.recent || 0}
+ description={t("admin.stats.last7Days")}
+ icon={Activity}
+ variant="info"
+ href="/admin/logs"
+ isLoading={isLoading}
+ />
+ </div>
+ );
+}
diff --git a/components/admin/user-ban-dialog.tsx b/components/admin/user-ban-dialog.tsx
new file mode 100644
index 0000000..ba2ed34
--- /dev/null
+++ b/components/admin/user-ban-dialog.tsx
@@ -0,0 +1,151 @@
+"use client";
+
+import { useState } from "react";
+import { useTranslations } from "next-intl";
+import { AlertTriangle } from "lucide-react";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Button } from "@/components/ui/button";
+import { Label } from "@/components/ui/label";
+import { Textarea } from "@/components/ui/textarea";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Input } from "@/components/ui/input";
+import type { AdminUser } from "@/hooks/useAdminUsers";
+
+interface UserBanDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ user: AdminUser;
+ onConfirm: (reason: string, expiresAt?: Date) => Promise<void>;
+}
+
+export function UserBanDialog({
+ open,
+ onOpenChange,
+ user,
+ onConfirm,
+}: UserBanDialogProps) {
+ const t = useTranslations();
+ const [reason, setReason] = useState("");
+ const [isPermanent, setIsPermanent] = useState(true);
+ const [expiresAt, setExpiresAt] = useState("");
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ const handleConfirm = async () => {
+ if (!reason.trim()) return;
+
+ setIsSubmitting(true);
+ try {
+ const expirationDate =
+ isPermanent || !expiresAt ? undefined : new Date(expiresAt);
+ await onConfirm(reason.trim(), expirationDate);
+ // Reset form
+ setReason("");
+ setIsPermanent(true);
+ setExpiresAt("");
+ onOpenChange(false);
+ } finally {
+ setIsSubmitting(false);
+ }
+ };
+
+ const handleCancel = () => {
+ // Reset form
+ setReason("");
+ setIsPermanent(true);
+ setExpiresAt("");
+ onOpenChange(false);
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-[500px]">
+ <DialogHeader>
+ <DialogTitle>{t("admin.banUser")}</DialogTitle>
+ <DialogDescription>
+ {t("admin.banUserConfirm", {
+ name: user.name || user.email,
+ })}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-4 py-4">
+ {/* Warning */}
+ <div className="flex gap-3 p-3 rounded-lg bg-yellow-50 dark:bg-yellow-950/20 border border-yellow-200 dark:border-yellow-900">
+ <AlertTriangle className="h-5 w-5 text-yellow-600 dark:text-yellow-400 flex-shrink-0 mt-0.5" />
+ <p className="text-sm text-yellow-800 dark:text-yellow-200">
+ {t("admin.banWarning")}
+ </p>
+ </div>
+
+ {/* Reason */}
+ <div className="space-y-2">
+ <Label htmlFor="reason">
+ {t("admin.banReason")} <span className="text-destructive">*</span>
+ </Label>
+ <Textarea
+ id="reason"
+ value={reason}
+ onChange={(e) => setReason(e.target.value)}
+ placeholder={t("admin.banReasonPlaceholder")}
+ rows={4}
+ className="resize-none"
+ />
+ </div>
+
+ {/* Permanent Ban Checkbox */}
+ <div className="flex items-center space-x-2">
+ <Checkbox
+ id="permanent"
+ checked={isPermanent}
+ onCheckedChange={(checked) => setIsPermanent(checked === true)}
+ />
+ <Label
+ htmlFor="permanent"
+ className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
+ >
+ {t("admin.permanentBan")}
+ </Label>
+ </div>
+
+ {/* Expiration Date */}
+ {!isPermanent && (
+ <div className="space-y-2">
+ <Label htmlFor="expires">{t("admin.banExpires")}</Label>
+ <Input
+ id="expires"
+ type="date"
+ value={expiresAt}
+ onChange={(e) => setExpiresAt(e.target.value)}
+ min={new Date().toISOString().split("T")[0]}
+ />
+ </div>
+ )}
+ </div>
+
+ <DialogFooter>
+ <Button
+ variant="outline"
+ onClick={handleCancel}
+ disabled={isSubmitting}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={handleConfirm}
+ disabled={!reason.trim() || isSubmitting}
+ >
+ {isSubmitting ? t("common.saving") : t("admin.confirmBan")}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/components/admin/user-delete-dialog.tsx b/components/admin/user-delete-dialog.tsx
new file mode 100644
index 0000000..c910937
--- /dev/null
+++ b/components/admin/user-delete-dialog.tsx
@@ -0,0 +1,136 @@
+"use client";
+
+import { useState } from "react";
+import { useTranslations } from "next-intl";
+import { AlertTriangle } from "lucide-react";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Button } from "@/components/ui/button";
+import { Label } from "@/components/ui/label";
+import { Input } from "@/components/ui/input";
+import { Checkbox } from "@/components/ui/checkbox";
+import type { AdminUser } from "@/hooks/useAdminUsers";
+
+interface UserDeleteDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ user: AdminUser;
+ onConfirm: () => Promise<void>;
+}
+
+export function UserDeleteDialog({
+ open,
+ onOpenChange,
+ user,
+ onConfirm,
+}: UserDeleteDialogProps) {
+ const t = useTranslations();
+ const [confirmation, setConfirmation] = useState("");
+ const [understood, setUnderstood] = useState(false);
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ const isConfirmed = confirmation === user.name && understood;
+
+ const handleConfirm = async () => {
+ if (!isConfirmed) return;
+
+ setIsSubmitting(true);
+ try {
+ await onConfirm();
+ // Reset form
+ setConfirmation("");
+ setUnderstood(false);
+ onOpenChange(false);
+ } finally {
+ setIsSubmitting(false);
+ }
+ };
+
+ const handleCancel = () => {
+ // Reset form
+ setConfirmation("");
+ setUnderstood(false);
+ onOpenChange(false);
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-[500px]">
+ <DialogHeader>
+ <DialogTitle>{t("admin.deleteUser")}</DialogTitle>
+ <DialogDescription>
+ {t("admin.deleteUserConfirm", {
+ name: user.name || user.email,
+ })}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-4 py-4">
+ {/* Warning */}
+ <div className="flex gap-3 p-3 rounded-lg bg-red-50 dark:bg-red-950/20 border border-red-200 dark:border-red-900">
+ <AlertTriangle className="h-5 w-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5" />
+ <p className="text-sm text-red-800 dark:text-red-200">
+ {t("admin.deleteWarning")}
+ </p>
+ </div>
+
+ {/* Checkbox Confirmation */}
+ <div className="flex items-start space-x-3">
+ <Checkbox
+ id="understood"
+ checked={understood}
+ onCheckedChange={(checked) => setUnderstood(checked === true)}
+ className="mt-1"
+ />
+ <Label
+ htmlFor="understood"
+ className="text-sm font-medium leading-normal cursor-pointer"
+ >
+ {t("admin.deleteUnderstood")}
+ </Label>
+ </div>
+
+ {/* Name Confirmation */}
+ <div className="space-y-2">
+ <Label htmlFor="confirmation">
+ {t("admin.deleteConfirmation", { name: user.name })}
+ </Label>
+ <Input
+ id="confirmation"
+ value={confirmation}
+ onChange={(e) => setConfirmation(e.target.value)}
+ placeholder={user.name}
+ className="font-mono"
+ />
+ <p className="text-xs text-muted-foreground">
+ {t("admin.deleteConfirmationHint")}
+ </p>
+ </div>
+ </div>
+
+ <DialogFooter>
+ <Button
+ variant="outline"
+ onClick={handleCancel}
+ disabled={isSubmitting}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={handleConfirm}
+ disabled={!isConfirmed || isSubmitting}
+ >
+ {isSubmitting ? t("common.saving") : t("admin.confirmDelete")}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/components/admin/user-details-sheet.tsx b/components/admin/user-details-sheet.tsx
new file mode 100644
index 0000000..3272833
--- /dev/null
+++ b/components/admin/user-details-sheet.tsx
@@ -0,0 +1,353 @@
+"use client";
+
+import { useState, useEffect } from "react";
+import { useTranslations } from "next-intl";
+import { useLocale } from "next-intl";
+import { format, formatDistanceToNow } from "date-fns";
+import {
+ Edit,
+ Key,
+ Ban,
+ ShieldOff,
+ Trash2,
+ Calendar,
+ Share2,
+ Monitor,
+} from "lucide-react";
+import { BaseSheet } from "@/components/ui/base-sheet";
+import { Button } from "@/components/ui/button";
+import { Badge } from "@/components/ui/badge";
+import { Separator } from "@/components/ui/separator";
+import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
+import { useAdminUsers, type UserDetails } from "@/hooks/useAdminUsers";
+import {
+ useCanEditUser,
+ useCanBanUser,
+ useCanDeleteUser,
+ useCanResetPassword,
+} from "@/hooks/useAdminAccess";
+import { getDateLocale } from "@/lib/locales";
+
+interface UserDetailsSheetProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ userId: string;
+ onEdit: () => void;
+ onResetPassword: () => void;
+ onBan: () => void;
+ onUnban: () => void;
+ onDelete: () => void;
+}
+
+export function UserDetailsSheet({
+ open,
+ onOpenChange,
+ userId,
+ onEdit,
+ onResetPassword,
+ onBan,
+ onUnban,
+ onDelete,
+}: UserDetailsSheetProps) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const dateLocale = getDateLocale(locale);
+ const { fetchUserDetails, isLoading } = useAdminUsers();
+ const [userDetails, setUserDetails] = useState<UserDetails | null>(null);
+
+ const canEdit = useCanEditUser(userDetails);
+ const canBan = useCanBanUser(userDetails);
+ const canDelete = useCanDeleteUser(userDetails);
+ const canResetPassword = useCanResetPassword(userDetails);
+
+ useEffect(() => {
+ if (!open) return;
+
+ const loadDetails = async () => {
+ const details = await fetchUserDetails(userId);
+ if (details) {
+ setUserDetails(details);
+ }
+ };
+
+ loadDetails();
+ }, [open, userId, fetchUserDetails]);
+
+ const getUserInitials = () => {
+ if (!userDetails) return "?";
+ if (userDetails.name) {
+ return userDetails.name
+ .split(" ")
+ .map((n) => n[0])
+ .join("")
+ .toUpperCase()
+ .slice(0, 2);
+ }
+ if (userDetails.email) {
+ return userDetails.email.slice(0, 2).toUpperCase();
+ }
+ return "?";
+ };
+
+ const getRoleBadgeClass = (role: string) => {
+ switch (role) {
+ case "superadmin":
+ return "bg-red-500/10 text-red-500 border-red-500/20";
+ case "admin":
+ return "bg-orange-500/10 text-orange-500 border-orange-500/20";
+ default:
+ return "bg-blue-500/10 text-blue-500 border-blue-500/20";
+ }
+ };
+
+ return (
+ <BaseSheet
+ open={open}
+ onOpenChange={onOpenChange}
+ title={t("admin.userDetails")}
+ description={t("admin.userDetailsDescription")}
+ maxWidth="lg"
+ >
+ {isLoading && !userDetails ? (
+ <div className="text-center py-12 text-muted-foreground">
+ {t("common.loading")}
+ </div>
+ ) : userDetails ? (
+ <div className="space-y-6">
+ {/* User Info Card */}
+ <div className="flex items-start gap-4 p-4 rounded-lg border bg-muted/30">
+ <Avatar className="h-16 w-16">
+ {userDetails.image && <AvatarImage src={userDetails.image} />}
+ <AvatarFallback className="text-lg">
+ {getUserInitials()}
+ </AvatarFallback>
+ </Avatar>
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 flex-wrap">
+ <h3 className="text-lg font-semibold truncate">
+ {userDetails.name}
+ </h3>
+ <span
+ className={`inline-flex items-center px-2 py-1 rounded-md text-xs font-medium border ${getRoleBadgeClass(
+ userDetails.role || "user"
+ )}`}
+ >
+ {t(`common.roles.${userDetails.role}`)}
+ </span>
+ {userDetails.banned && (
+ <Badge variant="destructive">{t("admin.banned")}</Badge>
+ )}
+ </div>
+ <p className="text-sm text-muted-foreground truncate">
+ {userDetails.email}
+ </p>
+ <div className="flex items-center gap-4 mt-2 text-xs text-muted-foreground">
+ <span>
+ {t("admin.joined")}{" "}
+ {format(userDetails.createdAt, "PP", {
+ locale: dateLocale,
+ })}
+ </span>
+ {userDetails.lastActivity && (
+ <span>
+ {t("common.time.lastActive")}{" "}
+ {formatDistanceToNow(userDetails.lastActivity, {
+ addSuffix: true,
+ locale: dateLocale,
+ })}
+ </span>
+ )}
+ </div>
+ </div>
+ </div>
+
+ {/* Ban Information */}
+ {userDetails.banned && (
+ <div className="p-4 rounded-lg border bg-destructive/5 border-destructive/20">
+ <h4 className="text-sm font-semibold text-destructive mb-2">
+ {t("admin.banned")}
+ </h4>
+ {userDetails.banReason && (
+ <p className="text-sm mb-2">{userDetails.banReason}</p>
+ )}
+ <p className="text-xs text-muted-foreground">
+ {userDetails.banExpires
+ ? t("admin.bannedUntil", {
+ date: format(userDetails.banExpires, "PPP", {
+ locale: dateLocale,
+ }),
+ })
+ : t("admin.bannedPermanently")}
+ </p>
+ </div>
+ )}
+
+ {/* Quick Actions */}
+ <div className="flex flex-wrap gap-2">
+ {canEdit && (
+ <Button size="sm" variant="outline" onClick={onEdit}>
+ <Edit className="h-4 w-4 mr-2" />
+ {t("admin.editUser")}
+ </Button>
+ )}
+ {canResetPassword && (
+ <Button size="sm" variant="outline" onClick={onResetPassword}>
+ <Key className="h-4 w-4 mr-2" />
+ {t("admin.resetPassword")}
+ </Button>
+ )}
+ {canBan && !userDetails.banned && (
+ <Button size="sm" variant="outline" onClick={onBan}>
+ <Ban className="h-4 w-4 mr-2" />
+ {t("admin.banUser")}
+ </Button>
+ )}
+ {canBan && userDetails.banned && (
+ <Button size="sm" variant="outline" onClick={onUnban}>
+ <ShieldOff className="h-4 w-4 mr-2" />
+ {t("admin.unbanUser")}
+ </Button>
+ )}
+ {canDelete && (
+ <Button size="sm" variant="destructive" onClick={onDelete}>
+ <Trash2 className="h-4 w-4 mr-2" />
+ {t("admin.deleteUser")}
+ </Button>
+ )}
+ </div>
+
+ <Separator />
+
+ {/* Statistics */}
+ <div>
+ <h4 className="text-sm font-medium mb-3">
+ {t("common.stats.statistics")}
+ </h4>
+ <div className="grid grid-cols-3 gap-4">
+ <div className="flex items-center gap-3 p-3 rounded-lg border bg-muted/30">
+ <Calendar className="h-5 w-5 text-primary" />
+ <div>
+ <p className="text-2xl font-bold">
+ {userDetails.ownedCalendars.length}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {t("admin.ownedCalendars")}
+ </p>
+ </div>
+ </div>
+ <div className="flex items-center gap-3 p-3 rounded-lg border bg-muted/30">
+ <Share2 className="h-5 w-5 text-primary" />
+ <div>
+ <p className="text-2xl font-bold">
+ {userDetails.sharedCalendars.length}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {t("common.labels.sharedCalendars")}
+ </p>
+ </div>
+ </div>
+ <div className="flex items-center gap-3 p-3 rounded-lg border bg-muted/30">
+ <Monitor className="h-5 w-5 text-primary" />
+ <div>
+ <p className="text-2xl font-bold">
+ {userDetails.sessionsCount}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {t("common.auth.activeSessions")}
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* Owned Calendars */}
+ {userDetails.ownedCalendars.length > 0 && (
+ <>
+ <Separator />
+ <div>
+ <h4 className="text-sm font-medium mb-3">
+ {t("admin.ownedCalendars")} (
+ {userDetails.ownedCalendars.length})
+ </h4>
+ <div className="space-y-2">
+ {userDetails.ownedCalendars.map((calendar) => (
+ <div
+ key={calendar.id}
+ className="flex items-center gap-3 p-3 rounded-lg border bg-muted/20"
+ >
+ <div
+ className="h-4 w-4 rounded-full flex-shrink-0"
+ style={{ backgroundColor: calendar.color }}
+ />
+ <span className="text-sm truncate">{calendar.name}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ </>
+ )}
+
+ {/* Shared Calendars */}
+ {userDetails.sharedCalendars.length > 0 && (
+ <>
+ <Separator />
+ <div>
+ <h4 className="text-sm font-medium mb-3">
+ {t("common.labels.sharedCalendars")} (
+ {userDetails.sharedCalendars.length})
+ </h4>
+ <div className="space-y-2">
+ {userDetails.sharedCalendars.map((share) => (
+ <div
+ key={share.id}
+ className="flex items-center justify-between gap-3 p-3 rounded-lg border bg-muted/20"
+ >
+ <span className="text-sm truncate">{share.name}</span>
+ <Badge variant="outline" className="text-xs">
+ {t(`common.labels.permissions.${share.permission}`)}
+ </Badge>
+ </div>
+ ))}
+ </div>
+ </div>
+ </>
+ )}
+
+ {/* Connected Accounts */}
+ {userDetails.accounts.length > 0 && (
+ <>
+ <Separator />
+ <div>
+ <h4 className="text-sm font-medium mb-3">
+ {t("common.auth.connectedAccounts")} (
+ {userDetails.accounts.length})
+ </h4>
+ <div className="space-y-2">
+ {userDetails.accounts.map((account) => (
+ <div
+ key={account.id}
+ className="flex items-center justify-between gap-3 p-3 rounded-lg border bg-muted/20"
+ >
+ <span className="text-sm font-medium capitalize">
+ {account.providerId}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ {format(account.createdAt, "PP", {
+ locale: dateLocale,
+ })}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ ) : (
+ <div className="text-center py-8 text-muted-foreground">
+ {t("admin.userNotFound")}
+ </div>
+ )}
+ </BaseSheet>
+ );
+}
diff --git a/components/admin/user-edit-sheet.tsx b/components/admin/user-edit-sheet.tsx
new file mode 100644
index 0000000..447aa39
--- /dev/null
+++ b/components/admin/user-edit-sheet.tsx
@@ -0,0 +1,134 @@
+"use client";
+
+import { useState } from "react";
+import { useTranslations } from "next-intl";
+import { BaseSheet } from "@/components/ui/base-sheet";
+import { Label } from "@/components/ui/label";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { useAdminUsers, type AdminUser } from "@/hooks/useAdminUsers";
+import { useCanEditUser, useCanChangeUserRole } from "@/hooks/useAdminAccess";
+
+interface UserEditSheetProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ user: AdminUser;
+ onSuccess: () => void;
+}
+
+export function UserEditSheet({
+ open,
+ onOpenChange,
+ user,
+ onSuccess,
+}: UserEditSheetProps) {
+ const t = useTranslations();
+ const { updateUser, isLoading } = useAdminUsers();
+ const canEdit = useCanEditUser(user);
+ const canChangeRole = useCanChangeUserRole(user);
+
+ // State will reset when component remounts (via key prop)
+ const [name, setName] = useState(user.name);
+ const [email, setEmail] = useState(user.email);
+ const [role, setRole] = useState(user.role || "user");
+
+ // Track if form has changes
+ const hasChanges =
+ name !== user.name || email !== user.email || role !== user.role;
+
+ if (!canEdit) {
+ return null;
+ }
+
+ const handleOpenChange = (newOpen: boolean) => {
+ onOpenChange(newOpen);
+ };
+
+ const handleSave = async () => {
+ const updates: { name?: string; email?: string; role?: string } = {};
+
+ if (name !== user.name) updates.name = name;
+ if (email !== user.email) updates.email = email;
+ if (canChangeRole && role !== user.role) updates.role = role;
+
+ const success = await updateUser(user.id, updates);
+ if (success) {
+ onSuccess();
+ handleOpenChange(false);
+ }
+ };
+
+ return (
+ <BaseSheet
+ open={open}
+ onOpenChange={handleOpenChange}
+ title={t("admin.editUser")}
+ description={t("admin.editUserDescription")}
+ showSaveButton
+ onSave={handleSave}
+ isSaving={isLoading}
+ saveDisabled={!hasChanges}
+ hasUnsavedChanges={hasChanges}
+ maxWidth="md"
+ >
+ <div className="space-y-6">
+ {/* Name */}
+ <div className="space-y-2">
+ <Label htmlFor="name">
+ {t("common.labels.name")}{" "}
+ <span className="text-destructive">*</span>
+ </Label>
+ <Input
+ id="name"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder={t("admin.namePlaceholder")}
+ />
+ </div>
+
+ {/* Email */}
+ <div className="space-y-2">
+ <Label htmlFor="email">
+ {t("common.labels.email")}{" "}
+ <span className="text-destructive">*</span>
+ </Label>
+ <Input
+ id="email"
+ type="email"
+ value={email}
+ onChange={(e) => setEmail(e.target.value)}
+ placeholder={t("admin.emailPlaceholder")}
+ />
+ </div>
+
+ {/* Role */}
+ {canChangeRole && (
+ <div className="space-y-2">
+ <Label htmlFor="role">{t("admin.role")}</Label>
+ <Select value={role} onValueChange={setRole}>
+ <SelectTrigger id="role">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="user">{t("common.roles.user")}</SelectItem>
+ <SelectItem value="admin">{t("common.roles.admin")}</SelectItem>
+ <SelectItem value="superadmin">
+ {t("common.roles.superadmin")}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ <p className="text-xs text-muted-foreground">
+ {t("admin.roleChangeWarning")}
+ </p>
+ </div>
+ )}
+ </div>
+ </BaseSheet>
+ );
+}
diff --git a/components/admin/user-password-reset-dialog.tsx b/components/admin/user-password-reset-dialog.tsx
new file mode 100644
index 0000000..8913c39
--- /dev/null
+++ b/components/admin/user-password-reset-dialog.tsx
@@ -0,0 +1,218 @@
+"use client";
+
+import { useState } from "react";
+import { useTranslations } from "next-intl";
+import { Eye, EyeOff, Copy, RefreshCw, AlertCircle } from "lucide-react";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Button } from "@/components/ui/button";
+import { Label } from "@/components/ui/label";
+import { Input } from "@/components/ui/input";
+import { toast } from "sonner";
+import type { AdminUser } from "@/hooks/useAdminUsers";
+
+interface UserPasswordResetDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ user: AdminUser;
+ onConfirm: (newPassword: string) => Promise<void>;
+}
+
+export function UserPasswordResetDialog({
+ open,
+ onOpenChange,
+ user,
+ onConfirm,
+}: UserPasswordResetDialogProps) {
+ const t = useTranslations();
+ const [password, setPassword] = useState("");
+ const [confirmPassword, setConfirmPassword] = useState("");
+ const [showPassword, setShowPassword] = useState(false);
+ const [showConfirmPassword, setShowConfirmPassword] = useState(false);
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ const passwordsMatch = password === confirmPassword;
+ const isValid = password.length >= 8 && passwordsMatch;
+
+ const generateRandomPassword = () => {
+ const length = 16;
+ const charset =
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*";
+ let newPassword = "";
+ for (let i = 0; i < length; i++) {
+ newPassword += charset.charAt(Math.floor(Math.random() * charset.length));
+ }
+ setPassword(newPassword);
+ setConfirmPassword(newPassword);
+ setShowPassword(true);
+ setShowConfirmPassword(true);
+ };
+
+ const copyPassword = () => {
+ navigator.clipboard.writeText(password);
+ toast.success(t("common.copied", { item: t("common.labels.password") }));
+ };
+
+ const handleConfirm = async () => {
+ if (!isValid) return;
+
+ setIsSubmitting(true);
+ try {
+ await onConfirm(password);
+ // Reset form
+ setPassword("");
+ setConfirmPassword("");
+ setShowPassword(false);
+ setShowConfirmPassword(false);
+ onOpenChange(false);
+ } finally {
+ setIsSubmitting(false);
+ }
+ };
+
+ const handleCancel = () => {
+ // Reset form
+ setPassword("");
+ setConfirmPassword("");
+ setShowPassword(false);
+ setShowConfirmPassword(false);
+ onOpenChange(false);
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-[500px]">
+ <DialogHeader>
+ <DialogTitle>{t("admin.resetPassword")}</DialogTitle>
+ <DialogDescription>
+ {t("admin.resetPasswordFor", {
+ name: user.name || user.email,
+ })}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-4 py-4">
+ {/* Warning */}
+ <div className="flex gap-3 p-3 rounded-lg bg-yellow-50 dark:bg-yellow-950/20 border border-yellow-200 dark:border-yellow-900">
+ <AlertCircle className="h-5 w-5 text-yellow-600 dark:text-yellow-400 flex-shrink-0 mt-0.5" />
+ <div className="text-sm text-yellow-800 dark:text-yellow-200 space-y-1">
+ <p className="font-medium">{t("admin.passwordResetWarning")}</p>
+ <p>{t("admin.passwordResetSecurityNote")}</p>
+ </div>
+ </div>
+
+ {/* Generate Button */}
+ <Button
+ type="button"
+ variant="outline"
+ onClick={generateRandomPassword}
+ className="w-full"
+ >
+ <RefreshCw className="h-4 w-4 mr-2" />
+ {t("admin.generatePassword")}
+ </Button>
+
+ {/* New Password */}
+ <div className="space-y-2">
+ <Label htmlFor="password">
+ {t("common.labels.newPassword")}{" "}
+ <span className="text-destructive">*</span>
+ </Label>
+ <div className="relative">
+ <Input
+ id="password"
+ type={showPassword ? "text" : "password"}
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ placeholder={t("admin.passwordPlaceholder")}
+ className="pr-10"
+ />
+ <button
+ type="button"
+ onClick={() => setShowPassword(!showPassword)}
+ className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
+ >
+ {showPassword ? (
+ <EyeOff className="h-4 w-4" />
+ ) : (
+ <Eye className="h-4 w-4" />
+ )}
+ </button>
+ </div>
+ {password && password.length < 8 && (
+ <p className="text-xs text-destructive">
+ {t("validation.passwordTooShort")}
+ </p>
+ )}
+ </div>
+
+ {/* Confirm Password */}
+ <div className="space-y-2">
+ <Label htmlFor="confirmPassword">
+ {t("common.labels.confirmPassword")}{" "}
+ <span className="text-destructive">*</span>
+ </Label>
+ <div className="relative">
+ <Input
+ id="confirmPassword"
+ type={showConfirmPassword ? "text" : "password"}
+ value={confirmPassword}
+ onChange={(e) => setConfirmPassword(e.target.value)}
+ placeholder={t("admin.confirmPasswordPlaceholder")}
+ className="pr-10"
+ />
+ <button
+ type="button"
+ onClick={() => setShowConfirmPassword(!showConfirmPassword)}
+ className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
+ >
+ {showConfirmPassword ? (
+ <EyeOff className="h-4 w-4" />
+ ) : (
+ <Eye className="h-4 w-4" />
+ )}
+ </button>
+ </div>
+ {confirmPassword && !passwordsMatch && (
+ <p className="text-xs text-destructive">
+ {t("validation.passwordsNoMatch")}
+ </p>
+ )}
+ </div>
+
+ {/* Copy Password Button */}
+ {password && isValid && (
+ <Button
+ type="button"
+ variant="secondary"
+ onClick={copyPassword}
+ className="w-full"
+ >
+ <Copy className="h-4 w-4 mr-2" />
+ {t("admin.copyPassword")}
+ </Button>
+ )}
+ </div>
+
+ <DialogFooter>
+ <Button
+ variant="outline"
+ onClick={handleCancel}
+ disabled={isSubmitting}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button onClick={handleConfirm} disabled={!isValid || isSubmitting}>
+ {isSubmitting ? t("common.saving") : t("admin.setPassword")}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/components/admin/user-table.tsx b/components/admin/user-table.tsx
new file mode 100644
index 0000000..355ac4c
--- /dev/null
+++ b/components/admin/user-table.tsx
@@ -0,0 +1,477 @@
+"use client";
+
+import { useState } from "react";
+import { useTranslations } from "next-intl";
+import { useLocale } from "next-intl";
+import { format, formatDistanceToNow } from "date-fns";
+import {
+ MoreVertical,
+ Edit,
+ Key,
+ Ban,
+ ShieldOff,
+ Trash2,
+ ChevronUp,
+ ChevronDown,
+} from "lucide-react";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { getDateLocale } from "@/lib/locales";
+import type { AdminUser } from "@/hooks/useAdminUsers";
+import {
+ useCanEditUser,
+ useCanBanUser,
+ useCanDeleteUser,
+ useCanResetPassword,
+} from "@/hooks/useAdminAccess";
+
+interface UserTableProps {
+ users: AdminUser[];
+ isLoading?: boolean;
+ onUserClick: (user: AdminUser) => void;
+ onEditUser: (user: AdminUser) => void;
+ onResetPassword: (user: AdminUser) => void;
+ onBanUser: (user: AdminUser) => void;
+ onUnbanUser: (user: AdminUser) => void;
+ onDeleteUser: (user: AdminUser) => void;
+}
+
+type SortColumn =
+ | "name"
+ | "email"
+ | "role"
+ | "status"
+ | "createdAt"
+ | "lastActivity"
+ | "calendarCount"
+ | "sharesCount";
+type SortDirection = "asc" | "desc";
+
+function UserTableRow({
+ user,
+ onUserClick,
+ onEditUser,
+ onResetPassword,
+ onBanUser,
+ onUnbanUser,
+ onDeleteUser,
+}: {
+ user: AdminUser;
+ onUserClick: (user: AdminUser) => void;
+ onEditUser: (user: AdminUser) => void;
+ onResetPassword: (user: AdminUser) => void;
+ onBanUser: (user: AdminUser) => void;
+ onUnbanUser: (user: AdminUser) => void;
+ onDeleteUser: (user: AdminUser) => void;
+}) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const dateLocale = getDateLocale(locale);
+
+ const canEdit = useCanEditUser(user);
+ const canBan = useCanBanUser(user);
+ const canDelete = useCanDeleteUser(user);
+ const canResetPassword = useCanResetPassword(user);
+
+ const getUserInitials = () => {
+ if (user.name) {
+ return user.name
+ .split(" ")
+ .map((n) => n[0])
+ .join("")
+ .toUpperCase()
+ .slice(0, 2);
+ }
+ return user.email.slice(0, 2).toUpperCase();
+ };
+
+ const getRoleBadgeClass = () => {
+ switch (user.role) {
+ case "superadmin":
+ return "bg-red-500/10 text-red-500 border-red-500/20";
+ case "admin":
+ return "bg-orange-500/10 text-orange-500 border-orange-500/20";
+ default:
+ return "bg-blue-500/10 text-blue-500 border-blue-500/20";
+ }
+ };
+
+ const hasActions = canEdit || canResetPassword || canBan || canDelete;
+
+ return (
+ <TableRow className="cursor-pointer" onClick={() => onUserClick(user)}>
+ {/* Avatar + Name + Email */}
+ <TableCell>
+ <div className="flex items-center gap-3">
+ <Avatar className="h-8 w-8">
+ {user.image && <AvatarImage src={user.image} />}
+ <AvatarFallback className="text-xs">
+ {getUserInitials()}
+ </AvatarFallback>
+ </Avatar>
+ <div className="min-w-0">
+ <p className="text-sm font-medium truncate">{user.name}</p>
+ <p className="text-xs text-muted-foreground truncate">
+ {user.email}
+ </p>
+ </div>
+ </div>
+ </TableCell>
+
+ {/* Role */}
+ <TableCell>
+ <span
+ className={`inline-flex items-center px-2 py-1 rounded-md text-xs font-medium border ${getRoleBadgeClass()}`}
+ >
+ {t(`common.roles.${user.role}`)}
+ </span>
+ </TableCell>
+
+ {/* Status */}
+ <TableCell>
+ {user.banned ? (
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger>
+ <Badge variant="destructive" className="cursor-help">
+ {t("admin.banned")}
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-xs">
+ <div className="space-y-1">
+ {user.banReason && (
+ <p className="text-xs font-medium">{user.banReason}</p>
+ )}
+ {user.banExpires ? (
+ <p className="text-xs text-muted-foreground">
+ {t("admin.bannedUntil", {
+ date: format(user.banExpires, "PPP", {
+ locale: dateLocale,
+ }),
+ })}
+ </p>
+ ) : (
+ <p className="text-xs text-muted-foreground">
+ {t("admin.bannedPermanently")}
+ </p>
+ )}
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ ) : (
+ <Badge variant="secondary">{t("common.status.active")}</Badge>
+ )}
+ </TableCell>
+
+ {/* Created */}
+ <TableCell>
+ <span className="text-sm text-muted-foreground">
+ {format(user.createdAt, "PP", { locale: dateLocale })}
+ </span>
+ </TableCell>
+
+ {/* Last Activity */}
+ <TableCell>
+ {user.lastActivity ? (
+ <span className="text-sm text-muted-foreground">
+ {formatDistanceToNow(user.lastActivity, {
+ addSuffix: true,
+ locale: dateLocale,
+ })}
+ </span>
+ ) : (
+ <span className="text-sm text-muted-foreground">
+ {t("admin.neverActive")}
+ </span>
+ )}
+ </TableCell>
+
+ {/* Calendar Count */}
+ <TableCell>
+ <span className="text-sm">{user.calendarCount}</span>
+ </TableCell>
+
+ {/* Shares Count */}
+ <TableCell>
+ <span className="text-sm">{user.sharesCount}</span>
+ </TableCell>
+
+ {/* Actions */}
+ <TableCell onClick={(e) => e.stopPropagation()}>
+ {hasActions && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="sm">
+ <MoreVertical className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {canEdit && (
+ <DropdownMenuItem onClick={() => onEditUser(user)}>
+ <Edit className="h-4 w-4 mr-2" />
+ {t("admin.editUser")}
+ </DropdownMenuItem>
+ )}
+ {canResetPassword && (
+ <DropdownMenuItem onClick={() => onResetPassword(user)}>
+ <Key className="h-4 w-4 mr-2" />
+ {t("admin.resetPassword")}
+ </DropdownMenuItem>
+ )}
+ {canBan && (
+ <>
+ {(canEdit || canResetPassword) && <DropdownMenuSeparator />}
+ {!user.banned ? (
+ <DropdownMenuItem onClick={() => onBanUser(user)}>
+ <Ban className="h-4 w-4 mr-2" />
+ {t("admin.banUser")}
+ </DropdownMenuItem>
+ ) : (
+ <DropdownMenuItem onClick={() => onUnbanUser(user)}>
+ <ShieldOff className="h-4 w-4 mr-2" />
+ {t("admin.unbanUser")}
+ </DropdownMenuItem>
+ )}
+ </>
+ )}
+ {canDelete && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={() => onDeleteUser(user)}
+ className="text-destructive"
+ >
+ <Trash2 className="h-4 w-4 mr-2" />
+ {t("admin.deleteUser")}
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </TableCell>
+ </TableRow>
+ );
+}
+
+export function UserTable({
+ users,
+ onUserClick,
+ onEditUser,
+ onResetPassword,
+ onBanUser,
+ onUnbanUser,
+ onDeleteUser,
+}: UserTableProps) {
+ const t = useTranslations();
+ const [sortColumn, setSortColumn] = useState<SortColumn | null>("createdAt");
+ const [sortDirection, setSortDirection] = useState<SortDirection>("desc");
+
+ // Sort users
+ const sortedUsers = [...users].sort((a, b) => {
+ if (!sortColumn) return 0;
+
+ let comparison = 0;
+
+ switch (sortColumn) {
+ case "name":
+ comparison = (a.name || "").localeCompare(b.name || "");
+ break;
+ case "email":
+ comparison = a.email.localeCompare(b.email);
+ break;
+ case "role":
+ const roleOrder = { user: 0, admin: 1, superadmin: 2 };
+ comparison =
+ (roleOrder[a.role as keyof typeof roleOrder] ?? 0) -
+ (roleOrder[b.role as keyof typeof roleOrder] ?? 0);
+ break;
+ case "status":
+ comparison = (a.banned ? 1 : 0) - (b.banned ? 1 : 0);
+ break;
+ case "createdAt":
+ comparison = a.createdAt.getTime() - b.createdAt.getTime();
+ break;
+ case "lastActivity":
+ const aTime = a.lastActivity?.getTime() ?? 0;
+ const bTime = b.lastActivity?.getTime() ?? 0;
+ comparison = aTime - bTime;
+ break;
+ case "calendarCount":
+ comparison = a.calendarCount - b.calendarCount;
+ break;
+ case "sharesCount":
+ comparison = a.sharesCount - b.sharesCount;
+ break;
+ }
+
+ return sortDirection === "asc" ? comparison : -comparison;
+ });
+
+ // Handle sort column click
+ const handleSort = (column: SortColumn) => {
+ if (sortColumn === column) {
+ setSortDirection((prev) => (prev === "asc" ? "desc" : "asc"));
+ } else {
+ setSortColumn(column);
+ setSortDirection("desc");
+ }
+ };
+
+ return (
+ <div className="border border-border/50 bg-gradient-to-br from-card/95 via-card to-card/80 backdrop-blur-sm rounded-lg overflow-hidden shadow-sm">
+ <Table>
+ <TableHeader className="bg-muted/50">
+ <TableRow>
+ <TableHead
+ className="cursor-pointer hover:bg-muted/80 transition-colors"
+ onClick={() => handleSort("name")}
+ >
+ <div className="flex items-center gap-2">
+ {t("common.labels.user")}
+ {sortColumn === "name" &&
+ (sortDirection === "asc" ? (
+ <ChevronUp className="h-4 w-4" />
+ ) : (
+ <ChevronDown className="h-4 w-4" />
+ ))}
+ </div>
+ </TableHead>
+ <TableHead
+ className="cursor-pointer hover:bg-muted/80 transition-colors"
+ onClick={() => handleSort("role")}
+ >
+ <div className="flex items-center gap-2">
+ {t("admin.role")}
+ {sortColumn === "role" &&
+ (sortDirection === "asc" ? (
+ <ChevronUp className="h-4 w-4" />
+ ) : (
+ <ChevronDown className="h-4 w-4" />
+ ))}
+ </div>
+ </TableHead>
+ <TableHead
+ className="cursor-pointer hover:bg-muted/80 transition-colors"
+ onClick={() => handleSort("status")}
+ >
+ <div className="flex items-center gap-2">
+ {t("common.labels.status")}
+ {sortColumn === "status" &&
+ (sortDirection === "asc" ? (
+ <ChevronUp className="h-4 w-4" />
+ ) : (
+ <ChevronDown className="h-4 w-4" />
+ ))}
+ </div>
+ </TableHead>
+ <TableHead
+ className="cursor-pointer hover:bg-muted/80 transition-colors"
+ onClick={() => handleSort("createdAt")}
+ >
+ <div className="flex items-center gap-2">
+ {t("common.stats.created")}
+ {sortColumn === "createdAt" &&
+ (sortDirection === "asc" ? (
+ <ChevronUp className="h-4 w-4" />
+ ) : (
+ <ChevronDown className="h-4 w-4" />
+ ))}
+ </div>
+ </TableHead>
+ <TableHead
+ className="cursor-pointer hover:bg-muted/80 transition-colors"
+ onClick={() => handleSort("lastActivity")}
+ >
+ <div className="flex items-center gap-2">
+ {t("common.time.lastActive")}
+ {sortColumn === "lastActivity" &&
+ (sortDirection === "asc" ? (
+ <ChevronUp className="h-4 w-4" />
+ ) : (
+ <ChevronDown className="h-4 w-4" />
+ ))}
+ </div>
+ </TableHead>
+ <TableHead
+ className="cursor-pointer hover:bg-muted/80 transition-colors"
+ onClick={() => handleSort("calendarCount")}
+ >
+ <div className="flex items-center gap-2">
+ {t("admin.calendarsCount")}
+ {sortColumn === "calendarCount" &&
+ (sortDirection === "asc" ? (
+ <ChevronUp className="h-4 w-4" />
+ ) : (
+ <ChevronDown className="h-4 w-4" />
+ ))}
+ </div>
+ </TableHead>
+ <TableHead
+ className="cursor-pointer hover:bg-muted/80 transition-colors"
+ onClick={() => handleSort("sharesCount")}
+ >
+ <div className="flex items-center gap-2">
+ {t("common.labels.shares")}
+ {sortColumn === "sharesCount" &&
+ (sortDirection === "asc" ? (
+ <ChevronUp className="h-4 w-4" />
+ ) : (
+ <ChevronDown className="h-4 w-4" />
+ ))}
+ </div>
+ </TableHead>
+ <TableHead className="w-[50px]"></TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {users.length === 0 ? (
+ <TableRow>
+ <TableCell colSpan={8} className="text-center py-8">
+ <p className="text-sm text-muted-foreground">
+ {t("common.empty.noUsersFound")}
+ </p>
+ </TableCell>
+ </TableRow>
+ ) : (
+ sortedUsers.map((user) => (
+ <UserTableRow
+ key={user.id}
+ user={user}
+ onUserClick={onUserClick}
+ onEditUser={onEditUser}
+ onResetPassword={onResetPassword}
+ onBanUser={onBanUser}
+ onUnbanUser={onUnbanUser}
+ onDeleteUser={onDeleteUser}
+ />
+ ))
+ )}
+ </TableBody>
+ </Table>
+ </div>
+ );
+}
diff --git a/components/admin/user-unban-dialog.tsx b/components/admin/user-unban-dialog.tsx
new file mode 100644
index 0000000..4f0a069
--- /dev/null
+++ b/components/admin/user-unban-dialog.tsx
@@ -0,0 +1,81 @@
+"use client";
+
+import { useState } from "react";
+import { useTranslations } from "next-intl";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Button } from "@/components/ui/button";
+import { Label } from "@/components/ui/label";
+import type { AdminUser } from "@/hooks/useAdminUsers";
+
+interface UserUnbanDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ user: AdminUser;
+ onConfirm: () => Promise<void>;
+}
+
+export function UserUnbanDialog({
+ open,
+ onOpenChange,
+ user,
+ onConfirm,
+}: UserUnbanDialogProps) {
+ const t = useTranslations();
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ const handleConfirm = async () => {
+ setIsSubmitting(true);
+ try {
+ await onConfirm();
+ onOpenChange(false);
+ } finally {
+ setIsSubmitting(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-[450px]">
+ <DialogHeader>
+ <DialogTitle>{t("admin.unbanUser")}</DialogTitle>
+ <DialogDescription>
+ {t("admin.unbanUserConfirm", {
+ name: user.name || user.email,
+ })}
+ </DialogDescription>
+ </DialogHeader>
+
+ {user.banReason && (
+ <div className="py-4">
+ <Label className="text-sm font-medium">
+ {t("admin.originalBanReason")}
+ </Label>
+ <div className="mt-2 p-3 rounded-lg bg-muted text-sm">
+ {user.banReason}
+ </div>
+ </div>
+ )}
+
+ <DialogFooter>
+ <Button
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={isSubmitting}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button onClick={handleConfirm} disabled={isSubmitting}>
+ {isSubmitting ? t("common.saving") : t("admin.confirmUnban")}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/components/app-header.tsx b/components/app-header.tsx
index e42dadb..2a5a376 100644
--- a/components/app-header.tsx
+++ b/components/app-header.tsx
@@ -1,10 +1,15 @@
import { motion } from "motion/react";
import { useTranslations } from "next-intl";
import { useState } from "react";
+import Link from "next/link";
import { CalendarWithCount } from "@/lib/types";
import { CalendarSelector } from "@/components/calendar-selector";
import { PresetSelector } from "@/components/preset-selector";
+import { UserMenu } from "@/components/user-menu";
+import { useAuth } from "@/hooks/useAuth";
+import { useAuthFeatures } from "@/hooks/useAuthFeatures";
import { Button } from "@/components/ui/button";
+import { Separator } from "@/components/ui/separator";
import {
Dialog,
DialogContent,
@@ -34,14 +39,12 @@ interface AppHeaderProps {
onSelectCalendar: (id: string) => void;
onSelectPreset: (id: string | undefined) => void;
onCreateCalendar: () => void;
- onManagePassword: () => void;
- onExternalSync: () => void;
+ onSettings: () => void;
onSyncNotifications: () => void;
onCompare?: () => void;
onPresetsChange: () => void;
onShiftsChange: () => void;
onStatsRefresh: () => void;
- onPasswordRequired: (action: () => Promise<void>) => void;
onManualShiftCreation: () => void;
onMobileCalendarDialogChange: (open: boolean) => void;
onViewSettingsClick: () => void;
@@ -61,14 +64,12 @@ export function AppHeader({
onSelectCalendar,
onSelectPreset,
onCreateCalendar,
- onManagePassword,
- onExternalSync,
+ onSettings,
onSyncNotifications,
onCompare,
onPresetsChange,
onShiftsChange,
onStatsRefresh,
- onPasswordRequired,
onManualShiftCreation,
onMobileCalendarDialogChange,
onViewSettingsClick,
@@ -78,6 +79,8 @@ export function AppHeader({
}: AppHeaderProps) {
const t = useTranslations();
const locale = useLocale();
+ const { isGuest } = useAuth();
+ const { isAuthEnabled } = useAuthFeatures();
const { versionInfo } = useVersionUpdateCheck();
const [showChangelog, setShowChangelog] = useState(false);
@@ -88,73 +91,94 @@ export function AppHeader({
<div className="space-y-3 sm:space-y-4">
{/* Desktop: Logo + Calendar Selector in one line */}
<div className="hidden sm:flex items-center justify-between gap-4">
- {/* Logo Section */}
- <motion.div
- className="flex items-center gap-3"
- initial={{ opacity: 0, x: -20 }}
- animate={{ opacity: 1, x: 0 }}
- transition={{ duration: 0.3 }}
- >
- <div className="relative shrink-0">
- <div className="w-12 h-12 rounded-2xl bg-gradient-to-br from-slate-900 via-slate-800 to-slate-700 dark:from-slate-800 dark:via-slate-700 dark:to-slate-600 flex items-center justify-center shadow-xl shadow-slate-900/50 dark:shadow-slate-950/70 ring-2 ring-slate-700/50 dark:ring-slate-600/50">
- <CalendarIcon className="h-6 w-6 text-white" />
+ {/* Logo Section - Clickable to go home */}
+ <Link href="/" className="flex items-center gap-3 group">
+ <motion.div
+ className="flex items-center gap-3"
+ initial={{ opacity: 0, x: -20 }}
+ animate={{ opacity: 1, x: 0 }}
+ transition={{ duration: 0.3 }}
+ >
+ <div className="relative shrink-0">
+ <div className="w-12 h-12 rounded-2xl bg-gradient-to-br from-slate-900 via-slate-800 to-slate-700 dark:from-slate-800 dark:via-slate-700 dark:to-slate-600 flex items-center justify-center shadow-xl shadow-slate-900/50 dark:shadow-slate-950/70 ring-2 ring-slate-700/50 dark:ring-slate-600/50 transition-transform group-hover:scale-105">
+ <CalendarIcon className="h-6 w-6 text-white" />
+ </div>
+ {/* Connection Status Indicator */}
+ <div
+ className={`absolute -bottom-0.5 -right-0.5 w-4 h-4 rounded-full border-2 border-background transition-colors ${
+ isConnected
+ ? "bg-green-500 animate-pulse"
+ : "bg-red-500"
+ }`}
+ title={
+ isConnected
+ ? t("sync.reconnected")
+ : t("sync.disconnected")
+ }
+ ></div>
</div>
- {/* Connection Status Indicator */}
- <div
- className={`absolute -bottom-0.5 -right-0.5 w-4 h-4 rounded-full border-2 border-background transition-colors ${
- isConnected ? "bg-green-500 animate-pulse" : "bg-red-500"
- }`}
- title={
- isConnected
- ? t("sync.reconnected")
- : t("sync.disconnected")
- }
- ></div>
- </div>
- <div>
- <h1 className="text-xl font-bold bg-gradient-to-r from-foreground via-foreground to-foreground/70 bg-clip-text">
- {t("app.title")}
- </h1>
- <p className="text-xs text-muted-foreground font-medium">
- {t("app.subtitle", { default: "Organize your shifts" })}
- </p>
- </div>
- </motion.div>
+ <div>
+ <h1 className="text-xl font-bold bg-gradient-to-r from-foreground via-foreground to-foreground/70 bg-clip-text transition-all group-hover:from-primary group-hover:via-primary group-hover:to-primary/70">
+ {t("app.title")}
+ </h1>
+ <p className="text-xs text-muted-foreground font-medium">
+ {t("app.subtitle", { default: "Organize your shifts" })}
+ </p>
+ </div>
+ </motion.div>
+ </Link>
- {/* Calendar Selector - Desktop */}
+ {/* Right Section: Unified Container */}
<motion.div
- className="flex items-center gap-3 min-w-0 flex-1 max-w-md bg-muted/30 rounded-xl p-2 border border-border/50"
+ className="flex items-center gap-2 bg-muted/30 rounded-xl p-2 border border-border/50"
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ duration: 0.3, delay: 0.1 }}
>
- <div
- className="w-1 h-8 bg-gradient-to-b rounded-full transition-colors duration-300"
- style={{
- backgroundImage: selectedCalendar
- ? `linear-gradient(to bottom, ${
- calendars.find((c) => c.id === selectedCalendar)
- ?.color || "hsl(var(--primary))"
- }, ${
- calendars.find((c) => c.id === selectedCalendar)
- ?.color || "hsl(var(--primary))"
- }80)`
- : "linear-gradient(to bottom, hsl(var(--primary)), hsl(var(--primary) / 0.5))",
- }}
- ></div>
- <div className="flex-1 min-w-0">
- <CalendarSelector
- calendars={calendars}
- selectedId={selectedCalendar}
- onSelect={onSelectCalendar}
- onCreateNew={onCreateCalendar}
- onManagePassword={onManagePassword}
- onExternalSync={onExternalSync}
- onSyncNotifications={onSyncNotifications}
- onCompare={onCompare}
- hasSyncErrors={hasSyncErrors}
- />
+ {/* Calendar Selector - Desktop */}
+ <div className="flex items-center gap-2 min-w-0 flex-1 max-w-md">
+ <div
+ className="w-1 h-8 bg-gradient-to-b rounded-full transition-colors duration-300"
+ style={{
+ backgroundImage: selectedCalendar
+ ? `linear-gradient(to bottom, ${
+ calendars.find((c) => c.id === selectedCalendar)
+ ?.color || "hsl(var(--primary))"
+ }, ${
+ calendars.find((c) => c.id === selectedCalendar)
+ ?.color || "hsl(var(--primary))"
+ }80)`
+ : "linear-gradient(to bottom, hsl(var(--primary)), hsl(var(--primary) / 0.5))",
+ }}
+ ></div>
+ <div className="flex-1 min-w-0">
+ <CalendarSelector
+ calendars={calendars}
+ selectedId={selectedCalendar}
+ onSelect={onSelectCalendar}
+ onCreateNew={onCreateCalendar}
+ onSettings={onSettings}
+ onSyncNotifications={onSyncNotifications}
+ onCompare={onCompare}
+ hasSyncErrors={hasSyncErrors}
+ />
+ </div>
</div>
+
+ {/* Divider */}
+ {isAuthEnabled && (
+ <Separator orientation="vertical" className="h-8" />
+ )}
+
+ {/* User Menu or Guest Login Button */}
+ {isAuthEnabled &&
+ (isGuest ? (
+ <Button asChild variant="default" size="sm">
+ <Link href="/login">{t("auth.login")}</Link>
+ </Button>
+ ) : (
+ <UserMenu />
+ ))}
</motion.div>
</div>
@@ -198,29 +222,42 @@ export function AppHeader({
</motion.div>
)}
- {/* Mobile: Logo Icon + Calendar Card + Add Button */}
+ {/* Mobile: Add Button + Calendar Card + User Menu (Logo hidden) */}
<div className="sm:hidden flex items-center gap-2">
- {/* Logo Icon Only */}
- <div className="relative shrink-0">
- <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-primary via-primary/90 to-primary/70 flex items-center justify-center shadow-lg shadow-primary/30 ring-2 ring-primary/20">
- <CalendarIcon className="h-5 w-5 text-primary-foreground" />
- </div>
- {/* Connection Status Indicator */}
+ {/* Mobile Add Shift Button - Left */}
+ {selectedCalendar && (
+ <motion.div
+ initial={{ scale: 0, opacity: 0 }}
+ animate={{ scale: 1, opacity: 1 }}
+ transition={{ delay: 0.2, type: "spring", stiffness: 200 }}
+ className="shrink-0"
+ >
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={onManualShiftCreation}
+ className="h-10 w-10 rounded-full bg-black dark:bg-white backdrop-blur-sm border border-border/50 hover:bg-accent transition-all shadow-sm"
+ >
+ <Plus className="h-5 w-5 dark:text-black text-white" />
+ </Button>
+ </motion.div>
+ )}
+
+ {/* Calendar Selection Card with Connection Indicator */}
+ <button
+ onClick={() => onMobileCalendarDialogChange(true)}
+ className="flex-1 bg-muted/30 backdrop-blur-sm border border-border/50 rounded-xl p-3 flex items-center justify-between gap-2 hover:bg-accent/50 transition-all active:scale-[0.98] shadow-sm relative"
+ >
+ {/* Connection Status Indicator - Top Right of Card */}
<div
- className={`absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full border-2 border-background transition-colors ${
+ className={`absolute top-2 right-2 w-2 h-2 rounded-full transition-colors ${
isConnected ? "bg-green-500 animate-pulse" : "bg-red-500"
}`}
title={
isConnected ? t("sync.reconnected") : t("sync.disconnected")
}
></div>
- </div>
- {/* Calendar Selection Card */}
- <button
- onClick={() => onMobileCalendarDialogChange(true)}
- className="flex-1 bg-muted/30 backdrop-blur-sm border border-border/50 rounded-xl p-3 flex items-center justify-between gap-2 hover:bg-accent/50 transition-all active:scale-[0.98] shadow-sm"
- >
<div className="flex items-center gap-2.5 min-w-0 flex-1">
<div
className="w-1 h-9 bg-gradient-to-b rounded-full transition-colors duration-300"
@@ -253,20 +290,21 @@ export function AppHeader({
</div>
</button>
- {/* Mobile Add Shift Button */}
- {selectedCalendar && (
+ {/* User Menu - Right */}
+ {isAuthEnabled && (
<motion.div
initial={{ scale: 0, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
- transition={{ delay: 0.2, type: "spring", stiffness: 200 }}
+ transition={{ delay: 0.3, type: "spring", stiffness: 200 }}
+ className="shrink-0"
>
- <Button
- size="icon"
- onClick={onManualShiftCreation}
- className="h-10 w-10 rounded-xl shadow-lg shadow-primary/30 shrink-0"
- >
- <Plus className="h-5 w-5" />
- </Button>
+ {isGuest ? (
+ <Button asChild variant="default" size="sm">
+ <Link href="/login">{t("auth.login")}</Link>
+ </Button>
+ ) : (
+ <UserMenu />
+ )}
</motion.div>
)}
</div>
@@ -283,7 +321,6 @@ export function AppHeader({
onShiftsChange={onShiftsChange}
onStatsRefresh={onStatsRefresh}
calendarId={selectedCalendar}
- onPasswordRequired={onPasswordRequired}
onViewSettingsClick={onViewSettingsClick}
loading={presetsLoading}
hidePresetHeader={hidePresetHeader}
@@ -324,13 +361,9 @@ export function AppHeader({
onMobileCalendarDialogChange(false);
onCreateCalendar();
}}
- onManagePassword={() => {
- onMobileCalendarDialogChange(false);
- onManagePassword();
- }}
- onExternalSync={() => {
+ onSettings={() => {
onMobileCalendarDialogChange(false);
- onExternalSync();
+ onSettings();
}}
onSyncNotifications={() => {
onMobileCalendarDialogChange(false);
diff --git a/components/auth-header.tsx b/components/auth-header.tsx
new file mode 100644
index 0000000..f0e99c6
--- /dev/null
+++ b/components/auth-header.tsx
@@ -0,0 +1,121 @@
+"use client";
+
+import { motion } from "motion/react";
+import { useTranslations, useLocale } from "next-intl";
+import { useState } from "react";
+import Link from "next/link";
+import { UserMenu } from "@/components/user-menu";
+import { Calendar as CalendarIcon, Bell, ExternalLink } from "lucide-react";
+import { useVersionUpdateCheck } from "@/hooks/useVersionUpdate";
+import { ChangelogDialog } from "@/components/changelog-dialog";
+
+/**
+ * Simplified header for authentication pages
+ * Shows only logo, app name, and user menu (for profile page)
+ * No calendar-related elements
+ */
+interface AuthHeaderProps {
+ showUserMenu?: boolean;
+}
+
+export function AuthHeader({ showUserMenu = false }: AuthHeaderProps) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const { versionInfo } = useVersionUpdateCheck();
+ const [showChangelog, setShowChangelog] = useState(false);
+
+ return (
+ <>
+ <div className="sticky top-0 z-10 bg-background/80 backdrop-blur-xl border-b border-border/50 shadow-sm">
+ <div className="container max-w-4xl mx-auto p-3 sm:p-4">
+ <div className="space-y-3 sm:space-y-4">
+ {/* Header with Logo and optional User Menu */}
+ <div className="flex items-center justify-between gap-4">
+ {/* Logo Section - Clickable to go home */}
+ <Link href="/" className="flex items-center gap-3 group">
+ <motion.div
+ className="flex items-center gap-3"
+ initial={{ opacity: 0, x: -20 }}
+ animate={{ opacity: 1, x: 0 }}
+ transition={{ duration: 0.3 }}
+ >
+ <div className="relative shrink-0">
+ <div className="w-12 h-12 rounded-2xl bg-gradient-to-br from-slate-900 via-slate-800 to-slate-700 dark:from-slate-800 dark:via-slate-700 dark:to-slate-600 flex items-center justify-center shadow-xl shadow-slate-900/50 dark:shadow-slate-950/70 ring-2 ring-slate-700/50 dark:ring-slate-600/50 transition-transform group-hover:scale-105">
+ <CalendarIcon className="h-6 w-6 text-white" />
+ </div>
+ </div>
+ <div>
+ <h1 className="text-xl font-bold bg-gradient-to-r from-foreground via-foreground to-foreground/70 bg-clip-text transition-all group-hover:from-primary group-hover:via-primary group-hover:to-primary/70">
+ {t("app.title")}
+ </h1>
+ <p className="text-xs text-muted-foreground font-medium">
+ {t("app.subtitle", { default: "Organize your shifts" })}
+ </p>
+ </div>
+ </motion.div>
+ </Link>
+
+ {/* User Menu (optional - shown on profile page) */}
+ {showUserMenu && (
+ <motion.div
+ initial={{ opacity: 0, scale: 0.9 }}
+ animate={{ opacity: 1, scale: 1 }}
+ transition={{ duration: 0.3, delay: 0.15 }}
+ >
+ <UserMenu />
+ </motion.div>
+ )}
+ </div>
+
+ {/* Update Notification Banner */}
+ {versionInfo?.hasUpdate && !versionInfo.isDev && (
+ <motion.div
+ initial={{ opacity: 0, y: -10 }}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{ duration: 0.3, delay: 0.15 }}
+ className="relative"
+ >
+ <button
+ onClick={() => setShowChangelog(true)}
+ className="w-full bg-gradient-to-r from-primary/10 via-primary/5 to-primary/10 backdrop-blur-sm border border-primary/30 rounded-xl p-3 sm:p-3.5 flex items-center justify-between gap-3 hover:from-primary/15 hover:via-primary/10 hover:to-primary/15 hover:border-primary/40 transition-all shadow-sm hover:shadow-md active:scale-[0.99] group"
+ >
+ <div className="flex items-center gap-2.5 sm:gap-3 flex-1 min-w-0">
+ <div className="relative shrink-0 w-9 h-9 sm:w-10 sm:h-10 rounded-lg bg-primary/10 flex items-center justify-center group-hover:bg-primary/15 transition-colors">
+ <Bell className="h-4 w-4 sm:h-5 sm:w-5 text-primary group-hover:scale-110 transition-transform" />
+ <div className="absolute -top-0.5 -right-0.5 w-2.5 h-2.5 bg-primary rounded-full animate-pulse shadow-sm"></div>
+ </div>
+ <div className="text-left flex-1 min-w-0">
+ <p className="text-sm sm:text-base font-semibold text-primary mb-0.5">
+ {t("update.available")}
+ </p>
+ <p className="text-xs sm:text-sm text-muted-foreground font-medium">
+ {t("update.newVersion", {
+ version: versionInfo.latestVersion || "unknown",
+ })}
+ </p>
+ </div>
+ </div>
+ <div className="shrink-0 flex items-center gap-2 text-primary">
+ <span className="text-xs sm:text-sm font-medium hidden sm:inline">
+ {t("update.viewChangelog")}
+ </span>
+ <div className="w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center group-hover:bg-primary/15 transition-colors">
+ <ExternalLink className="h-4 w-4 group-hover:rotate-12 transition-transform" />
+ </div>
+ </div>
+ </button>
+ </motion.div>
+ )}
+ </div>
+ </div>
+ </div>
+
+ {/* Changelog Dialog */}
+ <ChangelogDialog
+ open={showChangelog}
+ onOpenChange={setShowChangelog}
+ locale={locale}
+ />
+ </>
+ );
+}
diff --git a/components/auth-provider.tsx b/components/auth-provider.tsx
new file mode 100644
index 0000000..9ba2601
--- /dev/null
+++ b/components/auth-provider.tsx
@@ -0,0 +1,103 @@
+"use client";
+
+import { useEffect, useLayoutEffect, useState } from "react";
+import { useRouter, usePathname } from "next/navigation";
+import { useAuth } from "@/hooks/useAuth";
+import { usePublicConfig } from "@/hooks/usePublicConfig";
+
+/**
+ * Auth Provider for client-side session management
+ *
+ * Features:
+ * - Checks auth status on mount
+ * - Redirects to login if not authenticated (unless guest access enabled)
+ * - Handles loading states
+ * - Respects auth and guest access feature flags
+ */
+export function AuthProvider({ children }: { children: React.ReactNode }) {
+ const { isAuthenticated, isLoading } = useAuth();
+ const router = useRouter();
+ const pathname = usePathname();
+ const [mounted, setMounted] = useState(false);
+ const { auth } = usePublicConfig();
+
+ // Public routes that don't require authentication
+ const publicRoutes = ["/login", "/register"];
+ const isPublicRoute = publicRoutes.some((route) =>
+ pathname.startsWith(route)
+ );
+
+ // Set mounted after initial render to avoid hydration mismatch
+ // This is a legitimate pattern for SSR hydration - calling setState in useLayoutEffect
+ // is the recommended approach to avoid hydration mismatches in client components.
+ useLayoutEffect(() => {
+ // eslint-disable-next-line react-hooks/set-state-in-effect
+ setMounted(true);
+ }, []);
+
+ useEffect(() => {
+ if (!mounted) return;
+
+ // Skip auth check if auth is disabled
+ if (!auth.enabled) {
+ return;
+ }
+
+ // Wait for loading to complete
+ if (isLoading) {
+ return;
+ }
+
+ // Don't auto-redirect from login/register pages - let those pages handle their own navigation
+ // This allows users to stay on login after logout when guest access is enabled
+ if (isPublicRoute) {
+ return;
+ }
+
+ // Redirect unauthenticated users from protected routes to login
+ // ONLY if guest access is NOT allowed
+ if (!isPublicRoute && !isAuthenticated && !auth.allowGuestAccess) {
+ const loginUrl = `/login?returnUrl=${encodeURIComponent(pathname)}`;
+ router.replace(loginUrl);
+ }
+ }, [
+ mounted,
+ isAuthenticated,
+ isLoading,
+ auth.enabled,
+ auth.allowGuestAccess,
+ isPublicRoute,
+ pathname,
+ router,
+ ]);
+
+ // Show nothing until mounted to avoid hydration mismatch
+ if (!mounted) {
+ return <>{children}</>;
+ }
+
+ // Show loading state while checking auth
+ if (auth.enabled && !isPublicRoute && isLoading) {
+ return (
+ <div className="flex min-h-screen items-center justify-center">
+ <div className="flex flex-col items-center gap-4">
+ <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"></div>
+ <p className="text-sm text-muted-foreground">Loading...</p>
+ </div>
+ </div>
+ );
+ }
+
+ // Don't render protected content if not authenticated (unless guest access allowed)
+ if (
+ auth.enabled &&
+ !isPublicRoute &&
+ !isAuthenticated &&
+ !isLoading &&
+ !auth.allowGuestAccess
+ ) {
+ return null;
+ }
+
+ return <>{children}</>;
+}
diff --git a/components/calendar-compare-skeleton.tsx b/components/calendar-compare-skeleton.tsx
deleted file mode 100644
index 2f0129e..0000000
--- a/components/calendar-compare-skeleton.tsx
+++ /dev/null
@@ -1,91 +0,0 @@
-import { Skeleton } from "@/components/ui/skeleton";
-import { PresetListSkeleton } from "@/components/preset-list-skeleton";
-
-interface CalendarCompareSkeletonProps {
- count: number;
- hidePresetHeader?: boolean;
-}
-
-export function CalendarCompareSkeleton({
- count,
- hidePresetHeader = false,
-}: CalendarCompareSkeletonProps) {
- return (
- <div className="min-h-screen flex flex-col bg-background">
- {/* Header */}
- <div className="sticky top-0 z-10 bg-background/80 backdrop-blur-xl border-b border-border/50 shadow-sm">
- <div className="w-full px-3 sm:px-4 py-3 sm:py-4">
- <div className="space-y-3">
- {/* Title and Buttons */}
- <div className="flex items-center justify-between">
- <div className="space-y-2">
- <Skeleton className="h-8 w-48" />
- <Skeleton className="h-4 w-32" />
- </div>
- <div className="flex gap-2">
- <Skeleton className="h-10 w-32" />
- <Skeleton className="h-10 w-32" />
- </div>
- </div>
- </div>
- </div>
- </div>
-
- {/* Mobile Warning Skeleton */}
- <div className="lg:hidden mx-3 mt-3 mb-1">
- <Skeleton className="h-16 w-full rounded-lg" />
- </div>
-
- {/* Calendars Grid */}
- <div className="flex-1 w-full px-1 sm:px-4 py-4">
- <div
- className={`grid gap-4 ${
- count === 2
- ? "grid-cols-1 lg:grid-cols-2"
- : "grid-cols-1 lg:grid-cols-2 xl:grid-cols-3"
- }`}
- >
- {Array.from({ length: count }).map((_, index) => (
- <div
- key={index}
- className="border border-border rounded-xl overflow-hidden bg-card shadow-sm"
- >
- {/* Calendar Header */}
- <div className="border-b border-border/50 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent px-4 py-3">
- <div className="flex items-center gap-3">
- <Skeleton className="w-5 h-5 rounded-full" />
- <Skeleton className="h-6 w-32" />
- </div>
- </div>
-
- {/* Calendar Content */}
- <div className="p-4 space-y-4">
- {/* Preset List Skeleton */}
- <PresetListSkeleton hidePresetHeader={hidePresetHeader} />
-
- {/* Calendar Grid Skeleton (compact version) */}
- <div className="grid grid-cols-7 gap-1 mt-4">
- {/* Weekday headers */}
- {Array.from({ length: 7 }).map((_, i) => (
- <Skeleton key={`header-${index}-${i}`} className="h-5" />
- ))}
-
- {/* Calendar days (limited to 35 for performance) */}
- {Array.from({ length: 35 }).map((_, i) => (
- <div
- key={`day-${index}-${i}`}
- className="min-h-20 border border-border/30 rounded-lg p-1.5 space-y-1"
- >
- <Skeleton className="h-4 w-5" />
- <Skeleton className="h-3 w-full" />
- </div>
- ))}
- </div>
- </div>
- </div>
- ))}
- </div>
- </div>
- </div>
- );
-}
diff --git a/components/calendar-compare-view.tsx b/components/calendar-compare-view.tsx
index 659936c..0e5d651 100644
--- a/components/calendar-compare-view.tsx
+++ b/components/calendar-compare-view.tsx
@@ -6,13 +6,12 @@ import { CalendarNote, ExternalSync, ShiftPreset } from "@/lib/db/schema";
import { Button } from "@/components/ui/button";
import { CalendarContent } from "@/components/calendar-content";
import { PresetSelector } from "@/components/preset-selector";
-import { LockedCalendarView } from "@/components/locked-calendar-view";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { X, Link, Smartphone } from "lucide-react";
-import { getCachedPassword } from "@/lib/password-cache";
import { motion } from "motion/react";
import { Locale } from "date-fns";
import { toast } from "sonner";
+import { useCalendarPermission } from "@/hooks/useCalendarPermission";
interface CalendarCompareViewProps {
calendars: CalendarWithCount[];
@@ -69,9 +68,7 @@ interface CalendarCompareViewProps {
onPresetsChange: (calendarId: string) => void;
onShiftsChange?: () => void;
onStatsRefresh?: () => void;
- onPasswordRequired: (calendarId: string, action: () => Promise<void>) => void;
presetsLoadingMap?: Map<string, boolean>;
- onUnlockCalendar?: (calendarId: string) => void;
}
export function CalendarCompareView(props: CalendarCompareViewProps) {
@@ -81,6 +78,24 @@ export function CalendarCompareView(props: CalendarCompareViewProps) {
props.selectedIds.includes(cal.id)
);
+ // Pre-calculate permissions for all selected calendars
+ // We need to call hooks unconditionally, so we always get permissions for all selected calendars
+ const permission0 = useCalendarPermission(selectedCalendars[0]?.id);
+ const permission1 = useCalendarPermission(selectedCalendars[1]?.id);
+ const permission2 = useCalendarPermission(selectedCalendars[2]?.id);
+
+ // Map permissions by calendar ID
+ const permissionsMap = new Map<
+ string,
+ ReturnType<typeof useCalendarPermission>
+ >();
+ if (selectedCalendars[0])
+ permissionsMap.set(selectedCalendars[0].id, permission0);
+ if (selectedCalendars[1])
+ permissionsMap.set(selectedCalendars[1].id, permission1);
+ if (selectedCalendars[2])
+ permissionsMap.set(selectedCalendars[2].id, permission2);
+
// Find which calendar owns the selected preset
const selectedPresetCalendarId = props.selectedPresetId
? (() => {
@@ -100,7 +115,7 @@ export function CalendarCompareView(props: CalendarCompareViewProps) {
navigator.clipboard
.writeText(url.toString())
.then(() => {
- toast.success(t("calendar.linkCopied"));
+ toast.success(t("common.copied", { item: t("calendar.compareMode") }));
})
.catch(() => {
toast.error(t("common.error"));
@@ -182,10 +197,8 @@ export function CalendarCompareView(props: CalendarCompareViewProps) {
const presetsLoading =
props.presetsLoadingMap?.get(calendar.id) || false;
- // Check if calendar is locked (has password but no cached password)
- const isLocked = calendar.passwordHash && calendar.isLocked;
- const hasPassword = getCachedPassword(calendar.id);
- const showLockedView = isLocked && !hasPassword;
+ // Get pre-calculated permission for this calendar
+ const permission = permissionsMap.get(calendar.id)!;
// Check if this calendar is disabled (preset from different calendar selected)
const isDisabled =
@@ -220,119 +233,92 @@ export function CalendarCompareView(props: CalendarCompareViewProps) {
</div>
{/* Preset List for this calendar */}
- {!showLockedView && (
- <div className="-mx-2">
- <PresetSelector
- calendars={props.allCalendars}
- presets={calendarPresets}
- selectedPresetId={props.selectedPresetId}
- onSelectPreset={props.onSelectPreset}
- onPresetsChange={() =>
- props.onPresetsChange(calendar.id)
- }
- onShiftsChange={props.onShiftsChange}
- onStatsRefresh={props.onStatsRefresh}
- calendarId={calendar.id}
- onPasswordRequired={(action) =>
- props.onPasswordRequired(calendar.id, action)
- }
- onViewSettingsClick={props.onViewSettingsClick}
- loading={presetsLoading}
- hidePresetHeader={props.hidePresetHeader}
- onHidePresetHeaderChange={
- props.onHidePresetHeaderChange
- }
- hideManageButton={true}
- />
- </div>
- )}
+ <div className="-mx-2">
+ <PresetSelector
+ calendars={props.allCalendars}
+ presets={calendarPresets}
+ selectedPresetId={props.selectedPresetId}
+ onSelectPreset={props.onSelectPreset}
+ onPresetsChange={() => props.onPresetsChange(calendar.id)}
+ onShiftsChange={props.onShiftsChange}
+ onStatsRefresh={props.onStatsRefresh}
+ calendarId={calendar.id}
+ onViewSettingsClick={props.onViewSettingsClick}
+ loading={presetsLoading}
+ hidePresetHeader={props.hidePresetHeader}
+ onHidePresetHeaderChange={props.onHidePresetHeaderChange}
+ hideManageButton={true}
+ />
+ </div>
</div>
- {/* Calendar Content or Locked View */}
+ {/* Calendar Content */}
<div className="p-2 sm:p-3">
- {showLockedView ? (
- <LockedCalendarView
- calendarId={calendar.id}
- onUnlock={() => {
- if (props.onUnlockCalendar) {
- props.onUnlockCalendar(calendar.id);
- }
- }}
- />
- ) : (
- <>
- {/* Hint when preset from different calendar is selected */}
- {isDisabled && (
- <div className="mb-3 p-3 bg-muted/50 border border-border/50 rounded-lg">
- <p className="text-xs text-muted-foreground text-center">
- {t("preset.cannotAddPresetHint")}
- </p>
- </div>
- )}
- <CalendarContent
- calendarDays={props.calendarDays}
- currentDate={props.currentDate}
- onDateChange={props.onDateChange}
- shifts={shifts}
- notes={notes}
- selectedPresetId={
- isDisabled ? undefined : props.selectedPresetId
- }
- togglingDates={togglingDates}
- externalSyncs={externalSyncs}
- maxShiftsToShow={props.maxShiftsToShow}
- maxExternalShiftsToShow={props.maxExternalShiftsToShow}
- showShiftNotes={props.showShiftNotes}
- showFullTitles={props.showFullTitles}
- shiftSortType={props.shiftSortType}
- shiftSortOrder={props.shiftSortOrder}
- combinedSortMode={props.combinedSortMode}
- highlightedWeekdays={props.highlightedWeekdays}
- highlightColor={props.highlightColor}
- selectedCalendar={calendar.id}
- statsRefreshTrigger={props.statsRefreshTrigger}
- shouldHideUIElements={false}
- locale={props.locale}
- onDayClick={
- isDisabled
- ? () => {}
- : (date) => props.onDayClick(calendar.id, date)
- }
- onDayRightClick={
- props.onDayRightClick
- ? (e, date) =>
- props.onDayRightClick!(calendar.id, e, date)
- : undefined
- }
- onNoteIconClick={
- props.onNoteIconClick
- ? (e, date) =>
- props.onNoteIconClick!(calendar.id, e, date)
- : undefined
- }
- onLongPress={
- props.onLongPress
- ? (date) => props.onLongPress!(calendar.id, date)
- : undefined
- }
- onShowAllShifts={(date, dayShifts) =>
- props.onShowAllShifts(calendar.id, date, dayShifts)
- }
- onShowSyncedShifts={(date, syncedShifts) =>
- props.onShowSyncedShifts(
- calendar.id,
- date,
- syncedShifts
- )
- }
- onDeleteShift={
- props.onDeleteShift
- ? (id) => props.onDeleteShift!(calendar.id, id)
- : undefined
- }
- />
- </>
+ {/* Hint when preset from different calendar is selected */}
+ {isDisabled && (
+ <div className="mb-3 p-3 bg-muted/50 border border-border/50 rounded-lg">
+ <p className="text-xs text-muted-foreground text-center">
+ {t("preset.cannotAddPresetHint")}
+ </p>
+ </div>
)}
+ <CalendarContent
+ calendarDays={props.calendarDays}
+ currentDate={props.currentDate}
+ onDateChange={props.onDateChange}
+ shifts={shifts}
+ notes={notes}
+ selectedPresetId={
+ isDisabled ? undefined : props.selectedPresetId
+ }
+ togglingDates={togglingDates}
+ externalSyncs={externalSyncs}
+ maxShiftsToShow={props.maxShiftsToShow}
+ maxExternalShiftsToShow={props.maxExternalShiftsToShow}
+ showShiftNotes={props.showShiftNotes}
+ showFullTitles={props.showFullTitles}
+ shiftSortType={props.shiftSortType}
+ shiftSortOrder={props.shiftSortOrder}
+ combinedSortMode={props.combinedSortMode}
+ highlightedWeekdays={props.highlightedWeekdays}
+ highlightColor={props.highlightColor}
+ selectedCalendar={calendar.id}
+ statsRefreshTrigger={props.statsRefreshTrigger}
+ locale={props.locale}
+ onDayClick={
+ isDisabled
+ ? () => {}
+ : (date) => props.onDayClick(calendar.id, date)
+ }
+ onDayRightClick={
+ props.onDayRightClick && permission.canEdit
+ ? (e, date) =>
+ props.onDayRightClick!(calendar.id, e, date)
+ : undefined
+ }
+ onNoteIconClick={
+ props.onNoteIconClick && permission.canEdit
+ ? (e, date) =>
+ props.onNoteIconClick!(calendar.id, e, date)
+ : undefined
+ }
+ onLongPress={
+ props.onLongPress && permission.canEdit
+ ? (date) => props.onLongPress!(calendar.id, date)
+ : undefined
+ }
+ onShowAllShifts={(date, dayShifts) =>
+ props.onShowAllShifts(calendar.id, date, dayShifts)
+ }
+ onShowSyncedShifts={(date, syncedShifts) =>
+ props.onShowSyncedShifts(calendar.id, date, syncedShifts)
+ }
+ onDeleteShift={
+ props.onDeleteShift && permission.canEdit
+ ? (id) => props.onDeleteShift!(calendar.id, id)
+ : undefined
+ }
+ />
</div>
</motion.div>
);
diff --git a/components/calendar-content-skeleton.tsx b/components/calendar-content-skeleton.tsx
deleted file mode 100644
index 112a21e..0000000
--- a/components/calendar-content-skeleton.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-import { Skeleton } from "@/components/ui/skeleton";
-
-export function CalendarContentSkeleton({
- daysCount = 42,
-}: {
- daysCount?: number;
-}) {
- return (
- <div className="space-y-4">
- {/* Month Navigation Skeleton */}
- <div className="flex items-center justify-between mb-4">
- <Skeleton className="h-10 w-10 rounded-lg" />
- <Skeleton className="h-8 w-40" />
- <Skeleton className="h-10 w-10 rounded-lg" />
- </div>
-
- {/* Calendar Grid Skeleton */}
- <div className="grid grid-cols-7 gap-0 sm:gap-1.5 mb-6">
- {/* Weekday headers */}
- {Array.from({ length: 7 }).map((_, i) => (
- <Skeleton key={`header-${i}`} className="h-6 mx-1" />
- ))}
-
- {/* Calendar days */}
- {Array.from({ length: daysCount }).map((_, i) => (
- <div
- key={`day-${i}`}
- className="min-h-24 sm:min-h-28 border border-border/30 rounded-lg p-1.5 sm:p-2 space-y-1"
- >
- <Skeleton className="h-5 w-6" />
- <Skeleton className="h-4 w-full" />
- <Skeleton className="h-4 w-3/4" />
- </div>
- ))}
- </div>
-
- {/* Stats and Shifts Skeleton */}
- <div className="space-y-4">
- <Skeleton className="h-32 w-full rounded-xl" />
- <Skeleton className="h-32 w-full rounded-xl" />
- </div>
- </div>
- );
-}
diff --git a/components/calendar-content.tsx b/components/calendar-content.tsx
index 1470557..89872ea 100644
--- a/components/calendar-content.tsx
+++ b/components/calendar-content.tsx
@@ -5,9 +5,11 @@ import { CalendarGrid } from "@/components/calendar-grid";
import { ShiftStats } from "@/components/shift-stats";
import { ShiftsList } from "@/components/shifts-list";
import { MonthNavigation } from "@/components/month-navigation";
+import { GuestBanner } from "@/components/guest-banner";
import { ShiftWithCalendar } from "@/lib/types";
import { CalendarNote, ExternalSync } from "@/lib/db/schema";
import { Locale } from "date-fns";
+import { useAuth } from "@/hooks/useAuth";
interface CalendarContentProps {
calendarDays: Date[];
@@ -29,7 +31,6 @@ interface CalendarContentProps {
highlightColor?: string;
selectedCalendar: string | null;
statsRefreshTrigger: number;
- shouldHideUIElements: boolean;
locale?: Locale;
onDayClick: (date: Date) => void;
onDayRightClick?: (e: React.MouseEvent, date: Date) => void;
@@ -42,6 +43,7 @@ interface CalendarContentProps {
export function CalendarContent(props: CalendarContentProps) {
const t = useTranslations();
+ const { isGuest } = useAuth();
return (
<>
@@ -51,6 +53,18 @@ export function CalendarContent(props: CalendarContentProps) {
locale={props.locale}
/>
+ {/* Guest Banner - compact on mobile, default on desktop */}
+ {isGuest && (
+ <>
+ <div className="mb-4 px-2 sm:hidden">
+ <GuestBanner variant="compact" />
+ </div>
+ <div className="hidden sm:block mb-4">
+ <GuestBanner variant="default" />
+ </div>
+ </>
+ )}
+
<CalendarGrid
calendarDays={props.calendarDays}
currentDate={props.currentDate}
@@ -76,36 +90,34 @@ export function CalendarContent(props: CalendarContentProps) {
onShowSyncedShifts={props.onShowSyncedShifts}
/>
- {!props.shouldHideUIElements && (
- <motion.div
- className="px-2 sm:px-0 mb-4"
- initial={{ opacity: 0, y: 10 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ delay: 0.3 }}
- >
- <div className="bg-gradient-to-r from-primary/10 to-primary/5 border border-primary/20 rounded-xl p-3 sm:p-3.5 backdrop-blur-sm">
- <div className="flex items-center gap-2.5">
- <div className="shrink-0 w-8 h-8 rounded-lg bg-primary/20 flex items-center justify-center">
- <StickyNote className="h-4 w-4 text-orange-500" />
- </div>
- <div className="flex-1">
- <p className="text-xs sm:hidden text-foreground/80 leading-relaxed">
- {t("note.hintMobile", {
- default:
- "Long press on a day to open notes. The note icon shows existing notes.",
- })}
- </p>
- <p className="hidden sm:block text-sm text-foreground/80 leading-relaxed">
- {t("note.hintDesktop", {
- default:
- "Right-click on a day to open notes. The note icon shows existing notes.",
- })}
- </p>
- </div>
+ <motion.div
+ className="px-2 sm:px-0 mb-4"
+ initial={{ opacity: 0, y: 10 }}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{ delay: 0.3 }}
+ >
+ <div className="bg-gradient-to-r from-primary/10 to-primary/5 border border-primary/20 rounded-xl p-3 sm:p-3.5 backdrop-blur-sm">
+ <div className="flex items-center gap-2.5">
+ <div className="shrink-0 w-8 h-8 rounded-lg bg-primary/20 flex items-center justify-center">
+ <StickyNote className="h-4 w-4 text-orange-500" />
+ </div>
+ <div className="flex-1">
+ <p className="text-xs sm:hidden text-foreground/80 leading-relaxed">
+ {t("note.hintMobile", {
+ default:
+ "Long press on a day to open notes. The note icon shows existing notes.",
+ })}
+ </p>
+ <p className="hidden sm:block text-sm text-foreground/80 leading-relaxed">
+ {t("note.hintDesktop", {
+ default:
+ "Right-click on a day to open notes. The note icon shows existing notes.",
+ })}
+ </p>
</div>
</div>
- </motion.div>
- )}
+ </div>
+ </motion.div>
<div className="space-y-3 sm:space-y-4 px-2 sm:px-0">
<ShiftStats
@@ -117,9 +129,8 @@ export function CalendarContent(props: CalendarContentProps) {
<ShiftsList
shifts={props.shifts}
currentDate={props.currentDate}
- onDeleteShift={
- props.shouldHideUIElements ? undefined : props.onDeleteShift
- }
+ onDeleteShift={props.onDeleteShift}
+ calendarId={props.selectedCalendar || undefined}
/>
</div>
</>
diff --git a/components/calendar-discovery-sheet.tsx b/components/calendar-discovery-sheet.tsx
new file mode 100644
index 0000000..dcd3a8e
--- /dev/null
+++ b/components/calendar-discovery-sheet.tsx
@@ -0,0 +1,425 @@
+"use client";
+
+import { useState } from "react";
+import { useTranslations } from "next-intl";
+import {
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+ SheetDescription,
+ SheetFooter,
+} from "@/components/ui/sheet";
+import { Input } from "@/components/ui/input";
+import { Badge } from "@/components/ui/badge";
+import { Switch } from "@/components/ui/switch";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import {
+ useCalendarSubscriptions,
+ type AvailableCalendar,
+ type DismissedCalendar,
+} from "@/hooks/useCalendarSubscriptions";
+import {
+ Users,
+ Search,
+ Eye,
+ Edit,
+ EyeOff,
+ Loader2,
+ UserPlus,
+ Globe,
+} from "lucide-react";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { Button } from "@/components/ui/button";
+
+type CalendarDiscoverySheetProps = {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+};
+
+export function CalendarDiscoverySheet({
+ open,
+ onOpenChange,
+}: CalendarDiscoverySheetProps) {
+ const t = useTranslations();
+ const [searchQuery, setSearchQuery] = useState("");
+ const {
+ availableCalendars,
+ dismissedCalendars,
+ loading,
+ subscribe,
+ dismiss,
+ } = useCalendarSubscriptions();
+
+ // Separate calendars by source
+ const sharedCalendars = availableCalendars.filter(
+ (cal) => cal.source === "shared"
+ );
+ const publicCalendars = availableCalendars.filter(
+ (cal) => cal.source === "guest"
+ );
+
+ // Filter search in all tabs
+ const filterBySearch = (calendars: AvailableCalendar[]) =>
+ calendars.filter((cal) =>
+ cal.name.toLowerCase().includes(searchQuery.toLowerCase())
+ );
+
+ // Filter dismissed calendars by search
+ const filteredDismissed = dismissedCalendars.filter((cal) =>
+ cal.name.toLowerCase().includes(searchQuery.toLowerCase())
+ );
+
+ const handleToggleSubscription = async (
+ calendar: AvailableCalendar,
+ currentlySubscribed: boolean
+ ) => {
+ if (currentlySubscribed) {
+ await dismiss(calendar.id, calendar.name);
+ } else {
+ await subscribe(calendar.id, calendar.name);
+ }
+ };
+
+ const handleShowAgain = async (calendar: DismissedCalendar) => {
+ await subscribe(calendar.id, calendar.name);
+ };
+
+ const renderCalendarCard = (calendar: AvailableCalendar) => {
+ // Use permission for shared calendars (owner/admin/write/read), guestPermission for public calendars
+ const actualPermission =
+ calendar.source === "shared" && calendar.permission
+ ? calendar.permission
+ : calendar.guestPermission;
+ const isReadOnly = actualPermission === "read";
+ const isAdmin =
+ actualPermission === "admin" || actualPermission === "owner";
+
+ return (
+ <div
+ key={calendar.id}
+ className="flex flex-col sm:flex-row sm:items-center gap-3 rounded-xl border border-border/50 bg-muted/20 hover:bg-muted/30 transition-all p-4"
+ style={{ borderLeftColor: calendar.color, borderLeftWidth: 4 }}
+ >
+ <div className="flex items-start sm:items-center gap-3 flex-1 min-w-0">
+ {/* Calendar info */}
+ <div className="flex-1 min-w-0">
+ <div className="flex flex-col sm:flex-row sm:items-center gap-1.5 sm:gap-2 mb-1">
+ <div className="font-semibold flex items-center gap-2">
+ <div
+ className="w-1 h-4 rounded-full"
+ style={{ backgroundColor: calendar.color }}
+ />
+ <span className="truncate">{calendar.name}</span>
+ </div>
+ <div className="flex flex-wrap items-center gap-1.5">
+ {isAdmin ? (
+ <Badge
+ variant="default"
+ className="flex items-center gap-1 text-xs bg-blue-600 hover:bg-blue-700"
+ >
+ <Users className="h-3 w-3" />
+ <span>{t("common.labels.permissions.admin")}</span>
+ </Badge>
+ ) : isReadOnly ? (
+ <Badge
+ variant="secondary"
+ className="flex items-center gap-1 text-xs"
+ >
+ <Eye className="h-3 w-3" />
+ <span>{t("common.labels.permissions.read")}</span>
+ </Badge>
+ ) : (
+ <Badge
+ variant="default"
+ className="flex items-center gap-1 text-xs bg-green-600 hover:bg-green-700"
+ >
+ <Edit className="h-3 w-3" />
+ <span>{t("common.labels.permissions.write")}</span>
+ </Badge>
+ )}
+ </div>
+ </div>
+ {calendar.owner && (
+ <p className="text-sm text-muted-foreground truncate">
+ {calendar.owner.name}
+ </p>
+ )}
+ </div>
+ </div>
+
+ {/* Toggle switch */}
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div className="flex items-center justify-end sm:justify-start gap-2 sm:pl-0">
+ <span className="text-sm text-muted-foreground sm:hidden">
+ {calendar.isSubscribed
+ ? t("calendar.subscribed")
+ : t("calendar.subscribe")}
+ </span>
+ <Switch
+ checked={calendar.isSubscribed}
+ onCheckedChange={() =>
+ handleToggleSubscription(calendar, calendar.isSubscribed)
+ }
+ />
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ {calendar.isSubscribed
+ ? t("calendar.unsubscribeTooltip")
+ : t("calendar.subscribeTooltip")}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ );
+ };
+
+ const renderDismissedCard = (calendar: DismissedCalendar) => {
+ const isReadOnly = calendar.permission === "read";
+ const isAdmin =
+ calendar.permission === "admin" || calendar.permission === "owner";
+
+ return (
+ <div
+ key={calendar.id}
+ className="flex flex-col sm:flex-row sm:items-center gap-3 rounded-xl border border-border/50 bg-muted/20 hover:bg-muted/30 transition-all p-4 opacity-60"
+ style={{ borderLeftColor: calendar.color, borderLeftWidth: 4 }}
+ >
+ <div className="flex items-start sm:items-center gap-3 flex-1 min-w-0">
+ {/* Calendar info */}
+ <div className="flex-1 min-w-0">
+ <div className="flex flex-col sm:flex-row sm:items-center gap-1.5 sm:gap-2 mb-1">
+ <div className="font-semibold flex items-center gap-2">
+ <div
+ className="w-1 h-4 rounded-full"
+ style={{ backgroundColor: calendar.color }}
+ />
+ <span className="truncate">{calendar.name}</span>
+ </div>
+ <div className="flex flex-wrap items-center gap-1.5">
+ {calendar.source === "shared" && (
+ <Badge
+ variant="secondary"
+ className="flex items-center gap-1 text-xs"
+ >
+ <UserPlus className="h-3 w-3" />
+ <span>{t("share.sharedWithYou")}</span>
+ </Badge>
+ )}
+ {calendar.source === "guest" && (
+ <Badge
+ variant="outline"
+ className="flex items-center gap-1 text-xs"
+ >
+ <Globe className="h-3 w-3" />
+ <span>{t("calendar.publicBadge")}</span>
+ </Badge>
+ )}
+ {isAdmin ? (
+ <Badge
+ variant="secondary"
+ className="flex items-center gap-1 text-xs"
+ >
+ <Users className="h-3 w-3" />
+ <span>{t("common.labels.permissions.admin")}</span>
+ </Badge>
+ ) : isReadOnly ? (
+ <Badge
+ variant="secondary"
+ className="flex items-center gap-1 text-xs"
+ >
+ <Eye className="h-3 w-3" />
+ <span>{t("common.labels.permissions.read")}</span>
+ </Badge>
+ ) : (
+ <Badge
+ variant="secondary"
+ className="flex items-center gap-1 text-xs"
+ >
+ <Edit className="h-3 w-3" />
+ <span>{t("common.labels.permissions.write")}</span>
+ </Badge>
+ )}
+ </div>
+ </div>
+ {calendar.owner && (
+ <p className="text-sm text-muted-foreground truncate">
+ {calendar.owner.name}
+ </p>
+ )}
+ </div>
+ </div>
+
+ {/* Toggle switch */}
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div className="flex items-center justify-end sm:justify-start gap-2 sm:pl-0">
+ <span className="text-sm text-muted-foreground sm:hidden">
+ {t("calendar.showAgain")}
+ </span>
+ <Switch
+ checked={false}
+ onCheckedChange={() => handleShowAgain(calendar)}
+ />
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>{t("calendar.subscribeTooltip")}</TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ );
+ };
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent
+ side="right"
+ className="w-full sm:max-w-2xl flex flex-col p-0 gap-0"
+ >
+ <SheetHeader className="border-b border-border/50 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent p-6 pb-5 space-y-1.5">
+ <SheetTitle className="text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text flex items-center gap-2">
+ <Users className="h-5 w-5 flex-shrink-0" />
+ <span className="truncate">{t("calendar.browseCalendars")}</span>
+ </SheetTitle>
+ <SheetDescription className="text-sm text-muted-foreground">
+ {t("calendar.browseCalendarsDescription")}
+ </SheetDescription>
+ </SheetHeader>
+
+ <div className="flex flex-col flex-1 min-h-0 p-6 space-y-4 overflow-y-auto">
+ {/* Search */}
+ <div className="relative">
+ <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
+ <Input
+ placeholder={t("common.search")}
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ className="pl-9"
+ />
+ </div>
+
+ {loading ? (
+ <div className="flex items-center justify-center py-12">
+ <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
+ </div>
+ ) : (
+ <Tabs
+ defaultValue="shared"
+ className="flex-1 min-h-0 flex flex-col"
+ >
+ <TabsList className="grid w-full grid-cols-3">
+ <TabsTrigger value="shared" className="gap-2">
+ <UserPlus className="h-4 w-4" />
+ {t("calendar.sharedTab")}
+ {sharedCalendars.length > 0 && (
+ <Badge variant="secondary" className="ml-1 text-xs">
+ {sharedCalendars.length}
+ </Badge>
+ )}
+ </TabsTrigger>
+ <TabsTrigger value="public" className="gap-2">
+ <Globe className="h-4 w-4" />
+ {t("calendar.publicTab")}
+ {publicCalendars.length > 0 && (
+ <Badge variant="secondary" className="ml-1 text-xs">
+ {publicCalendars.length}
+ </Badge>
+ )}
+ </TabsTrigger>
+ <TabsTrigger value="hidden" className="gap-2">
+ <EyeOff className="h-4 w-4" />
+ {t("calendar.hiddenTab")}
+ {dismissedCalendars.length > 0 && (
+ <Badge variant="secondary" className="ml-1 text-xs">
+ {dismissedCalendars.length}
+ </Badge>
+ )}
+ </TabsTrigger>
+ </TabsList>
+
+ <TabsContent
+ value="shared"
+ className="flex-1 min-h-0 overflow-y-auto space-y-3 mt-4"
+ >
+ {filterBySearch(sharedCalendars).length === 0 ? (
+ <div className="flex flex-col items-center justify-center py-12 text-center">
+ <UserPlus className="h-12 w-12 text-muted-foreground/50 mb-3" />
+ <p className="text-sm text-muted-foreground">
+ {searchQuery
+ ? t("common.noResults")
+ : t("calendar.noSharedCalendars")}
+ </p>
+ </div>
+ ) : (
+ filterBySearch(sharedCalendars).map((calendar) =>
+ renderCalendarCard(calendar)
+ )
+ )}
+ </TabsContent>
+
+ <TabsContent
+ value="public"
+ className="flex-1 min-h-0 overflow-y-auto space-y-3 mt-4"
+ >
+ {filterBySearch(publicCalendars).length === 0 ? (
+ <div className="flex flex-col items-center justify-center py-12 text-center">
+ <Globe className="h-12 w-12 text-muted-foreground/50 mb-3" />
+ <p className="text-sm text-muted-foreground">
+ {searchQuery
+ ? t("common.noResults")
+ : t("calendar.noPublicCalendars")}
+ </p>
+ </div>
+ ) : (
+ filterBySearch(publicCalendars).map((calendar) =>
+ renderCalendarCard(calendar)
+ )
+ )}
+ </TabsContent>
+
+ <TabsContent
+ value="hidden"
+ className="flex-1 min-h-0 overflow-y-auto space-y-3 mt-4"
+ >
+ {filteredDismissed.length === 0 ? (
+ <div className="flex flex-col items-center justify-center py-12 text-center">
+ <EyeOff className="h-12 w-12 text-muted-foreground/50 mb-3" />
+ <p className="text-sm text-muted-foreground">
+ {searchQuery
+ ? t("common.noResults")
+ : t("calendar.noHiddenCalendars")}
+ </p>
+ </div>
+ ) : (
+ filteredDismissed.map((calendar) =>
+ renderDismissedCard(calendar)
+ )
+ )}
+ </TabsContent>
+ </Tabs>
+ )}
+ </div>
+
+ <SheetFooter className="border-t border-border/50 bg-muted/20 px-6 py-4 mt-auto">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ className="h-11 border-border/50 hover:bg-muted/50"
+ >
+ {t("common.cancel")}
+ </Button>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ );
+}
diff --git a/components/calendar-selector.tsx b/components/calendar-selector.tsx
index 6a4a435..b85dc38 100644
--- a/components/calendar-selector.tsx
+++ b/components/calendar-selector.tsx
@@ -10,16 +10,34 @@ import {
SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
-import { Plus, CalendarCog, Cloud, Bell, Copy } from "lucide-react";
-import { getCachedPassword } from "@/lib/password-cache";
+import { Separator } from "@/components/ui/separator";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import {
+ Plus,
+ Bell,
+ Copy,
+ Settings,
+ Lock,
+ User,
+ Users,
+ Globe,
+ ShieldCheck,
+} from "lucide-react";
+import { useAuth } from "@/hooks/useAuth";
+import { useAuthFeatures } from "@/hooks/useAuthFeatures";
+import { useCalendarPermission } from "@/hooks/useCalendarPermission";
interface CalendarSelectorProps {
calendars: CalendarWithCount[];
selectedId?: string;
onSelect: (id: string) => void;
onCreateNew: () => void;
- onManagePassword?: () => void;
- onExternalSync?: () => void;
+ onSettings?: () => void;
onSyncNotifications?: () => void;
onCompare?: () => void;
hasSyncErrors?: boolean;
@@ -31,21 +49,150 @@ export function CalendarSelector({
selectedId,
onSelect,
onCreateNew,
- onManagePassword,
- onExternalSync,
+ onSettings,
onSyncNotifications,
onCompare,
hasSyncErrors = false,
variant = "desktop",
}: CalendarSelectorProps) {
const t = useTranslations();
+ const { isGuest, user } = useAuth();
+ const { isAuthEnabled } = useAuthFeatures();
+
+ // Filter calendars: guests only see calendars with read or write permission
+ const visibleCalendars = isGuest
+ ? calendars.filter(
+ (c) =>
+ c.guestPermission === "read" ||
+ c.guestPermission === "write" ||
+ c.tokenPermission === "read" ||
+ c.tokenPermission === "write"
+ )
+ : calendars;
+
+ const selectedCalendar = visibleCalendars.find((c) => c.id === selectedId);
+ const canCompare = visibleCalendars.length >= 2;
+
+ // Group calendars by ownership
+ const ownCalendars = visibleCalendars.filter(
+ (c) => isAuthEnabled && user && !isGuest && c.ownerId === user.id
+ );
+ const sharedCalendars = visibleCalendars.filter(
+ (c) =>
+ isAuthEnabled &&
+ user &&
+ !isGuest &&
+ c.ownerId !== user.id &&
+ c.sharePermission // Only calendars with explicit share permission, not tokens
+ );
+ const tokenCalendars =
+ isAuthEnabled && !isGuest
+ ? visibleCalendars.filter(
+ (c) =>
+ c.tokenPermission &&
+ !c.sharePermission &&
+ (!user || c.ownerId !== user?.id)
+ )
+ : [];
+ // Public calendars: Calendars with guestPermission that authenticated users have subscribed to
+ // Exclude calendars already shown in other groups (own, shared, token)
+ const publicCalendars =
+ isAuthEnabled && user && !isGuest
+ ? visibleCalendars.filter(
+ (c) =>
+ c.guestPermission &&
+ !c.sharePermission &&
+ !c.tokenPermission &&
+ c.ownerId !== user.id
+ )
+ : [];
+ // For guests or when auth is disabled, show all visible calendars without grouping
+ // Guests see all their accessible calendars in one list (no separation by token/guest permission)
+ const guestAccessibleCalendars =
+ !isAuthEnabled || isGuest ? visibleCalendars : [];
+
+ // Check if selected calendar is read-only
+ // Owner is never read-only, even if guestPermission is "read"
+ // Guests (no user) or non-owners see read-only based on permissions
+ // Priority: owner > sharePermission > tokenPermission > guestPermission
+ const isReadOnly =
+ selectedCalendar &&
+ (!user || selectedCalendar.ownerId !== user.id) &&
+ (selectedCalendar.sharePermission === "read" ||
+ (!selectedCalendar.sharePermission &&
+ selectedCalendar.tokenPermission === "read") ||
+ (!selectedCalendar.sharePermission &&
+ !selectedCalendar.tokenPermission &&
+ selectedCalendar.guestPermission === "read"));
+
+ // Check if user can manage settings (owner or admin)
+ const { canManage } = useCalendarPermission(selectedCalendar);
- const selectedCalendar = calendars.find((c) => c.id === selectedId);
- // Hide external sync buttons if calendar requires password AND no valid password is cached
- const requiresPassword = !!selectedCalendar?.passwordHash;
- const hasPassword = selectedId ? !!getCachedPassword(selectedId) : false;
- const shouldHideSyncButtons = requiresPassword && !hasPassword;
- const canCompare = calendars.length >= 2;
+ // Helper function to render calendar icon
+ const getCalendarIcon = (calendar: CalendarWithCount) => {
+ if (!isAuthEnabled) {
+ return null;
+ }
+ if (!user) {
+ return <Globe className="h-3.5 w-3.5 text-muted-foreground/60" />;
+ }
+ // Check for admin/owner permission
+ if (
+ calendar.sharePermission === "admin" ||
+ calendar.sharePermission === "owner"
+ ) {
+ return (
+ <ShieldCheck className="h-3.5 w-3.5 text-blue-600 dark:text-blue-500" />
+ );
+ }
+ if (calendar.ownerId === user.id) {
+ return <User className="h-3.5 w-3.5 text-muted-foreground/60" />;
+ }
+ return <Users className="h-3.5 w-3.5 text-muted-foreground/60" />;
+ };
+
+ // Helper function to render calendar item
+ const renderCalendarItem = (calendar: CalendarWithCount) => {
+ // Check for admin/owner first
+ const isAdmin =
+ isAuthEnabled &&
+ (calendar.sharePermission === "admin" ||
+ calendar.sharePermission === "owner");
+
+ // Check if calendar is read-only
+ // Owner is never read-only, even if guestPermission is "read"
+ // Guests (no user) or non-owners see read-only based on permissions
+ // Priority: owner > sharePermission > tokenPermission > guestPermission
+ const isCalendarReadOnly =
+ isAuthEnabled &&
+ (!user || calendar.ownerId !== user.id) &&
+ (calendar.sharePermission === "read" ||
+ (!calendar.sharePermission && calendar.tokenPermission === "read") ||
+ (!calendar.sharePermission &&
+ !calendar.tokenPermission &&
+ calendar.guestPermission === "read"));
+
+ const icon = isAdmin ? (
+ <ShieldCheck className="h-3.5 w-3.5 text-blue-600 dark:text-blue-500 flex-shrink-0" />
+ ) : isCalendarReadOnly ? (
+ <Lock className="h-3.5 w-3.5 text-amber-600 dark:text-amber-500 flex-shrink-0" />
+ ) : (
+ getCalendarIcon(calendar)
+ );
+
+ return (
+ <SelectItem key={calendar.id} value={calendar.id}>
+ <div className="flex items-center gap-2.5 w-full">
+ {icon}
+ <div
+ className="w-3 h-3 rounded-full flex-shrink-0"
+ style={{ backgroundColor: calendar.color }}
+ />
+ <span className="flex-1 truncate">{calendar.name}</span>
+ </div>
+ </SelectItem>
+ );
+ };
// Desktop: Compact icon-based layout
if (variant === "desktop") {
@@ -53,25 +200,129 @@ export function CalendarSelector({
<div className="flex gap-2 items-center">
<Select value={selectedId} onValueChange={onSelect}>
<SelectTrigger className="flex-1 h-9 sm:h-10 text-sm">
- <SelectValue placeholder={t("calendar.title")} />
+ {selectedCalendar ? (
+ <div className="flex items-center gap-2 flex-1">
+ {isAuthEnabled &&
+ (selectedCalendar.sharePermission === "admin" ||
+ selectedCalendar.sharePermission === "owner" ? (
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <ShieldCheck className="h-3.5 w-3.5 text-blue-600 dark:text-blue-500 flex-shrink-0" />
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{t("common.labels.permissions.admin")}</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ ) : isReadOnly ? (
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Lock className="h-3.5 w-3.5 text-amber-600 dark:text-amber-500 flex-shrink-0" />
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{t("common.labels.permissions.read")}</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ ) : (
+ getCalendarIcon(selectedCalendar)
+ ))}
+ <div
+ className="w-3 h-3 rounded-full"
+ style={{ backgroundColor: selectedCalendar.color }}
+ />
+ <span className="truncate">{selectedCalendar.name}</span>
+ </div>
+ ) : (
+ <SelectValue placeholder={t("calendar.title")} />
+ )}
</SelectTrigger>
<SelectContent>
- {calendars.map((calendar) => (
- <SelectItem key={calendar.id} value={calendar.id}>
- <div className="flex items-center gap-2">
- <div
- className="w-3 h-3 rounded-full"
- style={{ backgroundColor: calendar.color }}
- />
- {calendar.name}
+ {/* Own Calendars */}
+ {isAuthEnabled && ownCalendars.length > 0 && (
+ <>
+ <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground flex items-center gap-1.5">
+ <User className="h-3 w-3" />
+ {t("calendar.myCalendars", { default: "Meine Kalender" })}
</div>
- </SelectItem>
- ))}
+ {ownCalendars.map(renderCalendarItem)}
+ </>
+ )}
+
+ {/* Shared Calendars */}
+ {isAuthEnabled && sharedCalendars.length > 0 && (
+ <>
+ {ownCalendars.length > 0 && <Separator className="my-1" />}
+ <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground flex items-center gap-1.5">
+ <Users className="h-3 w-3" />
+ {t("calendar.sharedCalendars", {
+ default: "Geteilte Kalender",
+ })}
+ </div>
+ {sharedCalendars.map(renderCalendarItem)}
+ </>
+ )}
+
+ {/* Token-accessible Calendars */}
+ {tokenCalendars.length > 0 && (
+ <>
+ {(ownCalendars.length > 0 || sharedCalendars.length > 0) && (
+ <Separator className="my-1" />
+ )}
+ <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground flex items-center gap-1.5">
+ <Globe className="h-3 w-3" />
+ {t("calendar.tokenCalendars", {
+ default: "Via Zugangslink",
+ })}
+ </div>
+ {tokenCalendars.map(renderCalendarItem)}
+ </>
+ )}
+
+ {/* Public Calendars (guestPermission subscribed by authenticated users) */}
+ {publicCalendars.length > 0 && (
+ <>
+ {(ownCalendars.length > 0 ||
+ sharedCalendars.length > 0 ||
+ tokenCalendars.length > 0) && <Separator className="my-1" />}
+ <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground flex items-center gap-1.5">
+ <Globe className="h-3 w-3" />
+ {t("calendar.publicCalendars", {
+ default: "Öffentliche Kalender",
+ })}
+ </div>
+ {publicCalendars.map(renderCalendarItem)}
+ </>
+ )}
+
+ {/* Guest Accessible Calendars (when auth disabled or user is guest) */}
+ {(!isAuthEnabled || isGuest) &&
+ guestAccessibleCalendars.length > 0 && (
+ <>{guestAccessibleCalendars.map(renderCalendarItem)}</>
+ )}
+
+ {!isGuest && (
+ <>
+ <Separator className="my-1" />
+ <div
+ onClick={(e) => {
+ e.stopPropagation();
+ onCreateNew();
+ }}
+ className="relative flex w-full cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
+ >
+ <Plus className="h-4 w-4 mr-2" />
+ {t("calendar.create")}
+ </div>
+ </>
+ )}
</SelectContent>
</Select>
- {onManagePassword && selectedId && (
+ {onSettings && selectedId && canManage && (
<Button
- onClick={onManagePassword}
+ onClick={onSettings}
size="icon"
variant="outline"
className="h-9 w-9 sm:h-10 sm:w-10"
@@ -79,21 +330,10 @@ export function CalendarSelector({
name: selectedCalendar?.name || "",
})}
>
- <CalendarCog className="h-4 w-4" />
- </Button>
- )}
- {onExternalSync && selectedId && !shouldHideSyncButtons && (
- <Button
- onClick={onExternalSync}
- size="icon"
- variant="outline"
- className="h-9 w-9 sm:h-10 sm:w-10"
- title={t("externalSync.manageTitle")}
- >
- <Cloud className="h-4 w-4" />
+ <Settings className="h-4 w-4" />
</Button>
)}
- {onSyncNotifications && selectedId && !shouldHideSyncButtons && (
+ {onSyncNotifications && selectedId && (
<Button
onClick={onSyncNotifications}
size="icon"
@@ -126,14 +366,6 @@ export function CalendarSelector({
<Copy className="h-4 w-4" />
</Button>
)}
- <Button
- onClick={onCreateNew}
- size="icon"
- variant="outline"
- className="h-9 w-9 sm:h-10 sm:w-10"
- >
- <Plus className="h-4 w-4" />
- </Button>
</div>
);
}
@@ -143,30 +375,116 @@ export function CalendarSelector({
<div className="flex flex-col gap-3">
{/* Calendar Dropdown - Full Width */}
<Select value={selectedId} onValueChange={onSelect}>
- <SelectTrigger className="h-10 text-sm">
- <SelectValue placeholder={t("calendar.title")} />
+ <SelectTrigger className="w-full h-10 text-sm">
+ {selectedCalendar ? (
+ <div className="flex items-center gap-2 flex-1">
+ {isAuthEnabled &&
+ (selectedCalendar.sharePermission === "admin" ||
+ selectedCalendar.sharePermission === "owner" ? (
+ <ShieldCheck className="h-3.5 w-3.5 text-blue-600 dark:text-blue-500 flex-shrink-0" />
+ ) : isReadOnly ? (
+ <Lock className="h-3.5 w-3.5 text-amber-600 dark:text-amber-500 flex-shrink-0" />
+ ) : (
+ getCalendarIcon(selectedCalendar)
+ ))}
+ <div
+ className="w-3 h-3 rounded-full"
+ style={{ backgroundColor: selectedCalendar.color }}
+ />
+ <span className="truncate">{selectedCalendar.name}</span>
+ </div>
+ ) : (
+ <SelectValue placeholder={t("calendar.title")} />
+ )}
</SelectTrigger>
<SelectContent>
- {calendars.map((calendar) => (
- <SelectItem key={calendar.id} value={calendar.id}>
- <div className="flex items-center gap-2">
- <div
- className="w-3 h-3 rounded-full"
- style={{ backgroundColor: calendar.color }}
- />
- {calendar.name}
+ {/* Own Calendars */}
+ {isAuthEnabled && ownCalendars.length > 0 && (
+ <>
+ <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground flex items-center gap-1.5">
+ <User className="h-3 w-3" />
+ {t("calendar.myCalendars", { default: "Meine Kalender" })}
</div>
- </SelectItem>
- ))}
+ {ownCalendars.map(renderCalendarItem)}
+ </>
+ )}
+
+ {/* Shared Calendars */}
+ {isAuthEnabled && sharedCalendars.length > 0 && (
+ <>
+ {ownCalendars.length > 0 && <Separator className="my-1" />}
+ <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground flex items-center gap-1.5">
+ <Users className="h-3 w-3" />
+ {t("calendar.sharedCalendars", {
+ default: "Geteilte Kalender",
+ })}
+ </div>
+ {sharedCalendars.map(renderCalendarItem)}
+ </>
+ )}
+
+ {/* Token-accessible Calendars */}
+ {tokenCalendars.length > 0 && (
+ <>
+ {(ownCalendars.length > 0 || sharedCalendars.length > 0) && (
+ <Separator className="my-1" />
+ )}
+ <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground flex items-center gap-1.5">
+ <Globe className="h-3 w-3" />
+ {t("calendar.tokenCalendars", {
+ default: "Via Zugangslink",
+ })}
+ </div>
+ {tokenCalendars.map(renderCalendarItem)}
+ </>
+ )}
+
+ {/* Public Calendars (guestPermission subscribed by authenticated users) */}
+ {publicCalendars.length > 0 && (
+ <>
+ {(ownCalendars.length > 0 ||
+ sharedCalendars.length > 0 ||
+ tokenCalendars.length > 0) && <Separator className="my-1" />}
+ <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground flex items-center gap-1.5">
+ <Globe className="h-3 w-3" />
+ {t("calendar.publicCalendars", {
+ default: "Öffentliche Kalender",
+ })}
+ </div>
+ {publicCalendars.map(renderCalendarItem)}
+ </>
+ )}
+
+ {/* Guest Accessible Calendars (when auth disabled or user is guest) */}
+ {(!isAuthEnabled || isGuest) &&
+ guestAccessibleCalendars.length > 0 && (
+ <>{guestAccessibleCalendars.map(renderCalendarItem)}</>
+ )}
+
+ {!isGuest && (
+ <>
+ <Separator className="my-1" />
+ <div
+ onClick={(e) => {
+ e.stopPropagation();
+ onCreateNew();
+ }}
+ className="relative flex w-full cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
+ >
+ <Plus className="h-4 w-4 mr-2" />
+ {t("calendar.create")}
+ </div>
+ </>
+ )}
</SelectContent>
</Select>
{/* Action Buttons - Even distribution */}
{selectedId && (
<div className="grid grid-cols-3 gap-2">
- {onManagePassword && (
+ {onSettings && canManage && (
<Button
- onClick={onManagePassword}
+ onClick={onSettings}
size="sm"
variant="outline"
className="h-9"
@@ -174,21 +492,10 @@ export function CalendarSelector({
name: selectedCalendar?.name || "",
})}
>
- <CalendarCog className="h-4 w-4" />
+ <Settings className="h-4 w-4" />
</Button>
)}
- {onExternalSync && !shouldHideSyncButtons && (
- <Button
- onClick={onExternalSync}
- size="sm"
- variant="outline"
- className="h-9"
- title={t("externalSync.manageTitle")}
- >
- <Cloud className="h-4 w-4" />
- </Button>
- )}
- {onSyncNotifications && !shouldHideSyncButtons && (
+ {onSyncNotifications && (
<Button
onClick={onSyncNotifications}
size="sm"
@@ -210,32 +517,18 @@ export function CalendarSelector({
)}
</Button>
)}
+ {onCompare && canCompare && (
+ <Button
+ onClick={onCompare}
+ size="sm"
+ variant="outline"
+ className="h-9"
+ >
+ <Copy className="h-4 w-4 mr-2" />
+ </Button>
+ )}
</div>
)}
-
- {/* Compare and Create Buttons */}
- <div className="grid grid-cols-2 gap-2">
- {onCompare && canCompare && (
- <Button
- onClick={onCompare}
- size="sm"
- variant="outline"
- className="h-9"
- >
- <Copy className="h-4 w-4 mr-2" />
- {t("calendar.compare")}
- </Button>
- )}
- <Button
- onClick={onCreateNew}
- size="sm"
- variant="outline"
- className={`h-9 ${canCompare && onCompare ? "" : "col-span-2"}`}
- >
- <Plus className="h-4 w-4 mr-2" />
- {t("common.create")}
- </Button>
- </div>
</div>
);
}
diff --git a/components/calendar-settings-sheet.tsx b/components/calendar-settings-sheet.tsx
index ffb5ac1..0ba8e35 100644
--- a/components/calendar-settings-sheet.tsx
+++ b/components/calendar-settings-sheet.tsx
@@ -14,15 +14,15 @@ import {
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
-import { Checkbox } from "@/components/ui/checkbox";
import { ColorPicker } from "@/components/ui/color-picker";
-import { getCachedPassword } from "@/lib/password-cache";
+import { CalendarShareManagementSheet } from "@/components/calendar-share-management-sheet";
import { useCalendars } from "@/hooks/useCalendars";
+import { useCalendarPermission } from "@/hooks/useCalendarPermission";
+import { useAuthFeatures } from "@/hooks/useAuthFeatures";
import { PRESET_COLORS } from "@/lib/constants";
-import { AlertTriangle, Trash2, Download } from "lucide-react";
+import { AlertTriangle, Trash2, Download, Cloud, Users } from "lucide-react";
import { ExportDialog } from "@/components/export-dialog";
import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
-import { toast } from "sonner";
import { useDirtyState } from "@/hooks/useDirtyState";
interface CalendarSettingsSheetProps {
@@ -31,17 +31,15 @@ interface CalendarSettingsSheetProps {
calendarId: string;
calendarName: string;
calendarColor: string;
- hasPassword: boolean;
- isLocked: boolean;
+ calendarGuestPermission?: "none" | "read" | "write";
onSuccess: () => void;
- onDelete: (password?: string) => void;
+ onDelete: () => void;
+ onExternalSync?: () => void;
}
interface FormState {
name: string;
selectedColor: string;
- lockCalendar: boolean;
- removePassword: boolean;
}
export function CalendarSettingsSheet({
@@ -50,32 +48,24 @@ export function CalendarSettingsSheet({
calendarId,
calendarName,
calendarColor,
- hasPassword,
- isLocked,
+ calendarGuestPermission = "none",
onSuccess,
onDelete,
+ onExternalSync,
}: CalendarSettingsSheetProps) {
const t = useTranslations();
const { updateCalendar } = useCalendars();
+ const { canShare, canManage, canDelete } = useCalendarPermission(calendarId);
+ const { isAuthEnabled } = useAuthFeatures();
// Use props directly as initial state, controlled by key prop on component
const [name, setName] = useState(calendarName);
const [selectedColor, setSelectedColor] = useState(calendarColor);
- const [currentPassword, setCurrentPassword] = useState("");
- const [newPassword, setNewPassword] = useState("");
- const [confirmPassword, setConfirmPassword] = useState("");
- const [removePassword, setRemovePassword] = useState(false);
- const [lockCalendar, setLockCalendar] = useState(isLocked);
const [loading, setLoading] = useState(false);
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [showExportDialog, setShowExportDialog] = useState(false);
- const [passwordError, setPasswordError] = useState(false);
+ const [showShareManagement, setShowShareManagement] = useState(false);
const initialFormStateRef = useRef<FormState | null>(null);
- const currentPasswordRef = useRef<HTMLInputElement>(null);
-
- // Calculate export permission based on password state (no useEffect needed)
- const canExport =
- !hasPassword || !isLocked || !!getCachedPassword(calendarId);
// Initialize form state reference when opening
useEffect(() => {
@@ -83,14 +73,12 @@ export function CalendarSettingsSheet({
initialFormStateRef.current = {
name: calendarName,
selectedColor: calendarColor,
- lockCalendar: isLocked,
- removePassword: false,
};
}
if (!open) {
initialFormStateRef.current = null;
}
- }, [open, calendarName, calendarColor, isLocked]);
+ }, [open, calendarName, calendarColor, calendarGuestPermission]);
const hasChanges = () => {
if (!initialFormStateRef.current) return false;
@@ -98,19 +86,12 @@ export function CalendarSettingsSheet({
const current: FormState = {
name,
selectedColor,
- lockCalendar,
- removePassword,
};
// Check basic fields
- const basicChanges =
- JSON.stringify(current) !== JSON.stringify(initialFormStateRef.current);
-
- // Check password fields
- const passwordChanges =
- newPassword.trim() !== "" || confirmPassword.trim() !== "";
-
- return basicChanges || passwordChanges;
+ return (
+ JSON.stringify(current) !== JSON.stringify(initialFormStateRef.current)
+ );
};
const {
@@ -125,41 +106,11 @@ export function CalendarSettingsSheet({
});
const handleSubmit = async () => {
- // Always require current password when calendar has password
- if (hasPassword && !currentPassword) {
- setPasswordError(true);
- toast.error(t("validation.passwordRequired"));
- currentPasswordRef.current?.focus();
- return;
- }
-
- // Validate new password fields if changing password
- const isChangingPassword = !removePassword && newPassword;
- if (isChangingPassword) {
- if (newPassword !== confirmPassword) {
- toast.error(t("validation.passwordMatch"));
- return;
- }
- }
-
- // If trying to lock without password
- if (lockCalendar && removePassword) {
- toast.error(t("calendar.lockRequiresPassword"));
- return;
- }
-
setLoading(true);
const updates = {
name: name !== calendarName ? name : undefined,
color: selectedColor !== calendarColor ? selectedColor : undefined,
- currentPassword: hasPassword ? currentPassword : undefined,
- isLocked: lockCalendar,
- password: removePassword
- ? (null as null)
- : newPassword
- ? newPassword
- : undefined,
};
const result = await updateCalendar(calendarId, updates);
@@ -169,21 +120,19 @@ export function CalendarSettingsSheet({
if (result.success) {
onSuccess();
onOpenChange(false);
- } else if (result.error === "unauthorized") {
- setPasswordError(true);
- currentPasswordRef.current?.focus();
}
};
const handleDelete = () => {
- if (hasPassword && !currentPassword) {
- toast.error(t("validation.passwordRequired"));
- return;
- }
- onDelete(hasPassword ? currentPassword : undefined);
+ onDelete();
onOpenChange(false);
};
+ // Only owner/admin can access settings
+ if (!canManage) {
+ return null;
+ }
+
return (
<>
<Sheet open={open} onOpenChange={handleClose}>
@@ -201,21 +150,6 @@ export function CalendarSettingsSheet({
</SheetHeader>
<div className="flex-1 overflow-y-auto px-6 py-6 space-y-6">
- {/* Password Required Notice */}
- {hasPassword && (
- <div className="p-4 bg-primary/10 border border-primary/20 rounded-xl space-y-2">
- <div className="flex items-center gap-2 text-primary">
- <AlertTriangle className="h-5 w-5" />
- <span className="font-semibold text-sm">
- {t("calendar.passwordProtected")}
- </span>
- </div>
- <p className="text-xs text-muted-foreground">
- {t("calendar.passwordRequiredToEdit")}
- </p>
- </div>
- )}
-
{/* Calendar Name */}
<div className="space-y-2.5">
<Label
@@ -223,7 +157,7 @@ export function CalendarSettingsSheet({
className="text-sm font-medium flex items-center gap-2"
>
<div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>
- {t("form.nameLabel")}
+ {t("common.labels.name")}
</Label>
<Input
id="calendarName"
@@ -246,221 +180,112 @@ export function CalendarSettingsSheet({
presetColors={PRESET_COLORS}
/>
- {/* Password Section */}
- <div className="space-y-4 pt-2">
- <div className="flex items-center gap-2 text-sm font-semibold">
- <div className="flex-1 h-px bg-border"></div>
- <span>{t("password.management")}</span>
- <div className="flex-1 h-px bg-border"></div>
- </div>
-
- {hasPassword && (
- <div className="space-y-4 p-4 bg-muted/30 rounded-xl border border-border/30">
- <div className="space-y-2.5">
- <Label
- htmlFor="currentPassword"
- className="text-sm font-medium flex items-center gap-2"
- >
- <div className="w-1 h-4 bg-gradient-to-b from-amber-500 to-amber-600 rounded-full"></div>
- {t("password.currentPassword")}
- <span className="text-xs text-destructive">*</span>
- </Label>
- <Input
- ref={currentPasswordRef}
- id="currentPassword"
- type="password"
- value={currentPassword}
- onChange={(e) => {
- setCurrentPassword(e.target.value);
- setPasswordError(false);
- }}
- placeholder={t("password.currentPasswordPlaceholder")}
- className={`h-11 bg-background ${
- passwordError
- ? "border-destructive focus:border-destructive focus:ring-destructive/20"
- : "border-amber-500/30 focus:border-amber-500/50 focus:ring-amber-500/20"
- }`}
- />
- {passwordError ? (
- <p className="text-xs text-destructive">
- {t("validation.passwordRequired")}
- </p>
- ) : (
- <p className="text-xs text-muted-foreground">
- {t("calendar.currentPasswordRequired")}
- </p>
- )}
- </div>
-
- <div className="flex items-center space-x-2 pt-2">
- <Checkbox
- id="removePassword"
- checked={removePassword}
- onCheckedChange={(checked: boolean) => {
- const isChecked = !!checked;
- setRemovePassword(isChecked);
- // Automatically unlock if removing password
- if (isChecked) {
- setLockCalendar(false);
- }
- }}
- />
- <Label
- htmlFor="removePassword"
- className="text-sm font-medium cursor-pointer"
- >
- {t("password.removePassword")}
- </Label>
- </div>
-
- {!removePassword && (
- <div className="flex items-center space-x-2 pt-2">
- <Checkbox
- id="lockCalendar"
- checked={lockCalendar}
- onCheckedChange={(checked: boolean) =>
- setLockCalendar(!!checked)
- }
- />
- <div className="flex-1">
- <Label
- htmlFor="lockCalendar"
- className="text-sm font-medium cursor-pointer"
- >
- {t("calendar.lockCalendar")}
- </Label>
- <p className="text-xs text-muted-foreground mt-0.5">
- {t("calendar.lockCalendarHint")}
- </p>
- </div>
- </div>
- )}
+ {/* External Sync Section */}
+ {onExternalSync && (
+ <div className="pt-4 mt-4 border-t border-border/50">
+ <div className="space-y-2.5">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={onExternalSync}
+ className="w-full h-11 border-primary/30 hover:bg-primary/10 hover:border-primary/50"
+ >
+ <Cloud className="h-4 w-4 mr-2" />
+ {t("externalSync.manageTitle")}
+ </Button>
</div>
- )}
-
- {!removePassword && (
- <motion.div
- initial={{ opacity: 0, height: 0 }}
- animate={{ opacity: 1, height: "auto" }}
- exit={{ opacity: 0, height: 0 }}
- transition={{ duration: 0.2 }}
- className="space-y-4"
- >
- <div className="space-y-2.5">
- <Label
- htmlFor="newPassword"
- className="text-sm font-medium flex items-center gap-2"
- >
- <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>
- {hasPassword
- ? t("password.newPassword")
- : t("form.passwordLabel")}
- </Label>
- <Input
- id="newPassword"
- type="password"
- value={newPassword}
- onChange={(e) => setNewPassword(e.target.value)}
- placeholder={t("password.newPasswordPlaceholder")}
- className="h-11 border-primary/30 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
- />
- </div>
+ </div>
+ )}
- <div className="space-y-2.5">
- <Label
- htmlFor="confirmPassword"
- className="text-sm font-medium flex items-center gap-2"
- >
- <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>
- {t("password.confirmPassword")}
- </Label>
- <Input
- id="confirmPassword"
- type="password"
- value={confirmPassword}
- onChange={(e) => setConfirmPassword(e.target.value)}
- placeholder={t("password.confirmPasswordPlaceholder")}
- className="h-11 border-primary/30 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
- />
- </div>
- </motion.div>
- )}
+ {/* Export Section */}
+ <div className="pt-4 mt-4 border-t border-border/50">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => setShowExportDialog(true)}
+ className="w-full h-11 border-primary/30 hover:bg-primary/10 hover:border-primary/50"
+ >
+ <Download className="h-4 w-4 mr-2" />
+ {t("export.exportCalendar")}
+ </Button>
</div>
- {/* Export Section */}
- {canExport && (
+ {/* Manage Sharing Section */}
+ {isAuthEnabled && canShare && (
<div className="pt-4 mt-4 border-t border-border/50">
<Button
type="button"
variant="outline"
- onClick={() => setShowExportDialog(true)}
+ onClick={() => setShowShareManagement(true)}
className="w-full h-11 border-primary/30 hover:bg-primary/10 hover:border-primary/50"
>
- <Download className="h-4 w-4 mr-2" />
- {t("export.exportCalendar")}
+ <Users className="h-4 w-4 mr-2" />
+ {t("share.manageSharing")}
</Button>
</div>
)}
{/* Delete Section */}
- <div className="pt-4 mt-4 border-t border-border/50">
- <div className="space-y-3">
- {!showDeleteConfirm ? (
- <Button
- type="button"
- variant="outline"
- onClick={() => setShowDeleteConfirm(true)}
- className="w-full h-11 border-destructive/30 text-destructive hover:bg-destructive/10 hover:border-destructive/50"
- >
- <Trash2 className="h-4 w-4 mr-2" />
- {t("calendar.deleteCalendar")}
- </Button>
- ) : (
- <motion.div
- initial={{ opacity: 0, height: 0 }}
- animate={{ opacity: 1, height: "auto" }}
- exit={{ opacity: 0, height: 0 }}
- className="space-y-3"
- >
- <div className="p-3 bg-destructive/5 rounded-lg border border-destructive/20">
- <div className="flex items-start gap-2.5 text-destructive mb-2">
- <AlertTriangle className="h-5 w-5 flex-shrink-0 mt-0.5" />
- <div className="flex-1 space-y-1">
- <p className="text-sm font-semibold">
- {t("common.deleteConfirm", {
- item: t("calendar.title"),
- name: calendarName,
- })}
- </p>
- <p className="text-xs text-muted-foreground">
- {t("calendar.deleteWarning")}
- </p>
+ {canDelete && (
+ <div className="pt-4 mt-4 border-t border-border/50">
+ <div className="space-y-3">
+ {!showDeleteConfirm ? (
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => setShowDeleteConfirm(true)}
+ className="w-full h-11 border-destructive/30 text-destructive hover:bg-destructive/10 hover:border-destructive/50"
+ >
+ <Trash2 className="h-4 w-4 mr-2" />
+ {t("calendar.deleteCalendar")}
+ </Button>
+ ) : (
+ <motion.div
+ initial={{ opacity: 0, height: 0 }}
+ animate={{ opacity: 1, height: "auto" }}
+ exit={{ opacity: 0, height: 0 }}
+ className="space-y-3"
+ >
+ <div className="p-3 bg-destructive/5 rounded-lg border border-destructive/20">
+ <div className="flex items-start gap-2.5 text-destructive mb-2">
+ <AlertTriangle className="h-5 w-5 flex-shrink-0 mt-0.5" />
+ <div className="flex-1 space-y-1">
+ <p className="text-sm font-semibold">
+ {t("common.deleteConfirm", {
+ item: t("calendar.title"),
+ name: calendarName,
+ })}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {t("calendar.deleteWarning")}
+ </p>
+ </div>
</div>
</div>
- </div>
- <div className="flex gap-2">
- <Button
- type="button"
- variant="outline"
- onClick={() => setShowDeleteConfirm(false)}
- className="flex-1 h-11"
- >
- {t("common.cancel")}
- </Button>
- <Button
- type="button"
- variant="destructive"
- onClick={handleDelete}
- className="flex-1 h-11 shadow-lg shadow-destructive/25"
- >
- <Trash2 className="h-4 w-4 mr-2" />
- {t("common.delete")}
- </Button>
- </div>
- </motion.div>
- )}
+ <div className="flex gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => setShowDeleteConfirm(false)}
+ className="flex-1 h-11"
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ type="button"
+ variant="destructive"
+ onClick={handleDelete}
+ className="flex-1 h-11 shadow-lg shadow-destructive/25"
+ >
+ <Trash2 className="h-4 w-4 mr-2" />
+ {t("common.delete")}
+ </Button>
+ </div>
+ </motion.div>
+ )}
+ </div>
</div>
- </div>
+ )}
</div>
<SheetFooter className="border-t border-border/50 bg-muted/20 px-6 py-4 mt-auto">
@@ -499,6 +324,15 @@ export function CalendarSettingsSheet({
onOpenChange={setShowConfirmDialog}
onConfirm={handleConfirmClose}
/>
+
+ <CalendarShareManagementSheet
+ open={showShareManagement}
+ onOpenChange={setShowShareManagement}
+ calendarId={calendarId}
+ calendarName={calendarName}
+ calendarGuestPermission={calendarGuestPermission}
+ canManageShares={canShare}
+ />
</>
);
}
diff --git a/components/calendar-share-list.tsx b/components/calendar-share-list.tsx
new file mode 100644
index 0000000..b6c6a9f
--- /dev/null
+++ b/components/calendar-share-list.tsx
@@ -0,0 +1,308 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { useTranslations } from "next-intl";
+import { format } from "date-fns";
+import { UserPlus, MoreVertical, Trash2, Shield } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
+import { CalendarShareUserSearch } from "@/components/calendar-share-user-search";
+import {
+ useCalendarShares,
+ type CalendarShare,
+} from "@/hooks/useCalendarShares";
+import { useAuth } from "@/hooks/useAuth";
+import { useCalendarPermission } from "@/hooks/useCalendarPermission";
+import { getDateLocale } from "@/lib/locales";
+import { useLocale } from "next-intl";
+
+interface CalendarShareListProps {
+ calendarId: string;
+ canManageShares: boolean;
+}
+
+export function CalendarShareList({
+ calendarId,
+ canManageShares,
+}: CalendarShareListProps) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const { user: currentUser } = useAuth();
+ const { isOwner } = useCalendarPermission(calendarId);
+ const { shares, fetchShares, updateShare, removeShare } =
+ useCalendarShares(calendarId);
+
+ const [showAddUser, setShowAddUser] = useState(false);
+ const [shareToDelete, setShareToDelete] = useState<CalendarShare | null>(
+ null
+ );
+
+ useEffect(() => {
+ fetchShares();
+ }, [fetchShares]);
+
+ const getUserInitials = (share: CalendarShare) => {
+ if (share.user.name) {
+ return share.user.name
+ .split(" ")
+ .map((n) => n[0])
+ .join("")
+ .toUpperCase()
+ .slice(0, 2);
+ }
+ return share.user.email.slice(0, 2).toUpperCase();
+ };
+
+ const getPermissionBadgeClass = (permission: string) => {
+ switch (permission) {
+ case "owner":
+ return "bg-purple-500/10 text-purple-500 border-purple-500/20";
+ case "admin":
+ return "bg-orange-500/10 text-orange-500 border-orange-500/20";
+ case "write":
+ return "bg-blue-500/10 text-blue-500 border-blue-500/20";
+ case "read":
+ return "bg-green-500/10 text-green-500 border-green-500/20";
+ default:
+ return "bg-muted text-muted-foreground";
+ }
+ };
+
+ const handlePermissionChange = async (
+ shareId: string,
+ newPermission: "admin" | "write" | "read"
+ ) => {
+ await updateShare(shareId, newPermission);
+ };
+
+ const handleRemoveShare = async () => {
+ if (!shareToDelete) return;
+ await removeShare(shareToDelete.id);
+ setShareToDelete(null);
+ };
+
+ const isSelf = (share: CalendarShare) => share.userId === currentUser?.id;
+
+ return (
+ <>
+ <div className="space-y-4">
+ {/* Header */}
+ <div className="flex items-center justify-between">
+ <div>
+ <p className="text-sm font-medium">
+ {t("share.userShares")} ({shares.length})
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {t("share.userSharesDescription")}
+ </p>
+ </div>
+ {canManageShares && (
+ <Button
+ onClick={() => setShowAddUser(true)}
+ size="sm"
+ className="gap-2"
+ >
+ <UserPlus className="h-4 w-4" />
+ {t("common.add")}
+ </Button>
+ )}
+ </div>
+
+ {/* Shares Table */}
+ {shares.length === 0 ? (
+ <div className="border rounded-lg p-8 text-center">
+ <div className="flex flex-col items-center gap-3">
+ <div className="h-12 w-12 rounded-full bg-muted flex items-center justify-center">
+ <Shield className="h-6 w-6 text-muted-foreground" />
+ </div>
+ <div>
+ <p className="text-sm font-medium">{t("share.noShares")}</p>
+ <p className="text-xs text-muted-foreground mt-1">
+ {t("share.noSharesDescription")}
+ </p>
+ </div>
+ {canManageShares && (
+ <Button
+ onClick={() => setShowAddUser(true)}
+ size="sm"
+ className="gap-2 mt-2"
+ >
+ <UserPlus className="h-4 w-4" />
+ {t("share.addUser")}
+ </Button>
+ )}
+ </div>
+ </div>
+ ) : (
+ <div className="border rounded-lg overflow-hidden">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>{t("common.labels.user")}</TableHead>
+ <TableHead>{t("common.labels.permission")}</TableHead>
+ <TableHead>{t("share.sharedBy")}</TableHead>
+ <TableHead>{t("share.sharedOn")}</TableHead>
+ {canManageShares && (
+ <TableHead className="w-[50px]"></TableHead>
+ )}
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {shares.map((share) => (
+ <TableRow key={share.id}>
+ <TableCell>
+ <div className="flex items-center gap-3">
+ <Avatar className="h-8 w-8">
+ {share.user.image && (
+ <AvatarImage src={share.user.image} />
+ )}
+ <AvatarFallback className="text-xs">
+ {getUserInitials(share)}
+ </AvatarFallback>
+ </Avatar>
+ <div className="min-w-0">
+ <p className="text-sm font-medium truncate">
+ {share.user.name || share.user.email}
+ {isSelf(share) && (
+ <span className="ml-2 text-xs text-muted-foreground">
+ ({t("share.you")})
+ </span>
+ )}
+ </p>
+ {share.user.name && (
+ <p className="text-xs text-muted-foreground truncate">
+ {share.user.email}
+ </p>
+ )}
+ </div>
+ </div>
+ </TableCell>
+ <TableCell>
+ {canManageShares &&
+ !isSelf(share) &&
+ (isOwner || share.permission !== "admin") ? (
+ <Select
+ value={share.permission}
+ onValueChange={(value) =>
+ handlePermissionChange(
+ share.id,
+ value as "admin" | "write" | "read"
+ )
+ }
+ >
+ <SelectTrigger className="w-[140px] h-8">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="read">
+ {t("common.labels.permissions.read")}
+ </SelectItem>
+ <SelectItem value="write">
+ {t("common.labels.permissions.write")}
+ </SelectItem>
+ {isOwner && (
+ <SelectItem value="admin">
+ {t("common.labels.permissions.admin")}
+ </SelectItem>
+ )}
+ </SelectContent>
+ </Select>
+ ) : (
+ <span
+ className={`inline-flex items-center px-2 py-1 rounded-md text-xs font-medium border ${getPermissionBadgeClass(
+ share.permission
+ )}`}
+ >
+ {t(`common.labels.permissions.${share.permission}`)}
+ </span>
+ )}
+ </TableCell>
+ <TableCell>
+ <p className="text-sm truncate">
+ {share.sharedByUser.name || share.sharedByUser.email}
+ </p>
+ </TableCell>
+ <TableCell>
+ <p className="text-sm text-muted-foreground">
+ {format(new Date(share.createdAt), "PP", {
+ locale: getDateLocale(locale),
+ })}
+ </p>
+ </TableCell>
+ {canManageShares &&
+ (isOwner || share.permission !== "admin") && (
+ <TableCell>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="sm">
+ <MoreVertical className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ onClick={() => setShareToDelete(share)}
+ className="text-destructive"
+ >
+ <Trash2 className="h-4 w-4 mr-2" />
+ {t("share.removeAccess")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ )}
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+ )}
+ </div>
+
+ {/* Add User Dialog */}
+ <CalendarShareUserSearch
+ open={showAddUser}
+ onOpenChange={setShowAddUser}
+ calendarId={calendarId}
+ onSuccess={fetchShares}
+ />
+
+ {/* Remove Confirmation */}
+ {shareToDelete && (
+ <ConfirmationDialog
+ open={!!shareToDelete}
+ onOpenChange={(open) => !open && setShareToDelete(null)}
+ onConfirm={handleRemoveShare}
+ title={t("share.removeShareConfirmTitle")}
+ description={t("share.removeShareConfirmDesc", {
+ user: shareToDelete.user.name || shareToDelete.user.email,
+ })}
+ confirmVariant="destructive"
+ confirmText={t("common.delete")}
+ cancelText={t("common.cancel")}
+ />
+ )}
+ </>
+ );
+}
diff --git a/components/calendar-share-management-sheet.tsx b/components/calendar-share-management-sheet.tsx
new file mode 100644
index 0000000..90da5f6
--- /dev/null
+++ b/components/calendar-share-management-sheet.tsx
@@ -0,0 +1,174 @@
+"use client";
+
+import { useState } from "react";
+import { useTranslations } from "next-intl";
+import { Users, Shield, Link as LinkIcon } from "lucide-react";
+import {
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+ SheetDescription,
+ SheetFooter,
+} from "@/components/ui/sheet";
+import { Button } from "@/components/ui/button";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { CalendarShareList } from "@/components/calendar-share-list";
+import { CalendarTokenList } from "@/components/calendar-token-list";
+import { GuestPermissionSelector } from "@/components/guest-permission-selector";
+import { useCalendars } from "@/hooks/useCalendars";
+import { useAuthFeatures } from "@/hooks/useAuthFeatures";
+
+interface CalendarShareManagementSheetProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ calendarId: string;
+ calendarName: string;
+ calendarGuestPermission?: "none" | "read" | "write";
+ canManageShares: boolean; // owner/admin permission
+}
+
+export function CalendarShareManagementSheet({
+ open,
+ onOpenChange,
+ calendarId,
+ calendarName,
+ calendarGuestPermission = "none",
+ canManageShares,
+}: CalendarShareManagementSheetProps) {
+ const t = useTranslations();
+ const { updateCalendar } = useCalendars();
+ const { isAuthEnabled } = useAuthFeatures();
+
+ const [activeTab, setActiveTab] = useState("users");
+ const [guestPermission, setGuestPermission] = useState<
+ "none" | "read" | "write"
+ >(calendarGuestPermission);
+ const [saving, setSaving] = useState(false);
+
+ // Show public access tab when auth is enabled (allows sharing with authenticated users via guestPermission)
+ // This is separate from allowGuest which controls unauthenticated access
+ const showGuestTab = isAuthEnabled;
+
+ const handleGuestPermissionChange = async (
+ value: "none" | "read" | "write"
+ ) => {
+ if (!canManageShares) return;
+
+ setGuestPermission(value);
+ setSaving(true);
+
+ await updateCalendar(calendarId, {
+ guestPermission: value,
+ });
+
+ setSaving(false);
+ };
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent
+ side="right"
+ className="w-full sm:max-w-[700px] p-0 flex flex-col gap-0 border-l border-border/50 overflow-hidden"
+ >
+ <SheetHeader className="border-b border-border/50 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent px-6 pt-6 pb-5 space-y-1.5">
+ <SheetTitle className="text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text flex items-center gap-2">
+ <Users className="h-5 w-5" />
+ {t("share.manageSharing")}
+ </SheetTitle>
+ <SheetDescription className="text-sm text-muted-foreground">
+ {t("share.manageSharingDescription", { name: calendarName })}
+ </SheetDescription>
+ </SheetHeader>
+
+ <div className="flex-1 overflow-y-auto">
+ <Tabs
+ value={activeTab}
+ onValueChange={setActiveTab}
+ className="h-full"
+ >
+ <div className="border-b border-border/50 px-6 pt-4">
+ <TabsList className="w-full grid grid-cols-3">
+ <TabsTrigger value="users" className="gap-2">
+ <Users className="h-4 w-4" />
+ <span className="hidden sm:inline">
+ {t("share.userShares")}
+ </span>
+ <span className="sm:hidden">{t("common.labels.users")}</span>
+ </TabsTrigger>
+ {showGuestTab && (
+ <TabsTrigger value="public" className="gap-2">
+ <Shield className="h-4 w-4" />
+ <span className="hidden sm:inline">
+ {t("share.publicAccess")}
+ </span>
+ <span className="sm:hidden">{t("share.public")}</span>
+ </TabsTrigger>
+ )}
+ <TabsTrigger value="links" className="gap-2">
+ <LinkIcon className="h-4 w-4" />
+ <span className="hidden sm:inline">
+ {t("share.accessLinks")}
+ </span>
+ <span className="sm:hidden">{t("share.links")}</span>
+ </TabsTrigger>
+ </TabsList>
+ </div>
+
+ <div className="px-6 py-6">
+ {/* User Shares Tab */}
+ <TabsContent value="users" className="mt-0 space-y-0">
+ <CalendarShareList
+ calendarId={calendarId}
+ canManageShares={canManageShares}
+ />
+ </TabsContent>
+
+ {/* Public Access Tab */}
+ {showGuestTab && (
+ <TabsContent value="public" className="mt-0 space-y-4">
+ <div>
+ <p className="text-sm font-medium mb-1">
+ {t("share.publicAccess")}
+ </p>
+ <p className="text-xs text-muted-foreground mb-4">
+ {t("share.publicAccessDescription")}
+ </p>
+ </div>
+
+ <GuestPermissionSelector
+ value={guestPermission}
+ onChange={handleGuestPermissionChange}
+ idPrefix="share-management"
+ />
+
+ {saving && (
+ <p className="text-xs text-muted-foreground italic">
+ {t("common.saving")}
+ </p>
+ )}
+ </TabsContent>
+ )}
+
+ {/* Access Links Tab */}
+ <TabsContent value="links" className="mt-0">
+ <CalendarTokenList calendarId={calendarId} />
+ </TabsContent>
+ </div>
+ </Tabs>
+ </div>
+
+ <SheetFooter className="border-t border-border/50 bg-muted/20 px-6 py-4 mt-auto">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ className="h-11 border-border/50 hover:bg-muted/50"
+ >
+ {t("common.cancel")}
+ </Button>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ );
+}
diff --git a/components/calendar-share-user-search.tsx b/components/calendar-share-user-search.tsx
new file mode 100644
index 0000000..610e711
--- /dev/null
+++ b/components/calendar-share-user-search.tsx
@@ -0,0 +1,292 @@
+"use client";
+
+import { useState, useCallback, useMemo } from "react";
+import { useTranslations } from "next-intl";
+import { Search, UserPlus, X } from "lucide-react";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogDescription,
+ DialogFooter,
+} from "@/components/ui/dialog";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
+import { useCalendarShares, type SearchUser } from "@/hooks/useCalendarShares";
+import { useCalendarPermission } from "@/hooks/useCalendarPermission";
+
+interface CalendarShareUserSearchProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ calendarId: string;
+ onSuccess: () => void;
+}
+
+export function CalendarShareUserSearch({
+ open,
+ onOpenChange,
+ calendarId,
+ onSuccess,
+}: CalendarShareUserSearchProps) {
+ const t = useTranslations();
+ const { searchUsers, searchResults, searchLoading, addShare } =
+ useCalendarShares(calendarId);
+ const { isOwner } = useCalendarPermission(calendarId);
+
+ const [query, setQuery] = useState("");
+ const [selectedUser, setSelectedUser] = useState<SearchUser | null>(null);
+ const [permission, setPermission] = useState<"admin" | "write" | "read">(
+ "read"
+ );
+ const [loading, setLoading] = useState(false);
+
+ // Debounced search
+ const handleSearch = useCallback(
+ (value: string) => {
+ setQuery(value);
+ setSelectedUser(null);
+ const timeoutId = setTimeout(() => {
+ searchUsers(value);
+ }, 300);
+ return () => clearTimeout(timeoutId);
+ },
+ [searchUsers]
+ );
+
+ const handleSelectUser = (user: SearchUser) => {
+ setSelectedUser(user);
+ setQuery(user.name || user.email);
+ };
+
+ const handleAddShare = async () => {
+ if (!selectedUser) return;
+
+ setLoading(true);
+ const result = await addShare(selectedUser.id, permission);
+ setLoading(false);
+
+ if (result.success) {
+ setQuery("");
+ setSelectedUser(null);
+ setPermission("read");
+ onSuccess();
+ onOpenChange(false);
+ }
+ };
+
+ const handleClose = () => {
+ setQuery("");
+ setSelectedUser(null);
+ setPermission("read");
+ onOpenChange(false);
+ };
+
+ const getUserInitials = (user: SearchUser) => {
+ if (user.name) {
+ return user.name
+ .split(" ")
+ .map((n) => n[0])
+ .join("")
+ .toUpperCase()
+ .slice(0, 2);
+ }
+ return user.email.slice(0, 2).toUpperCase();
+ };
+
+ const showResults = useMemo(
+ () => query.length >= 2 && !selectedUser && searchResults.length > 0,
+ [query, selectedUser, searchResults]
+ );
+
+ return (
+ <Dialog open={open} onOpenChange={handleClose}>
+ <DialogContent className="sm:max-w-[500px]">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <UserPlus className="h-5 w-5" />
+ {t("share.addUser")}
+ </DialogTitle>
+ <DialogDescription>{t("share.addUserDescription")}</DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-4 py-4">
+ {/* User Search */}
+ <div className="space-y-2">
+ <Label htmlFor="user-search">{t("share.searchUser")}</Label>
+ <div className="relative">
+ <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
+ <Input
+ id="user-search"
+ type="text"
+ value={query}
+ onChange={(e) => handleSearch(e.target.value)}
+ placeholder={t("share.searchUserPlaceholder")}
+ className="pl-10 pr-10"
+ autoComplete="off"
+ />
+ {query && (
+ <button
+ type="button"
+ onClick={() => {
+ setQuery("");
+ setSelectedUser(null);
+ }}
+ className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
+ >
+ <X className="h-4 w-4" />
+ </button>
+ )}
+ </div>
+
+ {/* Search Results Dropdown */}
+ {showResults && (
+ <div className="border rounded-lg overflow-hidden bg-background shadow-lg">
+ <div className="max-h-[200px] overflow-y-auto">
+ {searchResults.map((user) => (
+ <button
+ key={user.id}
+ type="button"
+ onClick={() => handleSelectUser(user)}
+ className="w-full flex items-center gap-3 p-3 hover:bg-muted transition-colors text-left"
+ >
+ <Avatar className="h-8 w-8">
+ {user.image && <AvatarImage src={user.image} />}
+ <AvatarFallback className="text-xs">
+ {getUserInitials(user)}
+ </AvatarFallback>
+ </Avatar>
+ <div className="flex-1 min-w-0">
+ <p className="text-sm font-medium truncate">
+ {user.name || user.email}
+ </p>
+ {user.name && (
+ <p className="text-xs text-muted-foreground truncate">
+ {user.email}
+ </p>
+ )}
+ </div>
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Search Loading */}
+ {searchLoading && (
+ <p className="text-sm text-muted-foreground">
+ {t("common.loading")}
+ </p>
+ )}
+
+ {/* No Results */}
+ {query.length >= 2 &&
+ !selectedUser &&
+ searchResults.length === 0 &&
+ !searchLoading && (
+ <p className="text-sm text-muted-foreground">
+ {t("common.empty.noUsersFound")}
+ </p>
+ )}
+ </div>
+
+ {/* Selected User */}
+ {selectedUser && (
+ <div className="border rounded-lg p-3 bg-muted/50">
+ <p className="text-xs font-medium text-muted-foreground mb-2">
+ {t("share.selectedUser")}
+ </p>
+ <div className="flex items-center gap-3">
+ <Avatar className="h-10 w-10">
+ {selectedUser.image && (
+ <AvatarImage src={selectedUser.image} />
+ )}
+ <AvatarFallback>
+ {getUserInitials(selectedUser)}
+ </AvatarFallback>
+ </Avatar>
+ <div className="flex-1 min-w-0">
+ <p className="text-sm font-medium">
+ {selectedUser.name || selectedUser.email}
+ </p>
+ {selectedUser.name && (
+ <p className="text-xs text-muted-foreground">
+ {selectedUser.email}
+ </p>
+ )}
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Permission Selection */}
+ <div className="space-y-2">
+ <Label htmlFor="permission">{t("common.labels.permission")}</Label>
+ <Select
+ value={permission}
+ onValueChange={(value) =>
+ setPermission(value as "admin" | "write" | "read")
+ }
+ >
+ <SelectTrigger id="permission">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="read">
+ <div className="flex flex-col items-start">
+ <span className="font-medium">
+ {t("common.labels.permissions.read")}
+ </span>
+ </div>
+ </SelectItem>
+ <SelectItem value="write">
+ <div className="flex flex-col items-start">
+ <span className="font-medium">
+ {t("common.labels.permissions.write")}
+ </span>
+ </div>
+ </SelectItem>
+ {isOwner && (
+ <SelectItem value="admin">
+ <div className="flex flex-col items-start">
+ <span className="font-medium">
+ {t("common.labels.permissions.admin")}
+ </span>
+ </div>
+ </SelectItem>
+ )}
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={handleClose}
+ disabled={loading}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ type="button"
+ onClick={handleAddShare}
+ disabled={!selectedUser || loading}
+ >
+ {loading ? t("common.adding") : t("common.add")}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/components/calendar-sheet.tsx b/components/calendar-sheet.tsx
index 92df42d..4c1ef01 100644
--- a/components/calendar-sheet.tsx
+++ b/components/calendar-sheet.tsx
@@ -2,23 +2,16 @@
import { useState } from "react";
import { useTranslations } from "next-intl";
-import { motion } from "motion/react";
import { BaseSheet } from "@/components/ui/base-sheet";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
-import { Checkbox } from "@/components/ui/checkbox";
import { ColorPicker } from "@/components/ui/color-picker";
import { PRESET_COLORS } from "@/lib/constants";
interface CalendarSheetProps {
open: boolean;
onOpenChange: (open: boolean) => void;
- onSubmit: (
- name: string,
- color: string,
- password?: string,
- isLocked?: boolean
- ) => void | Promise<void>;
+ onSubmit: (name: string, color: string) => void | Promise<void>;
}
export function CalendarSheet({
@@ -30,63 +23,23 @@ export function CalendarSheet({
const initialColor = PRESET_COLORS[0].value;
const [name, setName] = useState("");
const [selectedColor, setSelectedColor] = useState(initialColor);
- const [password, setPassword] = useState("");
- const [confirmPassword, setConfirmPassword] = useState("");
- const [usePassword, setUsePassword] = useState(false);
- const [lockCalendar, setLockCalendar] = useState(false);
- const [error, setError] = useState("");
const [isSaving, setIsSaving] = useState(false);
const hasChanges = () => {
- return (
- name.trim() !== "" ||
- selectedColor !== initialColor ||
- (usePassword && password !== "") ||
- (usePassword && confirmPassword !== "")
- );
+ return name.trim() !== "" || selectedColor !== initialColor;
};
const resetForm = () => {
setName("");
setSelectedColor(initialColor);
- setPassword("");
- setConfirmPassword("");
- setUsePassword(false);
- setLockCalendar(false);
- setError("");
};
const handleSave = async () => {
- setError("");
-
if (!name.trim() || isSaving) return;
- // Validate password if enabled
- if (usePassword) {
- if (!password) {
- setError(t("validation.passwordRequired"));
- return;
- }
- if (password !== confirmPassword) {
- setError(t("validation.passwordMatch"));
- return;
- }
- }
-
- // Can't lock without password
- if (lockCalendar && !usePassword) {
- setError(t("calendar.lockRequiresPassword"));
- return;
- }
-
setIsSaving(true);
try {
- await onSubmit(
- name.trim(),
- selectedColor,
- usePassword && password ? password : undefined,
- lockCalendar
- );
+ await onSubmit(name.trim(), selectedColor);
// Reset form on success
resetForm();
@@ -138,85 +91,6 @@ export function CalendarSheet({
label={t("form.colorLabel")}
presetColors={PRESET_COLORS}
/>
-
- <div className="space-y-3 p-4 bg-primary/5 border border-primary/20 rounded-xl">
- <div className="flex items-center space-x-2">
- <Checkbox
- id="usePassword"
- checked={usePassword}
- onCheckedChange={(checked: boolean) => setUsePassword(!!checked)}
- />
- <Label
- htmlFor="usePassword"
- className="text-sm font-medium cursor-pointer flex items-center gap-2"
- >
- <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>
- {t("password.optional")}
- </Label>
- </div>
- {usePassword && (
- <motion.div
- initial={{ opacity: 0, height: 0 }}
- animate={{ opacity: 1, height: "auto" }}
- exit={{ opacity: 0, height: 0 }}
- transition={{ duration: 0.2 }}
- className="space-y-3 pt-1"
- >
- <div className="space-y-2">
- <Label htmlFor="password" className="text-sm">
- {t("form.passwordLabel")}
- </Label>
- <Input
- id="password"
- type="password"
- placeholder={t("form.passwordPlaceholder")}
- value={password}
- onChange={(e) => setPassword(e.target.value)}
- className="h-10 border-primary/30 focus:border-primary/50 focus:ring-primary/20 bg-background/80"
- />
- </div>
- <div className="space-y-2">
- <Label htmlFor="confirmPassword" className="text-sm">
- {t("password.confirmPassword")}
- </Label>
- <Input
- id="confirmPassword"
- type="password"
- placeholder={t("password.confirmPasswordPlaceholder")}
- value={confirmPassword}
- onChange={(e) => setConfirmPassword(e.target.value)}
- className="h-10 border-primary/30 focus:border-primary/50 focus:ring-primary/20 bg-background/80"
- />
- </div>
- <div className="flex items-center space-x-2 pt-1">
- <Checkbox
- id="lockCalendar"
- checked={lockCalendar}
- onCheckedChange={(checked: boolean) =>
- setLockCalendar(!!checked)
- }
- />
- <div className="flex-1">
- <Label
- htmlFor="lockCalendar"
- className="text-sm font-medium cursor-pointer"
- >
- {t("calendar.lockCalendar")}
- </Label>
- <p className="text-xs text-muted-foreground mt-0.5">
- {t("calendar.lockCalendarHint")}
- </p>
- </div>
- </div>
- </motion.div>
- )}
- </div>
-
- {error && (
- <p className="text-sm text-red-500 flex items-center gap-1.5 bg-red-500/10 p-3 rounded-lg border border-red-500/20">
- {error}
- </p>
- )}
</div>
</BaseSheet>
);
diff --git a/components/calendar-skeleton.tsx b/components/calendar-skeleton.tsx
deleted file mode 100644
index c52de07..0000000
--- a/components/calendar-skeleton.tsx
+++ /dev/null
@@ -1,79 +0,0 @@
-import { Skeleton } from "@/components/ui/skeleton";
-
-export function CalendarSkeleton() {
- return (
- <div className="min-h-screen flex flex-col">
- {/* Header Skeleton */}
- <div className="border-b border-border/50 bg-background/80 backdrop-blur-xl sticky top-0 z-50">
- <div className="container max-w-4xl mx-auto px-2 sm:px-4 py-3 sm:py-4">
- <div className="flex flex-col gap-3 sm:gap-4">
- {/* Top row with calendar and theme switchers */}
- <div className="flex items-center justify-between gap-2">
- <Skeleton className="h-10 w-48" />
- <div className="flex items-center gap-2">
- <Skeleton className="h-9 w-9 rounded-lg" />
- <Skeleton className="h-9 w-9 rounded-lg" />
- </div>
- </div>
-
- {/* Preset selector row */}
- <div className="flex flex-wrap gap-2">
- <Skeleton className="h-9 w-24" />
- <Skeleton className="h-9 w-32" />
- <Skeleton className="h-9 w-28" />
- <Skeleton className="h-9 w-9" />
- </div>
- </div>
- </div>
- </div>
-
- {/* Main Content */}
- <div className="container max-w-4xl mx-auto px-1 py-3 sm:p-4 flex-1">
- <div className="space-y-4">
- {/* Month Navigation Skeleton */}
- <div className="flex items-center justify-between mb-4">
- <Skeleton className="h-10 w-10 rounded-lg" />
- <Skeleton className="h-8 w-40" />
- <Skeleton className="h-10 w-10 rounded-lg" />
- </div>
-
- {/* Calendar Grid Skeleton */}
- <div className="grid grid-cols-7 gap-0 sm:gap-1.5 mb-6">
- {/* Weekday headers */}
- {Array.from({ length: 7 }).map((_, i) => (
- <Skeleton key={`header-${i}`} className="h-6 mx-1" />
- ))}
-
- {/* Calendar days */}
- {Array.from({ length: 35 }).map((_, i) => (
- <div
- key={`day-${i}`}
- className="min-h-24 sm:min-h-28 border border-border/30 rounded-lg p-1.5 sm:p-2 space-y-1"
- >
- <Skeleton className="h-5 w-6" />
- <Skeleton className="h-4 w-full" />
- <Skeleton className="h-4 w-3/4" />
- </div>
- ))}
- </div>
-
- {/* Stats and Shifts Skeleton */}
- <div className="space-y-4">
- <Skeleton className="h-32 w-full rounded-xl" />
- <Skeleton className="h-32 w-full rounded-xl" />
- </div>
- </div>
- </div>
-
- {/* Footer Skeleton */}
- <div className="border-t border-border/50 bg-background/80 backdrop-blur-xl">
- <div className="container max-w-4xl mx-auto px-2 sm:px-4 py-3 sm:py-4">
- <div className="flex flex-col sm:flex-row items-center justify-between gap-2">
- <Skeleton className="h-4 w-40" />
- <Skeleton className="h-4 w-32" />
- </div>
- </div>
- </div>
- </div>
- );
-}
diff --git a/components/calendar-token-badge.tsx b/components/calendar-token-badge.tsx
new file mode 100644
index 0000000..14f7767
--- /dev/null
+++ b/components/calendar-token-badge.tsx
@@ -0,0 +1,95 @@
+"use client";
+
+import { useTranslations } from "next-intl";
+import { Badge } from "@/components/ui/badge";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { Link as LinkIcon, Eye, Edit } from "lucide-react";
+
+interface CalendarTokenBadgeProps {
+ /**
+ * Token name (optional)
+ */
+ tokenName?: string | null;
+
+ /**
+ * Permission level granted by token
+ */
+ permission: "read" | "write";
+
+ /**
+ * Show full info or compact version
+ */
+ variant?: "full" | "compact";
+}
+
+/**
+ * Badge to indicate a calendar is being accessed via share link/token
+ * Shown in calendar header when user has token-based access
+ */
+export function CalendarTokenBadge({
+ tokenName,
+ permission,
+ variant = "full",
+}: CalendarTokenBadgeProps) {
+ const t = useTranslations();
+
+ if (variant === "compact") {
+ return (
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant="secondary" className="gap-1 cursor-help">
+ <LinkIcon className="h-3 w-3" />
+ {permission === "read" ? (
+ <Eye className="h-3 w-3" />
+ ) : (
+ <Edit className="h-3 w-3" />
+ )}
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>
+ <div className="space-y-1">
+ <p className="font-medium">{t("token.accessedViaLink")}</p>
+ {tokenName && (
+ <p className="text-xs text-muted-foreground">
+ {t("token.linkName")}: {tokenName}
+ </p>
+ )}
+ <p className="text-xs">
+ {permission === "read"
+ ? t("common.labels.permissions.read")
+ : t("common.labels.permissions.write")}
+ </p>
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ );
+ }
+
+ return (
+ <Badge variant="secondary" className="gap-1.5">
+ <LinkIcon className="h-3.5 w-3.5" />
+ <span>{t("token.accessedViaLink")}</span>
+ {permission === "read" ? (
+ <>
+ <Eye className="h-3.5 w-3.5" />
+ <span>{t("common.labels.permissions.read")}</span>
+ </>
+ ) : (
+ <>
+ <Edit className="h-3.5 w-3.5" />
+ <span>{t("common.labels.permissions.write")}</span>
+ </>
+ )}
+ {tokenName && (
+ <span className="text-muted-foreground">({tokenName})</span>
+ )}
+ </Badge>
+ );
+}
diff --git a/components/calendar-token-create-dialog.tsx b/components/calendar-token-create-dialog.tsx
new file mode 100644
index 0000000..79db723
--- /dev/null
+++ b/components/calendar-token-create-dialog.tsx
@@ -0,0 +1,304 @@
+"use client";
+
+import { useState } from "react";
+import { useTranslations } from "next-intl";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { format } from "date-fns";
+import { Copy, Check, AlertTriangle, Link as LinkIcon } from "lucide-react";
+import { useCalendarTokens } from "@/hooks/useCalendarTokens";
+import { Alert, AlertDescription } from "@/components/ui/alert";
+import { getDateLocale } from "@/lib/locales";
+import { useLocale } from "next-intl";
+
+interface CalendarTokenCreateDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ calendarId: string;
+ onSuccess?: () => void;
+}
+
+export function CalendarTokenCreateDialog({
+ open,
+ onOpenChange,
+ calendarId,
+ onSuccess,
+}: CalendarTokenCreateDialogProps) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const dateLocale = getDateLocale(locale);
+ const { createToken, getShareLink } = useCalendarTokens(calendarId);
+
+ const [step, setStep] = useState<"config" | "success">("config");
+ const [name, setName] = useState("");
+ const [permission, setPermission] = useState<"read" | "write">("read");
+ const [expiresAt, setExpiresAt] = useState<Date | undefined>(undefined);
+ const [isCreating, setIsCreating] = useState(false);
+ const [generatedToken, setGeneratedToken] = useState<string | null>(null);
+ const [shareLink, setShareLink] = useState<string | null>(null);
+ const [copied, setCopied] = useState(false);
+
+ // Helper function to check if a preset button should be highlighted
+ const isPresetActive = (days: number): boolean => {
+ if (!expiresAt) return false;
+ const now = new Date();
+ const targetDate = new Date(now.getTime() + days * 86400000);
+ return Math.abs(expiresAt.getTime() - targetDate.getTime()) < 3600000;
+ };
+
+ const handleCreate = async () => {
+ setIsCreating(true);
+
+ const token = await createToken({
+ name: name.trim() || undefined,
+ permission,
+ expiresAt: expiresAt?.toISOString() || null,
+ });
+
+ setIsCreating(false);
+
+ if (token && token.token) {
+ setGeneratedToken(token.token);
+ setShareLink(getShareLink(token.token));
+ setStep("success");
+ }
+ };
+
+ const handleCopyLink = async () => {
+ if (!shareLink) return;
+
+ try {
+ await navigator.clipboard.writeText(shareLink);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ } catch (error) {
+ console.error("Failed to copy:", error);
+ }
+ };
+
+ const handleClose = () => {
+ // Call onSuccess when closing after successful creation
+ if (step === "success") {
+ onSuccess?.();
+ }
+
+ // Reset state
+ setStep("config");
+ setName("");
+ setPermission("read");
+ setExpiresAt(undefined);
+ setGeneratedToken(null);
+ setShareLink(null);
+ setCopied(false);
+ onOpenChange(false);
+ };
+
+ const handleExpirationPreset = (days: number | null) => {
+ if (days === null) {
+ setExpiresAt(undefined);
+ } else {
+ const date = new Date();
+ date.setDate(date.getDate() + days);
+ setExpiresAt(date);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={handleClose}>
+ <DialogContent className="max-w-md">
+ {step === "config" && (
+ <>
+ <DialogHeader>
+ <DialogTitle>{t("token.createLink")}</DialogTitle>
+ <DialogDescription>
+ {t("token.createLinkDescription")}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-4 py-4">
+ {/* Name (Optional) */}
+ <div className="space-y-2">
+ <Label htmlFor="token-name">
+ {t("common.labels.name")} {t("common.optional")}
+ </Label>
+ <Input
+ id="token-name"
+ placeholder={t("token.namePlaceholder")}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ maxLength={50}
+ />
+ </div>
+
+ {/* Permission */}
+ <div className="space-y-2">
+ <Label htmlFor="token-permission">
+ {t("common.labels.permission")}
+ </Label>
+ <Select
+ value={permission}
+ onValueChange={(value: "read" | "write") =>
+ setPermission(value)
+ }
+ >
+ <SelectTrigger id="token-permission">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="read">
+ {t("common.labels.permissions.read")} -{" "}
+ {t("token.readOnlyDescription")}
+ </SelectItem>
+ <SelectItem value="write">
+ {t("common.labels.permissions.write")} -{" "}
+ {t("token.editDescription")}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
+ {/* Expiration */}
+ <div className="space-y-2">
+ <Label>{t("token.expiration")}</Label>
+ <div className="grid grid-cols-2 gap-2">
+ <Button
+ type="button"
+ variant={isPresetActive(1) ? "default" : "outline"}
+ size="sm"
+ onClick={() => handleExpirationPreset(1)}
+ >
+ {t("token.expiration1Day")}
+ </Button>
+ <Button
+ type="button"
+ variant={isPresetActive(7) ? "default" : "outline"}
+ size="sm"
+ onClick={() => handleExpirationPreset(7)}
+ >
+ {t("token.expiration7Days")}
+ </Button>
+ <Button
+ type="button"
+ variant={isPresetActive(30) ? "default" : "outline"}
+ size="sm"
+ onClick={() => handleExpirationPreset(30)}
+ >
+ {t("token.expiration30Days")}
+ </Button>
+ <Button
+ type="button"
+ variant={!expiresAt ? "default" : "outline"}
+ size="sm"
+ onClick={() => handleExpirationPreset(null)}
+ >
+ {t("token.expirationNever")}
+ </Button>
+ </div>
+ {expiresAt && (
+ <p className="text-xs text-muted-foreground mt-2">
+ {t("token.expiresOn")}:{" "}
+ {format(expiresAt, "PPP", { locale: dateLocale })}
+ </p>
+ )}
+ </div>
+ </div>
+
+ <DialogFooter>
+ <Button variant="outline" onClick={handleClose}>
+ {t("common.cancel")}
+ </Button>
+ <Button onClick={handleCreate} disabled={isCreating}>
+ {isCreating ? t("common.adding") : t("token.generate")}
+ </Button>
+ </DialogFooter>
+ </>
+ )}
+
+ {step === "success" && (
+ <>
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <Check className="h-5 w-5 text-green-500" />
+ {t("token.linkCreated")}
+ </DialogTitle>
+ <DialogDescription>
+ {t("token.linkCreatedDescription")}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-4 py-4">
+ {/* Warning */}
+ <Alert>
+ <AlertTriangle className="h-4 w-4" />
+ <AlertDescription>{t("token.saveWarning")}</AlertDescription>
+ </Alert>
+
+ {/* Share Link */}
+ <div className="space-y-2">
+ <Label>{t("token.shareLink")}</Label>
+ <div className="flex gap-2">
+ <Input
+ value={shareLink || ""}
+ readOnly
+ className="font-mono text-sm"
+ />
+ <Button
+ size="icon"
+ variant="outline"
+ onClick={handleCopyLink}
+ >
+ {copied ? (
+ <Check className="h-4 w-4" />
+ ) : (
+ <Copy className="h-4 w-4" />
+ )}
+ </Button>
+ </div>
+ </div>
+
+ {/* Token Preview */}
+ {generatedToken && (
+ <div className="space-y-2">
+ <Label>{t("token.tokenValue")}</Label>
+ <div className="p-3 bg-muted rounded-md font-mono text-xs break-all">
+ {generatedToken}
+ </div>
+ </div>
+ )}
+
+ {/* Info */}
+ <div className="text-sm text-muted-foreground space-y-1">
+ <div className="flex items-start gap-2">
+ <LinkIcon className="h-4 w-4 mt-0.5 flex-shrink-0" />
+ <span>{t("token.shareInfo")}</span>
+ </div>
+ </div>
+ </div>
+
+ <DialogFooter>
+ <Button onClick={handleClose} className="w-full">
+ {t("common.close")}
+ </Button>
+ </DialogFooter>
+ </>
+ )}
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/components/calendar-token-list.tsx b/components/calendar-token-list.tsx
new file mode 100644
index 0000000..0b6dad3
--- /dev/null
+++ b/components/calendar-token-list.tsx
@@ -0,0 +1,303 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { useTranslations } from "next-intl";
+import {
+ useCalendarTokens,
+ CalendarAccessToken,
+} from "@/hooks/useCalendarTokens";
+import { Button } from "@/components/ui/button";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { Badge } from "@/components/ui/badge";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { CalendarTokenCreateDialog } from "@/components/calendar-token-create-dialog";
+import {
+ Plus,
+ MoreVertical,
+ Eye,
+ EyeOff,
+ Trash2,
+ Link as LinkIcon,
+} from "lucide-react";
+import { formatDistanceToNow } from "date-fns";
+import { getDateLocale } from "@/lib/locales";
+import { useLocale } from "next-intl";
+
+interface CalendarTokenListProps {
+ calendarId: string;
+}
+
+export function CalendarTokenList({ calendarId }: CalendarTokenListProps) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const dateLocale = getDateLocale(locale);
+
+ const { tokens, fetchTokens, deleteToken, updateToken } =
+ useCalendarTokens(calendarId);
+
+ const [createDialogOpen, setCreateDialogOpen] = useState(false);
+ const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
+ const [tokenToDelete, setTokenToDelete] =
+ useState<CalendarAccessToken | null>(null);
+
+ useEffect(() => {
+ if (calendarId) {
+ void fetchTokens();
+ }
+ }, [calendarId, fetchTokens]);
+
+ const handleDelete = async () => {
+ if (!tokenToDelete) return;
+
+ const success = await deleteToken(tokenToDelete.id);
+ if (success) {
+ setDeleteDialogOpen(false);
+ setTokenToDelete(null);
+ }
+ };
+
+ const handleToggleActive = async (token: CalendarAccessToken) => {
+ await updateToken(token.id, {
+ isActive: !token.isActive,
+ });
+ };
+
+ return (
+ <div className="space-y-4">
+ {/* Header */}
+ <div className="flex items-center justify-between">
+ <div>
+ <p className="text-sm font-medium">
+ {t("token.accessLinks")} ({tokens.length})
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {t("token.accessLinksDescription")}
+ </p>
+ </div>
+ <Button
+ onClick={() => setCreateDialogOpen(true)}
+ size="sm"
+ className="gap-2"
+ >
+ <Plus className="h-4 w-4" />
+ {t("common.add")}
+ </Button>
+ </div>
+
+ {/* Token List */}
+ {tokens.length === 0 ? (
+ <div className="border rounded-lg p-8 text-center">
+ <div className="flex flex-col items-center gap-3">
+ <div className="h-12 w-12 rounded-full bg-muted flex items-center justify-center">
+ <LinkIcon className="h-6 w-6 text-muted-foreground" />
+ </div>
+ <div>
+ <p className="text-sm font-medium">{t("token.noTokensYet")}</p>
+ <p className="text-xs text-muted-foreground mt-1">
+ {t("token.noTokensDescription")}
+ </p>
+ </div>
+ <Button
+ onClick={() => setCreateDialogOpen(true)}
+ size="sm"
+ className="gap-2 mt-2"
+ >
+ <Plus className="h-4 w-4" />
+ {t("token.createFirstLink")}
+ </Button>
+ </div>
+ </div>
+ ) : (
+ <div className="border rounded-lg overflow-hidden">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>{t("common.labels.name")}</TableHead>
+ <TableHead>{t("token.token")}</TableHead>
+ <TableHead>{t("common.labels.permission")}</TableHead>
+ <TableHead>{t("token.expires")}</TableHead>
+ <TableHead>{t("token.usage")}</TableHead>
+ <TableHead>{t("common.labels.status")}</TableHead>
+ <TableHead className="w-[50px]"></TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {tokens.map((token) => (
+ <TableRow key={token.id}>
+ {/* Name */}
+ <TableCell className="font-medium">
+ {token.name || (
+ <span className="text-muted-foreground italic">
+ {t("token.unnamed")}
+ </span>
+ )}
+ </TableCell>
+
+ {/* Token Preview */}
+ <TableCell className="font-mono text-xs">
+ {token.tokenPreview}
+ </TableCell>
+
+ {/* Permission */}
+ <TableCell>
+ <Badge variant="secondary">
+ {token.permission === "read"
+ ? t("common.labels.permissions.read")
+ : t("common.labels.permissions.write")}
+ </Badge>
+ </TableCell>
+
+ {/* Expiration */}
+ <TableCell className="text-sm">
+ {token.expiresAt ? (
+ <span>
+ {new Date(token.expiresAt) < new Date() ? (
+ <span className="text-destructive">
+ {t("token.expired")}
+ </span>
+ ) : (
+ formatDistanceToNow(new Date(token.expiresAt), {
+ addSuffix: true,
+ locale: dateLocale,
+ })
+ )}
+ </span>
+ ) : (
+ <span className="text-muted-foreground">
+ {t("common.time.never")}
+ </span>
+ )}
+ </TableCell>
+
+ {/* Usage Stats */}
+ <TableCell className="text-sm">
+ <div className="space-y-0.5">
+ <div>
+ {t("token.usedCount", { count: token.usageCount })}
+ </div>
+ {token.lastUsedAt ? (
+ <div className="text-xs text-muted-foreground">
+ {" "}
+ {formatDistanceToNow(new Date(token.lastUsedAt), {
+ addSuffix: true,
+ locale: dateLocale,
+ })}
+ </div>
+ ) : (
+ <div className="text-xs text-muted-foreground">
+ {t("token.neverUsed")}
+ </div>
+ )}
+ </div>
+ </TableCell>
+
+ {/* Status */}
+ <TableCell>
+ <Badge variant={token.isActive ? "default" : "secondary"}>
+ {token.isActive
+ ? t("common.status.active")
+ : t("common.status.inactive")}
+ </Badge>
+ </TableCell>
+
+ {/* Actions */}
+ <TableCell>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="icon">
+ <MoreVertical className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ onClick={() => handleToggleActive(token)}
+ >
+ {token.isActive ? (
+ <>
+ <EyeOff className="h-4 w-4 mr-2" />
+ {t("token.disable")}
+ </>
+ ) : (
+ <>
+ <Eye className="h-4 w-4 mr-2" />
+ {t("token.enable")}
+ </>
+ )}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={() => {
+ setTokenToDelete(token);
+ setDeleteDialogOpen(true);
+ }}
+ className="text-destructive"
+ >
+ <Trash2 className="h-4 w-4 mr-2" />
+ {t("token.revoke")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+ )}
+
+ {/* Create Dialog */}
+ <CalendarTokenCreateDialog
+ open={createDialogOpen}
+ onOpenChange={setCreateDialogOpen}
+ calendarId={calendarId}
+ onSuccess={fetchTokens}
+ />
+
+ {/* Delete Confirmation */}
+ <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{t("token.revokeConfirm")}</AlertDialogTitle>
+ <AlertDialogDescription>
+ {t("token.revokeConfirmDescription", {
+ name: tokenToDelete?.name || t("token.unnamed"),
+ })}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={handleDelete}
+ className="bg-destructive"
+ >
+ {t("token.revoke")}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+}
diff --git a/components/changelog-dialog.tsx b/components/changelog-dialog.tsx
index 1c381b8..9ab660f 100644
--- a/components/changelog-dialog.tsx
+++ b/components/changelog-dialog.tsx
@@ -51,10 +51,25 @@ export function ChangelogDialog({
setLoading(true);
try {
const response = await fetch("/api/releases");
- if (response.ok) {
- const data = await response.json();
- setReleases(data);
+ if (!response.ok) {
+ console.error(
+ "Failed to fetch releases:",
+ response.status,
+ response.statusText
+ );
+ setLoading(false);
+ return;
+ }
+
+ const contentType = response.headers.get("content-type");
+ if (!contentType || !contentType.includes("application/json")) {
+ console.error("Invalid content type:", contentType);
+ setLoading(false);
+ return;
}
+
+ const data = await response.json();
+ setReleases(data);
} catch (error) {
console.error("Failed to fetch releases:", error);
} finally {
diff --git a/components/dialog-manager.tsx b/components/dialog-manager.tsx
index 62efc45..449ea7a 100644
--- a/components/dialog-manager.tsx
+++ b/components/dialog-manager.tsx
@@ -1,6 +1,5 @@
import { CalendarSheet } from "@/components/calendar-sheet";
import { ShiftSheet, ShiftFormData } from "@/components/shift-sheet";
-import { PasswordDialog } from "@/components/password-dialog";
import { CalendarSettingsSheet } from "@/components/calendar-settings-sheet";
import { ExternalSyncManageSheet } from "@/components/external-sync-manage-sheet";
import { SyncNotificationDialog } from "@/components/sync-notification-dialog";
@@ -15,11 +14,7 @@ interface DialogManagerProps {
// Calendar Dialog
showCalendarDialog: boolean;
onCalendarDialogChange: (open: boolean) => void;
- onCreateCalendar: (
- name: string,
- color: string,
- password?: string
- ) => Promise<void>;
+ onCreateCalendar: (name: string, color: string) => Promise<void>;
// Shift Dialog
showShiftDialog: boolean;
@@ -28,18 +23,14 @@ interface DialogManagerProps {
selectedDate?: Date;
selectedCalendar: string | null;
onPresetsChange: () => void;
-
- // Password Dialog
- showPasswordDialog: boolean;
- onPasswordDialogChange: (open: boolean) => void;
calendars: CalendarWithCount[];
- onPasswordSuccess: (password: string) => void;
// Calendar Settings Dialog
showCalendarSettingsDialog: boolean;
onCalendarSettingsDialogChange: (open: boolean) => void;
onCalendarSettingsSuccess: () => void;
- onDeleteCalendar: (password?: string) => void;
+ onDeleteCalendar: () => void;
+ onExternalSyncFromSettings?: () => void;
// External Sync Sheet
showExternalSyncDialog: boolean;
@@ -139,17 +130,6 @@ export function DialogManager(props: DialogManagerProps) {
{props.selectedCalendar && (
<>
- <PasswordDialog
- open={props.showPasswordDialog}
- onOpenChange={props.onPasswordDialogChange}
- calendarId={props.selectedCalendar}
- calendarName={
- props.calendars.find((c) => c.id === props.selectedCalendar)
- ?.name || ""
- }
- onSuccess={props.onPasswordSuccess}
- />
-
<CalendarSettingsSheet
key={`settings-${props.selectedCalendar}-${props.showCalendarSettingsDialog}`}
open={props.showCalendarSettingsDialog}
@@ -163,16 +143,13 @@ export function DialogManager(props: DialogManagerProps) {
props.calendars.find((c) => c.id === props.selectedCalendar)
?.color || "#3b82f6"
}
- hasPassword={
- !!props.calendars.find((c) => c.id === props.selectedCalendar)
- ?.passwordHash
- }
- isLocked={
+ calendarGuestPermission={
props.calendars.find((c) => c.id === props.selectedCalendar)
- ?.isLocked || false
+ ?.guestPermission || "none"
}
onSuccess={props.onCalendarSettingsSuccess}
onDelete={props.onDeleteCalendar}
+ onExternalSync={props.onExternalSyncFromSettings}
/>
<ExternalSyncManageSheet
@@ -263,6 +240,7 @@ export function DialogManager(props: DialogManagerProps) {
onEditNote={props.onEditNoteFromList}
onDeleteNote={props.onDeleteNoteFromList}
onAddNew={props.onAddNewNote}
+ calendarId={props.selectedCalendar || undefined}
/>
)}
<NoteSheet
@@ -272,6 +250,7 @@ export function DialogManager(props: DialogManagerProps) {
onDelete={props.onNoteDelete}
selectedDate={props.selectedNoteDate}
note={props.selectedNote}
+ calendarId={props.selectedCalendar || undefined}
/>
</>
);
diff --git a/components/empty-calendar-state.tsx b/components/empty-calendar-state.tsx
index ecf210f..715b5f5 100644
--- a/components/empty-calendar-state.tsx
+++ b/components/empty-calendar-state.tsx
@@ -1,21 +1,27 @@
import { motion } from "motion/react";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
-import { LanguageSwitcher } from "@/components/language-switcher";
+import { AuthHeader } from "@/components/auth-header";
+import { AppFooter } from "@/components/app-footer";
+import { useVersionInfo } from "@/hooks/useVersionInfo";
import { Calendar as CalendarIcon, Plus } from "lucide-react";
interface EmptyCalendarStateProps {
onCreateCalendar: () => void;
+ showUserMenu?: boolean;
}
export function EmptyCalendarState({
onCreateCalendar,
+ showUserMenu = false,
}: EmptyCalendarStateProps) {
const t = useTranslations();
+ const versionInfo = useVersionInfo();
return (
<div className="min-h-screen flex flex-col">
- <div className="flex-1 flex items-center justify-center p-4">
+ <AuthHeader showUserMenu={showUserMenu} />
+ <div className="flex-1 flex items-center justify-center p-4 bg-gradient-to-br from-background via-background to-primary/5">
<motion.div
className="text-center space-y-6 max-w-md"
initial={{ opacity: 0, y: 20 }}
@@ -49,11 +55,7 @@ export function EmptyCalendarState({
</motion.div>
</motion.div>
</div>
- <div className="border-t bg-background">
- <div className="container max-w-4xl mx-auto p-3 sm:p-4 flex justify-center">
- <LanguageSwitcher />
- </div>
- </div>
+ <AppFooter versionInfo={versionInfo} />
</div>
);
}
diff --git a/components/export-dialog.tsx b/components/export-dialog.tsx
index c429347..e44d699 100644
--- a/components/export-dialog.tsx
+++ b/components/export-dialog.tsx
@@ -18,9 +18,12 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
+import {
+ isRateLimitError,
+ handleRateLimitError,
+} from "@/lib/rate-limit-client";
import { Download, FileText, Calendar } from "lucide-react";
import { toast } from "sonner";
-import { getCachedPassword } from "@/lib/password-cache";
interface ExportDialogProps {
open: boolean;
@@ -101,17 +104,10 @@ export function ExportDialog({
setLoading(true);
try {
- // Get cached password if calendar is protected
- const password = getCachedPassword(calendarId);
-
// Build URL
let url = `/api/calendars/${calendarId}/export/${exportFormat}`;
const params = new URLSearchParams();
- if (password) {
- params.append("password", password);
- }
-
if (exportFormat === "pdf") {
// Add locale for proper date formatting and translations
params.append("locale", locale);
@@ -130,6 +126,12 @@ export function ExportDialog({
// Fetch the file
const response = await fetch(url);
+ if (isRateLimitError(response)) {
+ await handleRateLimitError(response, t);
+ setLoading(false);
+ return;
+ }
+
if (!response.ok) {
if (response.status === 401) {
toast.error(t("validation.passwordRequired"));
diff --git a/components/external-sync-manage-sheet.tsx b/components/external-sync-manage-sheet.tsx
index 02524f7..0e75150 100644
--- a/components/external-sync-manage-sheet.tsx
+++ b/components/external-sync-manage-sheet.tsx
@@ -33,8 +33,11 @@ import {
Loader2,
} from "lucide-react";
import { toast } from "sonner";
+import {
+ isRateLimitError,
+ handleRateLimitError,
+} from "@/lib/rate-limit-client";
import { PRESET_COLORS } from "@/lib/constants";
-import { getCachedPassword } from "@/lib/password-cache";
import {
isValidCalendarUrl,
detectCalendarSyncType,
@@ -100,11 +103,7 @@ export function ExternalSyncManageSheet({
setIsLoading(true);
}
try {
- const password = getCachedPassword(calendarId);
const params = new URLSearchParams({ calendarId });
- if (password) {
- params.append("password", password);
- }
const response = await fetch(`/api/external-syncs?${params}`);
if (response.ok) {
@@ -113,9 +112,6 @@ export function ExternalSyncManageSheet({
// Fetch last sync logs to check for errors
const logsParams = new URLSearchParams({ calendarId, limit: "50" });
- if (password) {
- logsParams.append("password", password);
- }
const logsResponse = await fetch(`/api/sync-logs?${logsParams}`);
if (logsResponse.ok) {
@@ -242,8 +238,6 @@ export function ExternalSyncManageSheet({
icsContent = await icsFile.text();
}
- const password = getCachedPassword(calendarId);
-
const response = await fetch("/api/external-syncs", {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -257,7 +251,6 @@ export function ExternalSyncManageSheet({
icsContent,
isHidden: formIsHidden,
hideFromStats: formHideFromStats,
- password,
}),
});
@@ -300,14 +293,17 @@ export function ExternalSyncManageSheet({
const handleSync = async (syncId: string) => {
setIsSyncing(syncId);
try {
- const password = getCachedPassword(calendarId);
-
const response = await fetch(`/api/external-syncs/${syncId}/sync`, {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ password }),
+ body: JSON.stringify({}),
});
+ if (isRateLimitError(response)) {
+ await handleRateLimitError(response, t);
+ return;
+ }
+
const data = await response.json();
if (!response.ok) {
@@ -344,12 +340,10 @@ export function ExternalSyncManageSheet({
setIsDeleting(deleteTargetId);
try {
- const password = getCachedPassword(calendarId);
-
const response = await fetch(`/api/external-syncs/${deleteTargetId}`, {
method: "DELETE",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ password }),
+ body: JSON.stringify({}),
});
if (response.ok) {
@@ -422,14 +416,11 @@ export function ExternalSyncManageSheet({
}
try {
- const password = getCachedPassword(calendarId);
-
const response = await fetch(`/api/external-syncs/${syncId}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
[field]: !currentValue,
- password,
}),
});
@@ -532,8 +523,6 @@ export function ExternalSyncManageSheet({
setIsSavingEdit(true);
try {
- const password = getCachedPassword(calendarId);
-
const response = await fetch(`/api/external-syncs/${editingSync.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
@@ -545,7 +534,6 @@ export function ExternalSyncManageSheet({
color: formColor,
displayMode: formDisplayMode,
autoSyncInterval: formAutoSyncInterval,
- password,
}),
});
@@ -584,7 +572,6 @@ export function ExternalSyncManageSheet({
setIsSavingEdit(false);
}
}, [
- calendarId,
editingSync,
formName,
formUrl,
@@ -787,7 +774,7 @@ export function ExternalSyncManageSheet({
</h3>
<div className="space-y-2">
- <Label htmlFor="sync-name">{t("form.nameLabel")}</Label>
+ <Label htmlFor="sync-name">{t("common.labels.name")}</Label>
<Input
id="sync-name"
type="text"
diff --git a/components/fullscreen-loader.tsx b/components/fullscreen-loader.tsx
new file mode 100644
index 0000000..3a16e21
--- /dev/null
+++ b/components/fullscreen-loader.tsx
@@ -0,0 +1,35 @@
+"use client";
+
+import { Loader2 } from "lucide-react";
+import { motion } from "motion/react";
+
+interface FullscreenLoaderProps {
+ message?: string;
+}
+
+/**
+ * Fullscreen loading spinner component
+ *
+ * Shows a centered spinner with optional message during initial page load.
+ * Prevents skeleton flicker by providing single consistent loading state.
+ *
+ * Usage:
+ * ```tsx
+ * {isLoading ? <FullscreenLoader message="Loading calendars..." /> : <PageContent />}
+ * ```
+ */
+export function FullscreenLoader({ message }: FullscreenLoaderProps) {
+ return (
+ <motion.div
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ transition={{ duration: 0.2, delay: 0.1 }}
+ className="fixed inset-0 z-50 flex flex-col items-center justify-center bg-background"
+ >
+ <Loader2 className="h-12 w-12 animate-spin text-primary" />
+ {message && (
+ <p className="mt-4 text-sm text-muted-foreground">{message}</p>
+ )}
+ </motion.div>
+ );
+}
diff --git a/components/guest-banner.tsx b/components/guest-banner.tsx
new file mode 100644
index 0000000..4d3db92
--- /dev/null
+++ b/components/guest-banner.tsx
@@ -0,0 +1,74 @@
+"use client";
+
+import { useTranslations } from "next-intl";
+import { Info, LogIn } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { motion } from "motion/react";
+import Link from "next/link";
+
+interface GuestBannerProps {
+ variant?: "default" | "compact";
+}
+
+export function GuestBanner({ variant = "default" }: GuestBannerProps) {
+ const t = useTranslations();
+
+ if (variant === "compact") {
+ return (
+ <motion.div
+ initial={{ opacity: 0, y: -10 }}
+ animate={{ opacity: 1, y: 0 }}
+ className="bg-blue-50 dark:bg-blue-950/30 border border-blue-200 dark:border-blue-900/50 rounded-lg p-3 flex items-center justify-between gap-3"
+ >
+ <div className="flex items-center gap-2 min-w-0">
+ <Info className="h-4 w-4 text-blue-600 dark:text-blue-400 shrink-0" />
+ <p className="text-sm text-blue-900 dark:text-blue-100 truncate">
+ {t("guest.viewingAsGuest")}
+ </p>
+ </div>
+ <Button asChild size="sm" variant="outline" className="shrink-0">
+ <Link href="/login">
+ <LogIn className="h-3.5 w-3.5 mr-1.5" />
+ {t("auth.login")}
+ </Link>
+ </Button>
+ </motion.div>
+ );
+ }
+
+ return (
+ <motion.div
+ initial={{ opacity: 0, y: -10 }}
+ animate={{ opacity: 1, y: 0 }}
+ className="bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-950/30 dark:to-indigo-950/30 border border-blue-200 dark:border-blue-900/50 rounded-xl p-4 shadow-sm"
+ >
+ <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
+ <div className="flex items-start gap-3 min-w-0">
+ <div className="mt-0.5 shrink-0">
+ <div className="w-10 h-10 rounded-full bg-blue-100 dark:bg-blue-900/50 flex items-center justify-center">
+ <Info className="h-5 w-5 text-blue-600 dark:text-blue-400" />
+ </div>
+ </div>
+ <div className="min-w-0">
+ <h3 className="font-medium text-blue-900 dark:text-blue-100 mb-1">
+ {t("guest.viewingAsGuest")}
+ </h3>
+ <p className="text-sm text-blue-700 dark:text-blue-300">
+ {t("guest.bannerMessage")}
+ </p>
+ </div>
+ </div>
+ <Button
+ asChild
+ size="sm"
+ className="bg-blue-600 hover:bg-blue-700 text-white shrink-0"
+ >
+ <Link href="/login">
+ <LogIn className="h-4 w-4 mr-2" />
+ {t("guest.loginForFullAccess")}
+ </Link>
+ </Button>
+ </div>
+ </motion.div>
+ );
+}
diff --git a/components/guest-empty-state.tsx b/components/guest-empty-state.tsx
new file mode 100644
index 0000000..6ed407e
--- /dev/null
+++ b/components/guest-empty-state.tsx
@@ -0,0 +1,65 @@
+"use client";
+
+import { motion } from "motion/react";
+import { useTranslations } from "next-intl";
+import { Button } from "@/components/ui/button";
+import { AuthHeader } from "@/components/auth-header";
+import { AppFooter } from "@/components/app-footer";
+import { useVersionInfo } from "@/hooks/useVersionInfo";
+import { Calendar as CalendarIcon, LogIn } from "lucide-react";
+import { useRouter } from "next/navigation";
+
+/**
+ * Empty state shown to guests when no public calendars are available
+ * Displays a message prompting them to log in
+ */
+export function GuestEmptyState() {
+ const t = useTranslations();
+ const router = useRouter();
+ const versionInfo = useVersionInfo();
+
+ const handleLoginClick = () => {
+ router.push("/login");
+ };
+
+ return (
+ <div className="min-h-screen flex flex-col">
+ <AuthHeader showUserMenu={false} />
+ <div className="flex-1 flex items-center justify-center p-4 bg-gradient-to-br from-background via-background to-primary/5">
+ <motion.div
+ className="text-center space-y-6 max-w-md"
+ initial={{ opacity: 0, y: 20 }}
+ animate={{ opacity: 1, y: 0 }}
+ >
+ <motion.div
+ initial={{ scale: 0 }}
+ animate={{ scale: 1 }}
+ transition={{ delay: 0.1, type: "spring", stiffness: 200 }}
+ className="w-20 h-20 mx-auto rounded-full bg-gradient-to-br from-muted/50 to-muted/20 flex items-center justify-center"
+ >
+ <CalendarIcon className="h-10 w-10 text-muted-foreground" />
+ </motion.div>
+ <div className="space-y-3">
+ <h1 className="text-2xl sm:text-3xl font-bold">
+ {t("guestEmptyState.title")}
+ </h1>
+ <p className="text-muted-foreground text-sm sm:text-base leading-relaxed">
+ {t("guestEmptyState.description")}
+ </p>
+ </div>
+ <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
+ <Button
+ onClick={handleLoginClick}
+ size="lg"
+ className="h-12 px-8 text-base font-semibold shadow-lg shadow-primary/20"
+ >
+ <LogIn className="mr-2 h-5 w-5" />
+ {t("guestEmptyState.loginButton")}
+ </Button>
+ </motion.div>
+ </motion.div>
+ </div>
+ <AppFooter versionInfo={versionInfo} />
+ </div>
+ );
+}
diff --git a/components/guest-permission-selector.tsx b/components/guest-permission-selector.tsx
new file mode 100644
index 0000000..2694a42
--- /dev/null
+++ b/components/guest-permission-selector.tsx
@@ -0,0 +1,105 @@
+"use client";
+
+import { useTranslations } from "next-intl";
+import { Label } from "@/components/ui/label";
+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
+import { AlertTriangle, Eye, Edit } from "lucide-react";
+
+interface GuestPermissionSelectorProps {
+ value: "none" | "read" | "write";
+ onChange: (value: "none" | "read" | "write") => void;
+ idPrefix?: string;
+}
+
+export function GuestPermissionSelector({
+ value,
+ onChange,
+ idPrefix = "guest",
+}: GuestPermissionSelectorProps) {
+ const t = useTranslations();
+
+ return (
+ <div className="space-y-3">
+ <RadioGroup
+ value={value}
+ onValueChange={(val) => onChange(val as "none" | "read" | "write")}
+ className="space-y-3"
+ >
+ {/* No Access */}
+ <div className="group relative">
+ <Label
+ htmlFor={`${idPrefix}-none`}
+ className="flex items-start gap-3 p-4 rounded-xl border-2 border-border/50 hover:border-border hover:bg-muted/50 transition-all cursor-pointer"
+ >
+ <RadioGroupItem
+ value="none"
+ id={`${idPrefix}-none`}
+ className="mt-0.5"
+ />
+ <div className="flex-1 space-y-2">
+ <div className="flex items-center gap-2">
+ <AlertTriangle className="h-4 w-4 text-red-500 shrink-0" />
+ <span className="font-semibold text-sm">
+ {t("common.labels.permissions.none")}
+ </span>
+ </div>
+ <p className="text-xs text-muted-foreground leading-relaxed pl-6">
+ {t("share.publicPermissionNoneDesc")}
+ </p>
+ </div>
+ </Label>
+ </div>
+
+ {/* Read Only */}
+ <div className="group relative">
+ <Label
+ htmlFor={`${idPrefix}-read`}
+ className="flex items-start gap-3 p-4 rounded-xl border-2 border-border/50 hover:border-border hover:bg-muted/50 transition-all cursor-pointer"
+ >
+ <RadioGroupItem
+ value="read"
+ id={`${idPrefix}-read`}
+ className="mt-0.5"
+ />
+ <div className="flex-1 space-y-2">
+ <div className="flex items-center gap-2">
+ <Eye className="h-4 w-4 text-blue-500 shrink-0" />
+ <span className="font-semibold text-sm">
+ {t("common.labels.permissions.read")}
+ </span>
+ </div>
+ <p className="text-xs text-muted-foreground leading-relaxed pl-6">
+ {t("share.publicPermissionReadDesc")}
+ </p>
+ </div>
+ </Label>
+ </div>
+
+ {/* Read & Write */}
+ <div className="group relative">
+ <Label
+ htmlFor={`${idPrefix}-write`}
+ className="flex items-start gap-3 p-4 rounded-xl border-2 border-border/50 hover:border-border hover:bg-muted/50 transition-all cursor-pointer"
+ >
+ <RadioGroupItem
+ value="write"
+ id={`${idPrefix}-write`}
+ className="mt-0.5"
+ />
+ <div className="flex-1 space-y-2">
+ <div className="flex items-center gap-2">
+ <Edit className="h-4 w-4 text-green-500 shrink-0" />
+ <span className="font-semibold text-sm">
+ {t("common.labels.permissions.write")}
+ </span>
+ </div>
+ <p className="text-xs text-muted-foreground leading-relaxed pl-6">
+ {t("share.publicPermissionWriteDesc")}
+ </p>
+ </div>
+ </Label>
+ </div>
+ </RadioGroup>
+ </div>
+ );
+}
diff --git a/components/locked-calendar-skeleton.tsx b/components/locked-calendar-skeleton.tsx
deleted file mode 100644
index c45c833..0000000
--- a/components/locked-calendar-skeleton.tsx
+++ /dev/null
@@ -1,34 +0,0 @@
-import { Skeleton } from "@/components/ui/skeleton";
-import { Calendar as CalendarIcon } from "lucide-react";
-
-export function LockedCalendarSkeleton() {
- return (
- <div className="flex flex-col items-center justify-center py-20">
- <div className="w-full max-w-md">
- <div className="bg-gradient-to-b from-background via-background to-muted/30 backdrop-blur-xl shadow-2xl border border-border/50 rounded-2xl p-8">
- {/* Icon */}
- <div className="w-20 h-20 rounded-full bg-primary/10 flex items-center justify-center mb-6 mx-auto">
- <CalendarIcon className="h-10 w-10 text-primary animate-pulse" />
- </div>
-
- {/* Title */}
- <Skeleton className="h-8 w-3/4 mx-auto mb-2" />
-
- {/* Description */}
- <Skeleton className="h-5 w-full mx-auto mb-8" />
-
- {/* Password Input */}
- <div className="space-y-4">
- <div className="space-y-2">
- <Skeleton className="h-4 w-20" />
- <Skeleton className="h-11 w-full" />
- </div>
-
- {/* Submit Button */}
- <Skeleton className="h-11 w-full rounded-lg" />
- </div>
- </div>
- </div>
- </div>
- );
-}
diff --git a/components/locked-calendar-view.tsx b/components/locked-calendar-view.tsx
deleted file mode 100644
index b17582c..0000000
--- a/components/locked-calendar-view.tsx
+++ /dev/null
@@ -1,79 +0,0 @@
-import { motion } from "motion/react";
-import { useTranslations } from "next-intl";
-import { toast } from "sonner";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { Calendar as CalendarIcon } from "lucide-react";
-import { verifyAndCachePassword } from "@/lib/password-cache";
-
-interface LockedCalendarViewProps {
- calendarId: string;
- onUnlock: () => void;
-}
-
-export function LockedCalendarView({
- calendarId,
- onUnlock,
-}: LockedCalendarViewProps) {
- const t = useTranslations();
-
- const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
- e.preventDefault();
- const formData = new FormData(e.currentTarget);
- const password = formData.get("password") as string;
-
- if (password && calendarId) {
- const result = await verifyAndCachePassword(calendarId, password);
-
- if (result.valid) {
- onUnlock();
- } else {
- toast.error(t("validation.passwordIncorrect"));
- }
- }
- };
-
- return (
- <div className="flex flex-col items-center justify-center py-20">
- <motion.div
- initial={{ opacity: 0, y: 20 }}
- animate={{ opacity: 1, y: 0 }}
- className="w-full max-w-md"
- >
- <div className="bg-gradient-to-b from-background via-background to-muted/30 backdrop-blur-xl shadow-2xl border border-border/50 rounded-2xl p-8">
- <div className="w-20 h-20 rounded-full bg-primary/10 flex items-center justify-center mb-6 mx-auto">
- <CalendarIcon className="h-10 w-10 text-primary" />
- </div>
- <h3 className="text-2xl font-semibold mb-2 text-center">
- {t("password.currentlyLocked")}
- </h3>
- <p className="text-muted-foreground text-center mb-8">
- {t("password.enterCalendarPassword")}
- </p>
- <form onSubmit={handleSubmit} className="space-y-4">
- <div className="space-y-2">
- <Label htmlFor="unlock-password" className="text-sm font-medium">
- {t("form.passwordLabel")}
- </Label>
- <Input
- id="unlock-password"
- name="password"
- type="password"
- placeholder={t("form.passwordPlaceholder")}
- className="h-11 border-primary/30 focus:border-primary/50 focus:ring-primary/20"
- autoFocus
- />
- </div>
- <Button
- type="submit"
- className="w-full h-11 bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg shadow-primary/25"
- >
- {t("common.unlock")}
- </Button>
- </form>
- </div>
- </motion.div>
- </div>
- );
-}
diff --git a/components/note-sheet.tsx b/components/note-sheet.tsx
index b435e3d..76972d4 100644
--- a/components/note-sheet.tsx
+++ b/components/note-sheet.tsx
@@ -16,6 +16,8 @@ import {
SelectValue,
} from "@/components/ui/select";
import { Input } from "@/components/ui/input";
+import { ReadOnlyBanner } from "@/components/read-only-banner";
+import { useCalendarPermission } from "@/hooks/useCalendarPermission";
import { CalendarNote } from "@/lib/db/schema";
import { format } from "date-fns";
import { getDateLocale } from "@/lib/locales";
@@ -36,6 +38,8 @@ interface NoteSheetProps {
onDelete?: () => void;
selectedDate?: Date;
note?: CalendarNote;
+ calendarId?: string;
+ readOnly?: boolean;
}
export function NoteSheet({
@@ -45,10 +49,13 @@ export function NoteSheet({
onDelete,
selectedDate,
note,
+ calendarId,
+ readOnly = false,
}: NoteSheetProps) {
const t = useTranslations();
const locale = useLocale();
const dateLocale = getDateLocale(locale);
+ const permission = useCalendarPermission(calendarId);
const [noteText, setNoteText] = useState("");
const [type, setType] = useState<"note" | "event">("note");
const [color, setColor] = useState<string>("#3b82f6");
@@ -56,6 +63,9 @@ export function NoteSheet({
const [recurringInterval, setRecurringInterval] = useState<number>(1);
const [recurringUnit, setRecurringUnit] = useState<string>("months");
const [isSaving, setIsSaving] = useState(false);
+
+ // Determine if sheet should be in read-only mode
+ const isReadOnly = readOnly || !permission.canEdit;
const initialStateRef = useRef<{
text: string;
type: "note" | "event";
@@ -184,7 +194,7 @@ export function NoteSheet({
const customFooter = note ? (
// Edit mode: Delete button on left, Cancel/Save on right
<div className="flex gap-2.5 w-full">
- {onDelete && (
+ {onDelete && !isReadOnly && (
<Button
type="button"
variant="destructive"
@@ -205,14 +215,16 @@ export function NoteSheet({
>
{t("common.cancel")}
</Button>
- <Button
- type="button"
- onClick={handleSave}
- disabled={isSaving || !noteText.trim() || !hasChanges()}
- className="h-11 bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg shadow-primary/25 disabled:opacity-50 disabled:shadow-none"
- >
- {isSaving ? t("common.saving") : t("common.save")}
- </Button>
+ {!isReadOnly && (
+ <Button
+ type="button"
+ onClick={handleSave}
+ disabled={isSaving || !noteText.trim() || !hasChanges()}
+ className="h-11 bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg shadow-primary/25 disabled:opacity-50 disabled:shadow-none"
+ >
+ {isSaving ? t("common.saving") : t("common.save")}
+ </Button>
+ )}
</div>
) : (
// Create mode: Full-width buttons
@@ -226,14 +238,16 @@ export function NoteSheet({
>
{t("common.cancel")}
</Button>
- <Button
- type="button"
- onClick={handleSave}
- disabled={isSaving || !noteText.trim()}
- className="flex-1 h-11 bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg shadow-primary/25 disabled:opacity-50 disabled:shadow-none"
- >
- {isSaving ? t("common.saving") : t("common.save")}
- </Button>
+ {!isReadOnly && (
+ <Button
+ type="button"
+ onClick={handleSave}
+ disabled={isSaving || !noteText.trim()}
+ className="flex-1 h-11 bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg shadow-primary/25 disabled:opacity-50 disabled:shadow-none"
+ >
+ {isSaving ? t("common.saving") : t("common.save")}
+ </Button>
+ )}
</div>
);
@@ -257,6 +271,9 @@ export function NoteSheet({
maxWidth="md"
>
<div className="space-y-6">
+ {/* Read-Only Banner */}
+ {isReadOnly && <ReadOnlyBanner message={t("guest.cannotEdit")} />}
+
{/* Recurring Event Warning */}
{note &&
type === "event" &&
@@ -277,15 +294,24 @@ export function NoteSheet({
value={type}
onValueChange={(value) => setType(value as "note" | "event")}
className="flex gap-4"
+ disabled={isReadOnly}
>
<div className="flex items-center space-x-2">
- <RadioGroupItem value="note" id="type-note" />
+ <RadioGroupItem
+ value="note"
+ id="type-note"
+ disabled={isReadOnly}
+ />
<Label htmlFor="type-note" className="cursor-pointer font-normal">
{t("note.typeNote")}
</Label>
</div>
<div className="flex items-center space-x-2">
- <RadioGroupItem value="event" id="type-event" />
+ <RadioGroupItem
+ value="event"
+ id="type-event"
+ disabled={isReadOnly}
+ />
<Label
htmlFor="type-event"
className="cursor-pointer font-normal"
@@ -305,6 +331,7 @@ export function NoteSheet({
onChange={setColor}
label={t("note.eventColor")}
presetColors={PRESET_COLORS}
+ disabled={isReadOnly}
/>
{/* Recurring Pattern */}
@@ -315,6 +342,7 @@ export function NoteSheet({
<Select
value={recurringPattern}
onValueChange={setRecurringPattern}
+ disabled={isReadOnly}
>
<SelectTrigger className="w-full">
<SelectValue />
@@ -349,10 +377,12 @@ export function NoteSheet({
setRecurringInterval(parseInt(e.target.value) || 1)
}
className="w-20"
+ disabled={isReadOnly}
/>
<Select
value={recurringUnit}
onValueChange={setRecurringUnit}
+ disabled={isReadOnly}
>
<SelectTrigger className="flex-1">
<SelectValue />
@@ -383,6 +413,7 @@ export function NoteSheet({
: t("note.placeholder")
}
className="min-h-[200px] resize-none focus-visible:ring-primary/30 border-border/50"
+ disabled={isReadOnly}
/>
</div>
</div>
diff --git a/components/notes-list-dialog.tsx b/components/notes-list-dialog.tsx
index 5495135..63732ef 100644
--- a/components/notes-list-dialog.tsx
+++ b/components/notes-list-dialog.tsx
@@ -14,6 +14,8 @@ import {
import { Button } from "@/components/ui/button";
import { Pencil, Trash2, Plus, Calendar } from "lucide-react";
import { Badge } from "@/components/ui/badge";
+import { ReadOnlyBanner } from "@/components/read-only-banner";
+import { useCalendarPermission } from "@/hooks/useCalendarPermission";
interface NotesListDialogProps {
open: boolean;
@@ -23,6 +25,8 @@ interface NotesListDialogProps {
onEditNote: (note: CalendarNote) => void;
onDeleteNote: (noteId: string) => void;
onAddNew: () => void;
+ calendarId?: string;
+ readOnly?: boolean;
}
export function NotesListDialog({
@@ -33,10 +37,16 @@ export function NotesListDialog({
onEditNote,
onDeleteNote,
onAddNew,
+ calendarId,
+ readOnly = false,
}: NotesListDialogProps) {
const t = useTranslations();
const locale = useLocale();
const dateLocale = getDateLocale(locale);
+ const permission = useCalendarPermission(calendarId);
+
+ // Determine if dialog should be in read-only mode
+ const isReadOnly = readOnly || !permission.canEdit;
const formattedDate = format(date, "EEEE, dd. MMMM yyyy", {
locale: dateLocale,
@@ -77,6 +87,13 @@ export function NotesListDialog({
</DialogDescription>
</DialogHeader>
+ {/* Read-Only Banner */}
+ {isReadOnly && (
+ <div className="px-6 pt-6">
+ <ReadOnlyBanner message={t("guest.cannotEdit")} />
+ </div>
+ )}
+
<div className="space-y-6 overflow-y-auto flex-1 p-6">
{/* Events Section */}
{events.length > 0 && (
@@ -116,24 +133,26 @@ export function NotesListDialog({
)}
</div>
</div>
- <div className="flex gap-1.5 shrink-0 ml-auto">
- <Button
- variant="ghost"
- size="icon"
- onClick={() => onEditNote(event)}
- className="h-8 w-8 hover:bg-background/50"
- >
- <Pencil className="h-4 w-4" />
- </Button>
- <Button
- variant="ghost"
- size="icon"
- onClick={() => onDeleteNote(event.id)}
- className="h-8 w-8 hover:bg-destructive/10 hover:text-destructive"
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- </div>
+ {!isReadOnly && (
+ <div className="flex gap-1.5 shrink-0 ml-auto">
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={() => onEditNote(event)}
+ className="h-8 w-8 hover:bg-background/50"
+ >
+ <Pencil className="h-4 w-4" />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={() => onDeleteNote(event.id)}
+ className="h-8 w-8 hover:bg-destructive/10 hover:text-destructive"
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ </div>
+ )}
</div>
</div>
))}
@@ -159,24 +178,26 @@ export function NotesListDialog({
{note.note}
</p>
</div>
- <div className="flex gap-1.5 shrink-0 ml-auto">
- <Button
- variant="ghost"
- size="icon"
- onClick={() => onEditNote(note)}
- className="h-8 w-8"
- >
- <Pencil className="h-4 w-4" />
- </Button>
- <Button
- variant="ghost"
- size="icon"
- onClick={() => onDeleteNote(note.id)}
- className="h-8 w-8 hover:bg-destructive/10 hover:text-destructive"
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- </div>
+ {!isReadOnly && (
+ <div className="flex gap-1.5 shrink-0 ml-auto">
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={() => onEditNote(note)}
+ className="h-8 w-8"
+ >
+ <Pencil className="h-4 w-4" />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={() => onDeleteNote(note.id)}
+ className="h-8 w-8 hover:bg-destructive/10 hover:text-destructive"
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ </div>
+ )}
</div>
</div>
))}
@@ -202,16 +223,18 @@ export function NotesListDialog({
>
{t("common.cancel")}
</Button>
- <Button
- onClick={() => {
- onOpenChange(false);
- onAddNew();
- }}
- className="bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg shadow-primary/25"
- >
- <Plus className="h-4 w-4 mr-2" />
- {t("common.add")}
- </Button>
+ {!isReadOnly && (
+ <Button
+ onClick={() => {
+ onOpenChange(false);
+ onAddNew();
+ }}
+ className="bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg shadow-primary/25"
+ >
+ <Plus className="h-4 w-4 mr-2" />
+ {t("common.add")}
+ </Button>
+ )}
</div>
</DialogContent>
</Dialog>
diff --git a/components/password-dialog.tsx b/components/password-dialog.tsx
deleted file mode 100644
index bf9239f..0000000
--- a/components/password-dialog.tsx
+++ /dev/null
@@ -1,125 +0,0 @@
-"use client";
-
-import { useState, useEffect } from "react";
-import { useTranslations } from "next-intl";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- DialogDescription,
-} from "@/components/ui/dialog";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { verifyAndCachePassword } from "@/lib/password-cache";
-
-interface PasswordDialogProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- calendarId: string;
- calendarName: string;
- onSuccess: (password: string) => void;
-}
-
-export function PasswordDialog({
- open,
- onOpenChange,
- calendarId,
- calendarName,
- onSuccess,
-}: PasswordDialogProps) {
- const t = useTranslations();
- const [password, setPassword] = useState("");
- const [error, setError] = useState("");
- const [loading, setLoading] = useState(false);
-
- useEffect(() => {
- if (open) {
- setPassword("");
- setError("");
- }
- }, [open]);
-
- const handleSubmit = async (e: React.FormEvent) => {
- e.preventDefault();
- setError("");
- setLoading(true);
-
- try {
- const result = await verifyAndCachePassword(calendarId, password);
-
- if (result.valid) {
- onSuccess(password);
- onOpenChange(false);
- } else {
- setError(t("validation.passwordIncorrect"));
- }
- } catch (error) {
- console.error("Failed to verify password:", error);
- setError(t("validation.passwordIncorrect"));
- } finally {
- setLoading(false);
- }
- };
-
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="sm:max-w-[440px] p-0 gap-0 border border-border/50 bg-gradient-to-b from-background via-background to-muted/30 backdrop-blur-xl shadow-2xl">
- <DialogHeader className="border-b border-border/50 bg-gradient-to-r from-red-500/10 via-red-500/5 to-transparent p-6 pb-5 space-y-1.5">
- <DialogTitle className="text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">
- {t("form.passwordLabel")} {t("common.required")}
- </DialogTitle>
- <DialogDescription asChild>
- <div className="text-sm text-muted-foreground flex items-center gap-2">
- <div className="w-1 h-4 bg-gradient-to-b from-red-500 to-red-500/50 rounded-full"></div>
- {t("password.enter", { name: calendarName })}
- </div>
- </DialogDescription>
- </DialogHeader>
- <form onSubmit={handleSubmit} className="p-6 space-y-5">
- <div className="space-y-2.5">
- <Label
- htmlFor="password"
- className="text-sm font-medium flex items-center gap-2"
- >
- <div className="w-1 h-4 bg-gradient-to-b from-red-500 to-red-500/50 rounded-full"></div>
- {t("form.passwordLabel")}
- </Label>
- <Input
- id="password"
- type="password"
- value={password}
- onChange={(e) => setPassword(e.target.value)}
- placeholder={t("password.enterCalendarPassword")}
- className="h-11 border-red-500/30 focus:border-red-500/50 focus:ring-red-500/20 bg-background/50"
- autoFocus
- />
- {error && (
- <p className="text-sm text-red-500 flex items-center gap-1.5 bg-red-500/10 p-2 rounded-lg border border-red-500/20">
- {error}
- </p>
- )}
- </div>
- <div className="flex gap-2.5 pt-2">
- <Button
- type="button"
- variant="outline"
- onClick={() => onOpenChange(false)}
- className="flex-1 h-11 border-border/50 hover:bg-muted/50"
- >
- {t("common.cancel")}
- </Button>
- <Button
- type="submit"
- disabled={loading || !password}
- className="flex-1 h-11 bg-gradient-to-r from-red-500 to-red-500/90 hover:from-red-500/90 hover:to-red-500/80 shadow-lg shadow-red-500/25 disabled:opacity-50 disabled:shadow-none"
- >
- {loading ? t("common.loading") : t("common.unlock")}
- </Button>
- </div>
- </form>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/components/preset-list-skeleton.tsx b/components/preset-list-skeleton.tsx
deleted file mode 100644
index 84c2867..0000000
--- a/components/preset-list-skeleton.tsx
+++ /dev/null
@@ -1,31 +0,0 @@
-import { Skeleton } from "@/components/ui/skeleton";
-
-interface PresetListSkeletonProps {
- hidePresetHeader?: boolean;
-}
-
-export function PresetListSkeleton({
- hidePresetHeader = false,
-}: PresetListSkeletonProps) {
- return (
- <div className="space-y-2">
- {/* Preset Buttons Row */}
- {!hidePresetHeader && (
- <div className="flex flex-wrap gap-2">
- <Skeleton className="h-9 w-24 rounded-full" />
- <Skeleton className="h-9 w-32 rounded-full" />
- <Skeleton className="h-9 w-28 rounded-full" />
- <Skeleton className="h-9 w-36 rounded-full" />
- </div>
- )}
-
- {/* Control Buttons Row */}
- <div className="flex items-center gap-2">
- {!hidePresetHeader && <Skeleton className="h-9 w-9 rounded-lg" />}
- <div className="flex-1" />
- <Skeleton className="h-9 w-9 rounded-lg" />
- <Skeleton className="h-9 w-9 rounded-lg" />
- </div>
- </div>
- );
-}
diff --git a/components/preset-list.tsx b/components/preset-list.tsx
index 1460606..723f431 100644
--- a/components/preset-list.tsx
+++ b/components/preset-list.tsx
@@ -13,8 +13,7 @@ import {
import { ShiftPreset } from "@/lib/db/schema";
import { CalendarWithCount } from "@/lib/types";
-import { getCachedPassword } from "@/lib/password-cache";
-import { PresetListSkeleton } from "@/components/preset-list-skeleton";
+import { useCalendarPermission } from "@/hooks/useCalendarPermission";
interface PresetListProps {
calendars: CalendarWithCount[];
@@ -25,99 +24,34 @@ interface PresetListProps {
onCreateNew?: () => void;
onManageClick?: () => void;
onViewSettingsClick?: () => void;
- onUnlock?: () => void;
- loading?: boolean;
hidePresetHeader?: boolean;
onHidePresetHeaderChange?: (hide: boolean) => void;
hideManageButton?: boolean;
}
export function PresetList({
- calendars,
calendarId,
presets,
selectedPresetId,
onSelectPreset,
onManageClick,
onViewSettingsClick,
- onUnlock,
- loading = false,
hidePresetHeader = false,
onHidePresetHeaderChange,
hideManageButton = false,
}: PresetListProps) {
const t = useTranslations();
+ const permission = useCalendarPermission(calendarId);
const [showSecondary, setShowSecondary] = React.useState(false);
const primaryPresets = presets.filter((p) => !p.isSecondary);
const secondaryPresets = presets.filter((p) => p.isSecondary);
- // Hide preset buttons if calendar requires password AND no valid password is cached
- const selectedCalendar = calendars.find((c) => c.id === calendarId);
- const requiresPassword = !!selectedCalendar?.passwordHash;
- const hasPassword = calendarId ? !!getCachedPassword(calendarId) : false;
- const isLocked = selectedCalendar?.isLocked === true;
- const shouldHidePresetButtons = requiresPassword && !hasPassword;
- const shouldShowUnlockHint = shouldHidePresetButtons && !isLocked;
+ // Check if current calendar is read-only
+ const isReadOnly = !permission.canEdit;
- // Show loading state while fetching
- if (loading) {
- return <PresetListSkeleton hidePresetHeader={hidePresetHeader} />;
- }
-
- // Show unlock hint if calendar requires password and no password is cached (but not locked)
- if (shouldShowUnlockHint) {
- return (
- <div className="border-2 border-dashed border-primary/30 rounded-lg p-4 sm:p-6 text-center space-y-3">
- <div className="flex items-center justify-center gap-2 text-primary">
- <svg
- xmlns="http://www.w3.org/2000/svg"
- className="h-5 w-5"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinecap="round"
- strokeLinejoin="round"
- >
- <rect width="18" height="11" x="3" y="11" rx="2" ry="2" />
- <path d="M7 11V7a5 5 0 0 1 10 0v4" />
- </svg>
- <p className="text-sm font-semibold">
- {t("password.unlockRequired")}
- </p>
- </div>
- <p className="text-xs sm:text-sm text-muted-foreground max-w-md mx-auto leading-relaxed">
- {t("password.unlockRequiredDescription")}
- </p>
- {onUnlock && (
- <Button onClick={onUnlock} size="sm" className="gap-2">
- <svg
- xmlns="http://www.w3.org/2000/svg"
- className="h-4 w-4"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinecap="round"
- strokeLinejoin="round"
- >
- <rect width="18" height="11" x="3" y="11" rx="2" ry="2" />
- <path d="M7 11V7a5 5 0 0 1 9.9-1" />
- </svg>
- <span className="text-xs sm:text-sm">
- {t("password.unlockCalendar")}
- </span>
- </Button>
- )}
- </div>
- );
- }
-
- // Hide everything if calendar requires password but no password is cached (regardless of unlock hint)
- if (shouldHidePresetButtons) {
- return null;
- }
+ // Presets are now loaded at page level - no skeleton needed here
+ // If loading is true, parent should show FullscreenLoader
if (presets.length === 0) {
return (
@@ -163,6 +97,7 @@ export function PresetList({
selectedPresetId === preset.id ? undefined : preset.id
)
}
+ isReadOnly={isReadOnly}
/>
))}
</div>
@@ -199,6 +134,7 @@ export function PresetList({
)
}
compact
+ isReadOnly={isReadOnly}
/>
))}
</div>
@@ -261,6 +197,7 @@ interface PresetButtonProps {
isSelected: boolean;
onSelect: () => void;
compact?: boolean;
+ isReadOnly?: boolean;
}
function PresetButton({
@@ -268,6 +205,7 @@ function PresetButton({
isSelected,
onSelect,
compact,
+ isReadOnly = false,
}: PresetButtonProps) {
const t = useTranslations();
@@ -276,7 +214,8 @@ function PresetButton({
<Button
variant={isSelected ? "default" : "outline"}
size="sm"
- onClick={onSelect}
+ onClick={isReadOnly ? undefined : onSelect}
+ disabled={isReadOnly}
className="relative text-xs sm:text-sm px-2 sm:px-3 h-8 sm:h-9"
style={{
backgroundColor: isSelected ? preset.color : undefined,
@@ -312,7 +251,8 @@ function PresetButton({
<Button
variant={isSelected ? "default" : "outline"}
size="sm"
- onClick={onSelect}
+ onClick={isReadOnly ? undefined : onSelect}
+ disabled={isReadOnly}
className="relative text-[11px] sm:text-sm px-2 sm:px-4 h-8 sm:h-10 rounded-full font-semibold transition-all"
style={{
backgroundColor: isSelected ? preset.color : undefined,
diff --git a/components/preset-manage-sheet.tsx b/components/preset-manage-sheet.tsx
index ec17fbf..45dc0cd 100644
--- a/components/preset-manage-sheet.tsx
+++ b/components/preset-manage-sheet.tsx
@@ -37,8 +37,10 @@ import { ShiftPreset } from "@/lib/db/schema";
import { PRESET_COLORS } from "@/lib/constants";
import { Plus, Trash2, Edit2, Loader2, GripVertical } from "lucide-react";
import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
+import { ReadOnlyBanner } from "@/components/read-only-banner";
import { useDirtyState } from "@/hooks/useDirtyState";
import { usePresetManagement } from "@/hooks/usePresetManagement";
+import { useCalendarPermission } from "@/hooks/useCalendarPermission";
interface PresetFormData {
title: string;
@@ -57,6 +59,7 @@ interface PresetManageSheetProps {
calendarId: string;
presets: ShiftPreset[];
onPresetsChange: () => void;
+ readOnly?: boolean;
}
// Sortable preset item component
@@ -67,6 +70,7 @@ interface SortablePresetItemProps {
onDelete: (id: string) => void;
t: (key: string) => string;
showDragHandle?: boolean;
+ isReadOnly?: boolean;
}
const SortablePresetItem = memo(function SortablePresetItem({
@@ -76,6 +80,7 @@ const SortablePresetItem = memo(function SortablePresetItem({
onDelete,
t,
showDragHandle = true,
+ isReadOnly = false,
}: SortablePresetItemProps) {
const {
attributes,
@@ -141,28 +146,32 @@ const SortablePresetItem = memo(function SortablePresetItem({
)}
</div>
<div className="flex gap-1 shrink-0">
- <Button
- size="icon"
- variant="ghost"
- className="h-8 w-8"
- onClick={() => onEdit(preset)}
- disabled={isDeleting}
- >
- <Edit2 className="h-4 w-4" />
- </Button>
- <Button
- size="icon"
- variant="ghost"
- className="h-8 w-8 text-destructive hover:text-destructive"
- onClick={() => onDelete(preset.id)}
- disabled={isDeleting}
- >
- {isDeleting ? (
- <Loader2 className="h-4 w-4 animate-spin" />
- ) : (
- <Trash2 className="h-4 w-4" />
- )}
- </Button>
+ {!isReadOnly && (
+ <>
+ <Button
+ size="icon"
+ variant="ghost"
+ className="h-8 w-8"
+ onClick={() => onEdit(preset)}
+ disabled={isDeleting}
+ >
+ <Edit2 className="h-4 w-4" />
+ </Button>
+ <Button
+ size="icon"
+ variant="ghost"
+ className="h-8 w-8 text-destructive hover:text-destructive"
+ onClick={() => onDelete(preset.id)}
+ disabled={isDeleting}
+ >
+ {isDeleting ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Trash2 className="h-4 w-4" />
+ )}
+ </Button>
+ </>
+ )}
</div>
</div>
</div>
@@ -175,9 +184,15 @@ export function PresetManageSheet({
calendarId,
presets,
onPresetsChange,
+ readOnly = false,
}: PresetManageSheetProps) {
const t = useTranslations();
+ const permission = useCalendarPermission(calendarId);
+
+ // Determine if sheet should be in read-only mode
+ const isReadOnly = readOnly || !permission.canEdit;
+
const [showAddForm, setShowAddForm] = useState(false);
const [editingPreset, setEditingPreset] = useState<ShiftPreset | null>(null);
const [formData, setFormData] = useState<PresetFormData>({
@@ -474,6 +489,13 @@ export function PresetManageSheet({
</SheetDescription>
</SheetHeader>
+ {/* Read-Only Banner */}
+ {isReadOnly && (
+ <div className="px-6 pt-6">
+ <ReadOnlyBanner message={t("guest.cannotEdit")} />
+ </div>
+ )}
+
<div className="flex-1 overflow-y-auto px-6 py-6 space-y-3">
{/* Empty state when no presets exist */}
{presets.length === 0 && !showAddForm && !editingPreset && (
@@ -509,6 +531,7 @@ export function PresetManageSheet({
onDelete={handleDeleteClick}
t={t}
showDragHandle={orderedPrimaryPresets.length > 1}
+ isReadOnly={isReadOnly}
/>
))}
</div>
@@ -544,6 +567,7 @@ export function PresetManageSheet({
onDelete={handleDeleteClick}
t={t}
showDragHandle={orderedSecondaryPresets.length > 1}
+ isReadOnly={isReadOnly}
/>
))}
</div>
@@ -562,6 +586,7 @@ export function PresetManageSheet({
onDelete={handleDeleteClick}
t={t}
showDragHandle={false}
+ isReadOnly={isReadOnly}
/>
</div>
)}
@@ -732,7 +757,7 @@ export function PresetManageSheet({
</div>
{/* Footer: Always visible Add or Save button */}
- {!showAddForm && !editingPreset ? (
+ {!showAddForm && !editingPreset && !isReadOnly && (
<div className="border-t border-border/50 bg-muted/20 px-6 py-4 mt-auto">
<Button
onClick={startAdd}
@@ -743,7 +768,8 @@ export function PresetManageSheet({
{t("preset.createNew")}
</Button>
</div>
- ) : (
+ )}
+ {!isReadOnly && (showAddForm || editingPreset) && (
<SheetFooter className="border-t border-border/50 bg-muted/20 px-6 py-4 mt-auto">
<div className="flex gap-2.5 w-full">
<Button
diff --git a/components/preset-selector.tsx b/components/preset-selector.tsx
index 9e220e7..0a5f4a7 100644
--- a/components/preset-selector.tsx
+++ b/components/preset-selector.tsx
@@ -5,7 +5,6 @@ import { CalendarWithCount } from "@/lib/types";
import { useState } from "react";
import { PresetList } from "@/components/preset-list";
import { PresetManageSheet } from "@/components/preset-manage-sheet";
-import { usePasswordProtection } from "@/hooks/usePasswordProtection";
interface PresetSelectorProps {
calendars: CalendarWithCount[];
@@ -16,7 +15,6 @@ interface PresetSelectorProps {
onShiftsChange?: () => void;
onStatsRefresh?: () => void;
calendarId: string;
- onPasswordRequired: (action: () => Promise<void>) => void;
onViewSettingsClick?: () => void;
loading?: boolean;
hidePresetHeader?: boolean;
@@ -33,24 +31,15 @@ export function PresetSelector({
onShiftsChange,
onStatsRefresh,
calendarId,
- onPasswordRequired,
onViewSettingsClick,
- loading = false,
hidePresetHeader = false,
onHidePresetHeaderChange,
hideManageButton = false,
}: PresetSelectorProps) {
const [showManageDialog, setShowManageDialog] = useState(false);
- const { withPasswordCheck } = usePasswordProtection({
- calendarId,
- onPasswordRequired,
- });
-
- const handleManageClick = async () => {
- await withPasswordCheck(async () => {
- setShowManageDialog(true);
- });
+ const handleManageClick = () => {
+ setShowManageDialog(true);
};
const handlePresetsChange = () => {
@@ -70,8 +59,6 @@ export function PresetSelector({
onCreateNew={handleManageClick}
onManageClick={handleManageClick}
onViewSettingsClick={onViewSettingsClick}
- onUnlock={() => onPasswordRequired(async () => {})}
- loading={loading}
hidePresetHeader={hidePresetHeader}
onHidePresetHeaderChange={onHidePresetHeaderChange}
hideManageButton={hideManageButton}
diff --git a/components/public-config-provider.tsx b/components/public-config-provider.tsx
new file mode 100644
index 0000000..6d2cf6f
--- /dev/null
+++ b/components/public-config-provider.tsx
@@ -0,0 +1,110 @@
+"use client";
+
+import React, { createContext, useContext, useEffect, useState } from "react";
+import type { PublicConfig } from "@/lib/public-config";
+
+/**
+ * React Context for public configuration
+ */
+const PublicConfigContext = createContext<PublicConfig | null>(null);
+
+/**
+ * Props for PublicConfigProvider
+ */
+interface PublicConfigProviderProps {
+ children: React.ReactNode;
+ /**
+ * Initial config passed from server during SSR.
+ * This eliminates the need for a client-side API call on initial load.
+ */
+ initialConfig: PublicConfig;
+}
+
+/**
+ * Provider component that makes public configuration available to all client components.
+ *
+ * This provider uses two sources for configuration:
+ * 1. SSR: `initialConfig` prop passed from server (zero latency)
+ * 2. CSR: `window.__PUBLIC_CONFIG__` injected via script tag (fallback)
+ *
+ * If neither is available, it falls back to fetching from /api/public-config
+ * (rare edge case for pure CSR scenarios).
+ */
+export function PublicConfigProvider({
+ children,
+ initialConfig,
+}: PublicConfigProviderProps) {
+ // Initialize config with SSR value or hydrate from window
+ const [config, setConfig] = useState<PublicConfig>(() => {
+ // Try window first (CSR hydration)
+ if (typeof window !== "undefined" && window.__PUBLIC_CONFIG__) {
+ return window.__PUBLIC_CONFIG__;
+ }
+ // Fall back to SSR initial config
+ return initialConfig;
+ });
+
+ useEffect(() => {
+ // Only fetch if we have no config at all (rare edge case)
+ if (!config && typeof window !== "undefined") {
+ fetch("/api/public-config")
+ .then((res) => res.json())
+ .then((data) => setConfig(data))
+ .catch((err) =>
+ console.error("[PUBLIC_CONFIG] Failed to fetch config:", err)
+ );
+ }
+ }, [config]);
+
+ return (
+ <PublicConfigContext.Provider value={config}>
+ {children}
+ </PublicConfigContext.Provider>
+ );
+}
+
+/**
+ * Hook to access public configuration in client components.
+ *
+ * @throws Error if used outside of PublicConfigProvider
+ * @returns Public configuration object
+ *
+ * @example
+ * ```tsx
+ * function MyComponent() {
+ * const { auth, oauth } = usePublicConfig();
+ *
+ * if (!auth.enabled) {
+ * return <div>Auth is disabled</div>;
+ * }
+ *
+ * return (
+ * <div>
+ * {oauth.google && <GoogleLoginButton />}
+ * {oauth.github && <GitHubLoginButton />}
+ * </div>
+ * );
+ * }
+ * ```
+ */
+export function usePublicConfig(): PublicConfig {
+ const context = useContext(PublicConfigContext);
+
+ if (!context) {
+ throw new Error(
+ "usePublicConfig must be used within PublicConfigProvider. " +
+ "Make sure your component is wrapped in the provider (usually in the root layout)."
+ );
+ }
+
+ return context;
+}
+
+/**
+ * TypeScript declaration for the global window object
+ */
+declare global {
+ interface Window {
+ __PUBLIC_CONFIG__?: PublicConfig;
+ }
+}
diff --git a/components/read-only-banner.tsx b/components/read-only-banner.tsx
new file mode 100644
index 0000000..c3702e3
--- /dev/null
+++ b/components/read-only-banner.tsx
@@ -0,0 +1,32 @@
+"use client";
+
+import { Eye, Lock } from "lucide-react";
+import { Alert, AlertDescription } from "@/components/ui/alert";
+
+interface ReadOnlyBannerProps {
+ message?: string;
+ variant?: "default" | "compact";
+}
+
+export function ReadOnlyBanner({
+ message,
+ variant = "default",
+}: ReadOnlyBannerProps) {
+ if (variant === "compact") {
+ return (
+ <div className="bg-blue-50 dark:bg-blue-950/30 border border-blue-200 dark:border-blue-900/50 rounded-md p-2 flex items-center gap-2">
+ <Eye className="h-4 w-4 text-blue-600 dark:text-blue-400 shrink-0" />
+ <p className="text-xs text-blue-900 dark:text-blue-100">{message}</p>
+ </div>
+ );
+ }
+
+ return (
+ <Alert className="bg-blue-50 dark:bg-blue-950/30 border-blue-200 dark:border-blue-900/50">
+ <Lock className="h-4 w-4 text-blue-600 dark:text-blue-400" />
+ <AlertDescription className="text-sm text-blue-900 dark:text-blue-100">
+ {message}
+ </AlertDescription>
+ </Alert>
+ );
+}
diff --git a/components/shift-form-fields.tsx b/components/shift-form-fields.tsx
index 473cea2..2d3dcf8 100644
--- a/components/shift-form-fields.tsx
+++ b/components/shift-form-fields.tsx
@@ -18,6 +18,7 @@ interface ShiftFormFieldsProps {
isEditing: boolean;
onBlur?: () => void;
showSaved?: boolean;
+ readOnly?: boolean;
}
export function ShiftFormFields({
@@ -29,6 +30,7 @@ export function ShiftFormFields({
onPresetNameChange,
isEditing,
onBlur,
+ readOnly = false,
}: ShiftFormFieldsProps) {
const t = useTranslations();
@@ -50,6 +52,7 @@ export function ShiftFormFields({
onFormDataChange({ ...formData, date: e.target.value })
}
onBlur={onBlur}
+ disabled={readOnly}
className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50 backdrop-blur-sm"
/>
</div>
@@ -62,6 +65,7 @@ export function ShiftFormFields({
onFormDataChange({ ...formData, isAllDay: !!checked });
setTimeout(() => onBlur?.(), 10);
}}
+ disabled={readOnly}
/>
<Label htmlFor="allDay" className="text-sm font-medium cursor-pointer">
{t("shift.allDayShift")}
@@ -88,6 +92,7 @@ export function ShiftFormFields({
onFormDataChange({ ...formData, startTime: e.target.value })
}
onBlur={onBlur}
+ disabled={readOnly}
className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
/>
</div>
@@ -103,6 +108,7 @@ export function ShiftFormFields({
onFormDataChange({ ...formData, endTime: e.target.value })
}
onBlur={onBlur}
+ disabled={readOnly}
className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
/>
</div>
@@ -125,8 +131,9 @@ export function ShiftFormFields({
onFormDataChange({ ...formData, title: e.target.value })
}
onBlur={onBlur}
+ disabled={readOnly}
className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50 backdrop-blur-sm"
- autoFocus
+ autoFocus={!readOnly}
/>
</div>
@@ -146,6 +153,7 @@ export function ShiftFormFields({
onFormDataChange({ ...formData, notes: e.target.value })
}
onBlur={onBlur}
+ disabled={readOnly}
rows={3}
className="border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50 resize-none"
/>
@@ -156,10 +164,11 @@ export function ShiftFormFields({
onChange={(color) => onFormDataChange({ ...formData, color })}
label={t("form.colorLabel")}
presetColors={PRESET_COLORS}
+ disabled={readOnly}
/>
{/* Auto-Save as Preset */}
- {!isEditing && (
+ {!isEditing && !readOnly && (
<div className="space-y-3 p-4 bg-primary/5 border border-primary/20 rounded-xl">
<div className="flex items-center space-x-2">
<Checkbox
diff --git a/components/shift-sheet.tsx b/components/shift-sheet.tsx
index 7d48ec9..163dadf 100644
--- a/components/shift-sheet.tsx
+++ b/components/shift-sheet.tsx
@@ -6,7 +6,9 @@ import { BaseSheet } from "@/components/ui/base-sheet";
import { ShiftWithCalendar } from "@/lib/types";
import { ShiftFormFields } from "@/components/shift-form-fields";
import { PresetSelect } from "@/components/preset-select";
+import { ReadOnlyBanner } from "@/components/read-only-banner";
import { useShiftForm } from "@/hooks/useShiftForm";
+import { useCalendarPermission } from "@/hooks/useCalendarPermission";
import { formatDateToLocal } from "@/lib/date-utils";
interface ShiftSheetProps {
@@ -17,6 +19,7 @@ interface ShiftSheetProps {
shift?: ShiftWithCalendar;
onPresetsChange?: () => void;
calendarId?: string;
+ readOnly?: boolean; // Explicitly set read-only mode
}
export interface ShiftFormData {
@@ -38,11 +41,16 @@ export function ShiftSheet({
shift,
onPresetsChange,
calendarId,
+ readOnly = false,
}: ShiftSheetProps) {
const t = useTranslations();
+ const permission = useCalendarPermission(calendarId);
const [isSaving, setIsSaving] = useState(false);
const initialFormDataRef = useRef<string | null>(null);
+ // Determine if sheet should be in read-only mode
+ const isReadOnly = readOnly || !permission.canEdit;
+
const {
formData,
setFormData,
@@ -151,17 +159,20 @@ export function ShiftSheet({
description={
shift ? t("shift.editDescription") : t("shift.createDescription")
}
- showSaveButton
+ showSaveButton={!isReadOnly}
showCancelButton
onSave={handleSave}
isSaving={isSaving}
saveDisabled={!formData.title.trim() || (shift && !hasChanges())}
- hasUnsavedChanges={hasChanges()}
+ hasUnsavedChanges={!isReadOnly && hasChanges()}
maxWidth="md"
>
<div className="space-y-5">
+ {/* Read-only banner */}
+ {isReadOnly && <ReadOnlyBanner message={t("guest.cannotEdit")} />}
+
{/* Preset Selection */}
- {!shift && (
+ {!shift && !isReadOnly && (
<PresetSelect presets={presets} onPresetSelect={handlePresetSelect} />
)}
@@ -173,6 +184,7 @@ export function ShiftSheet({
presetName={presetName}
onPresetNameChange={setPresetName}
isEditing={!!shift}
+ readOnly={isReadOnly}
/>
</div>
</BaseSheet>
diff --git a/components/shift-stats-skeleton.tsx b/components/shift-stats-skeleton.tsx
deleted file mode 100644
index b9bfa3e..0000000
--- a/components/shift-stats-skeleton.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-"use client";
-import { Skeleton } from "@/components/ui/skeleton";
-import { useTranslations } from "next-intl";
-import { BarChart3 } from "lucide-react";
-
-export function ShiftStatsSkeleton() {
- const t = useTranslations();
-
- return (
- <div className="border border-border/50 rounded-xl bg-gradient-to-b from-card/80 via-card/60 to-card/40 backdrop-blur-sm overflow-hidden shadow-lg">
- <div className="px-3 sm:px-4 py-3 sm:py-3.5 flex items-center justify-between">
- <div className="flex items-center gap-2.5">
- <div className="w-9 h-9 rounded-xl bg-gradient-to-br from-primary to-primary/70 flex items-center justify-center shadow-lg shadow-primary/20">
- <BarChart3 className="h-4 w-4 sm:h-5 sm:w-5 text-primary-foreground" />
- </div>
- <h3 className="text-sm sm:text-base font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">
- {t("stats.title")}
- </h3>
- </div>
- </div>
-
- <div className="border-t border-border/30 bg-muted/20 p-3 sm:p-4 space-y-3">
- <div className="flex items-center justify-center gap-2">
- <Skeleton className="h-9 w-20 rounded-lg" />
- <Skeleton className="h-9 w-20 rounded-lg" />
- <Skeleton className="h-9 w-20 rounded-lg" />
- </div>
-
- <div className="space-y-2">
- <Skeleton className="h-12 w-full rounded-lg" />
- <Skeleton className="h-12 w-full rounded-lg" />
- <Skeleton className="h-12 w-full rounded-lg" />
- </div>
- </div>
- </div>
- );
-}
diff --git a/components/shift-stats.tsx b/components/shift-stats.tsx
index 8845f4e..585d568 100644
--- a/components/shift-stats.tsx
+++ b/components/shift-stats.tsx
@@ -11,7 +11,6 @@ import {
Radar as RadarIcon,
} from "lucide-react";
import { formatDuration } from "@/lib/date-utils";
-import { Skeleton } from "@/components/ui/skeleton";
import { useShiftStats } from "@/hooks/useShiftStats";
import {
PieChart as RechartsPieChart,
@@ -286,9 +285,8 @@ export function ShiftStats({
{/* Stats Display */}
{loading ? (
- <div className="space-y-3">
- <Skeleton className="h-20 w-full rounded-lg" />
- <Skeleton className="h-64 w-full rounded-lg" />
+ <div className="text-center py-8 text-sm text-muted-foreground">
+ {t("common.loading")}
</div>
) : stats && Object.keys(stats.stats).length > 0 ? (
<div className="space-y-3.5">
diff --git a/components/shifts-list.tsx b/components/shifts-list.tsx
index 87b5f7f..2c5feaa 100644
--- a/components/shifts-list.tsx
+++ b/components/shifts-list.tsx
@@ -6,23 +6,30 @@ import { getDateLocale } from "@/lib/locales";
import { ShiftWithCalendar } from "@/lib/types";
import { ShiftCard } from "@/components/shift-card";
import { ChevronUp, ChevronDown, Calendar as CalendarIcon } from "lucide-react";
+import { useCalendarPermission } from "@/hooks/useCalendarPermission";
interface ShiftsListProps {
shifts: ShiftWithCalendar[];
currentDate: Date;
onDeleteShift?: (id: string) => void;
+ calendarId?: string; // Optional: if provided, uses this for permission check instead of first shift's calendarId
}
export function ShiftsList({
shifts,
currentDate,
onDeleteShift,
+ calendarId: propCalendarId,
}: ShiftsListProps) {
const t = useTranslations();
const locale = useLocale();
const dateLocale = getDateLocale(locale);
const [showShiftsSection, setShowShiftsSection] = useState(false);
+ // Get calendar ID from props or first shift
+ const calendarId = propCalendarId || shifts[0]?.calendarId;
+ const { canEdit } = useCalendarPermission(calendarId);
+
const shiftsInMonth = shifts.filter((shift) => {
if (!shift.date) return false;
const shiftDate = new Date(shift.date);
@@ -156,7 +163,7 @@ export function ShiftsList({
<ShiftCard
key={shift.id}
shift={shift}
- onDelete={onDeleteShift}
+ onDelete={canEdit ? onDeleteShift : undefined}
/>
))}
</div>
diff --git a/components/sync-notification-dialog.tsx b/components/sync-notification-dialog.tsx
index 3f15362..b64ca96 100644
--- a/components/sync-notification-dialog.tsx
+++ b/components/sync-notification-dialog.tsx
@@ -2,7 +2,6 @@
import { useCallback, useEffect, useState } from "react";
import { useLocale, useTranslations } from "next-intl";
-import { getCachedPassword } from "@/lib/password-cache";
import {
Dialog,
DialogContent,
@@ -29,7 +28,6 @@ import {
CheckCheck,
} from "lucide-react";
import { toast } from "sonner";
-import { Skeleton } from "@/components/ui/skeleton";
interface SyncNotificationDialogProps {
open: boolean;
@@ -64,11 +62,7 @@ export function SyncNotificationDialog({
setLoading(true);
}
try {
- const password = getCachedPassword(calendarId);
const params = new URLSearchParams({ calendarId, limit: "20" });
- if (password) {
- params.append("password", password);
- }
const response = await fetch(`/api/sync-logs?${params}`);
if (response.ok) {
@@ -141,12 +135,10 @@ export function SyncNotificationDialog({
setShowDeleteConfirm(false);
try {
- const password = getCachedPassword(calendarId);
-
const response = await fetch(`/api/sync-logs?calendarId=${calendarId}`, {
method: "DELETE",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ password }),
+ body: JSON.stringify({}),
});
if (response.ok) {
@@ -174,14 +166,12 @@ export function SyncNotificationDialog({
setIsMarkingRead(true);
try {
- const password = getCachedPassword(calendarId);
-
const response = await fetch(
`/api/sync-logs?calendarId=${calendarId}&action=markErrorsAsRead`,
{
method: "PATCH",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ password }),
+ body: JSON.stringify({}),
}
);
@@ -267,10 +257,8 @@ export function SyncNotificationDialog({
<div className="space-y-4 overflow-y-auto flex-1 px-6 pb-6">
{loading ? (
- <div className="space-y-4">
- <Skeleton className="h-32 w-full rounded-lg" />
- <Skeleton className="h-32 w-full rounded-lg" />
- <Skeleton className="h-32 w-full rounded-lg" />
+ <div className="text-center py-8 text-muted-foreground">
+ {t("common.loading")}
</div>
) : filteredLogs.length === 0 ? (
<div className="text-center py-8 text-muted-foreground">
diff --git a/components/theme-switcher.tsx b/components/theme-switcher.tsx
index 0cd9c53..0d0ec38 100644
--- a/components/theme-switcher.tsx
+++ b/components/theme-switcher.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useState, useLayoutEffect } from "react";
import { useTheme } from "next-themes";
import { useTranslations } from "next-intl";
import { Moon, Sun } from "lucide-react";
@@ -8,11 +9,30 @@ import { Button } from "@/components/ui/button";
export function ThemeSwitcher() {
const { theme, setTheme } = useTheme();
const t = useTranslations();
+ const [mounted, setMounted] = useState(false);
+
+ // Set mounted after initial render to avoid hydration mismatch
+ // This is a legitimate pattern for SSR hydration - calling setState in useLayoutEffect
+ // is the recommended approach to avoid hydration mismatches in client components.
+ useLayoutEffect(() => {
+ // eslint-disable-next-line react-hooks/set-state-in-effect
+ setMounted(true);
+ }, []);
const toggleTheme = () => {
setTheme(theme === "dark" ? "light" : "dark");
};
+ // Render placeholder with same dimensions during SSR
+ if (!mounted) {
+ return (
+ <Button variant="ghost" size="icon" className="h-9 w-9" disabled>
+ <div className="h-4 w-4" />
+ <span className="sr-only">Toggle theme</span>
+ </Button>
+ );
+ }
+
return (
<Button
variant="ghost"
diff --git a/components/ui/avatar.tsx b/components/ui/avatar.tsx
new file mode 100644
index 0000000..fda1c3d
--- /dev/null
+++ b/components/ui/avatar.tsx
@@ -0,0 +1,48 @@
+import * as React from "react";
+import * as AvatarPrimitive from "@radix-ui/react-avatar";
+
+import { cn } from "@/lib/utils";
+
+const Avatar = React.forwardRef<
+ React.ElementRef<typeof AvatarPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
+>(({ className, ...props }, ref) => (
+ <AvatarPrimitive.Root
+ ref={ref}
+ className={cn(
+ "relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
+ className
+ )}
+ {...props}
+ />
+));
+Avatar.displayName = AvatarPrimitive.Root.displayName;
+
+const AvatarImage = React.forwardRef<
+ React.ElementRef<typeof AvatarPrimitive.Image>,
+ React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
+>(({ className, ...props }, ref) => (
+ <AvatarPrimitive.Image
+ ref={ref}
+ className={cn("aspect-square h-full w-full", className)}
+ {...props}
+ />
+));
+AvatarImage.displayName = AvatarPrimitive.Image.displayName;
+
+const AvatarFallback = React.forwardRef<
+ React.ElementRef<typeof AvatarPrimitive.Fallback>,
+ React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
+>(({ className, ...props }, ref) => (
+ <AvatarPrimitive.Fallback
+ ref={ref}
+ className={cn(
+ "flex h-full w-full items-center justify-center rounded-full bg-muted",
+ className
+ )}
+ {...props}
+ />
+));
+AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName;
+
+export { Avatar, AvatarImage, AvatarFallback };
diff --git a/components/ui/breadcrumb.tsx b/components/ui/breadcrumb.tsx
new file mode 100644
index 0000000..10d57b2
--- /dev/null
+++ b/components/ui/breadcrumb.tsx
@@ -0,0 +1,120 @@
+import * as React from "react";
+import { ChevronRight, MoreHorizontal } from "lucide-react";
+
+import { cn } from "@/lib/utils";
+
+const Breadcrumb = React.forwardRef<
+ HTMLElement,
+ React.ComponentPropsWithoutRef<"nav"> & {
+ separator?: React.ReactNode;
+ }
+>(({ ...props }, ref) => <nav ref={ref} aria-label="breadcrumb" {...props} />);
+Breadcrumb.displayName = "Breadcrumb";
+
+const BreadcrumbList = React.forwardRef<
+ HTMLOListElement,
+ React.ComponentPropsWithoutRef<"ol">
+>(({ className, ...props }, ref) => (
+ <ol
+ ref={ref}
+ className={cn(
+ "flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",
+ className
+ )}
+ {...props}
+ />
+));
+BreadcrumbList.displayName = "BreadcrumbList";
+
+const BreadcrumbItem = React.forwardRef<
+ HTMLLIElement,
+ React.ComponentPropsWithoutRef<"li">
+>(({ className, ...props }, ref) => (
+ <li
+ ref={ref}
+ className={cn("inline-flex items-center gap-1.5", className)}
+ {...props}
+ />
+));
+BreadcrumbItem.displayName = "BreadcrumbItem";
+
+const BreadcrumbLink = React.forwardRef<
+ HTMLAnchorElement,
+ React.ComponentPropsWithoutRef<"a"> & {
+ asChild?: boolean;
+ }
+>(({ className, asChild, ...props }, ref) => {
+ if (asChild) {
+ // Don't forward ref when using asChild pattern (children handle their own ref)
+ return <>{props.children}</>;
+ }
+
+ return (
+ <a
+ ref={ref}
+ className={cn(
+ "transition-colors hover:text-foreground cursor-pointer",
+ className
+ )}
+ {...props}
+ />
+ );
+});
+BreadcrumbLink.displayName = "BreadcrumbLink";
+
+const BreadcrumbPage = React.forwardRef<
+ HTMLSpanElement,
+ React.ComponentPropsWithoutRef<"span">
+>(({ className, ...props }, ref) => (
+ <span
+ ref={ref}
+ role="link"
+ aria-disabled="true"
+ aria-current="page"
+ className={cn("font-normal text-foreground", className)}
+ {...props}
+ />
+));
+BreadcrumbPage.displayName = "BreadcrumbPage";
+
+const BreadcrumbSeparator = ({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"li">) => (
+ <li
+ role="presentation"
+ aria-hidden="true"
+ className={cn("[&>svg]:size-3.5", className)}
+ {...props}
+ >
+ {children ?? <ChevronRight />}
+ </li>
+);
+BreadcrumbSeparator.displayName = "BreadcrumbSeparator";
+
+const BreadcrumbEllipsis = ({
+ className,
+ ...props
+}: React.ComponentProps<"span">) => (
+ <span
+ role="presentation"
+ aria-hidden="true"
+ className={cn("flex h-9 w-9 items-center justify-center", className)}
+ {...props}
+ >
+ <MoreHorizontal className="h-4 w-4" />
+ <span className="sr-only">More</span>
+ </span>
+);
+BreadcrumbEllipsis.displayName = "BreadcrumbEllipsis";
+
+export {
+ Breadcrumb,
+ BreadcrumbList,
+ BreadcrumbItem,
+ BreadcrumbLink,
+ BreadcrumbPage,
+ BreadcrumbSeparator,
+ BreadcrumbEllipsis,
+};
diff --git a/components/ui/calendar.tsx b/components/ui/calendar.tsx
new file mode 100644
index 0000000..3ffc0d9
--- /dev/null
+++ b/components/ui/calendar.tsx
@@ -0,0 +1,61 @@
+"use client";
+
+import * as React from "react";
+import { DayPicker } from "react-day-picker";
+
+import { cn } from "@/lib/utils";
+import { buttonVariants } from "@/components/ui/button";
+
+export type CalendarProps = React.ComponentProps<typeof DayPicker>;
+
+function Calendar({
+ className,
+ classNames,
+ showOutsideDays = true,
+ ...props
+}: CalendarProps) {
+ return (
+ <DayPicker
+ showOutsideDays={showOutsideDays}
+ className={cn("p-3", className)}
+ classNames={{
+ months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",
+ month: "space-y-4",
+ caption: "flex justify-center pt-1 relative items-center",
+ caption_label: "text-sm font-medium",
+ nav: "space-x-1 flex items-center",
+ nav_button: cn(
+ buttonVariants({ variant: "outline" }),
+ "h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"
+ ),
+ nav_button_previous: "absolute left-1",
+ nav_button_next: "absolute right-1",
+ table: "w-full border-collapse space-y-1",
+ head_row: "flex",
+ head_cell:
+ "text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",
+ row: "flex w-full mt-2",
+ cell: "h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",
+ day: cn(
+ buttonVariants({ variant: "ghost" }),
+ "h-9 w-9 p-0 font-normal aria-selected:opacity-100"
+ ),
+ day_range_end: "day-range-end",
+ day_selected:
+ "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",
+ day_today: "bg-accent text-accent-foreground",
+ day_outside:
+ "day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",
+ day_disabled: "text-muted-foreground opacity-50",
+ day_range_middle:
+ "aria-selected:bg-accent aria-selected:text-accent-foreground",
+ day_hidden: "invisible",
+ ...classNames,
+ }}
+ {...props}
+ />
+ );
+}
+Calendar.displayName = "Calendar";
+
+export { Calendar };
diff --git a/components/ui/color-picker.tsx b/components/ui/color-picker.tsx
index 56009c2..2afde37 100644
--- a/components/ui/color-picker.tsx
+++ b/components/ui/color-picker.tsx
@@ -19,6 +19,7 @@ interface ColorPickerProps {
onChange: (color: string) => void;
label?: string;
presetColors?: { name: string; value: string }[];
+ disabled?: boolean;
}
export function ColorPicker({
@@ -26,6 +27,7 @@ export function ColorPicker({
onChange,
label = "Color",
presetColors = [],
+ disabled = false,
}: ColorPickerProps) {
const [open, setOpen] = useState(false);
const t = useTranslations();
@@ -44,12 +46,13 @@ export function ColorPicker({
<button
key={preset.value}
type="button"
- onClick={() => onChange(preset.value)}
+ onClick={() => !disabled && onChange(preset.value)}
+ disabled={disabled}
className={`w-10 h-10 rounded-lg border-2 transition-all ${
color === preset.value
? "border-primary scale-110 shadow-lg"
: "border-border/30 hover:border-border/60 hover:scale-105"
- }`}
+ } ${disabled ? "opacity-50 cursor-not-allowed" : ""}`}
style={{
backgroundColor: preset.value,
boxShadow:
@@ -62,11 +65,12 @@ export function ColorPicker({
))}
{/* Custom Color Picker Button */}
- <Dialog open={open} onOpenChange={setOpen}>
+ <Dialog open={open} onOpenChange={disabled ? () => {} : setOpen}>
<DialogTrigger asChild>
<Button
type="button"
variant="outline"
+ disabled={disabled}
className="h-10 px-3 gap-2 border-2 border-dashed border-border/50 hover:border-primary/50 relative transition-all"
title={t("color.custom", { default: "Custom color" })}
>
diff --git a/components/ui/confirmation-dialog.tsx b/components/ui/confirmation-dialog.tsx
index 6eca753..c07a771 100644
--- a/components/ui/confirmation-dialog.tsx
+++ b/components/ui/confirmation-dialog.tsx
@@ -21,6 +21,8 @@ interface ConfirmationDialogProps {
cancelText?: string;
confirmText?: string;
confirmVariant?: "default" | "destructive";
+ confirmDisabled?: boolean;
+ children?: React.ReactNode;
}
export function ConfirmationDialog({
@@ -32,6 +34,8 @@ export function ConfirmationDialog({
cancelText,
confirmText,
confirmVariant = "default",
+ confirmDisabled = false,
+ children,
}: ConfirmationDialogProps) {
const t = useTranslations();
@@ -46,12 +50,14 @@ export function ConfirmationDialog({
{description || t("common.unsavedChangesDescription")}
</AlertDialogDescription>
</AlertDialogHeader>
+ {children}
<AlertDialogFooter>
<AlertDialogCancel>
{cancelText || t("common.cancel")}
</AlertDialogCancel>
<AlertDialogAction
onClick={onConfirm}
+ disabled={confirmDisabled}
className={
confirmVariant === "destructive"
? "bg-destructive text-destructive-foreground hover:bg-destructive/90"
diff --git a/components/ui/dropdown-menu.tsx b/components/ui/dropdown-menu.tsx
new file mode 100644
index 0000000..48c7147
--- /dev/null
+++ b/components/ui/dropdown-menu.tsx
@@ -0,0 +1,198 @@
+import * as React from "react";
+import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
+import { Check, ChevronRight, Circle } from "lucide-react";
+
+import { cn } from "@/lib/utils";
+
+const DropdownMenu = DropdownMenuPrimitive.Root;
+
+const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
+
+const DropdownMenuGroup = DropdownMenuPrimitive.Group;
+
+const DropdownMenuPortal = DropdownMenuPrimitive.Portal;
+
+const DropdownMenuSub = DropdownMenuPrimitive.Sub;
+
+const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;
+
+const DropdownMenuSubTrigger = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
+ inset?: boolean;
+ }
+>(({ className, inset, children, ...props }, ref) => (
+ <DropdownMenuPrimitive.SubTrigger
+ ref={ref}
+ className={cn(
+ "flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
+ inset && "pl-8",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ <ChevronRight className="ml-auto" />
+ </DropdownMenuPrimitive.SubTrigger>
+));
+DropdownMenuSubTrigger.displayName =
+ DropdownMenuPrimitive.SubTrigger.displayName;
+
+const DropdownMenuSubContent = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
+>(({ className, ...props }, ref) => (
+ <DropdownMenuPrimitive.SubContent
+ ref={ref}
+ className={cn(
+ "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
+ className
+ )}
+ {...props}
+ />
+));
+DropdownMenuSubContent.displayName =
+ DropdownMenuPrimitive.SubContent.displayName;
+
+const DropdownMenuContent = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
+>(({ className, sideOffset = 4, ...props }, ref) => (
+ <DropdownMenuPrimitive.Portal>
+ <DropdownMenuPrimitive.Content
+ ref={ref}
+ sideOffset={sideOffset}
+ className={cn(
+ "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
+ className
+ )}
+ {...props}
+ />
+ </DropdownMenuPrimitive.Portal>
+));
+DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
+
+const DropdownMenuItem = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.Item>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
+ inset?: boolean;
+ }
+>(({ className, inset, ...props }, ref) => (
+ <DropdownMenuPrimitive.Item
+ ref={ref}
+ className={cn(
+ "relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
+ inset && "pl-8",
+ className
+ )}
+ {...props}
+ />
+));
+DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
+
+const DropdownMenuCheckboxItem = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
+>(({ className, children, checked, ...props }, ref) => (
+ <DropdownMenuPrimitive.CheckboxItem
+ ref={ref}
+ className={cn(
+ "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
+ className
+ )}
+ checked={checked}
+ {...props}
+ >
+ <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
+ <DropdownMenuPrimitive.ItemIndicator>
+ <Check className="h-4 w-4" />
+ </DropdownMenuPrimitive.ItemIndicator>
+ </span>
+ {children}
+ </DropdownMenuPrimitive.CheckboxItem>
+));
+DropdownMenuCheckboxItem.displayName =
+ DropdownMenuPrimitive.CheckboxItem.displayName;
+
+const DropdownMenuRadioItem = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
+>(({ className, children, ...props }, ref) => (
+ <DropdownMenuPrimitive.RadioItem
+ ref={ref}
+ className={cn(
+ "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
+ className
+ )}
+ {...props}
+ >
+ <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
+ <DropdownMenuPrimitive.ItemIndicator>
+ <Circle className="h-2 w-2 fill-current" />
+ </DropdownMenuPrimitive.ItemIndicator>
+ </span>
+ {children}
+ </DropdownMenuPrimitive.RadioItem>
+));
+DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;
+
+const DropdownMenuLabel = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.Label>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
+ inset?: boolean;
+ }
+>(({ className, inset, ...props }, ref) => (
+ <DropdownMenuPrimitive.Label
+ ref={ref}
+ className={cn(
+ "px-2 py-1.5 text-sm font-semibold",
+ inset && "pl-8",
+ className
+ )}
+ {...props}
+ />
+));
+DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;
+
+const DropdownMenuSeparator = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
+>(({ className, ...props }, ref) => (
+ <DropdownMenuPrimitive.Separator
+ ref={ref}
+ className={cn("-mx-1 my-1 h-px bg-muted", className)}
+ {...props}
+ />
+));
+DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
+
+const DropdownMenuShortcut = ({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLSpanElement>) => {
+ return (
+ <span
+ className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
+ {...props}
+ />
+ );
+};
+DropdownMenuShortcut.displayName = "DropdownMenuShortcut";
+
+export {
+ DropdownMenu,
+ DropdownMenuTrigger,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuCheckboxItem,
+ DropdownMenuRadioItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuShortcut,
+ DropdownMenuGroup,
+ DropdownMenuPortal,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuRadioGroup,
+};
diff --git a/components/ui/popover.tsx b/components/ui/popover.tsx
new file mode 100644
index 0000000..f14fc6b
--- /dev/null
+++ b/components/ui/popover.tsx
@@ -0,0 +1,31 @@
+"use client";
+
+import * as React from "react";
+import * as PopoverPrimitive from "@radix-ui/react-popover";
+
+import { cn } from "@/lib/utils";
+
+const Popover = PopoverPrimitive.Root;
+
+const PopoverTrigger = PopoverPrimitive.Trigger;
+
+const PopoverContent = React.forwardRef<
+ React.ElementRef<typeof PopoverPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
+>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
+ <PopoverPrimitive.Portal>
+ <PopoverPrimitive.Content
+ ref={ref}
+ align={align}
+ sideOffset={sideOffset}
+ className={cn(
+ "z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
+ className
+ )}
+ {...props}
+ />
+ </PopoverPrimitive.Portal>
+));
+PopoverContent.displayName = PopoverPrimitive.Content.displayName;
+
+export { Popover, PopoverTrigger, PopoverContent };
diff --git a/components/ui/scroll-area.tsx b/components/ui/scroll-area.tsx
new file mode 100644
index 0000000..8e4fa13
--- /dev/null
+++ b/components/ui/scroll-area.tsx
@@ -0,0 +1,58 @@
+"use client"
+
+import * as React from "react"
+import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
+
+import { cn } from "@/lib/utils"
+
+function ScrollArea({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
+ return (
+ <ScrollAreaPrimitive.Root
+ data-slot="scroll-area"
+ className={cn("relative", className)}
+ {...props}
+ >
+ <ScrollAreaPrimitive.Viewport
+ data-slot="scroll-area-viewport"
+ className="focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1"
+ >
+ {children}
+ </ScrollAreaPrimitive.Viewport>
+ <ScrollBar />
+ <ScrollAreaPrimitive.Corner />
+ </ScrollAreaPrimitive.Root>
+ )
+}
+
+function ScrollBar({
+ className,
+ orientation = "vertical",
+ ...props
+}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
+ return (
+ <ScrollAreaPrimitive.ScrollAreaScrollbar
+ data-slot="scroll-area-scrollbar"
+ orientation={orientation}
+ className={cn(
+ "flex touch-none p-px transition-colors select-none",
+ orientation === "vertical" &&
+ "h-full w-2.5 border-l border-l-transparent",
+ orientation === "horizontal" &&
+ "h-2.5 flex-col border-t border-t-transparent",
+ className
+ )}
+ {...props}
+ >
+ <ScrollAreaPrimitive.ScrollAreaThumb
+ data-slot="scroll-area-thumb"
+ className="bg-border relative flex-1 rounded-full"
+ />
+ </ScrollAreaPrimitive.ScrollAreaScrollbar>
+ )
+}
+
+export { ScrollArea, ScrollBar }
diff --git a/components/ui/separator.tsx b/components/ui/separator.tsx
new file mode 100644
index 0000000..11b8741
--- /dev/null
+++ b/components/ui/separator.tsx
@@ -0,0 +1,29 @@
+import * as React from "react";
+import * as SeparatorPrimitive from "@radix-ui/react-separator";
+
+import { cn } from "@/lib/utils";
+
+const Separator = React.forwardRef<
+ React.ElementRef<typeof SeparatorPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
+>(
+ (
+ { className, orientation = "horizontal", decorative = true, ...props },
+ ref
+ ) => (
+ <SeparatorPrimitive.Root
+ ref={ref}
+ decorative={decorative}
+ orientation={orientation}
+ className={cn(
+ "shrink-0 bg-border",
+ orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
+ className
+ )}
+ {...props}
+ />
+ )
+);
+Separator.displayName = SeparatorPrimitive.Root.displayName;
+
+export { Separator };
diff --git a/components/ui/skeleton.tsx b/components/ui/skeleton.tsx
deleted file mode 100644
index 5c178be..0000000
--- a/components/ui/skeleton.tsx
+++ /dev/null
@@ -1,13 +0,0 @@
-import type { HTMLAttributes } from "react";
-import { cn } from "@/lib/utils";
-
-function Skeleton({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
- return (
- <div
- className={cn("animate-pulse rounded-md bg-muted", className)}
- {...props}
- />
- );
-}
-
-export { Skeleton };
diff --git a/components/ui/switch.tsx b/components/ui/switch.tsx
new file mode 100644
index 0000000..6a2b524
--- /dev/null
+++ b/components/ui/switch.tsx
@@ -0,0 +1,31 @@
+"use client"
+
+import * as React from "react"
+import * as SwitchPrimitive from "@radix-ui/react-switch"
+
+import { cn } from "@/lib/utils"
+
+function Switch({
+ className,
+ ...props
+}: React.ComponentProps<typeof SwitchPrimitive.Root>) {
+ return (
+ <SwitchPrimitive.Root
+ data-slot="switch"
+ className={cn(
+ "peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
+ className
+ )}
+ {...props}
+ >
+ <SwitchPrimitive.Thumb
+ data-slot="switch-thumb"
+ className={cn(
+ "bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0"
+ )}
+ />
+ </SwitchPrimitive.Root>
+ )
+}
+
+export { Switch }
diff --git a/components/ui/table.tsx b/components/ui/table.tsx
new file mode 100644
index 0000000..51b74dd
--- /dev/null
+++ b/components/ui/table.tsx
@@ -0,0 +1,116 @@
+"use client"
+
+import * as React from "react"
+
+import { cn } from "@/lib/utils"
+
+function Table({ className, ...props }: React.ComponentProps<"table">) {
+ return (
+ <div
+ data-slot="table-container"
+ className="relative w-full overflow-x-auto"
+ >
+ <table
+ data-slot="table"
+ className={cn("w-full caption-bottom text-sm", className)}
+ {...props}
+ />
+ </div>
+ )
+}
+
+function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
+ return (
+ <thead
+ data-slot="table-header"
+ className={cn("[&_tr]:border-b", className)}
+ {...props}
+ />
+ )
+}
+
+function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
+ return (
+ <tbody
+ data-slot="table-body"
+ className={cn("[&_tr:last-child]:border-0", className)}
+ {...props}
+ />
+ )
+}
+
+function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
+ return (
+ <tfoot
+ data-slot="table-footer"
+ className={cn(
+ "bg-muted/50 border-t font-medium [&>tr]:last:border-b-0",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
+ return (
+ <tr
+ data-slot="table-row"
+ className={cn(
+ "hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function TableHead({ className, ...props }: React.ComponentProps<"th">) {
+ return (
+ <th
+ data-slot="table-head"
+ className={cn(
+ "text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function TableCell({ className, ...props }: React.ComponentProps<"td">) {
+ return (
+ <td
+ data-slot="table-cell"
+ className={cn(
+ "p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function TableCaption({
+ className,
+ ...props
+}: React.ComponentProps<"caption">) {
+ return (
+ <caption
+ data-slot="table-caption"
+ className={cn("text-muted-foreground mt-4 text-sm", className)}
+ {...props}
+ />
+ )
+}
+
+export {
+ Table,
+ TableHeader,
+ TableBody,
+ TableFooter,
+ TableHead,
+ TableRow,
+ TableCell,
+ TableCaption,
+}
diff --git a/components/ui/tabs.tsx b/components/ui/tabs.tsx
new file mode 100644
index 0000000..497ba5e
--- /dev/null
+++ b/components/ui/tabs.tsx
@@ -0,0 +1,66 @@
+"use client"
+
+import * as React from "react"
+import * as TabsPrimitive from "@radix-ui/react-tabs"
+
+import { cn } from "@/lib/utils"
+
+function Tabs({
+ className,
+ ...props
+}: React.ComponentProps<typeof TabsPrimitive.Root>) {
+ return (
+ <TabsPrimitive.Root
+ data-slot="tabs"
+ className={cn("flex flex-col gap-2", className)}
+ {...props}
+ />
+ )
+}
+
+function TabsList({
+ className,
+ ...props
+}: React.ComponentProps<typeof TabsPrimitive.List>) {
+ return (
+ <TabsPrimitive.List
+ data-slot="tabs-list"
+ className={cn(
+ "bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function TabsTrigger({
+ className,
+ ...props
+}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
+ return (
+ <TabsPrimitive.Trigger
+ data-slot="tabs-trigger"
+ className={cn(
+ "data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function TabsContent({
+ className,
+ ...props
+}: React.ComponentProps<typeof TabsPrimitive.Content>) {
+ return (
+ <TabsPrimitive.Content
+ data-slot="tabs-content"
+ className={cn("flex-1 outline-none", className)}
+ {...props}
+ />
+ )
+}
+
+export { Tabs, TabsList, TabsTrigger, TabsContent }
diff --git a/components/ui/tooltip.tsx b/components/ui/tooltip.tsx
new file mode 100644
index 0000000..a4e5452
--- /dev/null
+++ b/components/ui/tooltip.tsx
@@ -0,0 +1,30 @@
+"use client";
+
+import * as React from "react";
+import * as TooltipPrimitive from "@radix-ui/react-tooltip";
+
+import { cn } from "@/lib/utils";
+
+const TooltipProvider = TooltipPrimitive.Provider;
+
+const Tooltip = TooltipPrimitive.Root;
+
+const TooltipTrigger = TooltipPrimitive.Trigger;
+
+const TooltipContent = React.forwardRef<
+ React.ElementRef<typeof TooltipPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
+>(({ className, sideOffset = 4, ...props }, ref) => (
+ <TooltipPrimitive.Content
+ ref={ref}
+ sideOffset={sideOffset}
+ className={cn(
+ "z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
+ className
+ )}
+ {...props}
+ />
+));
+TooltipContent.displayName = TooltipPrimitive.Content.displayName;
+
+export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
diff --git a/components/user-menu.tsx b/components/user-menu.tsx
new file mode 100644
index 0000000..96733a2
--- /dev/null
+++ b/components/user-menu.tsx
@@ -0,0 +1,139 @@
+"use client";
+
+import { useState } from "react";
+import { useRouter } from "next/navigation";
+import { useTranslations } from "next-intl";
+import { useAuth } from "@/hooks/useAuth";
+import { signOut } from "@/lib/auth/client";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
+import { Button } from "@/components/ui/button";
+import { User, LogOut, Users, FileText, Shield } from "lucide-react";
+import { toast } from "sonner";
+import { CalendarDiscoverySheet } from "@/components/calendar-discovery-sheet";
+import { useIsAdmin } from "@/hooks/useAdminAccess";
+
+/**
+ * User menu dropdown for authenticated users
+ *
+ * Shows:
+ * - User avatar and name
+ * - Profile link
+ * - Activity Log link
+ * - Admin Panel link (if user is admin)
+ * - Browse Calendars
+ * - Sign out button
+ */
+export function UserMenu() {
+ const t = useTranslations();
+ const router = useRouter();
+ const { user, isAuthenticated, isLoading } = useAuth();
+ const isAdmin = useIsAdmin();
+ const [discoveryOpen, setDiscoveryOpen] = useState(false);
+
+ if (isLoading || !isAuthenticated || !user) {
+ return null;
+ }
+
+ const handleSignOut = async () => {
+ try {
+ await signOut({
+ fetchOptions: {
+ onSuccess: () => {
+ toast.success(t("auth.logoutSuccess"));
+ },
+ },
+ });
+ // Always redirect to login after sign out, regardless of auth method
+ router.replace("/login");
+ } catch (error) {
+ console.error("Sign out error:", error);
+ toast.error(t("common.error"));
+ }
+ };
+
+ // Generate initials from name
+ const getInitials = (name: string) => {
+ return name
+ .split(" ")
+ .map((n) => n[0])
+ .join("")
+ .toUpperCase()
+ .slice(0, 2);
+ };
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-10 w-10 sm:h-8 sm:w-8 rounded-full"
+ >
+ <Avatar className="h-10 w-10 sm:h-8 sm:w-8">
+ <AvatarImage src={user.image || undefined} alt={user.name || ""} />
+ <AvatarFallback className="bg-primary/10 text-primary text-xs font-semibold">
+ {user.name ? (
+ getInitials(user.name)
+ ) : (
+ <User className="h-4 w-4" />
+ )}
+ </AvatarFallback>
+ </Avatar>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-56">
+ <DropdownMenuLabel className="font-normal">
+ <div className="flex flex-col space-y-1">
+ <p className="text-sm font-medium leading-none">{user.name}</p>
+ <p className="text-xs leading-none text-muted-foreground">
+ {user.email}
+ </p>
+ </div>
+ </DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={() => router.replace("/profile")}>
+ <User className="mr-2 h-4 w-4" />
+ {t("auth.profile")}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => router.replace("/profile/activity")}>
+ <FileText className="mr-2 h-4 w-4" />
+ {t("activityLog.title")}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setDiscoveryOpen(true)}>
+ <Users className="mr-2 h-4 w-4" />
+ {t("calendar.browseCalendars")}
+ </DropdownMenuItem>
+ {isAdmin && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={() => router.replace("/admin")}>
+ <Shield className="mr-2 h-4 w-4" />
+ {t("admin.adminPanel")}
+ </DropdownMenuItem>
+ </>
+ )}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={handleSignOut}
+ className="text-destructive focus:text-destructive"
+ >
+ <LogOut className="mr-2 h-4 w-4" />
+ {t("auth.logout")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+
+ <CalendarDiscoverySheet
+ open={discoveryOpen}
+ onOpenChange={setDiscoveryOpen}
+ />
+ </DropdownMenu>
+ );
+}
diff --git a/docker-compose.yml b/docker-compose.yml
index c73aa05..38ec925 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -13,15 +13,3 @@ services:
- ./data:/app/data
env_file:
- .env
- healthcheck:
- test:
- [
- "CMD",
- "node",
- "-e",
- "require('http').get('http://localhost:3000', (r) => process.exit(r.statusCode === 200 ? 0 : 1))",
- ]
- interval: 30s
- timeout: 10s
- retries: 3
- start_period: 40s
diff --git a/docs/ADMIN_PANEL.md b/docs/ADMIN_PANEL.md
new file mode 100644
index 0000000..70ac256
--- /dev/null
+++ b/docs/ADMIN_PANEL.md
@@ -0,0 +1,268 @@
+# Admin Panel Guide
+
+This guide covers the admin panel features in BetterShift, including user management, calendar administration, and audit logging.
+
+## Table of Contents
+
+1. [Overview](#overview)
+2. [Roles and Permissions](#roles-and-permissions)
+3. [User Management](#user-management)
+4. [Calendar Management](#calendar-management)
+5. [Audit Logs](#audit-logs)
+6. [Rate Limiting](#rate-limiting)
+
+---
+
+## Overview
+
+The admin panel is available at `/admin` and provides system-wide management capabilities. Access requires authentication with an admin or superadmin role.
+
+### Accessing the Admin Panel
+
+1. Login with an admin account
+2. Click your profile menu in the header
+3. Select "Admin Panel"
+
+Or navigate directly to `/admin`.
+
+---
+
+## Roles and Permissions
+
+BetterShift uses a three-tier role system:
+
+| Role | Description | Capabilities |
+| -------------- | ------------------- | ------------------------------------------------------------------------------------------------------- |
+| **user** | Standard user | Manage own calendars, view shared calendars |
+| **admin** | Administrator | View users/calendars/logs, edit regular users, reset passwords, transfer calendars |
+| **superadmin** | Super Administrator | All admin capabilities plus: delete users, delete calendars, delete audit logs, ban/unban, role changes |
+
+### Permission Matrix
+
+| Feature | Superadmin | Admin | User |
+| ------------------------------- | ---------- | ----- | ---- |
+| **User Management** | | | |
+| View all users | Yes | Yes | No |
+| Edit regular users (role: user) | Yes | Yes | No |
+| Edit admins/superadmins | Yes | No | No |
+| Delete regular users | Yes | No | No |
+| Ban/Unban users | Yes | No | No |
+| Change user roles | Yes | No | No |
+| Reset passwords | Yes | Yes | No |
+| **Calendar Management** | | | |
+| View all calendars | Yes | Yes | No |
+| Transfer calendar ownership | Yes | Yes | No |
+| Delete any calendar | Yes | No | No |
+| **Orphaned Calendars** | | | |
+| View orphaned calendars | Yes | Yes | No |
+| Assign orphaned calendars | Yes | Yes | No |
+| Delete orphaned calendars | Yes | No | No |
+| **Audit Logs** | | | |
+| View all audit logs | Yes | Yes | No |
+| Delete audit logs | Yes | No | No |
+| **System Stats** | | | |
+| View system statistics | Yes | Yes | No |
+
+### First User Promotion
+
+The first user to register automatically becomes a **superadmin**. This ensures there's always an administrator who can manage the system.
+
+### Role Assignment
+
+- Superadmins can promote users to admin via the user management page
+- Superadmins cannot be demoted (protection against lockout)
+- Admins cannot modify other admins or superadmins
+
+---
+
+## User Management
+
+Location: `/admin/users`
+
+### User Table
+
+The user table displays all registered users with:
+
+- Avatar, name, and email
+- Role badge (User, Admin, Superadmin)
+- Status badge (Active, Banned)
+- Registration date
+- Action menu
+
+### Available Actions
+
+| Action | Admin | Superadmin | Description |
+| -------------- | ------------------ | ---------- | ------------------------------------------ |
+| View Details | Yes | Yes | View user profile, calendars, and activity |
+| Edit User | Regular users only | Yes | Change name, email |
+| Change Role | No | Yes | Promote/demote user roles |
+| Reset Password | Yes | Yes | Generate new password for user |
+| Ban User | No | Yes | Temporarily or permanently ban with reason |
+| Unban User | No | Yes | Remove ban from user |
+| Delete User | No | Yes | Permanently delete user and their data |
+
+Admins can only edit users with the "user" role. They cannot modify other admins or superadmins.
+
+### Banning Users
+
+When banning a user:
+
+1. Click the action menu and select "Ban User"
+2. Enter a ban reason (required)
+3. Optionally set an expiration date
+4. Confirm the ban
+
+Banned users:
+
+- Cannot login (see ban reason on login page)
+- Have all sessions revoked immediately
+- Cannot access the API
+- Are automatically unbanned after expiration (if set)
+
+### Deleting Users
+
+Deleting a user permanently removes:
+
+- User account and profile
+- All sessions
+- All owned calendars (including shifts, presets, notes)
+- All calendar shares they created
+
+This action cannot be undone. A confirmation dialog requires typing the user's email.
+
+---
+
+## Calendar Management
+
+Location: `/admin/calendars`
+
+### Calendar Table
+
+Displays all calendars in the system with:
+
+- Calendar name and color indicator
+- Owner information (or "Orphaned" badge)
+- Statistics (shifts, notes, presets, shares)
+- Guest permission setting
+- Action menu
+
+### Orphaned Calendars
+
+Calendars without an owner (orphaned) appear at the top of the list with a red "Orphaned" badge. This happens when:
+
+- The calendar was created before auth was enabled
+- The owner was deleted
+- Database migration issues
+
+Orphaned calendars are invisible to regular users and can only be managed through the admin panel.
+
+### Available Actions
+
+| Action | Admin | Superadmin | Description |
+| ------------------ | ----- | ---------- | ------------------------------------ |
+| View Details | Yes | Yes | View calendar info and statistics |
+| Edit Calendar | Yes | Yes | Change name, color, guest permission |
+| Transfer Ownership | Yes | Yes | Assign calendar to a different user |
+| Delete Calendar | No | Yes | Permanently delete calendar |
+
+### Transferring Calendars
+
+To transfer calendar ownership:
+
+1. Click the action menu and select "Transfer"
+2. Search for the new owner by name or email
+3. Select the user from results
+4. Confirm the transfer
+
+The previous owner loses access (unless re-shared), and the new owner gains full control.
+
+### Bulk Operations
+
+Superadmins can select multiple calendars for:
+
+- **Bulk Transfer**: Assign all selected calendars to one user
+- **Bulk Delete**: Delete all selected calendars
+
+Use these carefully - bulk operations cannot be undone.
+
+---
+
+## Audit Logs
+
+Location: `/admin/logs`
+
+The audit log tracks all significant actions in the system for security and compliance.
+
+### Logged Events
+
+| Category | Events |
+| --------------- | ----------------------------------------------- |
+| Authentication | Login, logout, registration, password change |
+| User Management | Ban, unban, delete, role change, password reset |
+| Calendar | Create, delete, transfer, share changes |
+| Admin Actions | All admin panel operations |
+
+### Log Entry Details
+
+Each log entry includes:
+
+- Timestamp
+- Action type
+- Actor (who performed the action)
+- Severity level (Info, Warning, Error, Critical)
+- Metadata (additional context)
+- IP address and user agent
+
+### Filtering Logs
+
+Filter audit logs by:
+
+- Action type (dropdown)
+- Severity level
+- Date range
+- Search text (searches action and metadata)
+
+### Deleting Old Logs
+
+Superadmins can delete logs older than a specified date:
+
+1. Click "Delete Old Logs"
+2. Select the cutoff date
+3. Review what will be deleted
+4. Confirm deletion
+
+Consider exporting logs before deletion for compliance purposes.
+
+---
+
+## Rate Limiting
+
+Admin operations are rate-limited to prevent abuse:
+
+```bash
+# User mutations (ban/unban/delete/edit): 10 per minute
+RATE_LIMIT_ADMIN_USER_MUTATIONS=10
+RATE_LIMIT_ADMIN_USER_MUTATIONS_WINDOW=60
+
+# Password resets: 5 per 5 minutes
+RATE_LIMIT_ADMIN_PASSWORD_RESET=5
+RATE_LIMIT_ADMIN_PASSWORD_RESET_WINDOW=300
+
+# Bulk operations: 3 per 5 minutes
+RATE_LIMIT_ADMIN_BULK_OPERATIONS=3
+RATE_LIMIT_ADMIN_BULK_OPERATIONS_WINDOW=300
+
+# Calendar mutations: 10 per minute
+RATE_LIMIT_ADMIN_CALENDAR_MUTATIONS=10
+RATE_LIMIT_ADMIN_CALENDAR_MUTATIONS_WINDOW=60
+```
+
+---
+
+## Security Considerations
+
+1. **Audit everything**: All admin actions are logged with IP and user agent
+2. **Principle of least privilege**: Only grant admin roles when necessary
+3. **Regular review**: Periodically review admin users and audit logs
+4. **Protect superadmin**: The superadmin account should use a strong, unique password
+5. **Session security**: Admin sessions follow the same security as regular sessions
diff --git a/docs/AUTH_SETUP.md b/docs/AUTH_SETUP.md
new file mode 100644
index 0000000..dd541f9
--- /dev/null
+++ b/docs/AUTH_SETUP.md
@@ -0,0 +1,299 @@
+# Authentication Setup Guide
+
+This guide covers how to configure the authentication system in BetterShift, including local credentials, OAuth providers, and custom OIDC integration.
+
+## Table of Contents
+
+1. [Overview](#overview)
+2. [Basic Configuration](#basic-configuration)
+3. [Email and Password Authentication](#email-and-password-authentication)
+4. [OAuth Providers](#oauth-providers)
+5. [Custom OIDC Provider](#custom-oidc-provider)
+6. [Session Management](#session-management)
+7. [Rate Limiting](#rate-limiting)
+8. [Troubleshooting](#troubleshooting)
+
+---
+
+## Overview
+
+BetterShift uses [Better Auth](https://www.better-auth.com/) for authentication. The system supports:
+
+- Email/password authentication
+- OAuth providers (Google, GitHub, Discord)
+- Custom OIDC providers (Keycloak, Authentik, Authelia, etc.)
+- Session-based authentication with secure cookies
+- Role-based access control (user, admin, superadmin)
+
+Authentication is **enabled by default** for security. You can disable it by setting `AUTH_ENABLED=false` for single-user deployments.
+
+---
+
+## Basic Configuration
+
+### Required Environment Variables
+
+```bash
+# Enable/disable authentication (default: true)
+AUTH_ENABLED=true
+
+# Required when auth is enabled - generate with: npx @better-auth/cli secret
+BETTER_AUTH_SECRET=your-secret-here
+
+# Your application URL (used for OAuth callbacks)
+BETTER_AUTH_URL=http://localhost:3000
+```
+
+### Access Control
+
+```bash
+# Allow new user registration (default: true)
+ALLOW_USER_REGISTRATION=true
+
+# Allow viewing calendars without login (default: false)
+ALLOW_GUEST_ACCESS=false
+```
+
+### First User Setup
+
+The first user to register becomes the **superadmin** with full system access. This happens automatically - no manual configuration required.
+
+---
+
+## Email and Password Authentication
+
+Email/password authentication is enabled by default when auth is active. Users can:
+
+- Register with email and password
+- Login with credentials
+- Change password from profile settings
+- Reset password (admin can reset via admin panel)
+
+### Password Requirements
+
+Passwords are hashed using BCrypt. There are no specific complexity requirements enforced by default, but you can implement custom validation in your deployment.
+
+---
+
+## OAuth Providers
+
+BetterShift supports three built-in OAuth providers. Configure any combination based on your needs.
+
+### Google OAuth
+
+1. Go to [Google Cloud Console](https://console.cloud.google.com/)
+2. Create a new project or select existing
+3. Navigate to **APIs & Services > Credentials**
+4. Create an **OAuth 2.0 Client ID** (Web application)
+5. Add authorized redirect URI: `{BETTER_AUTH_URL}/api/auth/callback/google`
+6. Configure environment variables:
+
+```bash
+GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com
+GOOGLE_CLIENT_SECRET=your-client-secret
+```
+
+### GitHub OAuth
+
+1. Go to [GitHub Developer Settings](https://github.com/settings/developers)
+2. Click **New OAuth App**
+3. Set Authorization callback URL: `{BETTER_AUTH_URL}/api/auth/callback/github`
+4. Configure environment variables:
+
+```bash
+GITHUB_CLIENT_ID=your-client-id
+GITHUB_CLIENT_SECRET=your-client-secret
+```
+
+### Discord OAuth
+
+1. Go to [Discord Developer Portal](https://discord.com/developers/applications)
+2. Create a new application
+3. Navigate to **OAuth2 > General**
+4. Add redirect URI: `{BETTER_AUTH_URL}/api/auth/callback/discord`
+5. Configure environment variables:
+
+```bash
+DISCORD_CLIENT_ID=your-client-id
+DISCORD_CLIENT_SECRET=your-client-secret
+```
+
+---
+
+## Custom OIDC Provider
+
+For enterprise SSO or self-hosted identity providers, BetterShift supports generic OIDC configuration.
+
+### Supported Providers
+
+Any OIDC-compliant provider works, including:
+
+- Keycloak
+- Authentik
+- Authelia
+- Okta
+- Azure AD
+- Auth0
+
+### Configuration
+
+```bash
+# Enable custom OIDC
+CUSTOM_OIDC_ENABLED=true
+
+# Display name shown on login button
+CUSTOM_OIDC_NAME=Company SSO
+
+# OAuth credentials
+CUSTOM_OIDC_CLIENT_ID=bettershift
+CUSTOM_OIDC_CLIENT_SECRET=your-client-secret
+
+# OIDC Discovery URL (must include /.well-known/openid-configuration)
+CUSTOM_OIDC_ISSUER=https://sso.example.com/.well-known/openid-configuration
+
+# Scopes to request (space-separated)
+CUSTOM_OIDC_SCOPES=openid profile email
+```
+
+### Callback URL
+
+Configure your OIDC provider with this callback URL:
+
+```
+{BETTER_AUTH_URL}/api/auth/oauth2/callback/custom-oidc
+```
+
+### Keycloak Example
+
+1. Create a new client in your Keycloak realm
+2. Set **Client Protocol** to `openid-connect`
+3. Set **Access Type** to `confidential`
+4. Add Valid Redirect URI: `https://bettershift.example.com/api/auth/oauth2/callback/custom-oidc`
+5. Copy Client ID and Client Secret
+6. Configure BetterShift:
+
+```bash
+CUSTOM_OIDC_ENABLED=true
+CUSTOM_OIDC_NAME=Keycloak
+CUSTOM_OIDC_CLIENT_ID=bettershift
+CUSTOM_OIDC_CLIENT_SECRET=your-keycloak-secret
+CUSTOM_OIDC_ISSUER=https://keycloak.example.com/realms/myrealm/.well-known/openid-configuration
+```
+
+### Authentik Example
+
+1. Create a new OAuth2/OpenID Provider in Authentik
+2. Create an Application linked to the provider
+3. Set Redirect URI: `https://bettershift.example.com/api/auth/oauth2/callback/custom-oidc`
+4. Configure BetterShift:
+
+```bash
+CUSTOM_OIDC_ENABLED=true
+CUSTOM_OIDC_NAME=Authentik
+CUSTOM_OIDC_CLIENT_ID=your-authentik-client-id
+CUSTOM_OIDC_CLIENT_SECRET=your-authentik-secret
+CUSTOM_OIDC_ISSUER=https://authentik.example.com/application/o/bettershift/.well-known/openid-configuration
+```
+
+---
+
+## Session Management
+
+### Session Configuration
+
+```bash
+# Session lifetime in seconds (default: 7 days)
+SESSION_MAX_AGE=604800
+
+# Session refresh interval in seconds (default: 1 day)
+SESSION_UPDATE_AGE=86400
+```
+
+### User Session Control
+
+Users can manage their sessions from the profile page:
+
+- View all active sessions (device, browser, IP, last activity)
+- Revoke all other sessions (keeps current session active)
+
+### Admin Session Control
+
+Admins can revoke user sessions through the admin panel when banning users.
+
+---
+
+## Rate Limiting
+
+BetterShift includes built-in rate limiting to prevent abuse. All limits are configurable via environment variables.
+
+### Authentication Limits
+
+```bash
+# Login attempts: 5 per minute per IP
+RATE_LIMIT_AUTH_REQUESTS=5
+RATE_LIMIT_AUTH_WINDOW=60
+
+# Registration: 3 per 10 minutes per IP
+RATE_LIMIT_REGISTER_REQUESTS=3
+RATE_LIMIT_REGISTER_WINDOW=600
+
+# Password change: 3 per hour per user
+RATE_LIMIT_PASSWORD_CHANGE_REQUESTS=3
+RATE_LIMIT_PASSWORD_CHANGE_WINDOW=3600
+```
+
+### Response Headers
+
+Rate-limited endpoints return these headers:
+
+- `X-RateLimit-Limit`: Maximum requests allowed
+- `X-RateLimit-Remaining`: Requests remaining in window
+- `X-RateLimit-Reset`: Unix timestamp when limit resets
+
+---
+
+## Troubleshooting
+
+### OAuth Callback Errors
+
+**Problem**: OAuth login fails with "invalid_redirect_uri"
+
+**Solution**: Ensure the callback URL in your provider matches exactly:
+
+- Google: `{BETTER_AUTH_URL}/api/auth/callback/google`
+- GitHub: `{BETTER_AUTH_URL}/api/auth/callback/github`
+- Discord: `{BETTER_AUTH_URL}/api/auth/callback/discord`
+- Custom OIDC: `{BETTER_AUTH_URL}/api/auth/oauth2/callback/custom-oidc`
+
+### OIDC Discovery Fails
+
+**Problem**: Custom OIDC login shows "discovery failed"
+
+**Solution**: Verify the issuer URL ends with `/.well-known/openid-configuration` and is accessible from your server.
+
+### Session Not Persisting
+
+**Problem**: Users are logged out unexpectedly
+
+**Solution**:
+
+1. Check `BETTER_AUTH_SECRET` is set and consistent across restarts
+2. Verify cookies are not blocked by browser or proxy
+3. Check `BETTER_AUTH_TRUSTED_ORIGINS` includes your domain
+
+### Registration Disabled for OIDC Users
+
+**Problem**: New OIDC users cannot login when `ALLOW_USER_REGISTRATION=false`
+
+**Solution**: This is expected behavior. When registration is disabled, only existing users can login via OIDC. Create user accounts first via the admin panel, then users can link their OIDC accounts.
+
+---
+
+## Security Recommendations
+
+1. **Use HTTPS in production** - Set `BETTER_AUTH_URL` to your HTTPS URL
+2. **Set trusted origins** - Configure `BETTER_AUTH_TRUSTED_ORIGINS` for CORS protection
+3. **Rotate secrets periodically** - Change `BETTER_AUTH_SECRET` and regenerate sessions
+4. **Monitor failed logins** - Check audit logs for suspicious activity
+5. **Use strong passwords** - Educate users about password security
+6. **Enable MFA** (future feature) - When available, enable for admin accounts
diff --git a/docs/MIGRATION_AUTH_TOGGLE.md b/docs/MIGRATION_AUTH_TOGGLE.md
new file mode 100644
index 0000000..2d19986
--- /dev/null
+++ b/docs/MIGRATION_AUTH_TOGGLE.md
@@ -0,0 +1,203 @@
+# Enabling Authentication on an Existing Instance
+
+This guide explains how to enable authentication on a BetterShift instance that was previously running without it.
+
+## Table of Contents
+
+1. [Before You Start](#before-you-start)
+2. [Migration Steps](#migration-steps)
+3. [Handling Orphaned Calendars](#handling-orphaned-calendars)
+4. [FAQ](#faq)
+
+---
+
+## Before You Start
+
+### Prerequisites
+
+- BetterShift instance running with `AUTH_ENABLED=false`
+- Existing calendars created without authentication
+- Database backup (recommended)
+
+### What Happens to Existing Data
+
+When you enable authentication:
+
+| Data Type | Behavior |
+| -------------- | --------------------------------------------------------- |
+| Calendars | Become "orphaned" (no owner) - invisible to regular users |
+| Shifts | Preserved with their calendars |
+| Presets | Preserved with their calendars |
+| Notes | Preserved with their calendars |
+| External Syncs | Preserved with their calendars |
+
+Existing data is **not deleted** - it becomes orphaned and must be assigned to users through the admin panel.
+
+---
+
+## Migration Steps
+
+### Step 1: Backup Your Database
+
+Before making any changes, create a backup:
+
+```bash
+# SQLite database location (default)
+cp ./data/sqlite.db ./data/sqlite.db.backup
+
+# Or if using Docker
+docker cp bettershift:/app/data/sqlite.db ./sqlite.db.backup
+```
+
+### Step 2: Generate Auth Secret
+
+Generate a secure secret for Better Auth:
+
+```bash
+npx @better-auth/cli secret
+```
+
+Copy the output - you'll need it in the next step.
+
+### Step 3: Configure Environment Variables
+
+Update your `.env` file:
+
+```bash
+# Enable authentication
+AUTH_ENABLED=true
+
+# Set the generated secret
+BETTER_AUTH_SECRET=your-generated-secret-here
+
+# Set your application URL
+BETTER_AUTH_URL=https://your-domain.com
+
+# Optional: Configure registration and guest access
+ALLOW_USER_REGISTRATION=true
+ALLOW_GUEST_ACCESS=false
+```
+
+### Step 4: Restart the Application
+
+```bash
+# Docker Compose
+docker-compose restart
+
+# Or if running directly
+npm run build && npm start
+```
+
+### Step 5: Create the First User (Superadmin)
+
+1. Navigate to your BetterShift URL
+2. Click "Register" (or use OAuth if configured)
+3. Create your account
+
+The first registered user automatically becomes **superadmin** with full administrative access.
+
+### Step 6: Assign Orphaned Calendars
+
+After logging in as superadmin:
+
+1. Go to `/admin/calendars`
+2. Orphaned calendars appear at the top with a red "Orphaned" badge
+3. For each orphaned calendar:
+ - Click the action menu
+ - Select "Transfer Ownership"
+ - Search for and select the appropriate user
+ - Confirm the transfer
+
+---
+
+## Handling Orphaned Calendars
+
+### What Are Orphaned Calendars?
+
+Orphaned calendars have no owner (`ownerId = null`). This occurs when:
+
+- Calendars existed before auth was enabled
+- The owner was deleted
+- Database inconsistencies
+
+### Visibility
+
+Orphaned calendars are **invisible** to all regular users, even superadmins using the normal calendar view. They can only be managed through the admin panel at `/admin/calendars`.
+
+### Resolution Options
+
+| Option | When to Use |
+| ----------------- | -------------------------------------------- |
+| **Transfer** | Assign to the appropriate user |
+| **Delete** | Remove if no longer needed (superadmin only) |
+| **Bulk Transfer** | Move multiple calendars to one user |
+
+### Bulk Transfer Workflow
+
+For instances with many orphaned calendars:
+
+1. Go to `/admin/calendars`
+2. Filter by "Orphaned Only"
+3. Select multiple calendars using checkboxes
+4. Click "Transfer Selected"
+5. Choose the destination user
+6. Confirm the bulk transfer
+
+---
+
+## FAQ
+
+### What happens to existing calendars?
+
+They become orphaned (no owner) but retain all data. Assign them to users via the admin panel.
+
+### Can users still access their old calendars?
+
+No, orphaned calendars are invisible until assigned. Users need to login, then an admin must transfer ownership to them.
+
+### What if I want to disable auth again?
+
+Set `AUTH_ENABLED=false` in your environment. Calendars with owners will still work, but ownership restrictions won't be enforced.
+
+### Can I keep some calendars public?
+
+Yes, after assigning an owner:
+
+1. Open calendar settings
+2. Set "Guest Permission" to "Read" or "Write"
+3. Enable `ALLOW_GUEST_ACCESS=true` in environment
+
+### How do I add more admins?
+
+1. Login as superadmin
+2. Go to `/admin/users`
+3. Find the user
+4. Click Edit
+5. Change role to "Admin"
+6. Save
+
+### What if I lose access to the superadmin account?
+
+If you have database access, you can manually update the user role:
+
+```sql
+UPDATE user SET role = 'superadmin' WHERE email = '[email protected]';
+```
+
+Then restart the application.
+
+### Is there a way to auto-assign calendars?
+
+Not currently. Calendars must be manually assigned through the admin panel. For large migrations, consider a database script.
+
+---
+
+## Rollback Procedure
+
+If you need to revert to no-auth mode:
+
+1. Set `AUTH_ENABLED=false` in `.env`
+2. Restart the application
+3. All calendars become accessible again (ownership ignored when auth disabled)
+
+Note: User accounts and calendar ownership data are preserved in the database for future re-enabling.
diff --git a/docs/PERMISSIONS.md b/docs/PERMISSIONS.md
new file mode 100644
index 0000000..2eb14b6
--- /dev/null
+++ b/docs/PERMISSIONS.md
@@ -0,0 +1,216 @@
+# Permissions and Sharing Guide
+
+This guide explains how calendar permissions work in BetterShift, including sharing calendars with other users and managing access levels.
+
+## Table of Contents
+
+1. [Permission Hierarchy](#permission-hierarchy)
+2. [Calendar Ownership](#calendar-ownership)
+3. [Sharing Calendars](#sharing-calendars)
+4. [Access Tokens (Share Links)](#access-tokens-share-links)
+5. [Guest Access](#guest-access)
+6. [Calendar Discovery](#calendar-discovery)
+
+---
+
+## Permission Hierarchy
+
+BetterShift uses a four-level permission hierarchy for calendars:
+
+| Level | Can View | Can Edit | Can Share | Can Delete |
+| --------- | -------- | -------- | --------- | ---------- |
+| **owner** | Yes | Yes | Yes | Yes |
+| **admin** | Yes | Yes | Yes | No |
+| **write** | Yes | Yes | No | No |
+| **read** | Yes | No | No | No |
+
+### Permission Details
+
+- **owner**: Full control over the calendar, including deletion
+- **admin**: Can manage calendar settings and share with others, but cannot delete
+- **write**: Can create, edit, and delete shifts, notes, and presets
+- **read**: View-only access to all calendar data
+
+---
+
+## Calendar Ownership
+
+### How Ownership Works
+
+- The user who creates a calendar is automatically the **owner**
+- There is exactly one owner per calendar
+- Ownership can be transferred via the admin panel (admin or superadmin required)
+
+### Owner Capabilities
+
+- Full control over calendar settings
+- Grant/revoke access to other users
+- Set guest permission level
+- Create/manage access tokens
+- Delete the calendar permanently
+
+---
+
+## Sharing Calendars
+
+### Share with Specific Users
+
+Owners and admins can share calendars with other registered users:
+
+1. Open the calendar settings
+2. Go to "Sharing" section
+3. Search for users by name or email
+4. Select permission level (admin, write, or read)
+5. Click "Share"
+
+### Managing Shares
+
+From calendar settings, you can:
+
+- View all users with access
+- Change permission levels
+- Remove access for specific users
+
+### Share Permissions
+
+| Sharer's Role | Can Share With | Max Permission |
+| ------------- | -------------- | -------------- |
+| owner | Anyone | admin |
+| admin | Anyone | admin |
+| write | Cannot share | - |
+| read | Cannot share | - |
+
+---
+
+## Access Tokens (Share Links)
+
+Access tokens provide a way to share calendars via a URL, without requiring the recipient to have an account.
+
+### Creating Access Tokens
+
+1. Open calendar settings
+2. Navigate to "Access Tokens" section
+3. Click "Create Token"
+4. Configure:
+ - **Name**: Description for your reference
+ - **Permission**: read or write
+ - **Expiration**: Optional expiry date
+5. Copy the generated link
+
+### Token Properties
+
+| Property | Description |
+| ----------- | ------------------------------------------------- |
+| Name | Identifier for the token (e.g., "Team View Link") |
+| Permission | `read` or `write` access level |
+| Expiration | Optional date when token becomes invalid |
+| Active | Can be disabled without deletion |
+| Usage Count | Number of times the token was used |
+| Last Used | Timestamp of most recent access |
+
+### Managing Tokens
+
+- **Deactivate**: Temporarily disable without deleting
+- **Reactivate**: Re-enable a deactivated token
+- **Delete**: Permanently remove the token
+
+### Security Considerations
+
+- Tokens are stored in cookies after first validation
+- Users with tokens can access the calendar without logging in
+- Treat share links like passwords - anyone with the link has access
+- Set expiration dates for temporary access
+- Monitor usage in token management
+
+### Token vs. User Sharing
+
+| Aspect | Access Token | User Sharing |
+| ------------------------ | ----------------------- | ------------------ |
+| Requires account | No | Yes |
+| Trackable per-user | No | Yes |
+| Revocable per-person | No (revoke token) | Yes |
+| Can set admin permission | No | Yes |
+| Best for | Public/temporary access | Team collaboration |
+
+---
+
+## Guest Access
+
+Guest access allows unauthenticated users to view or edit calendars without any token or account.
+
+### Configuration
+
+1. Enable globally: Set `ALLOW_GUEST_ACCESS=true` in environment
+2. Enable per-calendar: Set "Guest Permission" in calendar settings
+
+### Guest Permission Levels
+
+| Setting | Description |
+| --------- | -------------------------------------- |
+| **none** | No guest access (default) |
+| **read** | Guests can view calendar data |
+| **write** | Guests can view and edit calendar data |
+
+### Guest vs. Token Access
+
+| Aspect | Guest Access | Token Access |
+| --------- | ----------------------- | ----------------------- |
+| URL | Standard calendar URL | Special token URL |
+| Scope | Per-calendar setting | Per-token setting |
+| Tracking | No tracking | Usage count, last used |
+| Revocable | Change calendar setting | Delete/disable token |
+| Security | Public to everyone | Limited to link holders |
+
+---
+
+## Calendar Discovery
+
+When guest access is enabled and calendars are set to allow guests, authenticated users can discover and subscribe to public calendars.
+
+### Finding Public Calendars
+
+1. Click your profile menu
+2. Select "Browse Calendars"
+3. View available public calendars
+4. Click "Subscribe" to add to your calendar list
+
+### Managing Subscriptions
+
+- **Subscribed calendars** appear in your calendar selector
+- **Dismiss**: Hide a calendar from your view (can be re-subscribed)
+- **Owned calendars** cannot be dismissed
+
+### Subscription vs. Sharing
+
+| Aspect | Subscription | Sharing |
+| ----------------- | --------------------------- | ------------------------- |
+| Permission source | Calendar's guest permission | Explicit share permission |
+| Initiated by | User subscribing | Owner/admin sharing |
+| Can be dismissed | Yes | Yes |
+| Permission level | As set on calendar | As granted when sharing |
+
+---
+
+## Permission Resolution
+
+When a user accesses a calendar, BetterShift resolves permissions in this order:
+
+1. **Owner check**: Is user the calendar owner? → `owner`
+2. **Share check**: Is user explicitly shared? → Use share permission
+3. **Subscription check**: Is user subscribed to public calendar? → Use guest permission
+4. **Token check**: Valid access token in cookie? → Use token permission
+5. **Guest check**: Guest access enabled + calendar allows guests? → Use guest permission
+6. **No access**: None of the above → Access denied
+
+The first matching rule determines the permission level.
+
+---
+
+## Best Practices
+
+1. **Use appropriate permission levels**: Grant minimum required access
+2. **Prefer user sharing over tokens**: Better tracking and individual revocation
+3. **Set token expiration**: Don't leave tokens valid indefinitely
+4. **Review shares periodically**: Remove access that's no longer needed
+5. **Use read permission by default**: Only grant write when editing is required
+6. **Consider guest access carefully**: Public calendars are visible to everyone
diff --git a/drizzle/0013_first_phantom_reporter.sql b/drizzle/0013_first_phantom_reporter.sql
new file mode 100644
index 0000000..069f2c2
--- /dev/null
+++ b/drizzle/0013_first_phantom_reporter.sql
@@ -0,0 +1,129 @@
+CREATE TABLE `account` (
+ `id` text PRIMARY KEY NOT NULL,
+ `account_id` text NOT NULL,
+ `provider_id` text NOT NULL,
+ `user_id` text NOT NULL,
+ `access_token` text,
+ `refresh_token` text,
+ `id_token` text,
+ `access_token_expires_at` integer,
+ `refresh_token_expires_at` integer,
+ `scope` text,
+ `password` text,
+ `created_at` integer DEFAULT (cast(unixepoch('subsecond') * 1000 as integer)) NOT NULL,
+ `updated_at` integer NOT NULL,
+ FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE INDEX `account_userId_idx` ON `account` (`user_id`);--> statement-breakpoint
+CREATE TABLE `audit_logs` (
+ `id` text PRIMARY KEY NOT NULL,
+ `user_id` text,
+ `action` text NOT NULL,
+ `resource_type` text,
+ `resource_id` text,
+ `metadata` text,
+ `ip_address` text,
+ `user_agent` text,
+ `severity` text DEFAULT 'info' NOT NULL,
+ `is_user_visible` integer DEFAULT false NOT NULL,
+ `timestamp` integer DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE INDEX `audit_logs_userId_timestamp_idx` ON `audit_logs` (`user_id`,`timestamp`);--> statement-breakpoint
+CREATE INDEX `audit_logs_action_timestamp_idx` ON `audit_logs` (`action`,`timestamp`);--> statement-breakpoint
+CREATE INDEX `audit_logs_userVisible_userId_timestamp_idx` ON `audit_logs` (`is_user_visible`,`user_id`,`timestamp`);--> statement-breakpoint
+CREATE TABLE `calendar_access_tokens` (
+ `id` text PRIMARY KEY NOT NULL,
+ `calendar_id` text NOT NULL,
+ `token` text NOT NULL,
+ `name` text,
+ `permission` text DEFAULT 'read' NOT NULL,
+ `expires_at` integer,
+ `created_by` text NOT NULL,
+ `created_at` integer DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ `last_used_at` integer,
+ `usage_count` integer DEFAULT 0 NOT NULL,
+ `is_active` integer DEFAULT true NOT NULL,
+ FOREIGN KEY (`calendar_id`) REFERENCES `calendars`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`created_by`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `calendar_access_tokens_token_unique` ON `calendar_access_tokens` (`token`);--> statement-breakpoint
+CREATE INDEX `calendar_access_tokens_token_idx` ON `calendar_access_tokens` (`token`);--> statement-breakpoint
+CREATE INDEX `calendar_access_tokens_calendarId_isActive_idx` ON `calendar_access_tokens` (`calendar_id`,`is_active`);--> statement-breakpoint
+CREATE INDEX `calendar_access_tokens_createdBy_idx` ON `calendar_access_tokens` (`created_by`);--> statement-breakpoint
+CREATE TABLE `calendar_shares` (
+ `id` text PRIMARY KEY NOT NULL,
+ `calendar_id` text NOT NULL,
+ `user_id` text NOT NULL,
+ `permission` text DEFAULT 'read' NOT NULL,
+ `shared_by` text NOT NULL,
+ `created_at` integer DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ FOREIGN KEY (`calendar_id`) REFERENCES `calendars`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`shared_by`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE INDEX `calendar_shares_calendarId_idx` ON `calendar_shares` (`calendar_id`);--> statement-breakpoint
+CREATE INDEX `calendar_shares_userId_idx` ON `calendar_shares` (`user_id`);--> statement-breakpoint
+CREATE TABLE `session` (
+ `id` text PRIMARY KEY NOT NULL,
+ `expires_at` integer NOT NULL,
+ `token` text NOT NULL,
+ `created_at` integer DEFAULT (cast(unixepoch('subsecond') * 1000 as integer)) NOT NULL,
+ `updated_at` integer NOT NULL,
+ `ip_address` text,
+ `user_agent` text,
+ `user_id` text NOT NULL,
+ `impersonated_by` text,
+ FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `session_token_unique` ON `session` (`token`);--> statement-breakpoint
+CREATE INDEX `session_userId_idx` ON `session` (`user_id`);--> statement-breakpoint
+CREATE TABLE `user` (
+ `id` text PRIMARY KEY NOT NULL,
+ `name` text NOT NULL,
+ `email` text NOT NULL,
+ `email_verified` integer DEFAULT false NOT NULL,
+ `image` text,
+ `created_at` integer DEFAULT (cast(unixepoch('subsecond') * 1000 as integer)) NOT NULL,
+ `updated_at` integer DEFAULT (cast(unixepoch('subsecond') * 1000 as integer)) NOT NULL,
+ `role` text,
+ `banned` integer DEFAULT false,
+ `ban_reason` text,
+ `ban_expires` integer
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `user_email_unique` ON `user` (`email`);--> statement-breakpoint
+CREATE TABLE `user_calendar_subscriptions` (
+ `id` text PRIMARY KEY NOT NULL,
+ `user_id` text NOT NULL,
+ `calendar_id` text NOT NULL,
+ `status` text DEFAULT 'subscribed' NOT NULL,
+ `source` text DEFAULT 'guest' NOT NULL,
+ `created_at` integer DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ `updated_at` integer DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`calendar_id`) REFERENCES `calendars`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE INDEX `user_calendar_subscriptions_userId_idx` ON `user_calendar_subscriptions` (`user_id`);--> statement-breakpoint
+CREATE INDEX `user_calendar_subscriptions_calendarId_idx` ON `user_calendar_subscriptions` (`calendar_id`);--> statement-breakpoint
+CREATE INDEX `user_calendar_subscriptions_status_idx` ON `user_calendar_subscriptions` (`status`);--> statement-breakpoint
+CREATE TABLE `verification` (
+ `id` text PRIMARY KEY NOT NULL,
+ `identifier` text NOT NULL,
+ `value` text NOT NULL,
+ `expires_at` integer NOT NULL,
+ `created_at` integer DEFAULT (cast(unixepoch('subsecond') * 1000 as integer)) NOT NULL,
+ `updated_at` integer
+);
+--> statement-breakpoint
+ALTER TABLE `calendars` ADD `owner_id` text REFERENCES user(id);--> statement-breakpoint
+ALTER TABLE `calendars` ADD `guest_permission` text DEFAULT 'none' NOT NULL;--> statement-breakpoint
+CREATE INDEX `calendars_ownerId_idx` ON `calendars` (`owner_id`);--> statement-breakpoint
+ALTER TABLE `calendars` DROP COLUMN `password_hash`;--> statement-breakpoint
+ALTER TABLE `calendars` DROP COLUMN `is_locked`;
\ No newline at end of file
diff --git a/drizzle/meta/0013_snapshot.json b/drizzle/meta/0013_snapshot.json
new file mode 100644
index 0000000..43b0bfd
--- /dev/null
+++ b/drizzle/meta/0013_snapshot.json
@@ -0,0 +1,1627 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "15a997db-247d-452f-8243-0146dfca9d63",
+ "prevId": "2c15a455-784b-48ee-b191-1feef86ebaed",
+ "tables": {
+ "account": {
+ "name": "account",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "access_token_expires_at": {
+ "name": "access_token_expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token_expires_at": {
+ "name": "refresh_token_expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "account_userId_idx": {
+ "name": "account_userId_idx",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "account_user_id_user_id_fk": {
+ "name": "account_user_id_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "audit_logs": {
+ "name": "audit_logs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "action": {
+ "name": "action",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "resource_type": {
+ "name": "resource_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resource_id": {
+ "name": "resource_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "severity": {
+ "name": "severity",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'info'"
+ },
+ "is_user_visible": {
+ "name": "is_user_visible",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "audit_logs_userId_timestamp_idx": {
+ "name": "audit_logs_userId_timestamp_idx",
+ "columns": [
+ "user_id",
+ "timestamp"
+ ],
+ "isUnique": false
+ },
+ "audit_logs_action_timestamp_idx": {
+ "name": "audit_logs_action_timestamp_idx",
+ "columns": [
+ "action",
+ "timestamp"
+ ],
+ "isUnique": false
+ },
+ "audit_logs_userVisible_userId_timestamp_idx": {
+ "name": "audit_logs_userVisible_userId_timestamp_idx",
+ "columns": [
+ "is_user_visible",
+ "user_id",
+ "timestamp"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "audit_logs_user_id_user_id_fk": {
+ "name": "audit_logs_user_id_user_id_fk",
+ "tableFrom": "audit_logs",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "calendar_access_tokens": {
+ "name": "calendar_access_tokens",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "permission": {
+ "name": "permission",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'read'"
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "usage_count": {
+ "name": "usage_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ }
+ },
+ "indexes": {
+ "calendar_access_tokens_token_unique": {
+ "name": "calendar_access_tokens_token_unique",
+ "columns": [
+ "token"
+ ],
+ "isUnique": true
+ },
+ "calendar_access_tokens_token_idx": {
+ "name": "calendar_access_tokens_token_idx",
+ "columns": [
+ "token"
+ ],
+ "isUnique": false
+ },
+ "calendar_access_tokens_calendarId_isActive_idx": {
+ "name": "calendar_access_tokens_calendarId_isActive_idx",
+ "columns": [
+ "calendar_id",
+ "is_active"
+ ],
+ "isUnique": false
+ },
+ "calendar_access_tokens_createdBy_idx": {
+ "name": "calendar_access_tokens_createdBy_idx",
+ "columns": [
+ "created_by"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "calendar_access_tokens_calendar_id_calendars_id_fk": {
+ "name": "calendar_access_tokens_calendar_id_calendars_id_fk",
+ "tableFrom": "calendar_access_tokens",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_access_tokens_created_by_user_id_fk": {
+ "name": "calendar_access_tokens_created_by_user_id_fk",
+ "tableFrom": "calendar_access_tokens",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "calendar_notes": {
+ "name": "calendar_notes",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "date": {
+ "name": "date",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "note": {
+ "name": "note",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'note'"
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "recurring_pattern": {
+ "name": "recurring_pattern",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'none'"
+ },
+ "recurring_interval": {
+ "name": "recurring_interval",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "calendar_notes_calendar_id_calendars_id_fk": {
+ "name": "calendar_notes_calendar_id_calendars_id_fk",
+ "tableFrom": "calendar_notes",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "calendar_shares": {
+ "name": "calendar_shares",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "permission": {
+ "name": "permission",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'read'"
+ },
+ "shared_by": {
+ "name": "shared_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "calendar_shares_calendarId_idx": {
+ "name": "calendar_shares_calendarId_idx",
+ "columns": [
+ "calendar_id"
+ ],
+ "isUnique": false
+ },
+ "calendar_shares_userId_idx": {
+ "name": "calendar_shares_userId_idx",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "calendar_shares_calendar_id_calendars_id_fk": {
+ "name": "calendar_shares_calendar_id_calendars_id_fk",
+ "tableFrom": "calendar_shares",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_shares_user_id_user_id_fk": {
+ "name": "calendar_shares_user_id_user_id_fk",
+ "tableFrom": "calendar_shares",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_shares_shared_by_user_id_fk": {
+ "name": "calendar_shares_shared_by_user_id_fk",
+ "tableFrom": "calendar_shares",
+ "tableTo": "user",
+ "columnsFrom": [
+ "shared_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "calendars": {
+ "name": "calendars",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'#3b82f6'"
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "guest_permission": {
+ "name": "guest_permission",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'none'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "calendars_ownerId_idx": {
+ "name": "calendars_ownerId_idx",
+ "columns": [
+ "owner_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "calendars_owner_id_user_id_fk": {
+ "name": "calendars_owner_id_user_id_fk",
+ "tableFrom": "calendars",
+ "tableTo": "user",
+ "columnsFrom": [
+ "owner_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "external_syncs": {
+ "name": "external_syncs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sync_type": {
+ "name": "sync_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'icloud'"
+ },
+ "calendar_url": {
+ "name": "calendar_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'#3b82f6'"
+ },
+ "display_mode": {
+ "name": "display_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'normal'"
+ },
+ "is_hidden": {
+ "name": "is_hidden",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "hide_from_stats": {
+ "name": "hide_from_stats",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "auto_sync_interval": {
+ "name": "auto_sync_interval",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "is_one_time_import": {
+ "name": "is_one_time_import",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "last_synced_at": {
+ "name": "last_synced_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "external_syncs_calendar_id_calendars_id_fk": {
+ "name": "external_syncs_calendar_id_calendars_id_fk",
+ "tableFrom": "external_syncs",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session": {
+ "name": "session",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "impersonated_by": {
+ "name": "impersonated_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "session_token_unique": {
+ "name": "session_token_unique",
+ "columns": [
+ "token"
+ ],
+ "isUnique": true
+ },
+ "session_userId_idx": {
+ "name": "session_userId_idx",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_user_id_user_id_fk": {
+ "name": "session_user_id_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "shift_presets": {
+ "name": "shift_presets",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "start_time": {
+ "name": "start_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "end_time": {
+ "name": "end_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'#3b82f6'"
+ },
+ "notes": {
+ "name": "notes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "is_secondary": {
+ "name": "is_secondary",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "is_all_day": {
+ "name": "is_all_day",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "hide_from_stats": {
+ "name": "hide_from_stats",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "order": {
+ "name": "order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "shift_presets_calendar_id_calendars_id_fk": {
+ "name": "shift_presets_calendar_id_calendars_id_fk",
+ "tableFrom": "shift_presets",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "shifts": {
+ "name": "shifts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "preset_id": {
+ "name": "preset_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "date": {
+ "name": "date",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "start_time": {
+ "name": "start_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "end_time": {
+ "name": "end_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'#3b82f6'"
+ },
+ "notes": {
+ "name": "notes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "is_all_day": {
+ "name": "is_all_day",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "is_secondary": {
+ "name": "is_secondary",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "external_event_id": {
+ "name": "external_event_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "external_sync_id": {
+ "name": "external_sync_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "synced_from_external": {
+ "name": "synced_from_external",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "shifts_calendar_id_calendars_id_fk": {
+ "name": "shifts_calendar_id_calendars_id_fk",
+ "tableFrom": "shifts",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "shifts_preset_id_shift_presets_id_fk": {
+ "name": "shifts_preset_id_shift_presets_id_fk",
+ "tableFrom": "shifts",
+ "tableTo": "shift_presets",
+ "columnsFrom": [
+ "preset_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "shifts_external_sync_id_external_syncs_id_fk": {
+ "name": "shifts_external_sync_id_external_syncs_id_fk",
+ "tableFrom": "shifts",
+ "tableTo": "external_syncs",
+ "columnsFrom": [
+ "external_sync_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "sync_logs": {
+ "name": "sync_logs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "external_sync_id": {
+ "name": "external_sync_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "external_sync_name": {
+ "name": "external_sync_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "error_message": {
+ "name": "error_message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "shifts_created": {
+ "name": "shifts_created",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "shifts_updated": {
+ "name": "shifts_updated",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "shifts_deleted": {
+ "name": "shifts_deleted",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "sync_type": {
+ "name": "sync_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'auto'"
+ },
+ "is_read": {
+ "name": "is_read",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "synced_at": {
+ "name": "synced_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "sync_logs_calendar_id_calendars_id_fk": {
+ "name": "sync_logs_calendar_id_calendars_id_fk",
+ "tableFrom": "sync_logs",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "sync_logs_external_sync_id_external_syncs_id_fk": {
+ "name": "sync_logs_external_sync_id_external_syncs_id_fk",
+ "tableFrom": "sync_logs",
+ "tableTo": "external_syncs",
+ "columnsFrom": [
+ "external_sync_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "user": {
+ "name": "user",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email_verified": {
+ "name": "email_verified",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "banned": {
+ "name": "banned",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": false
+ },
+ "ban_reason": {
+ "name": "ban_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ban_expires": {
+ "name": "ban_expires",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "user_email_unique": {
+ "name": "user_email_unique",
+ "columns": [
+ "email"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "user_calendar_subscriptions": {
+ "name": "user_calendar_subscriptions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'subscribed'"
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'guest'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "user_calendar_subscriptions_userId_idx": {
+ "name": "user_calendar_subscriptions_userId_idx",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": false
+ },
+ "user_calendar_subscriptions_calendarId_idx": {
+ "name": "user_calendar_subscriptions_calendarId_idx",
+ "columns": [
+ "calendar_id"
+ ],
+ "isUnique": false
+ },
+ "user_calendar_subscriptions_status_idx": {
+ "name": "user_calendar_subscriptions_status_idx",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "user_calendar_subscriptions_user_id_user_id_fk": {
+ "name": "user_calendar_subscriptions_user_id_user_id_fk",
+ "tableFrom": "user_calendar_subscriptions",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_calendar_subscriptions_calendar_id_calendars_id_fk": {
+ "name": "user_calendar_subscriptions_calendar_id_calendars_id_fk",
+ "tableFrom": "user_calendar_subscriptions",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "verification": {
+ "name": "verification",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
\ No newline at end of file
diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json
index 9c58b29..71f3ff7 100644
--- a/drizzle/meta/_journal.json
+++ b/drizzle/meta/_journal.json
@@ -92,6 +92,13 @@
"when": 1766343608483,
"tag": "0012_confused_nico_minoru",
"breakpoints": true
+ },
+ {
+ "idx": 13,
+ "version": "6",
+ "when": 1767124870128,
+ "tag": "0013_first_phantom_reporter",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/hooks/useActivityLogs.ts b/hooks/useActivityLogs.ts
new file mode 100644
index 0000000..a361b78
--- /dev/null
+++ b/hooks/useActivityLogs.ts
@@ -0,0 +1,215 @@
+"use client";
+
+import { useState, useEffect, useCallback } from "react";
+import { toast } from "sonner";
+
+// Unified activity log format (matches API response)
+export interface UnifiedActivityLog {
+ id: string;
+ type: "sync" | "auth" | "calendar" | "security";
+ action: string;
+ timestamp: Date;
+ severity: string;
+ metadata: object | null;
+ resourceType?: string;
+ resourceId?: string;
+}
+
+interface ActivityLogsFilters {
+ type?: "sync" | "auth" | "calendar" | "security";
+ startDate?: Date;
+ endDate?: Date;
+ severity?: "info" | "warning" | "error" | "critical";
+ search?: string;
+}
+
+interface ActivityLogsResponse {
+ logs: UnifiedActivityLog[];
+ total: number;
+ page: number;
+ limit: number;
+ hasMore: boolean;
+}
+
+export function useActivityLogs() {
+ const [logs, setLogs] = useState<UnifiedActivityLog[]>([]);
+ const [filteredLogs, setFilteredLogs] = useState<UnifiedActivityLog[]>([]);
+ const [total, setTotal] = useState(0);
+ const [page, setPage] = useState(0);
+ const [limit] = useState(50); // Fixed page size
+ const [hasMore, setHasMore] = useState(false);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ // Filters
+ const [filters, setFilters] = useState<ActivityLogsFilters>({});
+
+ // Fetch logs from API
+ const fetchLogs = useCallback(
+ async (pageNum = 0) => {
+ setLoading(true);
+ setError(null);
+
+ try {
+ const params = new URLSearchParams();
+ if (filters.type) params.set("type", filters.type);
+ if (filters.startDate)
+ params.set("startDate", filters.startDate.toISOString());
+ if (filters.endDate)
+ params.set("endDate", filters.endDate.toISOString());
+ params.set("page", pageNum.toString());
+ params.set("limit", limit.toString());
+
+ const response = await fetch(`/api/activity-logs?${params}`);
+
+ if (!response.ok) {
+ throw new Error("Failed to fetch activity logs");
+ }
+
+ const data: ActivityLogsResponse = await response.json();
+
+ // Parse timestamps
+ const parsedLogs = data.logs.map((log) => ({
+ ...log,
+ timestamp: new Date(log.timestamp),
+ }));
+
+ // Apply client-side filters (severity, search)
+ let filtered = parsedLogs;
+
+ if (filters.severity) {
+ filtered = filtered.filter(
+ (log) => log.severity === filters.severity
+ );
+ }
+
+ if (filters.search && filters.search.trim()) {
+ const searchLower = filters.search.toLowerCase();
+ filtered = filtered.filter(
+ (log) =>
+ log.action.toLowerCase().includes(searchLower) ||
+ (log.resourceType &&
+ log.resourceType.toLowerCase().includes(searchLower)) ||
+ (log.resourceId &&
+ log.resourceId.toLowerCase().includes(searchLower))
+ );
+ }
+
+ setLogs(parsedLogs);
+ setFilteredLogs(filtered);
+ setTotal(data.total);
+ setPage(pageNum);
+ setHasMore(data.hasMore);
+ } catch (err) {
+ console.error("Error fetching activity logs:", err);
+ setError(
+ err instanceof Error ? err.message : "Failed to fetch activity logs"
+ );
+ } finally {
+ setLoading(false);
+ }
+ },
+ [filters, limit]
+ );
+
+ // Clear all logs
+ const clearLogs = useCallback(async () => {
+ try {
+ const response = await fetch("/api/activity-logs", {
+ method: "DELETE",
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to clear activity logs");
+ }
+
+ toast.success("Activity logs cleared");
+ await fetchLogs(0); // Refresh logs
+ } catch (err) {
+ console.error("Error clearing logs:", err);
+ toast.error(
+ err instanceof Error ? err.message : "Failed to clear activity logs"
+ );
+ }
+ }, [fetchLogs]);
+
+ // Mark specific logs as read
+ // Update filters
+ const updateFilters = useCallback(
+ (newFilters: Partial<ActivityLogsFilters>) => {
+ setFilters((prev) => ({ ...prev, ...newFilters }));
+ setPage(0); // Reset to first page when filters change
+ },
+ []
+ );
+
+ // Clear filters
+ const clearFilters = useCallback(() => {
+ setFilters({});
+ setPage(0);
+ }, []);
+
+ // Pagination
+ const goToNextPage = useCallback(() => {
+ if (hasMore) {
+ setPage((prev) => prev + 1);
+ }
+ }, [hasMore]);
+
+ const goToPreviousPage = useCallback(() => {
+ if (page > 0) {
+ setPage((prev) => prev - 1);
+ }
+ }, [page]);
+
+ // Initial fetch + fetch on filter/page change
+ useEffect(() => {
+ fetchLogs(page);
+ }, [page, filters.type, filters.startDate, filters.endDate, fetchLogs]); // Re-fetch on server-side filter changes
+
+ // Apply client-side filters when they change
+ useEffect(() => {
+ let filtered = logs;
+
+ if (filters.severity) {
+ filtered = filtered.filter((log) => log.severity === filters.severity);
+ }
+
+ if (filters.search && filters.search.trim()) {
+ const searchLower = filters.search.toLowerCase();
+ filtered = filtered.filter(
+ (log) =>
+ log.action.toLowerCase().includes(searchLower) ||
+ (log.resourceType &&
+ log.resourceType.toLowerCase().includes(searchLower)) ||
+ (log.resourceId && log.resourceId.toLowerCase().includes(searchLower))
+ );
+ }
+
+ setFilteredLogs(filtered);
+ }, [logs, filters.severity, filters.search]);
+
+ return {
+ // Data
+ logs: filteredLogs,
+ total,
+ page,
+ limit,
+ hasMore,
+ loading,
+ error,
+
+ // Filters
+ filters,
+ updateFilters,
+ clearFilters,
+
+ // Actions
+ fetchLogs: () => fetchLogs(page),
+ clearLogs,
+
+ // Pagination
+ goToNextPage,
+ goToPreviousPage,
+ };
+}
diff --git a/hooks/useAdminAccess.ts b/hooks/useAdminAccess.ts
new file mode 100644
index 0000000..f9378fe
--- /dev/null
+++ b/hooks/useAdminAccess.ts
@@ -0,0 +1,232 @@
+"use client";
+
+import { useMemo, useEffect } from "react";
+import { useRouter } from "next/navigation";
+import { useAuth } from "@/hooks/useAuth";
+import {
+ isAdmin,
+ isSuperAdmin,
+ getAdminLevel,
+ canEditUser,
+ canDeleteUser,
+ canBanUser,
+ canChangeUserRole,
+ canManageCalendar,
+ canAssignOrphanedCalendar,
+ canViewAuditLogs,
+ canDeleteAuditLogs,
+ canResetPassword,
+} from "@/lib/auth/admin";
+import type { User } from "@/lib/auth";
+
+/**
+ * Hook to check if current user is an admin
+ *
+ * @returns boolean - true if user is admin or superadmin
+ */
+export function useIsAdmin(): boolean {
+ const { user } = useAuth();
+ return useMemo(() => isAdmin(user), [user]);
+}
+
+/**
+ * Hook to check if current user is a superadmin
+ *
+ * @returns boolean - true if user is superadmin
+ */
+export function useIsSuperAdmin(): boolean {
+ const { user } = useAuth();
+ return useMemo(() => isSuperAdmin(user), [user]);
+}
+
+/**
+ * Hook to get user's admin level
+ *
+ * @returns "superadmin" | "admin" | "user"
+ */
+export function useAdminLevel(): "superadmin" | "admin" | "user" {
+ const { user } = useAuth();
+ return useMemo(() => getAdminLevel(user), [user]);
+}
+
+/**
+ * Hook to require admin access (redirects non-admins)
+ *
+ * Use this in admin pages to enforce access control
+ * Redirects to home page if user is not an admin
+ *
+ * @param redirectTo - Optional redirect path (default: "/")
+ */
+export function useRequireAdmin(redirectTo: string = "/"): void {
+ const { user, isLoading } = useAuth();
+ const router = useRouter();
+
+ useEffect(() => {
+ // Wait for auth to load
+ if (isLoading) return;
+
+ // Check if user is admin
+ if (!isAdmin(user)) {
+ // Redirect non-admins
+ const url = new URL(redirectTo, window.location.origin);
+ url.searchParams.set("error", "admin_access_required");
+ router.push(url.toString());
+ }
+ }, [user, isLoading, router, redirectTo]);
+}
+
+/**
+ * Hook to check if current admin can edit a specific user
+ *
+ * @param targetUser - The user to check edit permissions for
+ * @returns boolean - true if current admin can edit the target user
+ */
+export function useCanEditUser(targetUser: User | null | undefined): boolean {
+ const { user } = useAuth();
+ return useMemo(() => canEditUser(user, targetUser), [user, targetUser]);
+}
+
+/**
+ * Hook to check if current admin can delete a specific user
+ *
+ * @param targetUser - The user to check delete permissions for
+ * @returns boolean - true if current admin can delete the target user
+ */
+export function useCanDeleteUser(targetUser: User | null | undefined): boolean {
+ const { user } = useAuth();
+ return useMemo(() => canDeleteUser(user, targetUser), [user, targetUser]);
+}
+
+/**
+ * Hook to check if current admin can ban a specific user
+ *
+ * @param targetUser - The user to check ban permissions for
+ * @returns boolean - true if current admin can ban the target user
+ */
+export function useCanBanUser(targetUser: User | null | undefined): boolean {
+ const { user } = useAuth();
+ return useMemo(() => canBanUser(user, targetUser), [user, targetUser]);
+}
+
+/**
+ * Hook to check if current admin can change user roles
+ *
+ * @param targetUser - The user to check role change permissions for
+ * @returns boolean - true if current admin can change the target user's role
+ */
+export function useCanChangeUserRole(
+ targetUser: User | null | undefined
+): boolean {
+ const { user } = useAuth();
+ return useMemo(() => canChangeUserRole(user, targetUser), [user, targetUser]);
+}
+
+/**
+ * Hook to check if current admin can manage calendars
+ *
+ * @param operation - The operation type ("view" | "delete")
+ * @returns boolean - true if current admin can perform the operation
+ */
+export function useCanManageCalendar(operation: "view" | "delete"): boolean {
+ const { user } = useAuth();
+ return useMemo(() => canManageCalendar(user, operation), [user, operation]);
+}
+
+/**
+ * Hook to check if current admin can assign orphaned calendars
+ *
+ * @returns boolean - true if current admin can assign orphaned calendars
+ */
+export function useCanAssignOrphanedCalendar(): boolean {
+ const { user } = useAuth();
+ return useMemo(() => canAssignOrphanedCalendar(user), [user]);
+}
+
+/**
+ * Hook to check if current admin can view audit logs
+ *
+ * @returns boolean - true if current admin can view audit logs
+ */
+export function useCanViewAuditLogs(): boolean {
+ const { user } = useAuth();
+ return useMemo(() => canViewAuditLogs(user), [user]);
+}
+
+/**
+ * Hook to check if current admin can delete audit logs
+ *
+ * @returns boolean - true if current admin can delete audit logs
+ */
+export function useCanDeleteAuditLogs(): boolean {
+ const { user } = useAuth();
+ return useMemo(() => canDeleteAuditLogs(user), [user]);
+}
+
+/**
+ * Hook to check if current admin can reset user passwords
+ *
+ * @param targetUser - The user to check password reset permissions for
+ * @returns boolean - true if current admin can reset the target user's password
+ */
+export function useCanResetPassword(
+ targetUser: User | null | undefined
+): boolean {
+ const { user } = useAuth();
+ return useMemo(() => canResetPassword(user, targetUser), [user, targetUser]);
+}
+
+/**
+ * Hook to get all admin permissions for a target user
+ *
+ * Convenience hook that returns all permission checks at once
+ *
+ * @param targetUser - The user to check permissions for
+ * @returns Object with all permission checks
+ */
+export function useUserPermissions(targetUser: User | null | undefined) {
+ const { user } = useAuth();
+
+ return useMemo(
+ () => ({
+ canEdit: canEditUser(user, targetUser),
+ canDelete: canDeleteUser(user, targetUser),
+ canBan: canBanUser(user, targetUser),
+ canChangeRole: canChangeUserRole(user, targetUser),
+ canResetPassword: canResetPassword(user, targetUser),
+ }),
+ [user, targetUser]
+ );
+}
+
+/**
+ * Hook to check if current admin can edit calendars
+ *
+ * @returns boolean - true if current admin can edit calendars
+ */
+export function useCanEditCalendar(): boolean {
+ const { user } = useAuth();
+ // Admin and Superadmin can edit calendars
+ return useMemo(() => isAdmin(user), [user]);
+}
+
+/**
+ * Hook to check if current admin can delete calendars
+ *
+ * @returns boolean - true if current admin can delete calendars
+ */
+export function useCanDeleteCalendar(): boolean {
+ const { user } = useAuth();
+ // Only Superadmin can delete calendars
+ return useMemo(() => isSuperAdmin(user), [user]);
+}
+
+/**
+ * Hook to check if current admin can transfer calendar ownership
+ *
+ * @returns boolean - true if current admin can transfer calendars
+ */
+export function useCanTransferCalendar(): boolean {
+ const { user } = useAuth();
+ // Admin and Superadmin can transfer calendars
+ return useMemo(() => isAdmin(user), [user]);
+}
diff --git a/hooks/useAdminCalendars.ts b/hooks/useAdminCalendars.ts
new file mode 100644
index 0000000..7e7487e
--- /dev/null
+++ b/hooks/useAdminCalendars.ts
@@ -0,0 +1,402 @@
+"use client";
+
+import { useState, useCallback } from "react";
+import { toast } from "sonner";
+import { useTranslations } from "next-intl";
+
+/**
+ * Calendar Owner Info
+ */
+export interface CalendarOwner {
+ name: string | null;
+ email: string | null;
+ image: string | null;
+}
+
+/**
+ * Extended Calendar Type with Admin-specific fields
+ */
+export interface AdminCalendar {
+ id: string;
+ name: string;
+ color: string;
+ guestPermission: "none" | "read" | "write";
+ createdAt: Date;
+ updatedAt: Date;
+ owner: CalendarOwner | null;
+ ownerId: string | null;
+ shiftsCount: number;
+ notesCount: number;
+ presetsCount: number;
+ sharesCount: number;
+ externalSyncsCount: number;
+}
+
+/**
+ * Calendar Details Type (for calendar details sheet)
+ */
+export interface CalendarDetails extends AdminCalendar {
+ shares: Array<{
+ userId: string;
+ userName: string;
+ userEmail: string;
+ userImage: string | null;
+ permission: string;
+ }>;
+ shareTokens: Array<{
+ id: string;
+ name: string;
+ permission: string;
+ createdAt: Date;
+ }>;
+ externalSyncs: Array<{
+ id: string;
+ name: string;
+ url: string;
+ lastSyncedAt: Date | null;
+ }>;
+}
+
+/**
+ * Calendar Filters
+ */
+export interface CalendarFilters {
+ search?: string;
+ status?: "all" | "orphaned" | "with-owner";
+}
+
+/**
+ * Calendar Sort Options
+ */
+export interface CalendarSort {
+ field: "name" | "createdAt" | "owner" | "shiftsCount";
+ direction: "asc" | "desc";
+}
+
+/**
+ * Calendars List Response
+ */
+export interface CalendarsListResponse {
+ calendars: AdminCalendar[];
+ total: number;
+ orphanedCount: number;
+}
+
+/**
+ * Admin Calendars Management Hook
+ *
+ * Provides functions for managing calendars in the admin panel.
+ *
+ * Features:
+ * - Fetch calendars with filtering and sorting
+ * - Get calendar details
+ * - Update calendar information
+ * - Delete calendars (single and bulk)
+ * - Transfer calendar ownership (single and bulk)
+ * - Error handling with toast notifications
+ *
+ * @returns Object with calendar management functions and state
+ */
+export function useAdminCalendars() {
+ const t = useTranslations();
+ const [isLoading, setIsLoading] = useState(false);
+
+ /**
+ * Fetch calendars list with filters and sort
+ */
+ const fetchCalendars = useCallback(
+ async (
+ filters?: CalendarFilters,
+ sort?: CalendarSort
+ ): Promise<CalendarsListResponse | null> => {
+ setIsLoading(true);
+ try {
+ const params = new URLSearchParams();
+
+ // Add filters
+ if (filters?.search) {
+ params.set("search", filters.search);
+ }
+ if (filters?.status && filters.status !== "all") {
+ params.set("status", filters.status);
+ }
+
+ // Add sort
+ if (sort?.field) {
+ params.set("sortBy", sort.field);
+ }
+ if (sort?.direction) {
+ params.set("sortDirection", sort.direction);
+ }
+
+ const response = await fetch(`/api/admin/calendars?${params}`);
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || "Failed to fetch calendars");
+ }
+
+ const data = await response.json();
+
+ // Parse dates
+ const calendars = data.calendars.map((cal: AdminCalendar) => ({
+ ...cal,
+ createdAt: new Date(cal.createdAt),
+ updatedAt: new Date(cal.updatedAt),
+ }));
+
+ return {
+ calendars,
+ total: data.total,
+ orphanedCount: data.orphanedCount,
+ };
+ } catch (error) {
+ console.error("Failed to fetch calendars:", error);
+ toast.error(
+ t("common.fetchError", { item: t("common.labels.calendar") })
+ );
+ return null;
+ } finally {
+ setIsLoading(false);
+ }
+ },
+ [t]
+ );
+
+ /**
+ * Get calendar details by ID
+ */
+ const fetchCalendarDetails = useCallback(
+ async (calendarId: string): Promise<CalendarDetails | null> => {
+ setIsLoading(true);
+ try {
+ const response = await fetch(`/api/admin/calendars/${calendarId}`);
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || "Failed to fetch calendar details");
+ }
+
+ const data = await response.json();
+
+ // Parse dates
+ return {
+ ...data,
+ createdAt: new Date(data.createdAt),
+ updatedAt: new Date(data.updatedAt),
+ externalSyncs: data.externalSyncs.map(
+ (sync: CalendarDetails["externalSyncs"][number]) => ({
+ ...sync,
+ lastSyncedAt: sync.lastSyncedAt
+ ? new Date(sync.lastSyncedAt)
+ : null,
+ })
+ ),
+ };
+ } catch (error) {
+ console.error("Failed to fetch calendar details:", error);
+ toast.error(
+ t("common.fetchError", { item: t("admin.calendars.calendarDetails") })
+ );
+ return null;
+ } finally {
+ setIsLoading(false);
+ }
+ },
+ [t]
+ );
+
+ /**
+ * Update calendar
+ */
+ const updateCalendar = useCallback(
+ async (
+ calendarId: string,
+ updates: { name?: string; color?: string; guestPermission?: string }
+ ): Promise<boolean> => {
+ setIsLoading(true);
+ try {
+ const response = await fetch(`/api/admin/calendars/${calendarId}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(updates),
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || "Failed to update calendar");
+ }
+
+ toast.success(
+ t("common.updated", { item: t("common.labels.calendar") })
+ );
+ return true;
+ } catch (error) {
+ console.error("Failed to update calendar:", error);
+ toast.error(
+ t("common.updateError", { item: t("common.labels.calendar") })
+ );
+ return false;
+ } finally {
+ setIsLoading(false);
+ }
+ },
+ [t]
+ );
+
+ /**
+ * Delete calendar
+ */
+ const deleteCalendar = useCallback(
+ async (calendarId: string): Promise<boolean> => {
+ setIsLoading(true);
+ try {
+ const response = await fetch(`/api/admin/calendars/${calendarId}`, {
+ method: "DELETE",
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || "Failed to delete calendar");
+ }
+
+ toast.success(
+ t("common.deleted", { item: t("common.labels.calendar") })
+ );
+ return true;
+ } catch (error) {
+ console.error("Failed to delete calendar:", error);
+ toast.error(
+ t("common.deleteError", { item: t("common.labels.calendar") })
+ );
+ return false;
+ } finally {
+ setIsLoading(false);
+ }
+ },
+ [t]
+ );
+
+ /**
+ * Transfer calendar ownership
+ */
+ const transferCalendar = useCallback(
+ async (calendarId: string, newOwnerId: string): Promise<boolean> => {
+ setIsLoading(true);
+ try {
+ const response = await fetch(
+ `/api/admin/calendars/${calendarId}/transfer`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ newOwnerId }),
+ }
+ );
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || "Failed to transfer calendar");
+ }
+
+ toast.success(
+ t("common.transferred", { item: t("common.labels.calendar") })
+ );
+ return true;
+ } catch (error) {
+ console.error("Failed to transfer calendar:", error);
+ toast.error(
+ t("common.transferError", { item: t("common.labels.calendar") })
+ );
+ return false;
+ } finally {
+ setIsLoading(false);
+ }
+ },
+ [t]
+ );
+
+ /**
+ * Bulk delete calendars
+ */
+ const bulkDeleteCalendars = useCallback(
+ async (calendarIds: string[]): Promise<boolean> => {
+ setIsLoading(true);
+ try {
+ const response = await fetch("/api/admin/calendars/bulk-delete", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ calendarIds }),
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || "Failed to delete calendars");
+ }
+
+ const data = await response.json();
+ toast.success(
+ t("admin.calendars.calendarsDeleted", { count: data.deletedCount })
+ );
+ return true;
+ } catch (error) {
+ console.error("Failed to bulk delete calendars:", error);
+ toast.error(
+ t("common.deleteError", { item: t("common.labels.calendar") })
+ );
+ return false;
+ } finally {
+ setIsLoading(false);
+ }
+ },
+ [t]
+ );
+
+ /**
+ * Bulk transfer calendars
+ */
+ const bulkTransferCalendars = useCallback(
+ async (calendarIds: string[], newOwnerId: string): Promise<boolean> => {
+ setIsLoading(true);
+ try {
+ const response = await fetch("/api/admin/calendars/bulk-transfer", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ calendarIds, newOwnerId }),
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || "Failed to transfer calendars");
+ }
+
+ const data = await response.json();
+ toast.success(
+ t("admin.calendars.calendarsTransferred", {
+ count: data.transferredCount,
+ })
+ );
+ return true;
+ } catch (error) {
+ console.error("Failed to bulk transfer calendars:", error);
+ toast.error(
+ t("common.transferError", { item: t("common.labels.calendar") })
+ );
+ return false;
+ } finally {
+ setIsLoading(false);
+ }
+ },
+ [t]
+ );
+
+ return {
+ fetchCalendars,
+ fetchCalendarDetails,
+ updateCalendar,
+ deleteCalendar,
+ transferCalendar,
+ bulkDeleteCalendars,
+ bulkTransferCalendars,
+ isLoading,
+ };
+}
diff --git a/hooks/useAdminStats.ts b/hooks/useAdminStats.ts
new file mode 100644
index 0000000..05abc73
--- /dev/null
+++ b/hooks/useAdminStats.ts
@@ -0,0 +1,143 @@
+"use client";
+
+import { useState, useEffect, useCallback } from "react";
+import { toast } from "sonner";
+import { useTranslations } from "next-intl";
+
+/**
+ * Admin Stats Type Definitions
+ */
+export interface AdminStats {
+ users: {
+ superadmin: number;
+ admin: number;
+ user: number;
+ total: number;
+ };
+ calendars: {
+ total: number;
+ orphaned: number;
+ };
+ shares: {
+ user: number;
+ token: number;
+ active: number;
+ };
+ shifts: {
+ total: number;
+ };
+ activity: {
+ recent: number;
+ logs: Array<{
+ id: string;
+ action: string;
+ resourceType: string | null;
+ resourceId: string | null;
+ userId: string | null;
+ severity: string;
+ timestamp: Date;
+ }>;
+ };
+}
+
+interface AuditLogResponse {
+ id: string;
+ action: string;
+ resourceType: string | null;
+ resourceId: string | null;
+ userId: string | null;
+ severity: string;
+ timestamp: string | Date;
+}
+
+/**
+ * Admin Statistics Hook
+ *
+ * Fetches and manages system-wide statistics for admin dashboard.
+ *
+ * Features:
+ * - Automatic data fetching on mount
+ * - Optional auto-refresh (configurable interval)
+ * - Error handling with toast notifications
+ * - Loading state management
+ *
+ * @param autoRefresh - Enable auto-refresh (default: false)
+ * @param refreshInterval - Refresh interval in milliseconds (default: 60000 = 1 minute)
+ */
+export function useAdminStats(
+ autoRefresh = false,
+ refreshInterval = 60000
+): {
+ stats: AdminStats | null;
+ isLoading: boolean;
+ error: Error | null;
+ refetch: () => Promise<void>;
+} {
+ const t = useTranslations();
+ const [stats, setStats] = useState<AdminStats | null>(null);
+ const [isLoading, setIsLoading] = useState(true);
+ const [error, setError] = useState<Error | null>(null);
+
+ const fetchStats = useCallback(async () => {
+ try {
+ setError(null);
+
+ const response = await fetch("/api/admin/stats", {
+ method: "GET",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+
+ if (!response.ok) {
+ if (response.status === 403) {
+ throw new Error(t("admin.accessDenied"));
+ }
+ throw new Error(t("admin.statsFetchError"));
+ }
+
+ const data = await response.json();
+
+ // Parse timestamp strings to Date objects
+ if (data.activity?.logs) {
+ data.activity.logs = data.activity.logs.map(
+ (log: AuditLogResponse) => ({
+ ...log,
+ timestamp: new Date(log.timestamp),
+ })
+ );
+ }
+
+ setStats(data);
+ } catch (err) {
+ const error = err instanceof Error ? err : new Error("Unknown error");
+ setError(error);
+ toast.error(error.message);
+ } finally {
+ setIsLoading(false);
+ }
+ }, [t]);
+
+ // Initial fetch on mount
+ useEffect(() => {
+ fetchStats();
+ }, [fetchStats]);
+
+ // Auto-refresh setup
+ useEffect(() => {
+ if (!autoRefresh) return;
+
+ const interval = setInterval(() => {
+ fetchStats();
+ }, refreshInterval);
+
+ return () => clearInterval(interval);
+ }, [autoRefresh, refreshInterval, fetchStats]);
+
+ return {
+ stats,
+ isLoading,
+ error,
+ refetch: fetchStats,
+ };
+}
diff --git a/hooks/useAdminUsers.ts b/hooks/useAdminUsers.ts
new file mode 100644
index 0000000..f6ba286
--- /dev/null
+++ b/hooks/useAdminUsers.ts
@@ -0,0 +1,480 @@
+"use client";
+
+import { useState, useCallback } from "react";
+import { toast } from "sonner";
+import { useTranslations } from "next-intl";
+import type { User } from "@/lib/auth";
+
+/**
+ * Extended User Type with Admin-specific fields
+ */
+export interface AdminUser extends User {
+ calendarCount: number;
+ sharesCount: number;
+ lastActivity: Date | null;
+ banned: boolean;
+ banReason: string | null;
+ banExpires: Date | null;
+}
+
+/**
+ * User Details Type (for user details sheet)
+ */
+export interface UserDetails extends AdminUser {
+ accounts: Array<{
+ id: string;
+ providerId: string;
+ accountId: string;
+ createdAt: Date;
+ }>;
+ sessionsCount: number;
+ ownedCalendars: Array<{
+ id: string;
+ name: string;
+ color: string;
+ }>;
+ sharedCalendars: Array<{
+ id: string;
+ name: string;
+ permission: string;
+ }>;
+}
+
+/**
+ * User Filters
+ */
+export interface UserFilters {
+ search?: string;
+ role?: "all" | "superadmin" | "admin" | "user";
+ status?: "all" | "active" | "banned";
+}
+
+/**
+ * User Sort Options
+ */
+export interface UserSort {
+ field: "name" | "email" | "createdAt" | "role";
+ direction: "asc" | "desc";
+}
+
+/**
+ * Pagination Options
+ */
+export interface Pagination {
+ page: number;
+ limit: number;
+}
+
+/**
+ * Users List Response
+ */
+export interface UsersListResponse {
+ users: AdminUser[];
+ total: number;
+ page: number;
+ limit: number;
+ totalPages: number;
+}
+
+/**
+ * Admin Users Management Hook
+ *
+ * Provides functions for managing users in the admin panel.
+ *
+ * Features:
+ * - Fetch users with filtering, sorting, and pagination
+ * - Get user details
+ * - Update user information
+ * - Ban/Unban users
+ * - Delete users
+ * - Reset user passwords
+ * - Error handling with toast notifications
+ *
+ * @returns Object with user management functions and state
+ */
+export function useAdminUsers() {
+ const t = useTranslations();
+ const [isLoading, setIsLoading] = useState(false);
+
+ /**
+ * Fetch users list with filters, sort, and pagination
+ */
+ const fetchUsers = useCallback(
+ async (
+ filters: UserFilters = {},
+ sort: UserSort = { field: "createdAt", direction: "desc" },
+ pagination: Pagination = { page: 1, limit: 25 }
+ ): Promise<UsersListResponse | null> => {
+ try {
+ setIsLoading(true);
+
+ const params = new URLSearchParams();
+ if (filters.search) params.set("search", filters.search);
+ if (filters.role && filters.role !== "all")
+ params.set("role", filters.role);
+ if (filters.status && filters.status !== "all") {
+ // Map 'active'/'banned' to boolean for API
+ params.set("banned", filters.status === "banned" ? "true" : "false");
+ }
+ params.set("sortBy", sort.field);
+ params.set("sortDir", sort.direction);
+ params.set("page", pagination.page.toString());
+ params.set("limit", pagination.limit.toString());
+
+ const response = await fetch(`/api/admin/users?${params.toString()}`, {
+ method: "GET",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+
+ if (!response.ok) {
+ if (response.status === 403) {
+ throw new Error(t("admin.accessDenied"));
+ }
+ throw new Error(
+ t("common.fetchError", { item: t("common.labels.users") })
+ );
+ }
+
+ const data = await response.json();
+
+ // Parse date strings to Date objects
+ const users = data.users.map((user: Record<string, unknown>) => ({
+ ...user,
+ createdAt: new Date(user.createdAt as string),
+ updatedAt: new Date(user.updatedAt as string),
+ lastActivity: user.lastActivity
+ ? new Date(user.lastActivity as string)
+ : null,
+ banExpires: user.banExpires
+ ? new Date(user.banExpires as string)
+ : null,
+ }));
+
+ return {
+ ...data,
+ users,
+ };
+ } catch (error) {
+ console.error("Failed to fetch users:", error);
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t("common.fetchError", { item: t("common.labels.users") })
+ );
+ return null;
+ } finally {
+ setIsLoading(false);
+ }
+ },
+ [t]
+ );
+
+ /**
+ * Fetch detailed user information
+ */
+ const fetchUserDetails = useCallback(
+ async (userId: string): Promise<UserDetails | null> => {
+ try {
+ setIsLoading(true);
+
+ const response = await fetch(`/api/admin/users/${userId}`, {
+ method: "GET",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+
+ if (!response.ok) {
+ if (response.status === 403) {
+ throw new Error(t("admin.accessDenied"));
+ }
+ if (response.status === 404) {
+ throw new Error(t("admin.userNotFound"));
+ }
+ throw new Error(
+ t("common.fetchError", { item: t("admin.userDetails") })
+ );
+ }
+
+ const data = await response.json();
+
+ // Parse date strings to Date objects
+ return {
+ ...data.user,
+ createdAt: new Date(data.user.createdAt as string),
+ updatedAt: new Date(data.user.updatedAt as string),
+ lastActivity: data.lastActivity
+ ? new Date(data.lastActivity as string)
+ : null,
+ banExpires: data.user.banExpires
+ ? new Date(data.user.banExpires as string)
+ : null,
+ ownedCalendars: data.calendars || [],
+ sharedCalendars: data.sharedCalendars || [],
+ sharesCount: data.sharesCount,
+ calendarCount: (data.calendars?.length || 0) + data.sharesCount,
+ accounts: data.accounts.map((account: Record<string, unknown>) => ({
+ ...account,
+ createdAt: new Date(account.createdAt as string),
+ })),
+ sessionsCount: data.sessionsCount,
+ };
+ } catch (error) {
+ console.error("Failed to fetch user details:", error);
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t("common.fetchError", { item: t("admin.userDetails") })
+ );
+ return null;
+ } finally {
+ setIsLoading(false);
+ }
+ },
+ [t]
+ );
+
+ /**
+ * Update user information
+ */
+ const updateUser = useCallback(
+ async (
+ userId: string,
+ data: { name?: string; email?: string; role?: string }
+ ): Promise<boolean> => {
+ try {
+ setIsLoading(true);
+
+ const response = await fetch(`/api/admin/users/${userId}`, {
+ method: "PATCH",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(data),
+ });
+
+ if (!response.ok) {
+ if (response.status === 403) {
+ throw new Error(t("admin.accessDenied"));
+ }
+ if (response.status === 404) {
+ throw new Error(t("admin.userNotFound"));
+ }
+ throw new Error(
+ t("common.updateError", { item: t("common.labels.user") })
+ );
+ }
+
+ toast.success(t("common.updated", { item: t("common.labels.user") }));
+ return true;
+ } catch (error) {
+ console.error("Failed to update user:", error);
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t("common.updateError", { item: t("common.labels.user") })
+ );
+ return false;
+ } finally {
+ setIsLoading(false);
+ }
+ },
+ [t]
+ );
+
+ /**
+ * Ban user
+ */
+ const banUser = useCallback(
+ async (
+ userId: string,
+ reason: string,
+ expiresAt?: Date
+ ): Promise<boolean> => {
+ try {
+ setIsLoading(true);
+
+ const response = await fetch(`/api/admin/users/${userId}/ban`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ reason,
+ expiresAt: expiresAt?.toISOString(),
+ }),
+ });
+
+ if (!response.ok) {
+ if (response.status === 403) {
+ throw new Error(t("admin.accessDenied"));
+ }
+ if (response.status === 404) {
+ throw new Error(t("admin.userNotFound"));
+ }
+ throw new Error(
+ t("common.banError", { item: t("common.labels.user") })
+ );
+ }
+
+ toast.success(t("common.banned", { item: t("common.labels.user") }));
+ return true;
+ } catch (error) {
+ console.error("Failed to ban user:", error);
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t("common.banError", { item: t("common.labels.user") })
+ );
+ return false;
+ } finally {
+ setIsLoading(false);
+ }
+ },
+ [t]
+ );
+
+ /**
+ * Unban user
+ */
+ const unbanUser = useCallback(
+ async (userId: string): Promise<boolean> => {
+ try {
+ setIsLoading(true);
+
+ const response = await fetch(`/api/admin/users/${userId}/unban`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+
+ if (!response.ok) {
+ if (response.status === 403) {
+ throw new Error(t("admin.accessDenied"));
+ }
+ if (response.status === 404) {
+ throw new Error(t("admin.userNotFound"));
+ }
+ throw new Error(
+ t("common.unbanError", { item: t("common.labels.user") })
+ );
+ }
+
+ toast.success(t("common.unbanned", { item: t("common.labels.user") }));
+ return true;
+ } catch (error) {
+ console.error("Failed to unban user:", error);
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t("common.unbanError", { item: t("common.labels.user") })
+ );
+ return false;
+ } finally {
+ setIsLoading(false);
+ }
+ },
+ [t]
+ );
+
+ /**
+ * Delete user
+ */
+ const deleteUser = useCallback(
+ async (userId: string): Promise<boolean> => {
+ try {
+ setIsLoading(true);
+
+ const response = await fetch(`/api/admin/users/${userId}`, {
+ method: "DELETE",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+
+ if (!response.ok) {
+ if (response.status === 403) {
+ throw new Error(t("admin.accessDenied"));
+ }
+ if (response.status === 404) {
+ throw new Error(t("admin.userNotFound"));
+ }
+ throw new Error(
+ t("common.deleteError", { item: t("common.labels.user") })
+ );
+ }
+
+ toast.success(t("common.deleted", { item: t("common.labels.user") }));
+ return true;
+ } catch (error) {
+ console.error("Failed to delete user:", error);
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t("common.deleteError", { item: t("common.labels.user") })
+ );
+ return false;
+ } finally {
+ setIsLoading(false);
+ }
+ },
+ [t]
+ );
+
+ /**
+ * Reset user password
+ */
+ const resetPassword = useCallback(
+ async (userId: string, newPassword: string): Promise<boolean> => {
+ try {
+ setIsLoading(true);
+
+ const response = await fetch(`/api/admin/users/${userId}/password`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ password: newPassword }),
+ });
+
+ if (!response.ok) {
+ if (response.status === 403) {
+ throw new Error(t("admin.accessDenied"));
+ }
+ if (response.status === 404) {
+ throw new Error(t("admin.userNotFound"));
+ }
+ throw new Error(t("common.passwordResetError"));
+ }
+
+ toast.success(t("common.passwordReset"));
+ return true;
+ } catch (error) {
+ console.error("Failed to reset password:", error);
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t("common.passwordResetError")
+ );
+ return false;
+ } finally {
+ setIsLoading(false);
+ }
+ },
+ [t]
+ );
+
+ return {
+ isLoading,
+ fetchUsers,
+ fetchUserDetails,
+ updateUser,
+ banUser,
+ unbanUser,
+ deleteUser,
+ resetPassword,
+ };
+}
diff --git a/hooks/useAuditLogs.ts b/hooks/useAuditLogs.ts
new file mode 100644
index 0000000..fbc3542
--- /dev/null
+++ b/hooks/useAuditLogs.ts
@@ -0,0 +1,220 @@
+import { useState, useCallback } from "react";
+import { toast } from "sonner";
+import { useTranslations } from "next-intl";
+
+/**
+ * Audit Log Types
+ */
+export interface AuditLog {
+ id: string;
+ userId: string | null;
+ action: string;
+ resourceType: string | null;
+ resourceId: string | null;
+ metadata: unknown;
+ ipAddress: string | null;
+ userAgent: string | null;
+ severity: "info" | "warning" | "error" | "critical";
+ isUserVisible: boolean;
+ timestamp: string;
+ userName: string | null;
+ userEmail: string | null;
+ userImage: string | null;
+}
+
+export interface AuditLogFilters {
+ action?: string;
+ userId?: string;
+ resourceType?: string;
+ resourceId?: string;
+ severity?: "info" | "warning" | "error" | "critical";
+ search?: string;
+ startDate?: string;
+ endDate?: string;
+}
+
+export interface AuditLogSort {
+ sortBy?: "timestamp" | "action" | "severity" | "user" | "ipAddress";
+ sortOrder?: "asc" | "desc";
+}
+
+export interface AuditLogPagination {
+ limit?: number;
+ offset?: number;
+}
+
+export interface AuditLogsResponse {
+ logs: AuditLog[];
+ pagination: {
+ total: number;
+ limit: number;
+ offset: number;
+ hasMore: boolean;
+ };
+}
+
+/**
+ * Hook for managing audit logs (admin only)
+ *
+ * Provides functions to:
+ * - Fetch audit logs with filtering, sorting, and pagination
+ * - Delete logs by date range
+ * - Delete specific logs by IDs
+ * - Export logs (future feature)
+ */
+export function useAuditLogs() {
+ const t = useTranslations();
+ const [isLoading, setIsLoading] = useState(false);
+
+ /**
+ * Fetch audit logs with filters, sorting, and pagination
+ */
+ const fetchAuditLogs = useCallback(
+ async (
+ filters: AuditLogFilters = {},
+ sort: AuditLogSort = {},
+ pagination: AuditLogPagination = {}
+ ): Promise<AuditLogsResponse | null> => {
+ setIsLoading(true);
+
+ try {
+ const params = new URLSearchParams();
+
+ // Add filters
+ if (filters.action) params.append("action", filters.action);
+ if (filters.userId) params.append("userId", filters.userId);
+ if (filters.resourceType)
+ params.append("resourceType", filters.resourceType);
+ if (filters.resourceId) params.append("resourceId", filters.resourceId);
+ if (filters.severity) params.append("severity", filters.severity);
+ if (filters.search) params.append("search", filters.search);
+ if (filters.startDate) params.append("startDate", filters.startDate);
+ if (filters.endDate) params.append("endDate", filters.endDate);
+
+ // Add sorting
+ if (sort.sortBy) params.append("sortBy", sort.sortBy);
+ if (sort.sortOrder) params.append("sortOrder", sort.sortOrder);
+
+ // Add pagination
+ if (pagination.limit)
+ params.append("limit", pagination.limit.toString());
+ if (pagination.offset !== undefined)
+ params.append("offset", pagination.offset.toString());
+
+ const response = await fetch(`/api/admin/audit-logs?${params}`, {
+ credentials: "include",
+ });
+
+ if (!response.ok) {
+ const error = await response.json().catch(() => ({}));
+ throw new Error(error.error || "Failed to fetch audit logs");
+ }
+
+ const data = await response.json();
+ return data;
+ } catch (error) {
+ console.error("[useAuditLogs] Fetch error:", error);
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t("admin.auditLogs.fetchError")
+ );
+ return null;
+ } finally {
+ setIsLoading(false);
+ }
+ },
+ [t]
+ );
+
+ /**
+ * Delete audit logs older than a specific date
+ * (Superadmin only)
+ */
+ const deleteLogsByDate = useCallback(
+ async (beforeDate: string): Promise<boolean> => {
+ setIsLoading(true);
+
+ try {
+ const response = await fetch(
+ `/api/admin/audit-logs?before=${encodeURIComponent(beforeDate)}`,
+ {
+ method: "DELETE",
+ credentials: "include",
+ }
+ );
+
+ if (!response.ok) {
+ const error = await response.json().catch(() => ({}));
+ throw new Error(error.error || "Failed to delete audit logs");
+ }
+
+ const data = await response.json();
+ toast.success(t("common.deletedCount", { count: data.deletedCount }));
+ return true;
+ } catch (error) {
+ console.error("[useAuditLogs] Delete by date error:", error);
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t("admin.auditLogs.deleteError")
+ );
+ return false;
+ } finally {
+ setIsLoading(false);
+ }
+ },
+ [t]
+ );
+
+ /**
+ * Delete specific audit logs by IDs
+ * (Superadmin only)
+ */
+ const deleteLogsByIds = useCallback(
+ async (logIds: string[]): Promise<boolean> => {
+ if (logIds.length === 0) {
+ toast.error(t("admin.auditLogs.noLogsSelected"));
+ return false;
+ }
+
+ setIsLoading(true);
+
+ try {
+ const response = await fetch("/api/admin/audit-logs", {
+ method: "DELETE",
+ headers: { "Content-Type": "application/json" },
+ credentials: "include",
+ body: JSON.stringify({ logIds }),
+ });
+
+ if (!response.ok) {
+ const error = await response.json().catch(() => ({}));
+ throw new Error(error.error || "Failed to delete audit logs");
+ }
+
+ const data = await response.json();
+ toast.success(t("common.deletedCount", { count: data.deletedCount }));
+ return true;
+ } catch (error) {
+ console.error("[useAuditLogs] Delete by IDs error:", error);
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t("admin.auditLogs.deleteError")
+ );
+ return false;
+ } finally {
+ setIsLoading(false);
+ }
+ },
+ [t]
+ );
+
+ return {
+ isLoading,
+ fetchAuditLogs,
+ deleteLogsByDate,
+ deleteLogsByIds,
+ };
+}
diff --git a/hooks/useAuth.ts b/hooks/useAuth.ts
new file mode 100644
index 0000000..83696ae
--- /dev/null
+++ b/hooks/useAuth.ts
@@ -0,0 +1,43 @@
+"use client";
+
+import { useSession } from "@/lib/auth/client";
+import type { User } from "@/lib/auth";
+import { usePublicConfig } from "@/hooks/usePublicConfig";
+
+/**
+ * Hook for auth state management
+ *
+ * Provides centralized access to:
+ * - Current user
+ * - Session state
+ * - Loading states
+ * - Authentication status
+ * - Guest mode detection
+ *
+ * @example
+ * const { user, isAuthenticated, isGuest, isLoading } = useAuth();
+ *
+ * if (isLoading) return <Spinner />;
+ * if (isGuest) return <GuestBanner />;
+ * if (!isAuthenticated) return <LoginPrompt />;
+ * return <div>Welcome {user.name}</div>;
+ */
+export function useAuth() {
+ const { data: session, isPending, error, refetch } = useSession();
+ const { auth } = usePublicConfig();
+
+ const hasUser = !!session?.user;
+
+ // Guest: Auth enabled, no user session, but guest access allowed
+ const isGuest = auth.enabled && !hasUser && auth.allowGuestAccess;
+
+ return {
+ user: session?.user as User | undefined,
+ session: session,
+ isAuthenticated: hasUser,
+ isGuest: isGuest,
+ isLoading: isPending,
+ error: error,
+ refetch: refetch,
+ };
+}
diff --git a/hooks/useAuthFeatures.ts b/hooks/useAuthFeatures.ts
new file mode 100644
index 0000000..ede9571
--- /dev/null
+++ b/hooks/useAuthFeatures.ts
@@ -0,0 +1,75 @@
+/**
+ * Client-side auth feature flags hook
+ *
+ * This hook provides client components with access to auth-related feature flags
+ * from the public configuration.
+ *
+ * Usage:
+ * ```tsx
+ * const { isAuthEnabled, allowRegistration, allowGuest, providers } = useAuthFeatures();
+ * ```
+ */
+
+import { usePublicConfig } from "./usePublicConfig";
+
+export interface AuthFeatures {
+ /**
+ * Whether authentication system is enabled
+ */
+ isAuthEnabled: boolean;
+
+ /**
+ * Whether new user registration is allowed
+ */
+ allowRegistration: boolean;
+
+ /**
+ * Whether guest access (unauthenticated) is allowed
+ */
+ allowGuest: boolean;
+
+ /**
+ * OAuth providers configuration
+ */
+ providers: {
+ google: string | undefined;
+ github: string | undefined;
+ discord: string | undefined;
+ hasAny: boolean;
+ };
+
+ /**
+ * Custom OIDC configuration
+ */
+ oidc: {
+ enabled: boolean;
+ name: string;
+ clientId: string | undefined;
+ issuer: string | undefined;
+ };
+}
+
+/**
+ * Hook to access auth-related feature flags in client components
+ */
+export function useAuthFeatures(): AuthFeatures {
+ const { auth, oauth, oidc } = usePublicConfig();
+
+ return {
+ isAuthEnabled: auth.enabled,
+ allowRegistration: auth.enabled && auth.allowRegistration,
+ allowGuest: !auth.enabled || auth.allowGuestAccess,
+ providers: {
+ google: oauth.google,
+ github: oauth.github,
+ discord: oauth.discord,
+ hasAny: !!(oauth.google || oauth.github || oauth.discord),
+ },
+ oidc: {
+ enabled: oidc.enabled,
+ name: oidc.name,
+ clientId: oidc.clientId,
+ issuer: oidc.issuer,
+ },
+ };
+}
diff --git a/hooks/useCalendarPermission.ts b/hooks/useCalendarPermission.ts
new file mode 100644
index 0000000..9acaa56
--- /dev/null
+++ b/hooks/useCalendarPermission.ts
@@ -0,0 +1,235 @@
+"use client";
+
+import { useMemo } from "react";
+import { useAuth } from "@/hooks/useAuth";
+import { useCalendars } from "@/hooks/useCalendars";
+import { CalendarWithCount } from "@/lib/types";
+import { usePublicConfig } from "@/hooks/usePublicConfig";
+import type { CalendarPermission } from "@/lib/auth/permissions";
+
+/**
+ * Hook to check calendar permissions client-side
+ *
+ * Returns permission helpers for the given calendar.
+ * Takes into account:
+ * - User authentication status
+ * - Calendar ownership
+ * - Guest permissions (if user is guest)
+ *
+ * Accepts either a calendar object or a calendar ID string.
+ * If a string is provided, it will look up the calendar from the calendars list.
+ *
+ * @example
+ * // With calendar object
+ * const { canEdit, canView, canManage, isReadOnly } = useCalendarPermission(calendar);
+ *
+ * // With calendar ID
+ * const { canEdit, canView, canManage, isReadOnly } = useCalendarPermission(calendarId);
+ *
+ * if (!canEdit) return <ReadOnlyBanner />;
+ */
+export function useCalendarPermission(
+ calendarOrId?: CalendarWithCount | string | null
+) {
+ const { user, isGuest } = useAuth();
+ const { calendars } = useCalendars();
+ const { auth } = usePublicConfig();
+
+ // Resolve calendar object if string ID was provided
+ const calendar = useMemo(() => {
+ if (!calendarOrId) return null;
+ if (typeof calendarOrId === "string") {
+ return calendars.find((cal) => cal.id === calendarOrId) || null;
+ }
+ return calendarOrId;
+ }, [calendarOrId, calendars]);
+
+ const permission = useMemo(() => {
+ if (!calendar) {
+ return {
+ level: "none" as const,
+ canView: false,
+ canEdit: false,
+ canManage: false,
+ canDelete: false,
+ canShare: false,
+ isReadOnly: true,
+ isOwner: false,
+ };
+ }
+
+ // If auth is disabled, grant full owner access (backwards compatibility)
+ if (!auth.enabled) {
+ return {
+ level: "owner" as const,
+ canView: true,
+ canEdit: true,
+ canManage: true,
+ canDelete: true,
+ canShare: true,
+ isReadOnly: false,
+ isOwner: true,
+ };
+ }
+
+ // If user is authenticated
+ if (user) {
+ // User is owner
+ if (calendar.ownerId === user.id) {
+ return {
+ level: "owner" as const,
+ canView: true,
+ canEdit: true,
+ canManage: true,
+ canDelete: true,
+ canShare: true,
+ isReadOnly: false,
+ isOwner: true,
+ };
+ }
+
+ // Check if user has explicit share permission
+ const sharePermission = (calendar as { sharePermission?: string })
+ .sharePermission;
+ if (sharePermission) {
+ const isOwner = sharePermission === "owner";
+ const isAdmin = sharePermission === "admin";
+ const isWrite = sharePermission === "write";
+ const isRead = sharePermission === "read";
+
+ return {
+ level: sharePermission,
+ canView: true,
+ canEdit: isOwner || isAdmin || isWrite,
+ canManage: isOwner || isAdmin,
+ canDelete: isOwner,
+ canShare: isOwner || isAdmin,
+ isReadOnly: isRead,
+ isOwner: isOwner,
+ };
+ }
+
+ // Check if user has token-based access
+ const tokenPermission = (
+ calendar as { tokenPermission?: "read" | "write" }
+ ).tokenPermission;
+ if (tokenPermission) {
+ return {
+ level: tokenPermission,
+ canView: true,
+ canEdit: tokenPermission === "write",
+ canManage: false,
+ canDelete: false,
+ canShare: false,
+ isReadOnly: tokenPermission === "read",
+ isOwner: false,
+ };
+ }
+
+ // Check if calendar is public (guest permission) and user is subscribed
+ // In this case, user gets the guest permission level
+ const isSubscribed = (calendar as { isSubscribed?: boolean })
+ .isSubscribed;
+ if (isSubscribed && calendar.guestPermission !== "none") {
+ const guestPerm = calendar.guestPermission as CalendarPermission;
+ return {
+ level: guestPerm,
+ canView: true,
+ canEdit: guestPerm === "write",
+ canManage: false,
+ canDelete: false,
+ canShare: false,
+ isReadOnly: guestPerm === "read",
+ isOwner: false,
+ };
+ }
+
+ // User has no access to this calendar
+ return {
+ level: "none" as const,
+ canView: false,
+ canEdit: false,
+ canManage: false,
+ canDelete: false,
+ canShare: false,
+ isReadOnly: true,
+ isOwner: false,
+ };
+ }
+
+ // If user is guest (not authenticated)
+ if (isGuest) {
+ // Check for token-based access first (higher priority)
+ const tokenPermission = (
+ calendar as { tokenPermission?: "read" | "write" }
+ ).tokenPermission;
+ if (tokenPermission) {
+ return {
+ level: tokenPermission,
+ canView: true,
+ canEdit: tokenPermission === "write",
+ canManage: false,
+ canDelete: false,
+ canShare: false,
+ isReadOnly: tokenPermission === "read",
+ isOwner: false,
+ };
+ }
+
+ // Then check guest permission
+ const guestPerm = calendar.guestPermission || "none";
+
+ if (guestPerm === "write") {
+ return {
+ level: "write" as const,
+ canView: true,
+ canEdit: true,
+ canManage: false,
+ canDelete: false,
+ canShare: false,
+ isReadOnly: false,
+ isOwner: false,
+ };
+ }
+
+ if (guestPerm === "read") {
+ return {
+ level: "read" as const,
+ canView: true,
+ canEdit: false,
+ canManage: false,
+ canDelete: false,
+ canShare: false,
+ isReadOnly: true,
+ isOwner: false,
+ };
+ }
+
+ // guestPerm === "none"
+ return {
+ level: "none" as const,
+ canView: false,
+ canEdit: false,
+ canManage: false,
+ canDelete: false,
+ canShare: false,
+ isReadOnly: true,
+ isOwner: false,
+ };
+ }
+
+ // No user, no guest access
+ return {
+ level: "none" as const,
+ canView: false,
+ canEdit: false,
+ canManage: false,
+ canDelete: false,
+ canShare: false,
+ isReadOnly: true,
+ isOwner: false,
+ };
+ }, [calendar, user, isGuest, auth.enabled]);
+
+ return permission;
+}
diff --git a/hooks/useCalendarShares.ts b/hooks/useCalendarShares.ts
new file mode 100644
index 0000000..1d85804
--- /dev/null
+++ b/hooks/useCalendarShares.ts
@@ -0,0 +1,188 @@
+import { useState, useCallback } from "react";
+import { toast } from "sonner";
+import { useTranslations } from "next-intl";
+
+export interface CalendarShare {
+ id: string;
+ calendarId: string;
+ userId: string;
+ permission: "owner" | "admin" | "write" | "read";
+ sharedBy: string;
+ createdAt: Date;
+ user: {
+ id: string;
+ name: string | null;
+ email: string;
+ image: string | null;
+ };
+ sharedByUser: {
+ id: string;
+ name: string | null;
+ email: string;
+ };
+}
+
+export interface SearchUser {
+ id: string;
+ name: string | null;
+ email: string;
+ image: string | null;
+}
+
+export function useCalendarShares(calendarId: string) {
+ const t = useTranslations();
+ const [shares, setShares] = useState<CalendarShare[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [searchResults, setSearchResults] = useState<SearchUser[]>([]);
+ const [searchLoading, setSearchLoading] = useState(false);
+
+ const fetchShares = useCallback(async () => {
+ if (!calendarId) return;
+
+ setLoading(true);
+ try {
+ const response = await fetch(`/api/calendars/${calendarId}/shares`);
+ if (!response.ok) {
+ throw new Error("Failed to fetch shares");
+ }
+ const data = await response.json();
+ setShares(data);
+ } catch (error) {
+ console.error("Failed to fetch shares:", error);
+ toast.error(t("common.fetchError", { item: t("common.labels.shares") }));
+ } finally {
+ setLoading(false);
+ }
+ }, [calendarId, t]);
+
+ const addShare = useCallback(
+ async (userId: string, permission: "admin" | "write" | "read") => {
+ try {
+ const response = await fetch(`/api/calendars/${calendarId}/shares`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ userId, permission }),
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || "Failed to add share");
+ }
+
+ const newShare = await response.json();
+ setShares((prev) => [newShare, ...prev]);
+ toast.success(t("share.shareAdded"));
+ return { success: true };
+ } catch (error) {
+ console.error("Failed to add share:", error);
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t("common.createError", { item: t("share.share") })
+ );
+ return { success: false };
+ }
+ },
+ [calendarId, t]
+ );
+
+ const updateShare = useCallback(
+ async (shareId: string, permission: "admin" | "write" | "read") => {
+ try {
+ const response = await fetch(
+ `/api/calendars/${calendarId}/shares/${shareId}`,
+ {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ permission }),
+ }
+ );
+
+ if (!response.ok) {
+ throw new Error("Failed to update share");
+ }
+
+ const updatedShare = await response.json();
+ setShares((prev) =>
+ prev.map((s) => (s.id === shareId ? updatedShare : s))
+ );
+ toast.success(t("share.shareUpdated"));
+ return { success: true };
+ } catch (error) {
+ console.error("Failed to update share:", error);
+ toast.error(t("common.updateError", { item: t("share.share") }));
+ return { success: false };
+ }
+ },
+ [calendarId, t]
+ );
+
+ const removeShare = useCallback(
+ async (shareId: string) => {
+ try {
+ const response = await fetch(
+ `/api/calendars/${calendarId}/shares/${shareId}`,
+ {
+ method: "DELETE",
+ }
+ );
+
+ if (!response.ok) {
+ throw new Error("Failed to remove share");
+ }
+
+ setShares((prev) => prev.filter((s) => s.id !== shareId));
+ toast.success(t("share.shareRemoved"));
+ return { success: true };
+ } catch (error) {
+ console.error("Failed to remove share:", error);
+ toast.error(t("common.deleteError", { item: t("share.share") }));
+ return { success: false };
+ }
+ },
+ [calendarId, t]
+ );
+
+ const searchUsers = useCallback(
+ async (query: string) => {
+ if (!query || query.length < 2) {
+ setSearchResults([]);
+ return;
+ }
+
+ setSearchLoading(true);
+ try {
+ const response = await fetch(
+ `/api/users/search?q=${encodeURIComponent(
+ query
+ )}&calendarId=${calendarId}`
+ );
+
+ if (!response.ok) {
+ throw new Error("Failed to search users");
+ }
+
+ const data = await response.json();
+ setSearchResults(data);
+ } catch (error) {
+ console.error("Failed to search users:", error);
+ toast.error(t("common.fetchError", { item: t("common.labels.users") }));
+ } finally {
+ setSearchLoading(false);
+ }
+ },
+ [calendarId, t]
+ );
+
+ return {
+ shares,
+ loading,
+ searchResults,
+ searchLoading,
+ fetchShares,
+ addShare,
+ updateShare,
+ removeShare,
+ searchUsers,
+ };
+}
diff --git a/hooks/useCalendarSubscriptions.ts b/hooks/useCalendarSubscriptions.ts
new file mode 100644
index 0000000..66dbfa4
--- /dev/null
+++ b/hooks/useCalendarSubscriptions.ts
@@ -0,0 +1,232 @@
+"use client";
+
+import { useState, useEffect, useCallback } from "react";
+import { toast } from "sonner";
+import { useTranslations } from "next-intl";
+
+type CalendarSource = "guest" | "shared";
+
+export type AvailableCalendar = {
+ id: string;
+ name: string;
+ color: string;
+ guestPermission: string;
+ permission?: string; // For shared calendars: actual share permission (owner/admin/write/read)
+ owner: {
+ id: string;
+ name: string;
+ } | null;
+ isSubscribed: boolean;
+ source: CalendarSource;
+};
+
+export type DismissedCalendar = {
+ id: string;
+ name: string;
+ color: string;
+ permission: string;
+ owner: {
+ id: string;
+ name: string;
+ } | null;
+ source: CalendarSource;
+};
+
+type SubscriptionResponse = {
+ available: AvailableCalendar[];
+ dismissed: DismissedCalendar[];
+};
+
+/**
+ * Hook for managing calendar subscriptions and dismissals
+ */
+export function useCalendarSubscriptions() {
+ const t = useTranslations();
+ const [availableCalendars, setAvailableCalendars] = useState<
+ AvailableCalendar[]
+ >([]);
+ const [dismissedCalendars, setDismissedCalendars] = useState<
+ DismissedCalendar[]
+ >([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+
+ const fetchCalendars = useCallback(async () => {
+ setLoading(true);
+ setError(null);
+
+ try {
+ const response = await fetch("/api/calendars/subscriptions");
+
+ if (!response.ok) {
+ throw new Error("Failed to fetch calendars");
+ }
+
+ const data: SubscriptionResponse = await response.json();
+ setAvailableCalendars(data.available);
+ setDismissedCalendars(data.dismissed);
+ } catch (err) {
+ const message =
+ err instanceof Error ? err.message : "Failed to load calendars";
+ setError(message);
+ toast.error(message);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ fetchCalendars();
+ }, [fetchCalendars]);
+
+ /**
+ * Subscribe to a public calendar or re-subscribe to a dismissed calendar
+ */
+ const subscribe = useCallback(
+ async (calendarId: string, calendarName: string) => {
+ // Find calendar in either list
+ const dismissedCal = dismissedCalendars.find(
+ (cal) => cal.id === calendarId
+ );
+ const availableCal = availableCalendars.find(
+ (cal) => cal.id === calendarId
+ );
+
+ // Optimistic update: Remove from dismissed and add/update in available
+ if (dismissedCal) {
+ setDismissedCalendars((prev) =>
+ prev.filter((cal) => cal.id !== calendarId)
+ );
+ setAvailableCalendars((prev) => [
+ ...prev,
+ {
+ id: dismissedCal.id,
+ name: dismissedCal.name,
+ color: dismissedCal.color,
+ guestPermission: dismissedCal.permission,
+ permission: dismissedCal.permission, // Preserve original permission
+ owner: dismissedCal.owner,
+ source: dismissedCal.source,
+ isSubscribed: true,
+ },
+ ]);
+ } else if (availableCal) {
+ setAvailableCalendars((prev) =>
+ prev.map((cal) =>
+ cal.id === calendarId ? { ...cal, isSubscribed: true } : cal
+ )
+ );
+ }
+
+ try {
+ const response = await fetch("/api/calendars/subscriptions", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ calendarId }),
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || "Failed to subscribe");
+ }
+
+ toast.success(
+ t("calendar.subscriptionSuccess", { name: calendarName })
+ );
+
+ // Dispatch custom event to trigger calendar list refresh
+ window.dispatchEvent(
+ new CustomEvent("calendar-list-change", {
+ detail: { action: "subscribe", calendarId },
+ })
+ );
+
+ return true;
+ } catch (err) {
+ const message =
+ err instanceof Error ? err.message : "Failed to subscribe";
+ toast.error(message);
+
+ // Revert optimistic update
+ await fetchCalendars();
+ return false;
+ }
+ },
+ [t, fetchCalendars, dismissedCalendars, availableCalendars]
+ );
+
+ /**
+ * Dismiss/Unsubscribe from a calendar
+ */
+ const dismiss = useCallback(
+ async (calendarId: string, calendarName: string) => {
+ // Find calendar in available list
+ const calendar = availableCalendars.find((cal) => cal.id === calendarId);
+
+ if (!calendar) return false;
+
+ // Optimistic update: Remove from available and add to dismissed
+ setAvailableCalendars((prev) =>
+ prev.filter((cal) => cal.id !== calendarId)
+ );
+
+ setDismissedCalendars((prev) => [
+ ...prev,
+ {
+ id: calendar.id,
+ name: calendar.name,
+ color: calendar.color,
+ permission: calendar.permission || calendar.guestPermission, // Use share permission if available, fallback to guest
+ owner: calendar.owner,
+ source: calendar.source,
+ },
+ ]);
+
+ try {
+ const response = await fetch(
+ `/api/calendars/subscriptions/${calendarId}`,
+ {
+ method: "DELETE",
+ }
+ );
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || "Failed to unsubscribe");
+ }
+
+ toast.success(t("calendar.unsubscribeSuccess", { name: calendarName }));
+
+ // Dispatch custom event to trigger calendar list refresh
+ window.dispatchEvent(
+ new CustomEvent("calendar-list-change", {
+ detail: { action: "dismiss", calendarId },
+ })
+ );
+
+ return true;
+ } catch (err) {
+ const message =
+ err instanceof Error ? err.message : "Failed to unsubscribe";
+ toast.error(message);
+
+ // Revert optimistic update
+ await fetchCalendars();
+ return false;
+ }
+ },
+ [t, fetchCalendars, availableCalendars]
+ );
+
+ return {
+ availableCalendars,
+ dismissedCalendars,
+ loading,
+ error,
+ subscribe,
+ dismiss,
+ refetch: fetchCalendars,
+ };
+}
diff --git a/hooks/useCalendarTokens.ts b/hooks/useCalendarTokens.ts
new file mode 100644
index 0000000..e9ee211
--- /dev/null
+++ b/hooks/useCalendarTokens.ts
@@ -0,0 +1,229 @@
+import { useState, useCallback } from "react";
+import { toast } from "sonner";
+import { useTranslations } from "next-intl";
+
+export interface CalendarAccessToken {
+ id: string;
+ tokenPreview: string; // First 6 chars (e.g., "abcxyz")
+ token?: string; // Full token only provided on creation
+ name: string | null;
+ permission: "read" | "write";
+ expiresAt: string | null;
+ createdBy: string;
+ createdAt: string;
+ lastUsedAt: string | null;
+ usageCount: number;
+ isActive: boolean;
+}
+
+export interface CreateTokenParams {
+ name?: string;
+ permission: "read" | "write";
+ expiresAt?: string | null;
+}
+
+export interface UpdateTokenParams {
+ name?: string;
+ permission?: "read" | "write";
+ expiresAt?: string | null;
+ isActive?: boolean;
+}
+
+export function useCalendarTokens(calendarId: string | null) {
+ const [tokens, setTokens] = useState<CalendarAccessToken[]>([]);
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const t = useTranslations();
+
+ /**
+ * Fetch all tokens for calendar
+ */
+ const fetchTokens = useCallback(async () => {
+ if (!calendarId) {
+ setTokens([]);
+ return;
+ }
+
+ setIsLoading(true);
+ setError(null);
+
+ try {
+ const response = await fetch(`/api/calendars/${calendarId}/tokens`);
+
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}`);
+ }
+
+ const data = await response.json();
+ setTokens(data);
+ } catch {
+ const message = t("common.fetchError", { item: t("token.accessLinks") });
+ setError(message);
+ toast.error(message);
+ } finally {
+ setIsLoading(false);
+ }
+ }, [calendarId, t]);
+
+ /**
+ * Create a new access token
+ * Returns full token (only time it's visible!)
+ */
+ const createToken = useCallback(
+ async (params: CreateTokenParams): Promise<CalendarAccessToken | null> => {
+ if (!calendarId) return null;
+
+ try {
+ const response = await fetch(`/api/calendars/${calendarId}/tokens`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(params),
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || `HTTP ${response.status}`);
+ }
+
+ const newToken = await response.json();
+
+ // Add to local state
+ setTokens((prev) => [newToken, ...prev]);
+
+ toast.success(t("common.created", { item: t("token.accessLinks") }));
+
+ return newToken; // Includes full token!
+ } catch (err) {
+ toast.error(
+ err instanceof Error
+ ? err.message
+ : t("common.createError", { item: t("token.accessLinks") })
+ );
+ return null;
+ }
+ },
+ [calendarId, t]
+ );
+
+ /**
+ * Update an existing token
+ */
+ const updateToken = useCallback(
+ async (tokenId: string, updates: UpdateTokenParams): Promise<boolean> => {
+ if (!calendarId) return false;
+
+ try {
+ const response = await fetch(
+ `/api/calendars/${calendarId}/tokens/${tokenId}`,
+ {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(updates),
+ }
+ );
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || `HTTP ${response.status}`);
+ }
+
+ const updatedToken = await response.json();
+
+ // Update local state
+ setTokens((prev) =>
+ prev.map((token) => (token.id === tokenId ? updatedToken : token))
+ );
+
+ toast.success(t("common.updated", { item: t("token.accessLinks") }));
+
+ return true;
+ } catch (err) {
+ toast.error(
+ err instanceof Error
+ ? err.message
+ : t("common.updateError", { item: t("token.accessLinks") })
+ );
+ return false;
+ }
+ },
+ [calendarId, t]
+ );
+
+ /**
+ * Delete (revoke) a token
+ */
+ const deleteToken = useCallback(
+ async (tokenId: string): Promise<boolean> => {
+ if (!calendarId) return false;
+
+ try {
+ const response = await fetch(
+ `/api/calendars/${calendarId}/tokens/${tokenId}`,
+ {
+ method: "DELETE",
+ }
+ );
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || `HTTP ${response.status}`);
+ }
+
+ // Remove from local state
+ setTokens((prev) => prev.filter((token) => token.id !== tokenId));
+
+ toast.success(t("common.revoked", { item: t("token.accessLinks") }));
+
+ return true;
+ } catch (err) {
+ toast.error(
+ err instanceof Error
+ ? err.message
+ : t("common.revokeError", { item: t("token.accessLinks") })
+ );
+ return false;
+ }
+ },
+ [calendarId, t]
+ );
+
+ /**
+ * Generate a shareable link from token
+ */
+ const getShareLink = useCallback((token: string): string => {
+ const baseUrl = window.location.origin;
+ return `${baseUrl}/share/token/${token}`;
+ }, []);
+
+ /**
+ * Copy share link to clipboard
+ */
+ const copyShareLink = useCallback(
+ async (token: string): Promise<boolean> => {
+ try {
+ const link = getShareLink(token);
+ await navigator.clipboard.writeText(link);
+
+ toast.success(t("common.copied", { item: t("share.share") }));
+
+ return true;
+ } catch {
+ toast.error(t("common.copyError", { item: t("share.share") }));
+ return false;
+ }
+ },
+ [getShareLink, t]
+ );
+
+ return {
+ tokens,
+ isLoading,
+ error,
+ fetchTokens,
+ createToken,
+ updateToken,
+ deleteToken,
+ getShareLink,
+ copyShareLink,
+ };
+}
diff --git a/hooks/useCalendars.ts b/hooks/useCalendars.ts
index 98bfdb4..a9f6f87 100644
--- a/hooks/useCalendars.ts
+++ b/hooks/useCalendars.ts
@@ -2,7 +2,10 @@ import { useState, useEffect, useCallback, useRef } from "react";
import { CalendarWithCount } from "@/lib/types";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
-import { removeCachedPassword, setCachedPassword } from "@/lib/password-cache";
+import {
+ isRateLimitError,
+ handleRateLimitError,
+} from "@/lib/rate-limit-client";
export function useCalendars(initialCalendarId?: string | null) {
const t = useTranslations();
@@ -11,6 +14,7 @@ export function useCalendars(initialCalendarId?: string | null) {
string | undefined
>();
const [loading, setLoading] = useState(true);
+ const [hasLoadedOnce, setHasLoadedOnce] = useState(false);
// Capture initialCalendarId on mount to prevent dependency changes
const initialCalendarIdRef = useRef(initialCalendarId);
@@ -19,43 +23,43 @@ export function useCalendars(initialCalendarId?: string | null) {
try {
const response = await fetch("/api/calendars");
const data = await response.json();
- setCalendars(data);
+
+ // Ensure data is an array
+ const calendarsData = Array.isArray(data) ? data : [];
+ setCalendars(calendarsData);
+ setHasLoadedOnce(true);
// Only auto-select on initial load
setSelectedCalendar((current) => {
// If a calendar is already selected and still exists, keep it
if (
current &&
- data.some((cal: CalendarWithCount) => cal.id === current)
+ calendarsData.some((cal: CalendarWithCount) => cal.id === current)
) {
return current;
}
// Otherwise, try initialCalendarId or fallback to first calendar
if (
initialCalendarIdRef.current &&
- data.some(
+ calendarsData.some(
(cal: CalendarWithCount) => cal.id === initialCalendarIdRef.current
)
) {
return initialCalendarIdRef.current;
- } else if (data.length > 0) {
- return data[0].id;
+ } else if (calendarsData.length > 0) {
+ return calendarsData[0].id;
}
return undefined;
});
} catch (error) {
console.error("Failed to fetch calendars:", error);
+ setCalendars([]);
} finally {
setLoading(false);
}
}, []);
- const createCalendar = async (
- name: string,
- color: string,
- password?: string,
- isLocked?: boolean
- ) => {
+ const createCalendar = async (name: string, color: string) => {
try {
const response = await fetch("/api/calendars", {
method: "POST",
@@ -63,11 +67,15 @@ export function useCalendars(initialCalendarId?: string | null) {
body: JSON.stringify({
name,
color,
- password,
- isLocked: isLocked || false,
+ guestPermission: "none", // Always default to "none" on creation
}),
});
+ if (isRateLimitError(response)) {
+ await handleRateLimitError(response, t);
+ return;
+ }
+
if (!response.ok) {
const errorText = await response.text();
console.error(
@@ -82,11 +90,6 @@ export function useCalendars(initialCalendarId?: string | null) {
setCalendars((prev) => [...prev, newCalendar]);
setSelectedCalendar(newCalendar.id);
- // Cache the password if one was provided
- if (password) {
- setCachedPassword(newCalendar.id, password);
- }
-
toast.success(t("common.created", { item: t("calendar.title") }));
} catch (error) {
console.error("Failed to create calendar:", error);
@@ -99,9 +102,7 @@ export function useCalendars(initialCalendarId?: string | null) {
updates: {
name?: string;
color?: string;
- currentPassword?: string;
- isLocked: boolean;
- password?: string | null;
+ guestPermission?: "none" | "read" | "write";
}
) => {
try {
@@ -111,11 +112,6 @@ export function useCalendars(initialCalendarId?: string | null) {
body: JSON.stringify(updates),
});
- if (response.status === 401) {
- toast.error(t("validation.passwordIncorrect"));
- return { success: false, error: "unauthorized" as const };
- }
-
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
const errorMessage =
@@ -132,15 +128,6 @@ export function useCalendars(initialCalendarId?: string | null) {
prev.map((cal) => (cal.id === calendarId ? updatedCalendar : cal))
);
- // Handle password caching
- if (updates.password === null) {
- removeCachedPassword(calendarId);
- } else if (updates.password) {
- setCachedPassword(calendarId, updates.password);
- } else if (updates.currentPassword) {
- setCachedPassword(calendarId, updates.currentPassword);
- }
-
toast.success(t("common.updated", { item: t("calendar.title") }));
return { success: true };
} catch (error) {
@@ -154,21 +141,15 @@ export function useCalendars(initialCalendarId?: string | null) {
}
};
- const deleteCalendar = async (calendarId: string, password?: string) => {
+ const deleteCalendar = async (calendarId: string) => {
try {
const response = await fetch(`/api/calendars/${calendarId}`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
- body: JSON.stringify({ password }),
});
- if (response.status === 401) {
- toast.error(t("validation.passwordIncorrect"));
- return false;
- }
-
if (response.ok) {
setCalendars((prev) => {
const remainingCalendars = prev.filter((c) => c.id !== calendarId);
@@ -183,7 +164,6 @@ export function useCalendars(initialCalendarId?: string | null) {
return remainingCalendars;
});
- removeCachedPassword(calendarId);
toast.success(t("common.deleted", { item: t("calendar.title") }));
return true;
@@ -208,11 +188,49 @@ export function useCalendars(initialCalendarId?: string | null) {
fetchCalendars();
}, [fetchCalendars]);
+ // Listen for calendar subscription changes (SSE events + custom events)
+ useEffect(() => {
+ const handleCalendarChange = (event: Event) => {
+ const customEvent = event as CustomEvent;
+ const { type, action } = customEvent.detail || {};
+
+ // Refetch calendars when subscriptions change
+ if (type === "calendar" && (action === "update" || action === "delete")) {
+ fetchCalendars();
+ }
+ };
+
+ const handleCalendarListChange = () => {
+ // Triggered by calendar subscription/dismissal actions
+ fetchCalendars();
+ };
+
+ // Listen to SSE calendar-change events
+ window.addEventListener("calendar-change" as never, handleCalendarChange);
+ // Listen to direct calendar list changes (subscriptions/dismissals)
+ window.addEventListener(
+ "calendar-list-change" as never,
+ handleCalendarListChange
+ );
+
+ return () => {
+ window.removeEventListener(
+ "calendar-change" as never,
+ handleCalendarChange
+ );
+ window.removeEventListener(
+ "calendar-list-change" as never,
+ handleCalendarListChange
+ );
+ };
+ }, [fetchCalendars]);
+
return {
calendars,
selectedCalendar,
setSelectedCalendar,
loading,
+ hasLoadedOnce,
createCalendar,
updateCalendar,
deleteCalendar,
diff --git a/hooks/useConnectedAccounts.ts b/hooks/useConnectedAccounts.ts
new file mode 100644
index 0000000..bf44f1b
--- /dev/null
+++ b/hooks/useConnectedAccounts.ts
@@ -0,0 +1,76 @@
+"use client";
+
+import { useState, useEffect } from "react";
+import { authClient } from "@/lib/auth/client";
+
+type ConnectedAccount = {
+ id: string;
+ provider: string;
+ accountId: string;
+ createdAt: Date | null;
+};
+
+/**
+ * Hook to manage user's connected OAuth/OIDC accounts
+ *
+ * Uses Better Auth's built-in listAccounts method
+ *
+ * Features:
+ * - Fetch connected accounts
+ * - Disconnect account
+ * - Auto-refresh on mount
+ */
+export function useConnectedAccounts() {
+ const [accounts, setAccounts] = useState<ConnectedAccount[]>([]);
+ const [isLoading, setIsLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+
+ const fetchAccounts = async () => {
+ try {
+ setIsLoading(true);
+ setError(null);
+
+ const { data, error: fetchError } = await authClient.listAccounts();
+
+ if (fetchError) {
+ throw new Error(fetchError.message || "Failed to fetch accounts");
+ }
+
+ // Format accounts for component
+ const formattedAccounts = (data || []).map(
+ (account: {
+ id: string;
+ providerId: string;
+ accountId: string;
+ createdAt: Date;
+ updatedAt: Date;
+ userId: string;
+ scopes: string[];
+ }) => ({
+ id: account.id,
+ provider: account.providerId,
+ accountId: account.accountId,
+ createdAt: account.createdAt ? new Date(account.createdAt) : null,
+ })
+ );
+
+ setAccounts(formattedAccounts);
+ } catch (err) {
+ console.error("Error fetching connected accounts:", err);
+ setError(err instanceof Error ? err.message : "Unknown error");
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ useEffect(() => {
+ fetchAccounts();
+ }, []);
+
+ return {
+ accounts,
+ isLoading,
+ error,
+ refetch: fetchAccounts,
+ };
+}
diff --git a/hooks/useDialogStates.ts b/hooks/useDialogStates.ts
index 8541e4c..a6ee31d 100644
--- a/hooks/useDialogStates.ts
+++ b/hooks/useDialogStates.ts
@@ -5,7 +5,6 @@ import { CalendarNote } from "@/lib/db/schema";
export function useDialogStates() {
const [showCalendarDialog, setShowCalendarDialog] = useState(false);
const [showShiftDialog, setShowShiftDialog] = useState(false);
- const [showPasswordDialog, setShowPasswordDialog] = useState(false);
const [showCalendarSettingsDialog, setShowCalendarSettingsDialog] =
useState(false);
const [showMobileCalendarDialog, setShowMobileCalendarDialog] =
@@ -32,8 +31,6 @@ export function useDialogStates() {
setShowCalendarDialog,
showShiftDialog,
setShowShiftDialog,
- showPasswordDialog,
- setShowPasswordDialog,
showCalendarSettingsDialog,
setShowCalendarSettingsDialog,
showMobileCalendarDialog,
diff --git a/hooks/useExternalSync.ts b/hooks/useExternalSync.ts
index 223529c..826930f 100644
--- a/hooks/useExternalSync.ts
+++ b/hooks/useExternalSync.ts
@@ -1,6 +1,5 @@
import { useState, useEffect, useCallback } from "react";
import { ExternalSync, SyncLog } from "@/lib/db/schema";
-import { getCachedPassword } from "@/lib/password-cache";
export function useExternalSync(selectedCalendar: string | null) {
const [externalSyncs, setExternalSyncs] = useState<ExternalSync[]>([]);
@@ -15,11 +14,7 @@ export function useExternalSync(selectedCalendar: string | null) {
}
try {
- const password = getCachedPassword(selectedCalendar);
const params = new URLSearchParams({ calendarId: selectedCalendar });
- if (password) {
- params.append("password", password);
- }
const response = await fetch(`/api/external-syncs?${params}`);
if (response.ok) {
@@ -38,14 +33,10 @@ export function useExternalSync(selectedCalendar: string | null) {
}
try {
- const password = getCachedPassword(selectedCalendar);
const params = new URLSearchParams({
calendarId: selectedCalendar,
limit: "50",
});
- if (password) {
- params.append("password", password);
- }
const response = await fetch(`/api/sync-logs?${params}`);
if (response.ok) {
diff --git a/hooks/useNoteActions.ts b/hooks/useNoteActions.ts
index 9e7af50..78851de 100644
--- a/hooks/useNoteActions.ts
+++ b/hooks/useNoteActions.ts
@@ -5,7 +5,6 @@ interface UseNoteActionsProps {
createNote: (
text: string,
date: Date,
- onPasswordRequired: () => void,
type?: "note" | "event",
color?: string,
recurringPattern?: string,
@@ -14,21 +13,18 @@ interface UseNoteActionsProps {
updateNote: (
id: string,
text: string,
- onPasswordRequired: () => void,
type?: "note" | "event",
color?: string,
recurringPattern?: string,
recurringInterval?: number
) => Promise<boolean>;
- deleteNote: (id: string, onPasswordRequired: () => void) => Promise<boolean>;
- onPasswordRequired: (action: () => Promise<void>) => void;
+ deleteNote: (id: string) => Promise<boolean>;
}
export function useNoteActions({
createNote,
updateNote,
deleteNote,
- onPasswordRequired,
}: UseNoteActionsProps) {
const [selectedNote, setSelectedNote] = useState<CalendarNote | undefined>();
const [selectedDate, setSelectedDate] = useState<Date | undefined>();
@@ -42,37 +38,10 @@ export function useNoteActions({
recurringPattern?: string,
recurringInterval?: number
) => {
- const handlePasswordRequired = () => {
- onPasswordRequired(async () => {
- if (selectedNote) {
- await updateNote(
- selectedNote.id,
- noteText,
- handlePasswordRequired,
- type,
- color,
- recurringPattern,
- recurringInterval
- );
- } else if (selectedDate) {
- await createNote(
- noteText,
- selectedDate,
- handlePasswordRequired,
- type,
- color,
- recurringPattern,
- recurringInterval
- );
- }
- });
- };
-
if (selectedNote) {
await updateNote(
selectedNote.id,
noteText,
- handlePasswordRequired,
type,
color,
recurringPattern,
@@ -82,7 +51,6 @@ export function useNoteActions({
await createNote(
noteText,
selectedDate,
- handlePasswordRequired,
type,
color,
recurringPattern,
@@ -90,32 +58,17 @@ export function useNoteActions({
);
}
},
- [selectedNote, selectedDate, createNote, updateNote, onPasswordRequired]
+ [selectedNote, selectedDate, createNote, updateNote]
);
const handleNoteDelete = useCallback(async () => {
if (!selectedNote) return;
- const handlePasswordRequired = () => {
- onPasswordRequired(async () => {
- if (selectedNote) {
- const success = await deleteNote(
- selectedNote.id,
- handlePasswordRequired
- );
- if (success) {
- setShowNoteDialog(false);
- setSelectedNote(undefined);
- }
- }
- });
- };
-
- const success = await deleteNote(selectedNote.id, handlePasswordRequired);
+ const success = await deleteNote(selectedNote.id);
if (success) {
setShowNoteDialog(false);
}
- }, [selectedNote, deleteNote, onPasswordRequired]);
+ }, [selectedNote, deleteNote]);
const openNoteDialog = useCallback((date: Date, note?: CalendarNote) => {
setSelectedDate(date);
diff --git a/hooks/useNotes.ts b/hooks/useNotes.ts
index 9a79f1d..423e97c 100644
--- a/hooks/useNotes.ts
+++ b/hooks/useNotes.ts
@@ -1,9 +1,8 @@
import { useState, useEffect, useCallback } from "react";
+import { useTranslations } from "next-intl";
import { CalendarNote } from "@/lib/db/schema";
import { formatDateToLocal } from "@/lib/date-utils";
import { toast } from "sonner";
-import { useTranslations } from "next-intl";
-import { getCachedPassword } from "@/lib/password-cache";
export function useNotes(calendarId: string | undefined) {
const t = useTranslations();
@@ -13,11 +12,7 @@ export function useNotes(calendarId: string | undefined) {
if (!calendarId) return;
try {
- const password = getCachedPassword(calendarId);
const params = new URLSearchParams({ calendarId });
- if (password) {
- params.append("password", password);
- }
const response = await fetch(`/api/notes?${params}`);
if (!response.ok) {
@@ -43,7 +38,6 @@ export function useNotes(calendarId: string | undefined) {
const createNote = async (
noteText: string,
date: Date,
- onPasswordRequired?: () => void,
type?: "note" | "event",
color?: string,
recurringPattern?: string,
@@ -52,8 +46,6 @@ export function useNotes(calendarId: string | undefined) {
if (!calendarId) return false;
try {
- const password = getCachedPassword(calendarId);
-
const response = await fetch("/api/notes", {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -65,15 +57,9 @@ export function useNotes(calendarId: string | undefined) {
color: color,
recurringPattern: recurringPattern,
recurringInterval: recurringInterval,
- password,
}),
});
- if (response.status === 401) {
- onPasswordRequired?.();
- return false;
- }
-
if (!response.ok) {
const errorText = await response.text();
console.error(
@@ -100,15 +86,12 @@ export function useNotes(calendarId: string | undefined) {
const updateNote = async (
noteId: string,
noteText: string,
- onPasswordRequired?: () => void,
type?: "note" | "event",
color?: string,
recurringPattern?: string,
recurringInterval?: number
) => {
try {
- const password = getCachedPassword(calendarId);
-
const response = await fetch(`/api/notes/${noteId}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
@@ -118,15 +101,9 @@ export function useNotes(calendarId: string | undefined) {
color: color,
recurringPattern: recurringPattern,
recurringInterval: recurringInterval,
- password,
}),
});
- if (response.status === 401) {
- onPasswordRequired?.();
- return false;
- }
-
if (!response.ok) {
const errorText = await response.text();
console.error(
@@ -150,26 +127,16 @@ export function useNotes(calendarId: string | undefined) {
}
};
- const deleteNote = async (
- noteId: string,
- onPasswordRequired?: () => void
- ) => {
+ const deleteNote = async (noteId: string) => {
try {
- const password = getCachedPassword(calendarId);
-
const response = await fetch(`/api/notes/${noteId}`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
- body: JSON.stringify({ password }),
+ body: JSON.stringify({}),
});
- if (response.status === 401) {
- onPasswordRequired?.();
- return false;
- }
-
if (!response.ok) {
const errorText = await response.text();
console.error(
diff --git a/hooks/usePasswordManagement.ts b/hooks/usePasswordManagement.ts
deleted file mode 100644
index 7d9a852..0000000
--- a/hooks/usePasswordManagement.ts
+++ /dev/null
@@ -1,164 +0,0 @@
-import { useState, useEffect, useMemo, useCallback } from "react";
-import {
- getCachedPassword,
- verifyAndCachePassword,
-} from "@/lib/password-cache";
-import { CalendarWithCount } from "@/lib/types";
-import { ShiftFormData } from "@/components/shift-sheet";
-
-export interface PendingAction {
- type: "delete" | "edit" | "syncNotifications";
- calendarId?: string;
- shiftId?: string;
- formData?: ShiftFormData;
- presetAction?: () => Promise<void>;
- noteAction?: () => Promise<void>;
- action?: () => Promise<void>;
-}
-
-export function usePasswordManagement(
- selectedCalendar: string | null,
- calendars: CalendarWithCount[]
-) {
- const [pendingAction, setPendingAction] = useState<PendingAction | null>(
- null
- );
- const [isCalendarUnlocked, setIsCalendarUnlocked] = useState(true);
- const [isVerifyingCalendarPassword, setIsVerifyingCalendarPassword] =
- useState(false);
- const [forceUpdate, setForceUpdate] = useState(0);
-
- const selectedCalendarData = useMemo(() => {
- return calendars.find((c) => c.id === selectedCalendar);
- }, [calendars, selectedCalendar]);
-
- const shouldHideUIElements = useMemo(() => {
- if (!selectedCalendar || !selectedCalendarData) return false;
- const requiresPassword = !!selectedCalendarData.passwordHash;
- const hasPassword = !!getCachedPassword(selectedCalendar);
- return requiresPassword && !hasPassword;
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [selectedCalendar, selectedCalendarData, forceUpdate]);
-
- const selectedCalendarIsLocked = useMemo(() => {
- if (!selectedCalendar) return false;
- const currentCalendar = calendars.find((c) => c.id === selectedCalendar);
- return currentCalendar?.isLocked ?? false;
- }, [selectedCalendar, calendars]);
-
- // Verify password when calendar changes
- useEffect(() => {
- let cancelled = false;
-
- const verifyCalendar = async () => {
- if (!selectedCalendar) {
- if (!cancelled) {
- setIsCalendarUnlocked(true);
- setIsVerifyingCalendarPassword(false);
- }
- return;
- }
-
- if (selectedCalendarIsLocked) {
- const cachedPassword = getCachedPassword(selectedCalendar);
-
- if (cachedPassword) {
- if (!cancelled) {
- setIsVerifyingCalendarPassword(true);
- setIsCalendarUnlocked(false);
- }
-
- verifyAndCachePassword(selectedCalendar, cachedPassword)
- .then((result) => {
- if (!cancelled) {
- setIsCalendarUnlocked(result.valid);
- }
- })
- .catch(() => {
- if (!cancelled) {
- setIsCalendarUnlocked(false);
- }
- })
- .finally(() => {
- if (!cancelled) {
- setIsVerifyingCalendarPassword(false);
- }
- });
- } else {
- if (!cancelled) {
- setIsCalendarUnlocked(false);
- setIsVerifyingCalendarPassword(false);
- }
- }
- } else {
- if (!cancelled) {
- setIsCalendarUnlocked(true);
- setIsVerifyingCalendarPassword(false);
- }
- }
- };
-
- verifyCalendar();
-
- return () => {
- cancelled = true;
- };
- }, [selectedCalendar, selectedCalendarIsLocked]);
-
- const handlePasswordSuccess = useCallback(() => {
- // Password is now verified and cached - trigger re-render to update shouldHideUIElements
- setIsCalendarUnlocked(true);
- setForceUpdate((prev) => prev + 1);
- }, []);
-
- const verifyPasswordForAction = useCallback(
- async (
- action: () => Promise<void>,
- actionType: "delete" | "edit" | "syncNotifications" = "edit"
- ) => {
- if (!selectedCalendar) return false;
-
- const calendar = calendars.find((c) => c.id === selectedCalendar);
- if (!calendar) return false;
-
- if (calendar.passwordHash) {
- const cachedPassword = getCachedPassword(selectedCalendar);
-
- if (cachedPassword) {
- try {
- const result = await verifyAndCachePassword(
- selectedCalendar,
- cachedPassword
- );
- if (result.valid) {
- await action();
- return true;
- }
- } catch (error) {
- console.error("Failed to verify password:", error);
- // Continue to show password dialog on error
- }
- }
-
- setPendingAction({ type: actionType, action });
- return false;
- }
-
- await action();
- return true;
- },
- [selectedCalendar, calendars]
- );
-
- return {
- pendingAction,
- setPendingAction,
- isCalendarUnlocked,
- setIsCalendarUnlocked,
- isVerifyingCalendarPassword,
- shouldHideUIElements,
- selectedCalendarData,
- handlePasswordSuccess,
- verifyPasswordForAction,
- };
-}
diff --git a/hooks/usePasswordProtection.ts b/hooks/usePasswordProtection.ts
deleted file mode 100644
index 20279bf..0000000
--- a/hooks/usePasswordProtection.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { useCallback } from "react";
-import {
- getCachedPassword,
- verifyAndCachePassword,
-} from "@/lib/password-cache";
-
-interface UsePasswordProtectionOptions {
- calendarId: string;
- onPasswordRequired: (action: () => Promise<void>) => void;
-}
-
-export function usePasswordProtection({
- calendarId,
- onPasswordRequired,
-}: UsePasswordProtectionOptions) {
- const verifyPassword = useCallback(async (): Promise<boolean> => {
- const password = getCachedPassword(calendarId);
- const result = await verifyAndCachePassword(calendarId, password);
- return result.valid;
- }, [calendarId]);
-
- const withPasswordCheck = useCallback(
- async <T>(action: () => Promise<T>): Promise<T | null> => {
- const isValid = await verifyPassword();
-
- if (!isValid) {
- await onPasswordRequired(async () => {
- await action();
- });
- return null;
- }
-
- return await action();
- },
- [verifyPassword, onPasswordRequired]
- );
-
- const getPassword = useCallback(() => {
- return getCachedPassword(calendarId);
- }, [calendarId]);
-
- return {
- verifyPassword,
- withPasswordCheck,
- getPassword,
- };
-}
diff --git a/hooks/usePresetManagement.ts b/hooks/usePresetManagement.ts
index 8c83f58..8942b33 100644
--- a/hooks/usePresetManagement.ts
+++ b/hooks/usePresetManagement.ts
@@ -1,7 +1,6 @@
import { useCallback } from "react";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
-import { getCachedPassword } from "@/lib/password-cache";
interface PresetFormData {
title: string;
@@ -28,15 +27,12 @@ export function usePresetManagement({
const createPreset = useCallback(
async (formData: PresetFormData) => {
try {
- const password = getCachedPassword(calendarId);
-
const response = await fetch("/api/presets", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
calendarId,
...formData,
- password,
}),
});
@@ -63,14 +59,11 @@ export function usePresetManagement({
const updatePreset = useCallback(
async (presetId: string, formData: PresetFormData) => {
try {
- const password = getCachedPassword(calendarId);
-
const response = await fetch(`/api/presets/${presetId}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
...formData,
- password,
}),
});
@@ -91,18 +84,16 @@ export function usePresetManagement({
return false;
}
},
- [calendarId, onSuccess, t]
+ [onSuccess, t]
);
const deletePreset = useCallback(
async (presetId: string) => {
try {
- const password = getCachedPassword(calendarId);
-
const response = await fetch(`/api/presets/${presetId}`, {
method: "DELETE",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ password }),
+ body: JSON.stringify({}),
});
if (response.ok) {
@@ -122,21 +113,18 @@ export function usePresetManagement({
return false;
}
},
- [calendarId, onSuccess, t]
+ [onSuccess, t]
);
const reorderPresets = useCallback(
async (presetOrders: Array<{ id: string; order: number }>) => {
try {
- const password = getCachedPassword(calendarId);
-
const response = await fetch("/api/presets/reorder", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
calendarId,
presetOrders,
- password,
}),
});
diff --git a/hooks/usePresets.ts b/hooks/usePresets.ts
index 4ddfcc9..e477c0a 100644
--- a/hooks/usePresets.ts
+++ b/hooks/usePresets.ts
@@ -1,10 +1,10 @@
import { useState, useEffect, useCallback } from "react";
import { ShiftPreset } from "@/lib/db/schema";
-import { getCachedPassword } from "@/lib/password-cache";
export function usePresets(calendarId: string | undefined) {
const [presets, setPresets] = useState<ShiftPreset[]>([]);
const [loading, setLoading] = useState(true);
+ const [hasLoadedOnce, setHasLoadedOnce] = useState(false);
const fetchPresets = useCallback(
async (silent = false) => {
@@ -18,21 +18,17 @@ export function usePresets(calendarId: string | undefined) {
setLoading(true);
}
try {
- const password = getCachedPassword(calendarId);
const params = new URLSearchParams({ calendarId });
- if (password) {
- params.append("password", password);
- }
const response = await fetch(`/api/presets?${params}`);
if (!response.ok) {
- // Calendar is locked and no valid password - return empty array
setPresets([]);
setLoading(false);
return;
}
const data = await response.json();
setPresets(data);
+ setHasLoadedOnce(true);
} catch (error) {
console.error("Failed to fetch presets:", error);
setPresets([]);
@@ -57,6 +53,7 @@ export function usePresets(calendarId: string | undefined) {
return {
presets,
loading,
+ hasLoadedOnce,
refetchPresets: fetchPresets,
};
}
diff --git a/hooks/usePublicConfig.ts b/hooks/usePublicConfig.ts
new file mode 100644
index 0000000..497df1c
--- /dev/null
+++ b/hooks/usePublicConfig.ts
@@ -0,0 +1,12 @@
+/**
+ * Re-export usePublicConfig hook for easier imports
+ *
+ * This allows importing directly from hooks/ directory:
+ * import { usePublicConfig } from '@/hooks/usePublicConfig'
+ *
+ * Instead of:
+ * import { usePublicConfig } from '@/components/public-config-provider'
+ */
+
+export { usePublicConfig } from "@/components/public-config-provider";
+export type { PublicConfig } from "@/lib/public-config";
diff --git a/hooks/useSSEConnection.ts b/hooks/useSSEConnection.ts
index ec57171..06c4a20 100644
--- a/hooks/useSSEConnection.ts
+++ b/hooks/useSSEConnection.ts
@@ -1,6 +1,10 @@
import { useEffect, useRef } from "react";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
+import {
+ isRateLimitError,
+ handleRateLimitError,
+} from "@/lib/rate-limit-client";
interface SSEConnectionOptions {
calendarId: string | undefined;
@@ -9,6 +13,7 @@ interface SSEConnectionOptions {
onNoteUpdate: () => void;
onStatsRefresh: () => void;
onSyncLogUpdate?: () => void;
+ onCalendarUpdate?: () => void;
isConnected: boolean;
setIsConnected: (connected: boolean) => void;
}
@@ -20,6 +25,7 @@ export function useSSEConnection({
onNoteUpdate,
onStatsRefresh,
onSyncLogUpdate,
+ onCalendarUpdate,
setIsConnected,
}: SSEConnectionOptions) {
const t = useTranslations();
@@ -42,6 +48,7 @@ export function useSSEConnection({
const noteUpdateRef = useRef(onNoteUpdate);
const statsRefreshRef = useRef(onStatsRefresh);
const syncLogUpdateRef = useRef(onSyncLogUpdate);
+ const calendarUpdateRef = useRef(onCalendarUpdate);
const setIsConnectedRef = useRef(setIsConnected);
const tRef = useRef(t);
@@ -52,6 +59,7 @@ export function useSSEConnection({
noteUpdateRef.current = onNoteUpdate;
statsRefreshRef.current = onStatsRefresh;
syncLogUpdateRef.current = onSyncLogUpdate;
+ calendarUpdateRef.current = onCalendarUpdate;
setIsConnectedRef.current = setIsConnected;
tRef.current = t;
}, [
@@ -60,6 +68,7 @@ export function useSSEConnection({
onNoteUpdate,
onStatsRefresh,
onSyncLogUpdate,
+ onCalendarUpdate,
setIsConnected,
t,
]);
@@ -78,6 +87,7 @@ export function useSSEConnection({
presetUpdateRef.current();
noteUpdateRef.current();
statsRefreshRef.current();
+ calendarUpdateRef.current?.();
lastSyncTimeRef.current = now;
disconnectTimeRef.current = null;
setTimeout(() => toast.dismiss(), 1000);
@@ -131,112 +141,159 @@ export function useSSEConnection({
eventSourceRef.current.close();
}
- const eventSource = new EventSource(
- `/api/events/stream?calendarId=${calendarId}`
- );
-
- eventSource.onopen = () => {
- setIsConnectedRef.current(true);
- toast.dismiss();
+ // Test connection first to check for rate limiting
+ const testConnection = async () => {
+ try {
+ const response = await fetch(
+ `/api/events/stream?calendarId=${calendarId}`,
+ {
+ method: "HEAD", // Just check headers, don't establish connection yet
+ }
+ );
- if (disconnectTimeRef.current) {
- const disconnectDuration = Date.now() - disconnectTimeRef.current;
- if (disconnectDuration > 10000) {
- console.log("Reconnected after long disconnect, resyncing...");
- toast.info(tRef.current("sync.resyncing"), { duration: Infinity });
- shiftUpdateRef.current();
- presetUpdateRef.current();
- noteUpdateRef.current();
- statsRefreshRef.current();
+ // Check for rate limit before establishing SSE connection
+ if (isRateLimitError(response)) {
+ await handleRateLimitError(response, t);
+ setIsConnectedRef.current(false);
+ return false;
}
- disconnectTimeRef.current = null;
+
+ return true;
+ } catch {
+ // If HEAD fails, try regular connection anyway
+ return true;
}
- lastSyncTimeRef.current = Date.now();
};
- eventSource.onmessage = (event) => {
- try {
- const data = JSON.parse(event.data);
+ testConnection().then((canConnect) => {
+ if (!canConnect) return;
- if (data.type === "connected") {
- console.log("SSE connected for calendar:", data.calendarId);
- return;
- }
+ const eventSource = new EventSource(
+ `/api/events/stream?calendarId=${calendarId}`
+ );
- if (data.type === "shift") {
- shiftUpdateRef.current();
- statsRefreshRef.current();
- } else if (data.type === "preset") {
- presetUpdateRef.current();
- } else if (data.type === "note") {
- noteUpdateRef.current();
- } else if (data.type === "sync-log") {
- syncLogUpdateRef.current?.();
- }
+ eventSource.onopen = () => {
+ setIsConnectedRef.current(true);
+ toast.dismiss();
+ if (disconnectTimeRef.current) {
+ const disconnectDuration = Date.now() - disconnectTimeRef.current;
+ if (disconnectDuration > 10000) {
+ console.log("Reconnected after long disconnect, resyncing...");
+ toast.info(tRef.current("sync.resyncing"), { duration: Infinity });
+ shiftUpdateRef.current();
+ presetUpdateRef.current();
+ noteUpdateRef.current();
+ statsRefreshRef.current();
+ }
+ disconnectTimeRef.current = null;
+ }
lastSyncTimeRef.current = Date.now();
- } catch (error) {
- console.error("Error parsing SSE message:", error);
- }
- };
+ };
- eventSource.onerror = (error) => {
- console.error("SSE connection error:", error);
- setIsConnectedRef.current(false);
- disconnectTimeRef.current = Date.now();
+ eventSource.onmessage = (event) => {
+ try {
+ const data = JSON.parse(event.data);
- // Clear any existing timeouts
- if (errorTimeoutRef.current) {
- clearTimeout(errorTimeoutRef.current);
- errorTimeoutRef.current = null;
- }
- if (resyncTimeoutRef.current) {
- clearTimeout(resyncTimeoutRef.current);
- resyncTimeoutRef.current = null;
- }
+ if (data.type === "connected") {
+ console.log("SSE connected for calendar:", data.calendarId);
+ return;
+ }
+
+ if (data.type === "shift") {
+ shiftUpdateRef.current();
+ statsRefreshRef.current();
+ } else if (data.type === "preset") {
+ presetUpdateRef.current();
+ } else if (data.type === "note") {
+ noteUpdateRef.current();
+ } else if (data.type === "calendar") {
+ calendarUpdateRef.current?.();
+ } else if (data.type === "sync-log") {
+ syncLogUpdateRef.current?.();
+ }
+
+ lastSyncTimeRef.current = Date.now();
+ } catch (error) {
+ console.error("Error parsing SSE message:", error);
+ }
+ };
+
+ eventSource.onerror = (error) => {
+ console.error("SSE connection error:", error);
+ setIsConnectedRef.current(false);
+ disconnectTimeRef.current = Date.now();
- // Show error toast after delay if offline
- errorTimeoutRef.current = setTimeout(() => {
- if (!navigator.onLine) {
- toast.error(tRef.current("sync.disconnected"), {
- duration: Infinity,
+ // Check if error is due to rate limiting
+ // EventSource doesn't provide status codes, but we can detect it by rapid reconnection failures
+ const timeSinceStart = Date.now() - lastSyncTimeRef.current;
+ if (timeSinceStart < 5000) {
+ // Connection failed within 5 seconds - likely rate limited
+ fetch(`/api/events/stream?calendarId=${calendarId}`, {
+ method: "HEAD",
+ }).then(async (response) => {
+ if (isRateLimitError(response)) {
+ await handleRateLimitError(response, t);
+ // Close the EventSource to prevent auto-reconnect
+ eventSource.close();
+ return;
+ }
});
}
- errorTimeoutRef.current = null;
- }, 5000);
- // Attempt resync after delay (EventSource will auto-reconnect)
- resyncTimeoutRef.current = setTimeout(() => {
+ // Clear any existing timeouts
if (errorTimeoutRef.current) {
clearTimeout(errorTimeoutRef.current);
errorTimeoutRef.current = null;
}
- if (calendarId && navigator.onLine) {
- console.log("Attempting to resync data...");
- shiftUpdateRef.current();
- presetUpdateRef.current();
- noteUpdateRef.current();
+ if (resyncTimeoutRef.current) {
+ clearTimeout(resyncTimeoutRef.current);
+ resyncTimeoutRef.current = null;
}
- resyncTimeoutRef.current = null;
- }, 3000);
- };
- eventSourceRef.current = eventSource;
+ // Show error toast after delay if offline
+ errorTimeoutRef.current = setTimeout(() => {
+ if (!navigator.onLine) {
+ toast.error(tRef.current("sync.disconnected"), {
+ duration: Infinity,
+ });
+ }
+ errorTimeoutRef.current = null;
+ }, 5000);
- return () => {
- // Clear all timeouts on cleanup
- if (errorTimeoutRef.current) {
- clearTimeout(errorTimeoutRef.current);
- errorTimeoutRef.current = null;
- }
- if (resyncTimeoutRef.current) {
- clearTimeout(resyncTimeoutRef.current);
- resyncTimeoutRef.current = null;
- }
- // Close EventSource on unmount or calendarId change
- eventSource.close();
- };
- }, [calendarId]);
+ // Attempt resync after delay (EventSource will auto-reconnect)
+ resyncTimeoutRef.current = setTimeout(() => {
+ if (errorTimeoutRef.current) {
+ clearTimeout(errorTimeoutRef.current);
+ errorTimeoutRef.current = null;
+ }
+ if (calendarId && navigator.onLine) {
+ console.log("Attempting to resync data...");
+ shiftUpdateRef.current();
+ presetUpdateRef.current();
+ noteUpdateRef.current();
+ }
+ resyncTimeoutRef.current = null;
+ }, 3000);
+ };
+
+ eventSourceRef.current = eventSource;
+
+ return () => {
+ // Clear all timeouts on cleanup
+ if (errorTimeoutRef.current) {
+ clearTimeout(errorTimeoutRef.current);
+ errorTimeoutRef.current = null;
+ }
+ if (resyncTimeoutRef.current) {
+ clearTimeout(resyncTimeoutRef.current);
+ resyncTimeoutRef.current = null;
+ }
+ // Close EventSource on unmount or calendarId change
+ eventSource.close();
+ };
+ }); // End of testConnection().then()
+ }, [calendarId, t]);
return {
lastSyncTimeRef,
diff --git a/hooks/useSessions.ts b/hooks/useSessions.ts
new file mode 100644
index 0000000..a48a26c
--- /dev/null
+++ b/hooks/useSessions.ts
@@ -0,0 +1,78 @@
+import { useState, useEffect, useCallback } from "react";
+import { authClient } from "@/lib/auth/client";
+
+/**
+ * Session with device information (from Better Auth listSessions)
+ */
+export interface SessionWithDevice {
+ id: string;
+ token: string;
+ userId: string;
+ expiresAt: Date;
+ ipAddress?: string | null;
+ userAgent?: string | null;
+ createdAt: Date;
+ updatedAt: Date;
+}
+
+/**
+ * Hook to manage user sessions using Better Auth client
+ */
+export function useSessions() {
+ const [sessions, setSessions] = useState<SessionWithDevice[]>([]);
+ const [isLoading, setIsLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+
+ const fetchSessions = useCallback(async () => {
+ setIsLoading(true);
+ setError(null);
+
+ try {
+ // Use Better Auth's built-in listSessions
+ const data = await authClient.listSessions();
+ setSessions(data.data || []);
+ } catch (err) {
+ console.error("Error fetching sessions:", err);
+ setError(err instanceof Error ? err.message : "Unknown error");
+ } finally {
+ setIsLoading(false);
+ }
+ }, []);
+
+ const revokeAllSessions = useCallback(async (): Promise<{
+ success: boolean;
+ error?: string;
+ revokedCount?: number;
+ }> => {
+ try {
+ // Use Better Auth's built-in revokeOtherSessions
+ await authClient.revokeOtherSessions();
+
+ // Count sessions before refresh
+ const beforeCount = sessions.length - 1; // -1 for current session
+
+ // Refresh sessions list
+ await fetchSessions();
+
+ return { success: true, revokedCount: beforeCount };
+ } catch (err) {
+ console.error("Error revoking all sessions:", err);
+ return {
+ success: false,
+ error: err instanceof Error ? err.message : "Unknown error",
+ };
+ }
+ }, [fetchSessions, sessions.length]);
+
+ useEffect(() => {
+ fetchSessions();
+ }, [fetchSessions]);
+
+ return {
+ sessions,
+ isLoading,
+ error,
+ refetch: fetchSessions,
+ revokeAllSessions,
+ };
+}
diff --git a/hooks/useShiftActions.ts b/hooks/useShiftActions.ts
index dc30026..a210d28 100644
--- a/hooks/useShiftActions.ts
+++ b/hooks/useShiftActions.ts
@@ -6,29 +6,18 @@ import { ShiftFormData } from "@/components/shift-sheet";
import { ShiftWithCalendar } from "@/lib/types";
import { ShiftPreset } from "@/lib/db/schema";
import { formatDateToLocal } from "@/lib/date-utils";
-import {
- getCachedPassword,
- verifyAndCachePassword,
-} from "@/lib/password-cache";
interface UseShiftActionsProps {
- selectedCalendar: string | null;
shifts: ShiftWithCalendar[];
setShifts: (shifts: ShiftWithCalendar[]) => void;
presets: ShiftPreset[];
createShift: (data: ShiftFormData) => Promise<ShiftWithCalendar | null>;
- updateShift: (
- id: string,
- data: ShiftFormData,
- onPasswordRequired: () => void
- ) => Promise<boolean>;
- deleteShift: (id: string, onPasswordRequired: () => void) => Promise<boolean>;
+ updateShift: (id: string, data: ShiftFormData) => Promise<boolean>;
+ deleteShift: (id: string) => Promise<boolean>;
onStatsRefresh: () => void;
- onPasswordRequired: (action: () => Promise<void>) => void;
}
export function useShiftActions({
- selectedCalendar,
shifts,
setShifts,
presets,
@@ -36,7 +25,6 @@ export function useShiftActions({
updateShift,
deleteShift,
onStatsRefresh,
- onPasswordRequired,
}: UseShiftActionsProps) {
const t = useTranslations();
const [togglingDates, setTogglingDates] = useState<Set<string>>(new Set());
@@ -63,30 +51,22 @@ export function useShiftActions({
const handleUpdateShift = useCallback(
async (id: string, formData: ShiftFormData) => {
- const success = await updateShift(id, formData, () => {
- onPasswordRequired(async () => {
- await updateShift(id, formData, () => {});
- });
- });
+ const success = await updateShift(id, formData);
if (success) {
onStatsRefresh();
}
},
- [updateShift, onStatsRefresh, onPasswordRequired]
+ [updateShift, onStatsRefresh]
);
const handleDeleteShift = useCallback(
async (id: string) => {
- const success = await deleteShift(id, () => {
- onPasswordRequired(async () => {
- await deleteShift(id, () => {});
- });
- });
+ const success = await deleteShift(id);
if (success) {
onStatsRefresh();
}
},
- [deleteShift, onStatsRefresh, onPasswordRequired]
+ [deleteShift, onStatsRefresh]
);
const handleAddShift = useCallback(
@@ -104,29 +84,6 @@ export function useShiftActions({
setTogglingDates((prev) => new Set(prev).add(dateKey));
try {
- const password = selectedCalendar
- ? getCachedPassword(selectedCalendar)
- : null;
-
- if (selectedCalendar) {
- const result = await verifyAndCachePassword(
- selectedCalendar,
- password
- );
-
- if (result.protected && !result.valid) {
- onPasswordRequired(() =>
- handleAddShift(targetDate, selectedPresetId)
- );
- setTogglingDates((prev) => {
- const next = new Set(prev);
- next.delete(dateKey);
- return next;
- });
- return;
- }
- }
-
const existingShift = shifts.find(
(shift) =>
shift.date &&
@@ -147,7 +104,7 @@ export function useShiftActions({
headers: {
"Content-Type": "application/json",
},
- body: JSON.stringify({ password }),
+ body: JSON.stringify({}),
});
if (!response.ok) {
@@ -194,16 +151,7 @@ export function useShiftActions({
});
}
},
- [
- selectedCalendar,
- shifts,
- setShifts,
- presets,
- createShift,
- onStatsRefresh,
- onPasswordRequired,
- t,
- ]
+ [shifts, setShifts, presets, createShift, onStatsRefresh, t]
);
return {
diff --git a/hooks/useShiftStats.ts b/hooks/useShiftStats.ts
index 5072a43..97a3038 100644
--- a/hooks/useShiftStats.ts
+++ b/hooks/useShiftStats.ts
@@ -1,5 +1,4 @@
import { useState, useEffect, useCallback, useRef } from "react";
-import { getCachedPassword } from "@/lib/password-cache";
export interface ShiftStatsData {
period: string;
@@ -43,19 +42,15 @@ export function useShiftStats({
}
try {
- const password = getCachedPassword(calendarId);
const params = new URLSearchParams({
calendarId,
period,
date: currentDate.toISOString(),
});
- if (password) {
- params.append("password", password);
- }
const response = await fetch(`/api/shifts/stats?${params}`);
if (!response.ok) {
- return; // Calendar is locked and no valid password
+ return;
}
const data = await response.json();
setStats(data);
diff --git a/hooks/useShifts.ts b/hooks/useShifts.ts
index 74d168c..33dc1e6 100644
--- a/hooks/useShifts.ts
+++ b/hooks/useShifts.ts
@@ -3,12 +3,12 @@ import { ShiftWithCalendar } from "@/lib/types";
import { ShiftFormData } from "@/components/shift-sheet";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
-import { getCachedPassword } from "@/lib/password-cache";
export function useShifts(calendarId: string | undefined) {
const t = useTranslations();
const [shifts, setShifts] = useState<ShiftWithCalendar[]>([]);
const [loading, setLoading] = useState(false);
+ const [hasLoadedOnce, setHasLoadedOnce] = useState(false);
const fetchShifts = useCallback(
async (showLoading = true) => {
@@ -18,20 +18,16 @@ export function useShifts(calendarId: string | undefined) {
setLoading(true);
}
try {
- const password = getCachedPassword(calendarId);
const params = new URLSearchParams({ calendarId });
- if (password) {
- params.append("password", password);
- }
const response = await fetch(`/api/shifts?${params}`);
if (!response.ok) {
- // Calendar is locked and no valid password - return empty array
setShifts([]);
return;
}
const data = await response.json();
setShifts(data);
+ setHasLoadedOnce(true);
} catch (error) {
console.error("Failed to fetch shifts:", error);
setShifts([]);
@@ -65,15 +61,12 @@ export function useShifts(calendarId: string | undefined) {
setShifts((prev) => [...prev, optimisticShift]);
try {
- const password = getCachedPassword(calendarId);
-
const response = await fetch("/api/shifts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
...formData,
calendarId: calendarId,
- password,
}),
});
@@ -84,7 +77,7 @@ export function useShifts(calendarId: string | undefined) {
errorText
);
setShifts((shifts) => shifts.filter((s) => s.id !== tempId));
- toast.error(t("common.createError", { item: t("shift.title") }));
+ toast.error(t("common.createError", { item: t("shift.shift_one") }));
return null;
}
@@ -97,84 +90,66 @@ export function useShifts(calendarId: string | undefined) {
} catch (error) {
console.error("Failed to create shift:", error);
setShifts((shifts) => shifts.filter((s) => s.id !== tempId));
- toast.error(t("common.createError", { item: t("shift.title") }));
+ toast.error(t("common.createError", { item: t("shift.shift_one") }));
return null;
}
};
- const updateShift = async (
- id: string,
- formData: ShiftFormData,
- onPasswordRequired?: () => void
- ) => {
+ const updateShift = async (id: string, formData: ShiftFormData) => {
try {
- const password = getCachedPassword(calendarId);
-
const response = await fetch(`/api/shifts/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ ...formData, password }),
+ body: JSON.stringify({ ...formData }),
});
- if (response.status === 401) {
- onPasswordRequired?.();
- return false;
- }
-
if (!response.ok) {
const errorText = await response.text();
console.error(
`Failed to update shift: ${response.status} ${response.statusText}`,
errorText
);
- toast.error(t("common.updateError", { item: t("shift.title") }));
+ toast.error(t("common.updateError", { item: t("shift.shift_one") }));
return false;
}
const updatedShift = await response.json();
setShifts((prev) => prev.map((s) => (s.id === id ? updatedShift : s)));
- toast.success(t("common.updated", { item: t("shift.title") }));
+ toast.success(t("common.updated", { item: t("shift.shift_one") }));
return true;
} catch (error) {
console.error("Failed to update shift:", error);
- toast.error(t("common.updateError", { item: t("shift.title") }));
+ toast.error(t("common.updateError", { item: t("shift.shift_one") }));
return false;
}
};
- const deleteShift = async (id: string, onPasswordRequired?: () => void) => {
+ const deleteShift = async (id: string) => {
try {
- const password = getCachedPassword(calendarId);
-
const response = await fetch(`/api/shifts/${id}`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
- body: JSON.stringify({ password }),
+ body: JSON.stringify({}),
});
- if (response.status === 401) {
- onPasswordRequired?.();
- return false;
- }
-
if (!response.ok) {
const errorText = await response.text();
console.error(
`Failed to delete shift: ${response.status} ${response.statusText}`,
errorText
);
- toast.error(t("common.deleteError", { item: t("shift.title") }));
+ toast.error(t("common.deleteError", { item: t("shift.shift_one") }));
return false;
}
setShifts((prev) => prev.filter((s) => s.id !== id));
- toast.success(t("common.deleted", { item: t("shift.title") }));
+ toast.success(t("common.deleted", { item: t("shift.shift_one") }));
return true;
} catch (error) {
console.error("Failed to delete shift:", error);
- toast.error(t("common.deleteError", { item: t("shift.title") }));
+ toast.error(t("common.deleteError", { item: t("shift.shift_one") }));
return false;
}
};
@@ -193,6 +168,7 @@ export function useShifts(calendarId: string | undefined) {
shifts,
setShifts,
loading,
+ hasLoadedOnce,
createShift,
updateShift,
deleteShift,
diff --git a/hooks/useVersionUpdate.ts b/hooks/useVersionUpdate.ts
index fa277cf..d9aeefd 100644
--- a/hooks/useVersionUpdate.ts
+++ b/hooks/useVersionUpdate.ts
@@ -29,10 +29,23 @@ export function useVersionUpdateCheck() {
try {
// Server has 15-minute cache, no need for cache-busting
const response = await fetch("/api/version");
- if (response.ok) {
- const data = await response.json();
- setVersionInfo(data);
+ if (!response.ok) {
+ console.error(
+ "Failed to fetch version info:",
+ response.status,
+ response.statusText
+ );
+ return;
}
+
+ const contentType = response.headers.get("content-type");
+ if (!contentType || !contentType.includes("application/json")) {
+ console.error("Invalid content type for version info:", contentType);
+ return;
+ }
+
+ const data = await response.json();
+ setVersionInfo(data);
} catch (error) {
console.error("Failed to fetch version info:", error);
} finally {
diff --git a/lib/audit-log.ts b/lib/audit-log.ts
new file mode 100644
index 0000000..b7fab86
--- /dev/null
+++ b/lib/audit-log.ts
@@ -0,0 +1,285 @@
+import { NextRequest } from "next/server";
+import { db } from "@/lib/db";
+import { auditLogs } from "@/lib/db/schema";
+import { getClientIp } from "@/lib/ip-utils";
+
+// =====================================================
+// Typed Metadata Interfaces
+// =====================================================
+
+export interface LoginFailedMetadata {
+ email: string;
+ reason: "invalid_password" | "user_not_found" | "rate_limited";
+}
+
+export interface LoginSuccessMetadata {
+ email: string;
+ newDevice: boolean;
+ provider?: string; // OAuth/OIDC provider ID (e.g., "google", "custom-oidc")
+ method: "email" | "oauth" | "oidc";
+}
+
+export interface UserRegisteredMetadata {
+ email: string;
+ name: string | null;
+ registrationMethod:
+ | "email"
+ | "oauth_google"
+ | "oauth_github"
+ | "oauth_discord"
+ | "oidc_custom";
+ provider?: string; // OAuth/OIDC provider ID (e.g., "google", "custom-oidc")
+}
+
+export interface ProfileUpdatedMetadata {
+ changes: string[]; // e.g., ["name", "email", "avatar"]
+ oldValues?: {
+ name?: string;
+ email?: string;
+ };
+ newValues?: {
+ name?: string;
+ email?: string;
+ };
+}
+
+export interface PasswordChangedMetadata {
+ sessionsRevoked: number;
+}
+
+export interface AccountDeletedMetadata {
+ calendarsDeleted: number;
+}
+
+export interface SessionRevokedMetadata {
+ revokedBy: "user" | "password_change" | "admin";
+ sessionId?: string; // For single session revocation
+ count?: number; // For bulk revocation
+}
+
+export interface CalendarCreatedMetadata {
+ calendarName: string;
+ color: string;
+}
+
+export interface CalendarDeletedMetadata {
+ calendarName: string;
+ shiftsDeleted: number;
+ presetsDeleted: number;
+ notesDeleted: number;
+}
+
+export interface CalendarUpdatedMetadata {
+ calendarName: string;
+ changes: string[]; // e.g., ["name", "color", "guestPermission"]
+}
+
+export interface CalendarSharedMetadata {
+ calendarName: string;
+ sharedWith: string; // user email
+ permission: "read" | "write" | "admin";
+}
+
+export interface CalendarShareRemovedMetadata {
+ calendarName: string;
+ removedUser: string;
+ removedBy: "owner" | "admin" | "self";
+}
+
+export interface CalendarPermissionChangedMetadata {
+ calendarName: string;
+ user: string;
+ oldPermission: string;
+ newPermission: string;
+}
+
+export interface CalendarGuestPermissionChangedMetadata {
+ calendarName: string;
+ oldPermission: "none" | "read" | "write";
+ newPermission: "none" | "read" | "write";
+}
+
+export interface SyncCreatedMetadata {
+ calendarName: string;
+ syncUrl: string;
+ syncName: string;
+}
+
+export interface SyncDeletedMetadata {
+ calendarName: string;
+ syncUrl: string;
+ syncName: string;
+}
+
+export interface SyncExecutedMetadata {
+ calendarName: string;
+ syncName: string;
+ shiftsAdded: number;
+ shiftsUpdated: number;
+ shiftsDeleted: number;
+ success: boolean;
+ error?: string;
+}
+
+export interface RateLimitHitMetadata {
+ endpoint: string;
+ limit: number;
+ resetTime: number;
+}
+
+export interface AdminUserDeleteMetadata {
+ deletedUser: string;
+ calendarsTransferred: number;
+}
+
+export interface AdminCalendarTransferMetadata {
+ calendarName: string;
+ fromUser: string;
+ toUser: string;
+}
+
+export interface AdminPasswordResetMetadata {
+ targetUser: string;
+}
+
+// Union type for all metadata
+export type AuditLogMetadata =
+ | LoginFailedMetadata
+ | LoginSuccessMetadata
+ | PasswordChangedMetadata
+ | AccountDeletedMetadata
+ | SessionRevokedMetadata
+ | CalendarCreatedMetadata
+ | CalendarDeletedMetadata
+ | CalendarUpdatedMetadata
+ | CalendarSharedMetadata
+ | CalendarShareRemovedMetadata
+ | CalendarPermissionChangedMetadata
+ | SyncCreatedMetadata
+ | SyncDeletedMetadata
+ | SyncExecutedMetadata
+ | RateLimitHitMetadata
+ | AdminUserDeleteMetadata
+ | AdminCalendarTransferMetadata
+ | AdminPasswordResetMetadata;
+
+// =====================================================
+// Audit Log Types
+// =====================================================
+
+export type AuditLogSeverity = "info" | "warning" | "error" | "critical";
+
+export interface LogAuditEventOptions<T = AuditLogMetadata> {
+ action: string;
+ userId?: string | null;
+ resourceType?: string | null;
+ resourceId?: string | null;
+ metadata?: T;
+ request?: NextRequest | Request; // Support both types
+ severity?: AuditLogSeverity;
+ isUserVisible?: boolean;
+}
+
+// =====================================================
+// Core Logging Function
+// =====================================================
+
+/**
+ * Log an audit event to the database.
+ * Uses fire-and-forget pattern (queueMicrotask) to avoid blocking requests.
+ */
+export async function logAuditEvent<T = AuditLogMetadata>(
+ options: LogAuditEventOptions<T>
+): Promise<void> {
+ const {
+ action,
+ userId = null,
+ resourceType = null,
+ resourceId = null,
+ metadata = undefined,
+ request,
+ severity = "info",
+ isUserVisible = false,
+ } = options;
+
+ // Extract IP and user agent from request if provided
+ const ipAddress = request ? getClientIp(request) : null;
+ const userAgent = request ? request.headers.get("user-agent") : null;
+
+ // Fire-and-forget: don't block the request
+ queueMicrotask(async () => {
+ try {
+ await db.insert(auditLogs).values({
+ userId,
+ action,
+ resourceType,
+ resourceId,
+ metadata: metadata ? JSON.stringify(metadata) : null,
+ ipAddress,
+ userAgent,
+ severity,
+ isUserVisible,
+ timestamp: new Date(),
+ });
+ } catch (error) {
+ // Log error but don't throw (fire-and-forget)
+ console.error("Failed to log audit event:", error);
+ }
+ });
+}
+
+// =====================================================
+// Helper Functions for Common Use Cases
+// =====================================================
+
+/**
+ * Log a security-related event (critical severity, user-visible)
+ */
+export async function logSecurityEvent<T = AuditLogMetadata>(
+ options: Omit<LogAuditEventOptions<T>, "severity" | "isUserVisible">
+): Promise<void> {
+ return logAuditEvent({
+ ...options,
+ severity: "critical",
+ isUserVisible: true,
+ });
+}
+
+/**
+ * Log a user action (info severity, user-visible)
+ */
+export async function logUserAction<T = AuditLogMetadata>(
+ options: Omit<LogAuditEventOptions<T>, "severity" | "isUserVisible">
+): Promise<void> {
+ return logAuditEvent({
+ ...options,
+ severity: "info",
+ isUserVisible: true,
+ });
+}
+
+/**
+ * Log an admin action (warning severity, NOT user-visible)
+ */
+export async function logAdminAction<T = AuditLogMetadata>(
+ options: Omit<LogAuditEventOptions<T>, "severity" | "isUserVisible">
+): Promise<void> {
+ return logAuditEvent({
+ ...options,
+ severity: "warning",
+ isUserVisible: false,
+ });
+}
+
+/**
+ * Log a system event (info severity, NOT user-visible)
+ */
+export async function logSystemEvent<T = AuditLogMetadata>(
+ options: Omit<LogAuditEventOptions<T>, "severity" | "isUserVisible">
+): Promise<void> {
+ return logAuditEvent({
+ ...options,
+ severity: "info",
+ isUserVisible: false,
+ });
+}
diff --git a/lib/auth.ts b/lib/auth.ts
new file mode 100644
index 0000000..8eb812b
--- /dev/null
+++ b/lib/auth.ts
@@ -0,0 +1,196 @@
+import { betterAuth } from "better-auth";
+import { drizzleAdapter } from "better-auth/adapters/drizzle";
+import { genericOAuth, admin } from "better-auth/plugins";
+import { createAuthMiddleware } from "better-auth/api";
+import { db } from "@/lib/db";
+import * as schema from "@/lib/db/schema";
+import { auditLogPlugin } from "@/lib/auth/audit-plugin";
+import { handleFirstUserPromotion } from "@/lib/auth/first-user";
+import { ac, roles } from "@/lib/auth/access-control";
+import {
+ GOOGLE_CLIENT_ID,
+ GOOGLE_CLIENT_SECRET,
+ GITHUB_CLIENT_ID,
+ GITHUB_CLIENT_SECRET,
+ DISCORD_CLIENT_ID,
+ DISCORD_CLIENT_SECRET,
+ CUSTOM_OIDC_ENABLED,
+ CUSTOM_OIDC_CLIENT_ID,
+ CUSTOM_OIDC_CLIENT_SECRET,
+ CUSTOM_OIDC_ISSUER,
+ CUSTOM_OIDC_SCOPES,
+ SESSION_MAX_AGE,
+ SESSION_UPDATE_AGE,
+ BETTER_AUTH_TRUSTED_ORIGINS,
+ BETTER_AUTH_URL,
+ ALLOW_USER_REGISTRATION,
+} from "@/lib/auth/env";
+
+export const auth = betterAuth({
+ // Base URL configuration (critical for reverse proxy setups)
+ baseURL: BETTER_AUTH_URL,
+ basePath: "/api/auth",
+
+ database: drizzleAdapter(db, {
+ provider: "sqlite",
+ schema: {
+ ...schema,
+ },
+ }),
+
+ // Email and Password authentication
+ emailAndPassword: {
+ disableSignUp: !ALLOW_USER_REGISTRATION,
+ enabled: true,
+ },
+
+ // Built-in social providers
+ socialProviders: {
+ google: GOOGLE_CLIENT_ID
+ ? {
+ clientId: GOOGLE_CLIENT_ID,
+ clientSecret: GOOGLE_CLIENT_SECRET!,
+ }
+ : undefined,
+ github: GITHUB_CLIENT_ID
+ ? {
+ clientId: GITHUB_CLIENT_ID,
+ clientSecret: GITHUB_CLIENT_SECRET!,
+ }
+ : undefined,
+ discord: DISCORD_CLIENT_ID
+ ? {
+ clientId: DISCORD_CLIENT_ID,
+ clientSecret: DISCORD_CLIENT_SECRET!,
+ }
+ : undefined,
+ },
+
+ // Generic OAuth plugin for Custom OIDC
+ plugins: [
+ // Audit logging plugin
+ auditLogPlugin(),
+
+ // Admin plugin for user management
+ admin({
+ defaultRole: "user",
+ // Custom access control to support "admin" and "superadmin" roles
+ // Both roles get all Better Auth admin permissions
+ // Fine-grained permission control (e.g., only superadmin can ban/delete)
+ // is handled by our custom checks in lib/auth/admin.ts
+ ac,
+ roles,
+ }),
+
+ // Custom OIDC
+ genericOAuth({
+ config: [
+ // Custom OIDC Provider
+ ...(CUSTOM_OIDC_ENABLED && CUSTOM_OIDC_CLIENT_ID
+ ? [
+ {
+ providerId: "custom-oidc",
+ clientId: CUSTOM_OIDC_CLIENT_ID,
+ clientSecret: CUSTOM_OIDC_CLIENT_SECRET!,
+ discoveryUrl: CUSTOM_OIDC_ISSUER!,
+ scopes: CUSTOM_OIDC_SCOPES?.split(" ") || [
+ "openid",
+ "profile",
+ "email",
+ ],
+ },
+ ]
+ : []),
+ ],
+ }),
+ ],
+
+ // Session configuration
+ session: {
+ expiresIn: SESSION_MAX_AGE,
+ updateAge: SESSION_UPDATE_AGE,
+ },
+
+ // Advanced settings
+ advanced: {
+ // Secure cookies: Use HTTPS detection instead of just NODE_ENV
+ // Better Auth will automatically add __Secure- prefix when enabled
+ useSecureCookies: BETTER_AUTH_URL.startsWith("https://"),
+
+ // Default cookie attributes (defense in depth)
+ defaultCookieAttributes: {
+ sameSite: "lax",
+ secure: BETTER_AUTH_URL.startsWith("https://"), // Only send over HTTPS
+ httpOnly: true, // Prevent XSS attacks (already default, but explicit)
+ },
+ },
+
+ // User registration settings
+ user: {
+ // Disable sign-up if configured
+ changeEmail: {
+ enabled: true,
+ updateEmailWithoutVerification: true,
+ },
+ deleteUser: {
+ enabled: true,
+ },
+ },
+
+ // Database hooks for user creation control
+ databaseHooks: {
+ user: {
+ create: {
+ before: async () => {
+ // Block OAuth/OIDC registration when ALLOW_USER_REGISTRATION is false
+ // This hook runs for ALL user creation attempts (email + OAuth/OIDC)
+ // Email registration is already blocked by disableSignUp config
+ if (!ALLOW_USER_REGISTRATION) {
+ throw new Error(
+ "Registration is currently disabled. Please contact an administrator."
+ );
+ }
+ // Return void to allow creation
+ },
+ },
+ },
+ },
+
+ // Hooks for custom logic
+ hooks: {
+ after: createAuthMiddleware(async (ctx) => {
+ // Auto-promote first user to superadmin
+ // This runs for both email registration (/sign-up/email) and OAuth/OIDC callbacks
+ const newSession = ctx.context.newSession;
+
+ if (newSession?.user?.id) {
+ // Check if this is a new user registration
+ // For email: /sign-up/email path
+ // For OAuth/OIDC: /callback/* path with newly created user (check createdAt timestamp)
+ const isEmailSignup = ctx.path.startsWith("/sign-up");
+
+ let isOAuthCallback = false;
+ if (ctx.path.startsWith("/callback/")) {
+ // Check if user was just created (within last 5 seconds)
+ const userCreatedAt = new Date(newSession.user.createdAt);
+ const now = new Date();
+ const timeDiff = now.getTime() - userCreatedAt.getTime();
+ isOAuthCallback = timeDiff < 5000;
+ }
+
+ if (isEmailSignup || isOAuthCallback) {
+ // Non-blocking promotion (don't wait for it)
+ handleFirstUserPromotion(newSession.user.id).catch((error) => {
+ console.error("Failed to promote first user:", error);
+ });
+ }
+ }
+ }),
+ },
+
+ // Trust host for deployment
+ trustedOrigins: BETTER_AUTH_TRUSTED_ORIGINS,
+});
+
+export type Session = typeof auth.$Infer.Session.session;
+export type User = typeof auth.$Infer.Session.user;
diff --git a/lib/auth/access-control.ts b/lib/auth/access-control.ts
new file mode 100644
index 0000000..bb0c886
--- /dev/null
+++ b/lib/auth/access-control.ts
@@ -0,0 +1,71 @@
+/**
+ * Better Auth Access Control Configuration
+ *
+ * This file defines custom roles and permissions for Better Auth's Admin Plugin.
+ * Required ONLY for Better Auth admin operations (ban, unban, password reset, removeUser).
+ *
+ * NOTE: This is NOT used for our custom permission checks (canEditUser, canDeleteUser, etc).
+ * Those are in lib/auth/admin.ts and work independently.
+ *
+ * Why we need this:
+ * - Better Auth doesn't recognize "admin" and "superadmin" by default
+ * - Without this, Better Auth admin APIs (banUser, setUserPassword) throw permission errors
+ * - This tells Better Auth: "superadmin" and "admin" are admin roles with full admin permissions
+ */
+
+import { createAccessControl } from "better-auth/plugins/access";
+
+/**
+ * Access control configuration for Better Auth
+ *
+ * Both "admin" and "superadmin" get ALL Better Auth admin permissions.
+ * Fine-grained permission control (e.g., only superadmin can ban) is handled
+ * by our custom permission functions in lib/auth/admin.ts
+ */
+export const ac = createAccessControl({
+ user: [
+ "create",
+ "list",
+ "set-role",
+ "ban",
+ "impersonate",
+ "delete",
+ "set-password",
+ ],
+ session: ["list", "delete"],
+});
+
+/**
+ * Define custom roles with their permissions
+ *
+ * Strategy:
+ * - Give both "admin" and "superadmin" ALL Better Auth permissions
+ * - Use lib/auth/admin.ts functions to restrict actions (e.g., only superadmin can ban)
+ * - This allows both roles to call Better Auth APIs, but we control what they can do
+ */
+export const roles = {
+ superadmin: ac.newRole({
+ user: [
+ "create",
+ "list",
+ "set-role",
+ "ban",
+ "impersonate",
+ "delete",
+ "set-password",
+ ],
+ session: ["list", "delete"],
+ }),
+ admin: ac.newRole({
+ user: [
+ "create",
+ "list",
+ "set-role",
+ "ban",
+ "impersonate",
+ "delete",
+ "set-password",
+ ],
+ session: ["list", "delete"],
+ }),
+};
diff --git a/lib/auth/admin-helpers.ts b/lib/auth/admin-helpers.ts
new file mode 100644
index 0000000..51f8019
--- /dev/null
+++ b/lib/auth/admin-helpers.ts
@@ -0,0 +1,79 @@
+import { NextRequest, NextResponse } from "next/server";
+import { db } from "@/lib/db";
+import { user as userTable } from "@/lib/db/schema";
+import { eq } from "drizzle-orm";
+import { getSessionUser } from "@/lib/auth/sessions";
+import type { User } from "@/lib/auth";
+
+export type AdminUser = User;
+
+/**
+ * Get the current admin user from request headers.
+ * Returns null if not authenticated.
+ */
+export async function getAdminUser(
+ headers: Headers
+): Promise<AdminUser | null> {
+ const sessionUser = await getSessionUser(headers);
+ if (!sessionUser) {
+ return null;
+ }
+
+ const [currentUser] = await db
+ .select()
+ .from(userTable)
+ .where(eq(userTable.id, sessionUser.id))
+ .limit(1);
+
+ return currentUser || null;
+}
+
+/**
+ * Get and validate the current admin user from request.
+ * Returns NextResponse with error if not authenticated or user not found.
+ * Returns the admin user object if successful.
+ */
+export async function getValidatedAdminUser(
+ request: NextRequest
+): Promise<AdminUser | NextResponse> {
+ const currentUser = await getAdminUser(request.headers);
+
+ if (!currentUser) {
+ return NextResponse.json(
+ { error: "Authentication required" },
+ { status: 401 }
+ );
+ }
+
+ return currentUser;
+}
+
+/**
+ * Get and validate a target user by ID.
+ * Returns NextResponse with error if not found.
+ * Returns the user object if successful.
+ */
+export async function getValidatedTargetUser(
+ userId: string
+): Promise<AdminUser | NextResponse> {
+ const [targetUser] = await db
+ .select()
+ .from(userTable)
+ .where(eq(userTable.id, userId))
+ .limit(1);
+
+ if (!targetUser) {
+ return NextResponse.json({ error: "User not found" }, { status: 404 });
+ }
+
+ return targetUser;
+}
+
+/**
+ * Type guard to check if result is a NextResponse (error)
+ */
+export function isErrorResponse(
+ result: AdminUser | NextResponse
+): result is NextResponse {
+ return result instanceof NextResponse;
+}
diff --git a/lib/auth/admin.ts b/lib/auth/admin.ts
new file mode 100644
index 0000000..01546ae
--- /dev/null
+++ b/lib/auth/admin.ts
@@ -0,0 +1,322 @@
+/**
+ * Admin Role Helpers
+ *
+ * Utility functions for checking and enforcing admin permissions.
+ * Used throughout the application to protect admin-only routes and features.
+ */
+
+import type { User } from "@/lib/auth";
+import { APIError } from "better-auth/api";
+
+/**
+ * Valid admin roles in the system
+ */
+const ADMIN_ROLES = ["admin", "superadmin"] as const;
+export type AdminRole = (typeof ADMIN_ROLES)[number];
+
+/**
+ * Check if a user has an admin role (admin or superadmin)
+ *
+ * @param user - The user object (can be null for unauthenticated users)
+ * @returns boolean - true if user is admin or superadmin
+ */
+export function isAdmin(user: User | null | undefined): boolean {
+ if (!user?.role) return false;
+ return ADMIN_ROLES.includes(user.role as AdminRole);
+}
+
+/**
+ * Check if a user has the superadmin role specifically
+ *
+ * @param user - The user object (can be null for unauthenticated users)
+ * @returns boolean - true if user is superadmin
+ */
+export function isSuperAdmin(user: User | null | undefined): boolean {
+ return user?.role === "superadmin";
+}
+
+/**
+ * Require admin role or throw an error
+ * Use this in API routes to protect admin-only endpoints
+ *
+ * @param user - The user object (can be null for unauthenticated users)
+ * @throws APIError with status 403 if user is not an admin
+ */
+export function requireAdmin(
+ user: User | null | undefined
+): asserts user is User & { role: AdminRole } {
+ if (!isAdmin(user)) {
+ throw new APIError("FORBIDDEN", {
+ message: "Admin access required",
+ });
+ }
+}
+
+/**
+ * Require superadmin role or throw an error
+ * Use this in API routes to protect superadmin-only endpoints
+ *
+ * @param user - The user object (can be null for unauthenticated users)
+ * @throws APIError with status 403 if user is not a superadmin
+ */
+export function requireSuperAdmin(
+ user: User | null | undefined
+): asserts user is User & { role: "superadmin" } {
+ if (!isSuperAdmin(user)) {
+ throw new APIError("FORBIDDEN", {
+ message: "Superadmin access required",
+ });
+ }
+}
+
+/**
+ * Get user's admin level (for display purposes)
+ *
+ * @param user - The user object
+ * @returns string - "superadmin", "admin", or "user"
+ */
+export function getAdminLevel(
+ user: User | null | undefined
+): "superadmin" | "admin" | "user" {
+ if (!user?.role) return "user";
+ if (user.role === "superadmin") return "superadmin";
+ if (user.role === "admin") return "admin";
+ return "user";
+}
+
+/**
+ * Admin Permission Check Functions
+ *
+ * These functions determine what actions an admin can perform.
+ * Used by both API routes (server-side) and React hooks (client-side).
+ * All checks are synchronous - no async API calls needed.
+ */
+
+/**
+ * Check if admin can edit a target user
+ *
+ * Rules:
+ * - Superadmin: Can edit anyone
+ * - Admin: Can edit only regular users (role: "user" or null)
+ * - Cannot edit self (use profile page instead)
+ *
+ * @param adminUser - The admin performing the action
+ * @param targetUser - The user being edited
+ * @returns boolean - true if admin can edit target user
+ */
+export function canEditUser(
+ adminUser: User | null | undefined,
+ targetUser: User | null | undefined
+): boolean {
+ if (!isAdmin(adminUser) || !targetUser) return false;
+
+ // Superadmin can edit anyone
+ if (isSuperAdmin(adminUser)) return true;
+
+ // Admin can only edit regular users
+ const targetRole = targetUser.role || "user";
+ return targetRole === "user";
+}
+
+/**
+ * Check if admin can delete a target user
+ *
+ * Rules:
+ * - Only superadmin can delete users
+ * - Cannot delete self
+ *
+ * @param adminUser - The admin performing the action
+ * @param targetUser - The user being deleted
+ * @returns boolean - true if admin can delete target user
+ */
+export function canDeleteUser(
+ adminUser: User | null | undefined,
+ targetUser: User | null | undefined
+): boolean {
+ if (!isSuperAdmin(adminUser) || !targetUser) return false;
+ if (adminUser!.id === targetUser.id) return false;
+
+ return true;
+}
+
+/**
+ * Check if admin can ban a target user
+ *
+ * Rules:
+ * - Only superadmin can ban users
+ * - Cannot ban self
+ * - Cannot ban other superadmins
+ *
+ * @param adminUser - The admin performing the action
+ * @param targetUser - The user being banned
+ * @returns boolean - true if admin can ban target user
+ */
+export function canBanUser(
+ adminUser: User | null | undefined,
+ targetUser: User | null | undefined
+): boolean {
+ if (!isSuperAdmin(adminUser) || !targetUser) return false;
+ if (adminUser!.id === targetUser.id) return false;
+ if (targetUser.role === "superadmin") return false;
+
+ return true;
+}
+
+/**
+ * Check if admin can change a user's role
+ *
+ * Rules:
+ * - Only superadmin can change roles
+ * - Cannot change own role
+ *
+ * @param adminUser - The admin performing the action
+ * @param targetUser - The user whose role is being changed
+ * @returns boolean - true if admin can change target user's role
+ */
+export function canChangeUserRole(
+ adminUser: User | null | undefined,
+ targetUser: User | null | undefined
+): boolean {
+ if (!isSuperAdmin(adminUser) || !targetUser) return false;
+ if (adminUser!.id === targetUser.id) return false;
+
+ return true;
+}
+
+/**
+ * Check if admin can reset a user's password
+ *
+ * Rules:
+ * - Both admin and superadmin can reset passwords
+ * - Cannot reset own password (use change password instead)
+ * - Admin cannot reset superadmin passwords
+ *
+ * @param adminUser - The admin performing the action
+ * @param targetUser - The user whose password is being reset
+ * @returns boolean - true if admin can reset target user's password
+ */
+export function canResetPassword(
+ adminUser: User | null | undefined,
+ targetUser: User | null | undefined
+): boolean {
+ if (!isAdmin(adminUser) || !targetUser) return false;
+ if (adminUser!.id === targetUser.id) return false;
+
+ // Superadmin can reset anyone's password
+ if (isSuperAdmin(adminUser)) return true;
+
+ // Admin cannot reset superadmin passwords
+ if (targetUser.role === "superadmin") return false;
+
+ return true;
+}
+
+/**
+ * Check if admin can manage calendar operations
+ *
+ * Rules:
+ * - View: Both admin and superadmin
+ * - Delete: Only superadmin
+ *
+ * @param adminUser - The admin performing the action
+ * @param operation - The operation being performed ('view' or 'delete')
+ * @returns boolean - true if admin can perform the operation
+ */
+export function canManageCalendar(
+ adminUser: User | null | undefined,
+ operation: "view" | "delete"
+): boolean {
+ if (!isAdmin(adminUser)) return false;
+
+ if (operation === "view") return true;
+
+ // Delete requires superadmin
+ return isSuperAdmin(adminUser);
+}
+
+/**
+ * Check if admin can edit a calendar
+ *
+ * Rules:
+ * - Both admin and superadmin can edit calendars
+ * - Can edit name, color, guest permission
+ * - Cannot change owner via edit (use transfer instead)
+ *
+ * @param adminUser - The admin performing the action
+ * @returns boolean - true if admin can edit calendars
+ */
+export function canEditCalendar(adminUser: User | null | undefined): boolean {
+ return isAdmin(adminUser);
+}
+
+/**
+ * Check if admin can delete a calendar
+ *
+ * Rules:
+ * - Only superadmin can delete calendars
+ *
+ * @param adminUser - The admin performing the action
+ * @returns boolean - true if admin can delete calendars
+ */
+export function canDeleteCalendar(adminUser: User | null | undefined): boolean {
+ return isSuperAdmin(adminUser);
+}
+
+/**
+ * Check if admin can transfer calendar ownership
+ *
+ * Rules:
+ * - Both admin and superadmin can transfer calendars
+ * - Can transfer any calendar (orphaned or owned)
+ *
+ * @param adminUser - The admin performing the action
+ * @returns boolean - true if admin can transfer calendars
+ */
+export function canTransferCalendar(
+ adminUser: User | null | undefined
+): boolean {
+ return isAdmin(adminUser);
+}
+
+/**
+ * Check if admin can assign orphaned calendars
+ *
+ * Rules:
+ * - Both admin and superadmin can assign calendars
+ *
+ * @param adminUser - The admin performing the action
+ * @returns boolean - true if admin can assign orphaned calendars
+ */
+export function canAssignOrphanedCalendar(
+ adminUser: User | null | undefined
+): boolean {
+ return isAdmin(adminUser);
+}
+
+/**
+ * Check if admin can view audit logs
+ *
+ * Rules:
+ * - Both admin and superadmin can view logs
+ *
+ * @param adminUser - The admin performing the action
+ * @returns boolean - true if admin can view audit logs
+ */
+export function canViewAuditLogs(adminUser: User | null | undefined): boolean {
+ return isAdmin(adminUser);
+}
+
+/**
+ * Check if admin can delete audit logs
+ *
+ * Rules:
+ * - Only superadmin can delete logs
+ *
+ * @param adminUser - The admin performing the action
+ * @returns boolean - true if admin can delete audit logs
+ */
+export function canDeleteAuditLogs(
+ adminUser: User | null | undefined
+): boolean {
+ return isSuperAdmin(adminUser);
+}
diff --git a/lib/auth/audit-plugin.ts b/lib/auth/audit-plugin.ts
new file mode 100644
index 0000000..ba5ba53
--- /dev/null
+++ b/lib/auth/audit-plugin.ts
@@ -0,0 +1,170 @@
+import { BetterAuthPlugin } from "better-auth";
+import { createAuthMiddleware } from "better-auth/api";
+import {
+ logSecurityEvent,
+ logUserAction,
+ type LoginFailedMetadata,
+ type LoginSuccessMetadata,
+ type UserRegisteredMetadata,
+ type ProfileUpdatedMetadata,
+} from "@/lib/audit-log";
+
+/**
+ * Better Auth plugin for audit logging
+ *
+ * Logs all authentication events using Better Auth's hooks system
+ */
+export const auditLogPlugin = () => {
+ return {
+ id: "audit-log",
+ hooks: {
+ after: [
+ {
+ // Match all auth endpoints
+ matcher: (context) => {
+ return (
+ context.path.startsWith("/sign-in") ||
+ context.path.startsWith("/sign-up") ||
+ context.path.startsWith("/callback") ||
+ context.path === "/update-user"
+ );
+ },
+ handler: createAuthMiddleware(async (ctx) => {
+ try {
+ const newSession = ctx.context.newSession;
+
+ // Log successful email logins
+ if (ctx.path === "/sign-in/email" && newSession?.user) {
+ await logUserAction<LoginSuccessMetadata>({
+ action: "auth.login.success",
+ userId: newSession.user.id,
+ resourceType: "user",
+ metadata: {
+ email: newSession.user.email,
+ newDevice: false, // TODO: Track device fingerprint
+ method: "email",
+ },
+ request: ctx.request!,
+ });
+ }
+
+ // Log OIDC/OAuth callback events
+ if (ctx.path.startsWith("/callback/") && newSession?.user) {
+ // Extract provider from path (e.g., /callback/google -> "google")
+ const provider = ctx.path.replace("/callback/", "");
+
+ // Determine if this is a registration or login
+ // Better Auth creates the user just before calling this hook
+ // We check if the user was created very recently (within last 5 seconds)
+ const userCreatedAt = new Date(newSession.user.createdAt);
+ const now = new Date();
+ const timeDiff = now.getTime() - userCreatedAt.getTime();
+ const isNewUser = timeDiff < 5000; // User created within last 5 seconds
+
+ if (isNewUser) {
+ // This is a new user registration via OAuth/OIDC
+ await logUserAction<UserRegisteredMetadata>({
+ action: "auth.user.registered",
+ userId: newSession.user.id,
+ resourceType: "user",
+ metadata: {
+ email: newSession.user.email,
+ name: newSession.user.name,
+ registrationMethod:
+ provider === "custom-oidc"
+ ? "oidc_custom"
+ : (`oauth_${provider}` as
+ | "oauth_google"
+ | "oauth_github"
+ | "oauth_discord"),
+ provider,
+ },
+ request: ctx.request!,
+ });
+ } else {
+ // This is an existing user login via OAuth/OIDC
+ await logUserAction<LoginSuccessMetadata>({
+ action: "auth.login.success",
+ userId: newSession.user.id,
+ resourceType: "user",
+ metadata: {
+ email: newSession.user.email,
+ newDevice: false, // TODO: Track device fingerprint
+ provider,
+ method: provider === "custom-oidc" ? "oidc" : "oauth",
+ },
+ request: ctx.request!,
+ });
+ }
+ }
+
+ // Log failed logins (no session was created)
+ if (ctx.path === "/sign-in/email" && !newSession) {
+ const email = ctx.body?.email;
+ if (email) {
+ // Default to invalid_password, actual reason detection would need response parsing
+ await logSecurityEvent<LoginFailedMetadata>({
+ action: "auth.login.failed",
+ resourceType: "user",
+ metadata: {
+ email,
+ reason: "invalid_password",
+ },
+ request: ctx.request!,
+ });
+ }
+ }
+
+ // Log user registrations via email
+ if (ctx.path === "/sign-up/email" && newSession?.user) {
+ await logUserAction<UserRegisteredMetadata>({
+ action: "auth.user.registered",
+ userId: newSession.user.id,
+ resourceType: "user",
+ metadata: {
+ email: newSession.user.email,
+ name: newSession.user.name,
+ registrationMethod: "email",
+ provider: "email",
+ },
+ request: ctx.request!,
+ });
+ }
+
+ // Log profile updates
+ if (ctx.path === "/update-user" && ctx.body) {
+ const changes: string[] = [];
+
+ if (ctx.body.name !== undefined) changes.push("name");
+ if (ctx.body.email !== undefined) changes.push("email");
+ if (ctx.body.image !== undefined) changes.push("avatar");
+
+ if (changes.length > 0 && newSession?.user) {
+ await logUserAction<ProfileUpdatedMetadata>({
+ action: "auth.profile.updated",
+ userId: newSession.user.id,
+ resourceType: "user",
+ metadata: {
+ changes,
+ newValues: {
+ name: ctx.body.name,
+ email: ctx.body.email,
+ },
+ },
+ request: ctx.request!,
+ });
+ }
+ }
+ } catch (error) {
+ // Audit logging failures should not break auth flow
+ console.error("[Audit Log Plugin] Failed to log event:", error);
+ }
+
+ // Don't modify the response
+ return;
+ }),
+ },
+ ],
+ },
+ } satisfies BetterAuthPlugin;
+};
diff --git a/lib/auth/client.ts b/lib/auth/client.ts
new file mode 100644
index 0000000..017df43
--- /dev/null
+++ b/lib/auth/client.ts
@@ -0,0 +1,32 @@
+"use client";
+
+import { createAuthClient } from "better-auth/react";
+import { genericOAuthClient, adminClient } from "better-auth/client/plugins";
+import { ac, roles } from "@/lib/auth/access-control";
+
+/**
+ * Better Auth client for client-side authentication
+ *
+ * Provides methods for:
+ * - Sign in with email/password
+ * - Sign in with social providers (Google, GitHub, Discord)
+ * - Sign in with custom OIDC provider
+ * - Sign out
+ * - User session management
+ * - Registration
+ */
+export const authClient = createAuthClient({
+ baseURL:
+ typeof window !== "undefined" && window.__PUBLIC_CONFIG__
+ ? window.__PUBLIC_CONFIG__.auth.url
+ : "",
+ plugins: [
+ genericOAuthClient(),
+ adminClient({
+ ac,
+ roles,
+ }),
+ ],
+});
+
+export const { signIn, signOut, signUp, useSession } = authClient;
diff --git a/lib/auth/env.ts b/lib/auth/env.ts
new file mode 100644
index 0000000..c8a13a2
--- /dev/null
+++ b/lib/auth/env.ts
@@ -0,0 +1,204 @@
+/**
+ * Centralized environment variable configuration for authentication
+ *
+ * This file provides a single source of truth for all auth-related
+ * environment variables, with validation and type safety.
+ *
+ * NOTE: For client-side access to public config values, use:
+ * import { usePublicConfig } from '@/hooks/usePublicConfig'
+ */
+
+// =============================================================================
+// Core Auth Settings
+// =============================================================================
+
+export const AUTH_ENABLED = process.env.AUTH_ENABLED !== "false"; // Default: true
+
+export const BETTER_AUTH_SECRET = process.env.BETTER_AUTH_SECRET || "";
+
+export const BETTER_AUTH_URL =
+ process.env.BETTER_AUTH_URL || "http://localhost:3000";
+
+// SECURITY: Always set trustedOrigins to enable CSRF protection
+// Default to BETTER_AUTH_URL if not explicitly configured
+export const BETTER_AUTH_TRUSTED_ORIGINS = process.env
+ .BETTER_AUTH_TRUSTED_ORIGINS
+ ? process.env.BETTER_AUTH_TRUSTED_ORIGINS.split(",").map((origin) =>
+ origin.trim()
+ )
+ : [BETTER_AUTH_URL]; // Default: Trust only the configured base URL
+
+// =============================================================================
+// User Registration Settings
+// =============================================================================
+
+export const ALLOW_USER_REGISTRATION =
+ process.env.ALLOW_USER_REGISTRATION !== "false"; // Default: true
+
+// =============================================================================
+// Guest Access Settings
+// =============================================================================
+
+export const ALLOW_GUEST_ACCESS = process.env.ALLOW_GUEST_ACCESS === "true"; // Default: false
+
+// =============================================================================
+// Session Settings
+// =============================================================================
+
+export const SESSION_MAX_AGE = parseInt(
+ process.env.SESSION_MAX_AGE || "604800",
+ 10
+); // 7 days
+
+export const SESSION_UPDATE_AGE = parseInt(
+ process.env.SESSION_UPDATE_AGE || "86400",
+ 10
+); // 1 day
+
+// =============================================================================
+// Google OAuth
+// =============================================================================
+
+export const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID || "";
+export const GOOGLE_CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET || "";
+
+// =============================================================================
+// GitHub OAuth
+// =============================================================================
+
+export const GITHUB_CLIENT_ID = process.env.GITHUB_CLIENT_ID || "";
+export const GITHUB_CLIENT_SECRET = process.env.GITHUB_CLIENT_SECRET || "";
+
+// =============================================================================
+// Discord OAuth
+// =============================================================================
+
+export const DISCORD_CLIENT_ID = process.env.DISCORD_CLIENT_ID || "";
+export const DISCORD_CLIENT_SECRET = process.env.DISCORD_CLIENT_SECRET || "";
+
+// =============================================================================
+// Custom OIDC Provider
+// =============================================================================
+
+export const CUSTOM_OIDC_ENABLED = process.env.CUSTOM_OIDC_ENABLED === "true";
+
+export const CUSTOM_OIDC_NAME = process.env.CUSTOM_OIDC_NAME || "Custom SSO";
+
+export const CUSTOM_OIDC_CLIENT_ID = process.env.CUSTOM_OIDC_CLIENT_ID || "";
+
+export const CUSTOM_OIDC_ISSUER = process.env.CUSTOM_OIDC_ISSUER || "";
+
+export const CUSTOM_OIDC_CLIENT_SECRET =
+ process.env.CUSTOM_OIDC_CLIENT_SECRET || "";
+
+export const CUSTOM_OIDC_SCOPES =
+ process.env.CUSTOM_OIDC_SCOPES || "openid profile email";
+
+// =============================================================================
+// Computed Values & Helper Functions
+// =============================================================================
+
+/**
+ * Check if any social providers are configured (server-side)
+ */
+export const hasSocialProviders = (): boolean => {
+ return !!(
+ GOOGLE_CLIENT_ID ||
+ GITHUB_CLIENT_ID ||
+ DISCORD_CLIENT_ID ||
+ (CUSTOM_OIDC_ENABLED && CUSTOM_OIDC_CLIENT_ID)
+ );
+};
+
+/**
+ * Get list of enabled social providers (server-side)
+ */
+export const getEnabledProviders = (): string[] => {
+ const providers: string[] = [];
+
+ if (GOOGLE_CLIENT_ID) providers.push("google");
+ if (GITHUB_CLIENT_ID) providers.push("github");
+ if (DISCORD_CLIENT_ID) providers.push("discord");
+ if (CUSTOM_OIDC_ENABLED && CUSTOM_OIDC_CLIENT_ID)
+ providers.push("custom-oidc");
+
+ return providers;
+};
+
+/**
+ * Validate that required auth environment variables are set
+ * (only if auth is enabled)
+ */
+export const validateAuthEnv = (): {
+ valid: boolean;
+ errors: string[];
+} => {
+ if (!AUTH_ENABLED) {
+ return { valid: true, errors: [] };
+ }
+
+ const errors: string[] = [];
+
+ // Check required core settings
+ if (!BETTER_AUTH_SECRET) {
+ errors.push(
+ "BETTER_AUTH_SECRET is required when auth is enabled. Generate with: npx @better-auth/cli secret"
+ );
+ }
+
+ if (!BETTER_AUTH_URL) {
+ errors.push("BETTER_AUTH_URL is required when auth is enabled");
+ }
+
+ // Check that at least one auth method is available
+ const hasEmailPassword = true; // Always enabled
+ const hasSocial = hasSocialProviders();
+
+ if (!hasEmailPassword && !hasSocial) {
+ errors.push(
+ "At least one authentication method must be configured (email/password or social provider)"
+ );
+ }
+
+ // Validate OAuth provider configuration
+ if (GOOGLE_CLIENT_ID && !GOOGLE_CLIENT_SECRET) {
+ errors.push(
+ "GOOGLE_CLIENT_SECRET is required when GOOGLE_CLIENT_ID is set"
+ );
+ }
+
+ if (GITHUB_CLIENT_ID && !GITHUB_CLIENT_SECRET) {
+ errors.push(
+ "GITHUB_CLIENT_SECRET is required when GITHUB_CLIENT_ID is set"
+ );
+ }
+
+ if (DISCORD_CLIENT_ID && !DISCORD_CLIENT_SECRET) {
+ errors.push(
+ "DISCORD_CLIENT_SECRET is required when DISCORD_CLIENT_ID is set"
+ );
+ }
+
+ if (CUSTOM_OIDC_ENABLED) {
+ if (!CUSTOM_OIDC_ISSUER) {
+ errors.push(
+ "CUSTOM_OIDC_ISSUER is required when CUSTOM_OIDC_ENABLED=true"
+ );
+ }
+ if (!CUSTOM_OIDC_CLIENT_ID) {
+ errors.push(
+ "CUSTOM_OIDC_CLIENT_ID is required when CUSTOM_OIDC_ENABLED=true"
+ );
+ }
+ if (!CUSTOM_OIDC_CLIENT_SECRET) {
+ errors.push(
+ "CUSTOM_OIDC_CLIENT_SECRET is required when CUSTOM_OIDC_ENABLED=true"
+ );
+ }
+ }
+
+ return {
+ valid: errors.length === 0,
+ errors,
+ };
+};
diff --git a/lib/auth/feature-flags.ts b/lib/auth/feature-flags.ts
new file mode 100644
index 0000000..8f891e1
--- /dev/null
+++ b/lib/auth/feature-flags.ts
@@ -0,0 +1,66 @@
+/**
+ * Feature flags for authentication system
+ *
+ * Controls whether the auth system is enabled or disabled.
+ * When disabled, the app operates in single-user mode (backwards compatible).
+ *
+ * This module provides SERVER-SIDE feature flag checks.
+ * For CLIENT components, use @/hooks/useAuthFeatures instead.
+ */
+
+import {
+ AUTH_ENABLED,
+ ALLOW_USER_REGISTRATION,
+ ALLOW_GUEST_ACCESS,
+ CUSTOM_OIDC_NAME,
+ hasSocialProviders as hasSocialProvidersEnv,
+ getEnabledProviders as getEnabledProvidersEnv,
+} from "./env";
+
+/**
+ * Server-side: Check if auth system is enabled
+ */
+export const isAuthEnabled = (): boolean => {
+ return AUTH_ENABLED;
+};
+
+/**
+ * Server-side: Check if user registration is allowed
+ */
+export const allowUserRegistration = (): boolean => {
+ if (!isAuthEnabled()) return false;
+ return ALLOW_USER_REGISTRATION;
+};
+
+/**
+ * Server-side: Check if guest access is allowed
+ * Returns true if auth is disabled (entire system public) OR if guest access is explicitly enabled
+ */
+export const allowGuestAccess = (): boolean => {
+ // If auth is disabled, everything is public (backward compatibility)
+ if (!isAuthEnabled()) return true;
+
+ // If auth is enabled, check explicit guest access flag
+ return ALLOW_GUEST_ACCESS;
+};
+
+/**
+ * Server-side: Check if any social providers are configured
+ */
+export const hasSocialProviders = (): boolean => {
+ return hasSocialProvidersEnv();
+};
+
+/**
+ * Server-side: Get list of enabled social providers
+ */
+export const getEnabledProviders = (): string[] => {
+ return getEnabledProvidersEnv();
+};
+
+/**
+ * Server-side: Get display name for custom OIDC provider
+ */
+export const getCustomOIDCName = (): string => {
+ return CUSTOM_OIDC_NAME;
+};
diff --git a/lib/auth/first-user.ts b/lib/auth/first-user.ts
new file mode 100644
index 0000000..22d388b
--- /dev/null
+++ b/lib/auth/first-user.ts
@@ -0,0 +1,66 @@
+/**
+ * First User Auto-Promotion
+ *
+ * Handles automatic promotion of the first registered user to superadmin role.
+ * This ensures there's always at least one admin user who can access the admin panel
+ * and manage orphaned calendars.
+ */
+
+import { db } from "@/lib/db";
+import { user } from "@/lib/db/schema";
+import { eq } from "drizzle-orm";
+import { logAuditEvent } from "@/lib/audit-log";
+
+/**
+ * Check if this is the only user in the database (i.e., the first user)
+ * @param currentUserId - The ID of the current user to exclude from count
+ * @returns Promise<boolean> - true if this is the only user (first user)
+ */
+export async function isFirstUser(currentUserId: string): Promise<boolean> {
+ const users = await db.select({ id: user.id }).from(user).limit(2);
+ // First user if only one user exists and it's the current user
+ return users.length === 1 && users[0].id === currentUserId;
+}
+
+/**
+ * Promote a user to superadmin role
+ * This should only be called for the first registered user
+ *
+ * @param userId - The ID of the user to promote
+ * @returns Promise<void>
+ */
+export async function promoteToSuperAdmin(userId: string): Promise<void> {
+ await db.update(user).set({ role: "superadmin" }).where(eq(user.id, userId));
+
+ // Log the promotion to audit log
+ await logAuditEvent({
+ userId,
+ action: "user_promoted_to_superadmin",
+ resourceType: "user",
+ resourceId: userId,
+ severity: "info",
+ metadata: {
+ reason: "First user registration - automatic superadmin promotion",
+ },
+ });
+}
+
+/**
+ * Check if this is the first user and promote them to superadmin if true
+ * This is called from the Better Auth after hook during sign-up
+ *
+ * @param userId - The ID of the newly registered user
+ * @returns Promise<boolean> - true if user was promoted, false otherwise
+ */
+export async function handleFirstUserPromotion(
+ userId: string
+): Promise<boolean> {
+ const isFirst = await isFirstUser(userId);
+
+ if (isFirst) {
+ await promoteToSuperAdmin(userId);
+ return true;
+ }
+
+ return false;
+}
diff --git a/lib/auth/index.ts b/lib/auth/index.ts
new file mode 100644
index 0000000..6152f51
--- /dev/null
+++ b/lib/auth/index.ts
@@ -0,0 +1,84 @@
+/**
+ * Better Auth server configuration
+ *
+ * This is the main auth instance used by:
+ * - API route handler (/api/auth/[...all])
+ * - Server-side authentication checks
+ * - Middleware
+ */
+
+import { betterAuth } from "better-auth";
+import { drizzleAdapter } from "better-auth/adapters/drizzle";
+import { db } from "@/lib/db";
+import * as schema from "@/lib/db/schema";
+import {
+ AUTH_ENABLED,
+ GOOGLE_CLIENT_ID,
+ GOOGLE_CLIENT_SECRET,
+ GITHUB_CLIENT_ID,
+ GITHUB_CLIENT_SECRET,
+ DISCORD_CLIENT_ID,
+ DISCORD_CLIENT_SECRET,
+ SESSION_MAX_AGE,
+ SESSION_UPDATE_AGE,
+ BETTER_AUTH_TRUSTED_ORIGINS,
+} from "./env";
+
+// Only initialize Better Auth if auth is enabled
+export const auth = AUTH_ENABLED
+ ? betterAuth({
+ database: drizzleAdapter(db, {
+ provider: "sqlite",
+ schema: {
+ user: schema.user,
+ session: schema.session,
+ account: schema.account,
+ verification: schema.verification,
+ },
+ }),
+ emailAndPassword: {
+ enabled: true,
+ },
+ socialProviders: {
+ google: GOOGLE_CLIENT_ID
+ ? {
+ clientId: GOOGLE_CLIENT_ID,
+ clientSecret: GOOGLE_CLIENT_SECRET,
+ }
+ : undefined,
+ github: GITHUB_CLIENT_ID
+ ? {
+ clientId: GITHUB_CLIENT_ID,
+ clientSecret: GITHUB_CLIENT_SECRET,
+ }
+ : undefined,
+ discord: DISCORD_CLIENT_ID
+ ? {
+ clientId: DISCORD_CLIENT_ID,
+ clientSecret: DISCORD_CLIENT_SECRET,
+ }
+ : undefined,
+ },
+ session: {
+ expiresIn: SESSION_MAX_AGE,
+ updateAge: SESSION_UPDATE_AGE,
+ },
+ trustedOrigins:
+ BETTER_AUTH_TRUSTED_ORIGINS.length > 0
+ ? BETTER_AUTH_TRUSTED_ORIGINS
+ : undefined,
+ })
+ : // Fallback mock when auth is disabled
+ ({
+ handler: async () => new Response("Auth disabled", { status: 404 }),
+ api: {},
+ $Infer: {} as { Session: { user: Record<string, unknown> } },
+ } as {
+ handler: () => Promise<Response>;
+ api: Record<string, unknown>;
+ $Infer: { Session: { user: Record<string, unknown> } };
+ });
+
+// Export types for TypeScript
+export type Session = (typeof auth)["$Infer"]["Session"];
+export type User = (typeof auth)["$Infer"]["Session"]["user"];
diff --git a/lib/auth/permissions.ts b/lib/auth/permissions.ts
new file mode 100644
index 0000000..9feff34
--- /dev/null
+++ b/lib/auth/permissions.ts
@@ -0,0 +1,497 @@
+import { db } from "@/lib/db";
+import {
+ calendars,
+ calendarShares,
+ userCalendarSubscriptions,
+} from "@/lib/db/schema";
+import { eq, and, isNull } from "drizzle-orm";
+import { allowGuestAccess, isAuthEnabled } from "@/lib/auth/feature-flags";
+import {
+ getTokenPermission,
+ getTokensFromCookie,
+ validateAccessToken,
+} from "@/lib/auth/token-auth";
+
+/**
+ * Calendar permission levels
+ * - owner: Full control, can delete calendar
+ * - admin: Can manage calendar settings and shares
+ * - write: Can create/edit/delete shifts, presets, notes
+ * - read: Can only view calendar data
+ */
+export type CalendarPermission = "owner" | "admin" | "write" | "read";
+
+/**
+ * Guest permission levels (subset of CalendarPermission)
+ * - none: No guest access
+ * - read: Guests can view calendar data
+ * - write: Guests can create/edit/delete shifts, presets, notes
+ */
+export type GuestPermission = "none" | "read" | "write";
+
+/**
+ * Get user's permission level for a specific calendar
+ * Returns null if user has no access to the calendar
+ *
+ * Permission priority (highest to lowest):
+ * 1. Owner (calendar.ownerId matches userId)
+ * 2. Shared permission (via calendarShares)
+ * 3. Access token (via cookie)
+ * 4. Public/Guest permission (for subscribed users or when guest access enabled)
+ *
+ * For guest users (userId = null), checks:
+ * - Access token permission
+ * - Guest permission (if auth enabled + guest access enabled + calendar allows it)
+ */
+export async function getUserCalendarPermission(
+ userId: string | null | undefined,
+ calendarId: string
+): Promise<CalendarPermission | null> {
+ // If auth is disabled, grant full owner access (backwards compatibility)
+ if (!isAuthEnabled()) {
+ const calendar = await db.query.calendars.findFirst({
+ where: eq(calendars.id, calendarId),
+ });
+ return calendar ? "owner" : null;
+ }
+
+ // Fetch calendar first (needed for all checks)
+ const calendar = await db.query.calendars.findFirst({
+ where: eq(calendars.id, calendarId),
+ });
+
+ if (!calendar) {
+ return null;
+ }
+
+ // CRITICAL: Orphaned calendars (ownerId=null) are invisible to ALL users
+ // They can only be accessed via dedicated admin panel API routes
+ if (calendar.ownerId === null) {
+ return null;
+ }
+
+ // If no user ID, check token and guest permissions
+ if (!userId) {
+ // Check for access token first (higher priority than guest)
+ const tokenPermission = await getTokenPermission(calendarId);
+ if (tokenPermission) {
+ return tokenPermission;
+ }
+
+ // Guest access only works when explicitly enabled
+ if (allowGuestAccess() && calendar.guestPermission !== "none") {
+ return calendar.guestPermission as CalendarPermission;
+ }
+ return null;
+ }
+
+ // Owner has full control
+ if (calendar.ownerId === userId) {
+ return "owner";
+ }
+
+ // Check shared permissions (higher priority than tokens)
+ const share = await db.query.calendarShares.findFirst({
+ where: and(
+ eq(calendarShares.calendarId, calendarId),
+ eq(calendarShares.userId, userId)
+ ),
+ });
+
+ if (share) {
+ return share.permission as CalendarPermission;
+ }
+
+ // Check for access token (authenticated users can also use tokens)
+ const tokenPermission = await getTokenPermission(calendarId);
+ if (tokenPermission) {
+ return tokenPermission;
+ }
+
+ // Check if user is subscribed to this public calendar
+ const subscription = await db.query.userCalendarSubscriptions.findFirst({
+ where: and(
+ eq(userCalendarSubscriptions.calendarId, calendarId),
+ eq(userCalendarSubscriptions.userId, userId),
+ eq(userCalendarSubscriptions.status, "subscribed")
+ ),
+ });
+
+ // If subscribed and calendar has public access (guestPermission != "none"), return that permission
+ // Authenticated users can always access public calendars, regardless of allowGuestAccess setting
+ if (subscription && calendar.guestPermission !== "none") {
+ return calendar.guestPermission as CalendarPermission;
+ }
+
+ return null;
+}
+
+/**
+ * Check if user has at least the required permission level
+ */
+export async function checkPermission(
+ userId: string | null | undefined,
+ calendarId: string,
+ required: CalendarPermission
+): Promise<boolean> {
+ const userPermission = await getUserCalendarPermission(userId, calendarId);
+
+ if (!userPermission) {
+ return false;
+ }
+
+ // Permission hierarchy: owner > admin > write > read
+ const hierarchy: CalendarPermission[] = ["owner", "admin", "write", "read"];
+ const userLevel = hierarchy.indexOf(userPermission);
+ const requiredLevel = hierarchy.indexOf(required);
+
+ return userLevel <= requiredLevel;
+}
+
+/**
+ * Check if user can view a calendar
+ */
+export async function canViewCalendar(
+ userId: string | null | undefined,
+ calendarId: string
+): Promise<boolean> {
+ return checkPermission(userId, calendarId, "read");
+}
+
+/**
+ * Check if user can edit calendar data (shifts, presets, notes)
+ */
+export async function canEditCalendar(
+ userId: string | null | undefined,
+ calendarId: string
+): Promise<boolean> {
+ return checkPermission(userId, calendarId, "write");
+}
+
+/**
+ * Check if user can manage calendar settings and shares
+ */
+export async function canManageCalendar(
+ userId: string | null | undefined,
+ calendarId: string
+): Promise<boolean> {
+ return checkPermission(userId, calendarId, "admin");
+}
+
+/**
+ * Check if user can delete the calendar (owner only)
+ */
+export async function canDeleteCalendar(
+ userId: string | null | undefined,
+ calendarId: string
+): Promise<boolean> {
+ return checkPermission(userId, calendarId, "owner");
+}
+
+/**
+ * Get all calendar IDs accessible to a user (or guest)
+ * Returns array of calendar IDs with their permission levels
+ *
+ * For guest users (userId = null), returns:
+ * - Calendars accessible via access tokens (always, regardless of allowGuestAccess)
+ * - Calendars with guestPermission != "none" (only if guest access is enabled)
+ */
+export async function getUserAccessibleCalendars(
+ userId: string | null | undefined
+): Promise<Array<{ id: string; permission: CalendarPermission }>> {
+ // If auth is disabled, return all calendars with owner permission (backwards compatibility)
+ if (!isAuthEnabled()) {
+ const allCalendars = await db.query.calendars.findMany();
+ return allCalendars.map((cal) => ({
+ id: cal.id,
+ permission: "owner" as const,
+ }));
+ }
+
+ // Guest access: return calendars accessible via tokens or guest permissions
+ if (!userId) {
+ const results: Array<{ id: string; permission: CalendarPermission }> = [];
+ const existingIds = new Set<string>();
+
+ // First, check for token-based access (always works, regardless of allowGuestAccess)
+ const tokens = await getTokensFromCookie();
+ for (const tokenData of tokens) {
+ // Validate token is still valid
+ const validation = await validateAccessToken(tokenData.token);
+ if (validation && validation.calendarId === tokenData.calendarId) {
+ results.push({
+ id: tokenData.calendarId,
+ permission: tokenData.permission as CalendarPermission,
+ });
+ existingIds.add(tokenData.calendarId);
+ }
+ }
+
+ // Then, check for guest permissions (only if guest access is enabled)
+ if (allowGuestAccess()) {
+ const guestAccessibleCalendars = await db.query.calendars.findMany({
+ where: (calendars, { ne }) => ne(calendars.guestPermission, "none"),
+ });
+
+ for (const cal of guestAccessibleCalendars) {
+ if (!existingIds.has(cal.id)) {
+ results.push({
+ id: cal.id,
+ permission: cal.guestPermission as CalendarPermission,
+ });
+ existingIds.add(cal.id);
+ }
+ }
+ }
+
+ return results;
+ }
+
+ const results: Array<{ id: string; permission: CalendarPermission }> = [];
+
+ // Get owned calendars (ALWAYS visible, cannot be dismissed)
+ const ownedCalendars = await db.query.calendars.findMany({
+ where: eq(calendars.ownerId, userId),
+ });
+
+ results.push(
+ ...ownedCalendars.map((cal) => ({
+ id: cal.id,
+ permission: "owner" as const,
+ }))
+ );
+
+ // Get all subscriptions for this user (including dismissed)
+ const subscriptions = await db.query.userCalendarSubscriptions.findMany({
+ where: eq(userCalendarSubscriptions.userId, userId),
+ with: {
+ calendar: true,
+ },
+ });
+
+ // Get shared calendars (not owned by user)
+ const sharedCalendars = await db.query.calendarShares.findMany({
+ where: eq(calendarShares.userId, userId),
+ with: {
+ calendar: true,
+ },
+ });
+
+ // Track which calendars exist to prevent duplicates
+ const existingIds = new Set(results.map((r) => r.id));
+
+ // Add shared calendars (share permission takes precedence over guest permission)
+ for (const share of sharedCalendars) {
+ if (existingIds.has(share.calendarId)) continue; // Skip if owned
+
+ // Check if user has dismissed this shared calendar
+ const isDismissed = subscriptions.find(
+ (sub) => sub.calendarId === share.calendarId && sub.status === "dismissed"
+ );
+
+ if (!isDismissed) {
+ results.push({
+ id: share.calendarId,
+ permission: share.permission as CalendarPermission,
+ });
+ existingIds.add(share.calendarId);
+ }
+ }
+
+ // Add guest-subscribed calendars (only if not already included via shares and not dismissed)
+ for (const sub of subscriptions) {
+ if (existingIds.has(sub.calendarId)) continue;
+ if (sub.calendar.guestPermission === "none") continue;
+ if (sub.source !== "guest") continue;
+ if (sub.status === "dismissed") continue; // Skip dismissed guest subscriptions
+
+ results.push({
+ id: sub.calendarId,
+ permission: sub.calendar.guestPermission as CalendarPermission,
+ });
+ existingIds.add(sub.calendarId);
+ }
+
+ // Add token-accessible calendars (authenticated users can also use access tokens)
+ const tokens = await getTokensFromCookie();
+ for (const tokenData of tokens) {
+ if (existingIds.has(tokenData.calendarId)) continue;
+
+ // Validate token is still valid
+ const validation = await validateAccessToken(tokenData.token);
+ if (validation && validation.calendarId === tokenData.calendarId) {
+ results.push({
+ id: tokenData.calendarId,
+ permission: tokenData.permission as CalendarPermission,
+ });
+ existingIds.add(tokenData.calendarId);
+ }
+ }
+
+ return results;
+}
+
+/**
+ * Check if a calendar is dismissed by the user
+ */
+export async function isCalendarDismissed(
+ userId: string,
+ calendarId: string
+): Promise<boolean> {
+ const subscription = await db.query.userCalendarSubscriptions.findFirst({
+ where: and(
+ eq(userCalendarSubscriptions.userId, userId),
+ eq(userCalendarSubscriptions.calendarId, calendarId),
+ eq(userCalendarSubscriptions.status, "dismissed")
+ ),
+ });
+
+ return !!subscription;
+}
+
+/**
+ * Dismiss/Unsubscribe from a calendar (hide it from view)
+ * - Throws error if user tries to dismiss their own calendar
+ * - For shared calendars: creates/updates subscription with status="dismissed", source="shared"
+ * - For guest-subscribed calendars: updates subscription to status="dismissed"
+ */
+export async function dismissCalendar(
+ userId: string,
+ calendarId: string
+): Promise<void> {
+ // Check if user owns the calendar
+ const calendar = await db.query.calendars.findFirst({
+ where: eq(calendars.id, calendarId),
+ });
+
+ if (!calendar) {
+ throw new Error("Calendar not found");
+ }
+
+ if (calendar.ownerId === userId) {
+ throw new Error("Cannot dismiss your own calendar");
+ }
+
+ // Check if it's a shared calendar
+ const share = await db.query.calendarShares.findFirst({
+ where: and(
+ eq(calendarShares.calendarId, calendarId),
+ eq(calendarShares.userId, userId)
+ ),
+ });
+
+ // Check if subscription already exists
+ const existingSub = await db.query.userCalendarSubscriptions.findFirst({
+ where: and(
+ eq(userCalendarSubscriptions.userId, userId),
+ eq(userCalendarSubscriptions.calendarId, calendarId)
+ ),
+ });
+
+ if (existingSub) {
+ // Update existing subscription to dismissed
+ await db
+ .update(userCalendarSubscriptions)
+ .set({
+ status: "dismissed",
+ source: share ? "shared" : "guest",
+ updatedAt: new Date(),
+ })
+ .where(eq(userCalendarSubscriptions.id, existingSub.id));
+ } else {
+ // Create new dismissal entry
+ await db.insert(userCalendarSubscriptions).values({
+ userId,
+ calendarId,
+ status: "dismissed",
+ source: share ? "shared" : "guest",
+ });
+ }
+}
+
+/**
+ * Re-subscribe to a dismissed calendar
+ * - For shared calendars: updates status to "subscribed"
+ * - For public calendars: updates/creates subscription with status="subscribed", source="guest"
+ */
+export async function undismissCalendar(
+ userId: string,
+ calendarId: string
+): Promise<void> {
+ const calendar = await db.query.calendars.findFirst({
+ where: eq(calendars.id, calendarId),
+ });
+
+ if (!calendar) {
+ throw new Error("Calendar not found");
+ }
+
+ if (calendar.ownerId === userId) {
+ throw new Error("Cannot subscribe to your own calendar");
+ }
+
+ // Check if it's a shared calendar
+ const share = await db.query.calendarShares.findFirst({
+ where: and(
+ eq(calendarShares.calendarId, calendarId),
+ eq(calendarShares.userId, userId)
+ ),
+ });
+
+ // For guest calendars, verify it's public
+ if (!share && calendar.guestPermission === "none") {
+ throw new Error("Calendar is not public");
+ }
+
+ // Check if subscription exists
+ const existingSub = await db.query.userCalendarSubscriptions.findFirst({
+ where: and(
+ eq(userCalendarSubscriptions.userId, userId),
+ eq(userCalendarSubscriptions.calendarId, calendarId)
+ ),
+ });
+
+ if (existingSub) {
+ // Update to subscribed
+ await db
+ .update(userCalendarSubscriptions)
+ .set({
+ status: "subscribed",
+ source: share ? "shared" : "guest",
+ updatedAt: new Date(),
+ })
+ .where(eq(userCalendarSubscriptions.id, existingSub.id));
+ } else {
+ // Create new subscription
+ await db.insert(userCalendarSubscriptions).values({
+ userId,
+ calendarId,
+ status: "subscribed",
+ source: share ? "shared" : "guest",
+ });
+ }
+}
+
+/**
+ * Get all orphaned calendars (calendars with ownerId=null)
+ * ADMIN-ONLY function - must check admin permissions before calling
+ *
+ * This function is used exclusively by the Admin Panel to list calendars
+ * that need owner assignment. Normal calendar APIs exclude these calendars.
+ *
+ * @returns Promise<Array> - List of orphaned calendars with basic info
+ */
+export async function getOrphanedCalendars() {
+ const orphanedCalendars = await db.query.calendars.findMany({
+ where: isNull(calendars.ownerId),
+ columns: {
+ id: true,
+ name: true,
+ color: true,
+ createdAt: true,
+ updatedAt: true,
+ },
+ });
+
+ return orphanedCalendars;
+}
diff --git a/lib/auth/sessions.ts b/lib/auth/sessions.ts
new file mode 100644
index 0000000..b12e76c
--- /dev/null
+++ b/lib/auth/sessions.ts
@@ -0,0 +1,164 @@
+import { db } from "@/lib/db";
+import { session } from "@/lib/db/schema";
+import { eq, and, desc, ne } from "drizzle-orm";
+import { UAParser } from "ua-parser-js";
+import { auth } from "@/lib/auth";
+import { isAuthEnabled } from "@/lib/auth/feature-flags";
+
+// =====================================================
+// Current Session Context (Request-scoped)
+// =====================================================
+
+/**
+ * Get current user session from request headers
+ * Returns null if auth is disabled or user is not authenticated
+ */
+export async function getSessionUser(
+ headers: Headers
+): Promise<{ id: string; email: string; name: string } | null> {
+ // If auth is disabled, return null (single-user mode)
+ if (!isAuthEnabled()) {
+ return null;
+ }
+
+ try {
+ const session = await auth.api.getSession({ headers });
+ return session?.user || null;
+ } catch (error) {
+ console.error("Failed to get session:", error);
+ return null;
+ }
+}
+
+/**
+ * Check if user is authenticated
+ * When auth is disabled, always returns true (backwards compatibility)
+ */
+export async function isAuthenticated(headers: Headers): Promise<boolean> {
+ // If auth is disabled, always allow (single-user mode)
+ if (!isAuthEnabled()) {
+ return true;
+ }
+
+ const user = await getSessionUser(headers);
+ return user !== null;
+}
+
+// =====================================================
+// Session Management (Multi-device, User-scoped)
+// =====================================================
+
+/**
+ * Parsed session information with device details
+ */
+export interface ParsedSession {
+ id: string;
+ deviceName: string; // e.g., "Chrome on Windows"
+ browser: string; // e.g., "Chrome 120.0"
+ os: string; // e.g., "Windows 10"
+ deviceType: string; // "desktop" | "mobile" | "tablet" | "unknown"
+ ipAddress: string | null;
+ lastActive: Date;
+ createdAt: Date;
+ expiresAt: Date;
+}
+
+/**
+ * Parse user agent string into human-readable device information
+ */
+function parseUserAgent(userAgent: string | null): {
+ browser: string;
+ os: string;
+ deviceType: string;
+ deviceName: string;
+} {
+ if (!userAgent) {
+ return {
+ browser: "Unknown Browser",
+ os: "Unknown OS",
+ deviceType: "unknown",
+ deviceName: "Unknown Device",
+ };
+ }
+
+ const parser = new UAParser(userAgent);
+ const browserData = parser.getBrowser();
+ const osData = parser.getOS();
+ const deviceData = parser.getDevice();
+
+ const browser = browserData.name
+ ? `${browserData.name}${
+ browserData.version ? ` ${browserData.version.split(".")[0]}` : ""
+ }`
+ : "Unknown Browser";
+
+ const os = osData.name
+ ? `${osData.name}${osData.version ? ` ${osData.version}` : ""}`
+ : "Unknown OS";
+
+ const deviceType = deviceData.type || "desktop";
+
+ const deviceName = `${browser} on ${os}`;
+
+ return {
+ browser,
+ os,
+ deviceType,
+ deviceName,
+ };
+}
+
+/**
+ * Get all active sessions for a user with parsed device information
+ */
+export async function getUserSessions(
+ userId: string
+): Promise<ParsedSession[]> {
+ const sessions = await db
+ .select()
+ .from(session)
+ .where(eq(session.userId, userId))
+ .orderBy(desc(session.updatedAt));
+
+ return sessions.map((s) => {
+ const parsed = parseUserAgent(s.userAgent);
+
+ return {
+ id: s.id,
+ deviceName: parsed.deviceName,
+ browser: parsed.browser,
+ os: parsed.os,
+ deviceType: parsed.deviceType,
+ ipAddress: s.ipAddress,
+ lastActive: new Date(s.updatedAt),
+ createdAt: new Date(s.createdAt),
+ expiresAt: new Date(s.expiresAt),
+ };
+ });
+}
+
+/**
+ * Revoke all sessions for a user, optionally keeping the current session active
+ */
+export async function revokeAllSessions(
+ userId: string,
+ exceptSessionId?: string
+): Promise<number> {
+ let result;
+
+ if (exceptSessionId) {
+ // Delete all sessions EXCEPT the specified one
+ result = await db
+ .delete(session)
+ .where(and(eq(session.userId, userId), ne(session.id, exceptSessionId)))
+ .returning();
+ } else {
+ // Delete all sessions
+ result = await db
+ .delete(session)
+ .where(eq(session.userId, userId))
+ .returning();
+ }
+
+ return result.length;
+}
diff --git a/lib/auth/token-auth.ts b/lib/auth/token-auth.ts
new file mode 100644
index 0000000..4c67253
--- /dev/null
+++ b/lib/auth/token-auth.ts
@@ -0,0 +1,347 @@
+import { db } from "@/lib/db";
+import { calendarAccessTokens, calendars } from "@/lib/db/schema";
+import { eq } from "drizzle-orm";
+import { NextRequest, NextResponse } from "next/server";
+import { cookies } from "next/headers";
+
+/**
+ * Cookie name for storing validated access tokens
+ */
+const TOKEN_COOKIE_NAME = "calendar_access_tokens";
+
+/**
+ * Cookie options for token storage
+ */
+const TOKEN_COOKIE_OPTIONS = {
+ httpOnly: true,
+ secure: process.env.NODE_ENV === "production",
+ sameSite: "lax" as const,
+ maxAge: 60 * 60 * 24 * 90, // 90 days
+ path: "/",
+};
+
+/**
+ * Type for token data stored in cookie
+ */
+export interface TokenCookieData {
+ token: string;
+ calendarId: string;
+ permission: "read" | "write";
+}
+
+/**
+ * Validate an access token
+ * Checks: exists, active, not expired
+ *
+ * @param token - The token string to validate
+ * @param skipActiveCheck - If true, only checks expiration (for cookie cleanup)
+ * @returns Token data if valid, null otherwise
+ */
+export async function validateAccessToken(
+ token: string,
+ skipActiveCheck = false
+): Promise<{
+ id: string;
+ calendarId: string;
+ permission: "read" | "write";
+ calendarName: string;
+} | null> {
+ try {
+ const [tokenData] = await db
+ .select({
+ id: calendarAccessTokens.id,
+ calendarId: calendarAccessTokens.calendarId,
+ permission: calendarAccessTokens.permission,
+ expiresAt: calendarAccessTokens.expiresAt,
+ isActive: calendarAccessTokens.isActive,
+ calendarName: calendars.name,
+ })
+ .from(calendarAccessTokens)
+ .innerJoin(calendars, eq(calendarAccessTokens.calendarId, calendars.id))
+ .where(eq(calendarAccessTokens.token, token))
+ .limit(1);
+
+ if (!tokenData) {
+ return null;
+ }
+
+ // Check if token is expired (always check)
+ if (tokenData.expiresAt && new Date(tokenData.expiresAt) < new Date()) {
+ return null;
+ }
+
+ // Check if token is active (skip for cookie cleanup)
+ if (!skipActiveCheck && !tokenData.isActive) {
+ return null;
+ }
+
+ return {
+ id: tokenData.id,
+ calendarId: tokenData.calendarId,
+ permission: tokenData.permission as "read" | "write",
+ calendarName: tokenData.calendarName,
+ };
+ } catch (error) {
+ console.error("[token-auth] validateAccessToken error:", error);
+ return null;
+ }
+}
+
+/**
+ * Update token usage statistics (non-blocking)
+ * Updates lastUsedAt and increments usageCount
+ *
+ * @param tokenId - The token ID to update
+ */
+export async function updateTokenUsage(tokenId: string): Promise<void> {
+ // Fire and forget - don't block the request
+ void (async () => {
+ try {
+ // Fetch current usage count
+ const [currentToken] = await db
+ .select({ usageCount: calendarAccessTokens.usageCount })
+ .from(calendarAccessTokens)
+ .where(eq(calendarAccessTokens.id, tokenId))
+ .limit(1);
+
+ if (!currentToken) return;
+
+ await db
+ .update(calendarAccessTokens)
+ .set({
+ lastUsedAt: new Date(),
+ usageCount: currentToken.usageCount + 1,
+ })
+ .where(eq(calendarAccessTokens.id, tokenId));
+ } catch (error) {
+ console.error("[token-auth] updateTokenUsage error:", error);
+ }
+ })();
+}
+
+/**
+ * Store a validated token in a cookie
+ *
+ * @param token - The token string
+ * @param calendarId - The calendar ID
+ * @param permission - The permission level
+ * @param response - The NextResponse to set the cookie on
+ * @param request - Optional NextRequest to read existing tokens from
+ */
+export function storeTokenInCookie(
+ token: string,
+ calendarId: string,
+ permission: "read" | "write",
+ response: NextResponse,
+ request?: NextRequest
+): void {
+ try {
+ // Get existing tokens from request (if provided) or response
+ const existingTokens = request
+ ? getTokensFromRequest(request)
+ : getTokensFromResponse(response);
+
+ // Check if this token already exists
+ const tokenExists = existingTokens.some((t) => t.token === token);
+
+ if (!tokenExists) {
+ // Add new token
+ const newTokens: TokenCookieData[] = [
+ ...existingTokens,
+ { token, calendarId, permission },
+ ];
+
+ // Store in cookie
+ response.cookies.set(
+ TOKEN_COOKIE_NAME,
+ JSON.stringify(newTokens),
+ TOKEN_COOKIE_OPTIONS
+ );
+ }
+ } catch (error) {
+ console.error("[token-auth] storeTokenInCookie error:", error);
+ }
+}
+
+/**
+ * Get all validated tokens from cookie (for Server Components)
+ * Also removes expired tokens from the cookie (but keeps inactive ones)
+ *
+ * @returns Array of token data
+ */
+export async function getTokensFromCookie(): Promise<TokenCookieData[]> {
+ try {
+ const cookieStore = await cookies();
+ const tokenCookie = cookieStore.get(TOKEN_COOKIE_NAME);
+
+ if (!tokenCookie?.value) {
+ return [];
+ }
+
+ const tokens = JSON.parse(tokenCookie.value) as TokenCookieData[];
+
+ // Validate structure
+ if (!Array.isArray(tokens)) {
+ return [];
+ }
+
+ const validTokens = tokens.filter(
+ (t) =>
+ typeof t.token === "string" &&
+ typeof t.calendarId === "string" &&
+ (t.permission === "read" || t.permission === "write")
+ );
+
+ // Validate each token against the database
+ // Note: We skip the isActive check - only remove expired tokens
+ // This allows owners to reactivate tokens without users losing access
+ const validatedTokens: TokenCookieData[] = [];
+ let hasExpiredTokens = false;
+
+ for (const tokenData of validTokens) {
+ // skipActiveCheck = true: Only check expiration, not isActive
+ const validation = await validateAccessToken(tokenData.token, true);
+ if (validation) {
+ validatedTokens.push(tokenData);
+ } else {
+ // Token is expired or doesn't exist - remove from cookie
+ hasExpiredTokens = true;
+ }
+ }
+
+ // If we found expired tokens, update the cookie to remove them
+ if (hasExpiredTokens && validatedTokens.length !== validTokens.length) {
+ cookieStore.set(
+ TOKEN_COOKIE_NAME,
+ JSON.stringify(validatedTokens),
+ TOKEN_COOKIE_OPTIONS
+ );
+ }
+
+ return validatedTokens;
+ } catch (error) {
+ console.error("[token-auth] getTokensFromCookie error:", error);
+ return [];
+ }
+}
+
+/**
+ * Get tokens from a NextRequest (for middleware)
+ *
+ * @param request - The NextRequest object
+ * @returns Array of token data
+ */
+export function getTokensFromRequest(request: NextRequest): TokenCookieData[] {
+ try {
+ const tokenCookie = request.cookies.get(TOKEN_COOKIE_NAME);
+
+ if (!tokenCookie?.value) {
+ return [];
+ }
+
+ const tokens = JSON.parse(tokenCookie.value) as TokenCookieData[];
+
+ // Validate structure
+ if (!Array.isArray(tokens)) {
+ return [];
+ }
+
+ return tokens.filter(
+ (t) =>
+ typeof t.token === "string" &&
+ typeof t.calendarId === "string" &&
+ (t.permission === "read" || t.permission === "write")
+ );
+ } catch (error) {
+ console.error("[token-auth] getTokensFromRequest error:", error);
+ return [];
+ }
+}
+
+/**
+ * Get tokens from a NextResponse (for middleware)
+ *
+ * @param response - The NextResponse object
+ * @returns Array of token data
+ */
+function getTokensFromResponse(response: NextResponse): TokenCookieData[] {
+ try {
+ const tokenCookie = response.cookies.get(TOKEN_COOKIE_NAME);
+
+ if (!tokenCookie?.value) {
+ return [];
+ }
+
+ const tokens = JSON.parse(tokenCookie.value) as TokenCookieData[];
+
+ // Validate structure
+ if (!Array.isArray(tokens)) {
+ return [];
+ }
+
+ return tokens.filter(
+ (t) =>
+ typeof t.token === "string" &&
+ typeof t.calendarId === "string" &&
+ (t.permission === "read" || t.permission === "write")
+ );
+ } catch (error) {
+ console.error("[token-auth] getTokensFromResponse error:", error);
+ return [];
+ }
+}
+
+/**
+ * Generate a secure access token
+ *
+ * @returns A base64url encoded token (43 characters)
+ */
+export function generateAccessToken(): string {
+ // Generate 32 random bytes (256 bits)
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
+
+ // Convert to base64url (URL-safe)
+ return btoa(String.fromCharCode(...bytes))
+ .replace(/\+/g, "-")
+ .replace(/\//g, "_")
+ .replace(/=/g, "");
+}
+
+/**
+ * Get calendar permission from access token
+ * Used by permission checks to grant token-based access
+ *
+ * @param calendarId - The calendar ID to check
+ * @returns Permission level or null if no token grants access
+ */
+export async function getTokenPermission(
+ calendarId: string
+): Promise<"read" | "write" | null> {
+ try {
+ const tokens = await getTokensFromCookie();
+
+ // Find ALL tokens for this calendar
+ const calendarTokens = tokens.filter((t) => t.calendarId === calendarId);
+
+ if (calendarTokens.length === 0) {
+ return null;
+ }
+
+ // Try to validate each token - use the first valid one
+ // This handles the case where expired tokens are in the cookie
+ for (const tokenData of calendarTokens) {
+ const validation = await validateAccessToken(tokenData.token);
+
+ if (validation && validation.calendarId === calendarId) {
+ // Found a valid token - return its permission
+ return validation.permission;
+ }
+ }
+
+ // No valid tokens found
+ return null;
+ } catch (error) {
+ console.error("[token-auth] getTokenPermission error:", error);
+ return null;
+ }
+}
diff --git a/lib/auto-sync-service.ts b/lib/auto-sync-service.ts
index babe0c2..61dfda8 100644
--- a/lib/auto-sync-service.ts
+++ b/lib/auto-sync-service.ts
@@ -5,10 +5,11 @@
*/
import { db } from "@/lib/db";
-import { externalSyncs } from "@/lib/db/schema";
-import { gt } from "drizzle-orm";
+import { externalSyncs, calendars } from "@/lib/db/schema";
+import { gt, eq } from "drizzle-orm";
import { eventEmitter } from "@/lib/event-emitter";
import { syncExternalCalendar } from "@/app/api/external-syncs/[id]/sync/route";
+import { isAuthEnabled } from "@/lib/auth/feature-flags";
interface SyncJob {
syncId: string;
@@ -20,6 +21,8 @@ class AutoSyncService {
private jobs: Map<string, SyncJob> = new Map();
private timers: Map<string, NodeJS.Timeout> = new Map();
private pollInterval: NodeJS.Timeout | null = null;
+ private cleanupInterval: NodeJS.Timeout | null = null;
+ private lastCleanupTime: number = 0;
private isRunning = false;
/**
@@ -39,6 +42,13 @@ class AutoSyncService {
// Check for syncs every 5 minutes in case of changes
this.pollInterval = setInterval(() => this.loadSyncs(), 5 * 60 * 1000);
+
+ // Run orphaned sync cleanup every 24 hours
+ await this.cleanupOrphanedSyncs();
+ this.cleanupInterval = setInterval(
+ () => this.cleanupOrphanedSyncs(),
+ 24 * 60 * 60 * 1000
+ );
}
/**
@@ -54,6 +64,12 @@ class AutoSyncService {
this.pollInterval = null;
}
+ // Clear the cleanup interval
+ if (this.cleanupInterval) {
+ clearInterval(this.cleanupInterval);
+ this.cleanupInterval = null;
+ }
+
// Clear all sync job timers
for (const timer of this.timers.values()) {
clearTimeout(timer);
@@ -69,19 +85,46 @@ class AutoSyncService {
try {
// Get all syncs with auto-sync enabled (autoSyncInterval > 0)
const syncs = await db
- .select()
+ .select({
+ sync: externalSyncs,
+ calendar: calendars,
+ })
.from(externalSyncs)
+ .leftJoin(calendars, eq(externalSyncs.calendarId, calendars.id))
.where(gt(externalSyncs.autoSyncInterval, 0));
// Remove jobs for syncs that were deleted or disabled
for (const [syncId] of this.jobs) {
- if (!syncs.find((s) => s.id === syncId)) {
+ if (!syncs.find((s) => s.sync.id === syncId)) {
this.removeJob(syncId);
}
}
// Add or update jobs for active syncs
- for (const sync of syncs) {
+ for (const { sync, calendar } of syncs) {
+ // Skip syncs for orphaned calendars (only when auth is enabled)
+ if (isAuthEnabled() && calendar && !calendar.ownerId) {
+ console.warn(
+ `Sync skipped for calendar [${calendar.id}] - no owner (orphaned calendar)`
+ );
+ // Remove job if it exists (calendar lost its owner)
+ if (this.jobs.has(sync.id)) {
+ this.removeJob(sync.id);
+ }
+ continue;
+ }
+
+ // Skip if calendar doesn't exist (shouldn't happen with foreign keys)
+ if (!calendar) {
+ console.warn(
+ `Sync skipped for external sync [${sync.id}] - calendar not found`
+ );
+ if (this.jobs.has(sync.id)) {
+ this.removeJob(sync.id);
+ }
+ continue;
+ }
+
const intervalMs = sync.autoSyncInterval * 60 * 1000; // Convert minutes to milliseconds
const existingJob = this.jobs.get(sync.id);
@@ -213,6 +256,87 @@ class AutoSyncService {
return null;
}
}
+
+ /**
+ * Cleanup orphaned syncs (syncs for calendars without owners)
+ * This runs periodically to disable auto-sync for orphaned calendars
+ */
+ private async cleanupOrphanedSyncs() {
+ // Only run cleanup when auth is enabled
+ if (!isAuthEnabled()) {
+ return;
+ }
+
+ // Prevent running cleanup too frequently (minimum 1 hour between runs)
+ const now = Date.now();
+ if (now - this.lastCleanupTime < 60 * 60 * 1000) {
+ return;
+ }
+
+ this.lastCleanupTime = now;
+ console.log("Running orphaned sync cleanup...");
+
+ try {
+ // Find all external syncs with auto-sync enabled that belong to orphaned calendars
+ const results = await db
+ .select({
+ syncId: externalSyncs.id,
+ syncName: externalSyncs.name,
+ calendarId: externalSyncs.calendarId,
+ ownerId: calendars.ownerId,
+ })
+ .from(externalSyncs)
+ .leftJoin(calendars, eq(externalSyncs.calendarId, calendars.id))
+ .where(gt(externalSyncs.autoSyncInterval, 0));
+
+ // Filter for orphaned syncs (calendar exists but has no owner)
+ const orphanedSyncs = results.filter(
+ (r) => r.calendarId && r.ownerId === null
+ );
+
+ if (orphanedSyncs.length === 0) {
+ console.log("No orphaned syncs found.");
+ return;
+ }
+
+ console.log(`Found ${orphanedSyncs.length} orphaned sync(s) to disable`);
+
+ // Disable auto-sync for orphaned calendars by setting interval to 0
+ for (const orphanedSync of orphanedSyncs) {
+ try {
+ await db
+ .update(externalSyncs)
+ .set({
+ autoSyncInterval: 0,
+ updatedAt: new Date(),
+ })
+ .where(eq(externalSyncs.id, orphanedSync.syncId));
+
+ console.log(
+ `Disabled auto-sync for orphaned calendar: ${orphanedSync.syncName} (Calendar: ${orphanedSync.calendarId})`
+ );
+
+ // Remove from active jobs
+ if (this.jobs.has(orphanedSync.syncId)) {
+ this.removeJob(orphanedSync.syncId);
+ }
+
+ // TODO: Log to audit log when Admin Panel is implemented (Phase 9)
+ // This will be tracked as: action: "sync.orphaned.disabled"
+ // Metadata: { calendarId, syncName, reason: "calendar_has_no_owner" }
+ } catch (error) {
+ console.error(
+ `Failed to disable sync ${orphanedSync.syncId}:`,
+ error
+ );
+ }
+ }
+
+ console.log("Orphaned sync cleanup completed.");
+ } catch (error) {
+ console.error("Error during orphaned sync cleanup:", error);
+ }
+ }
}
// Singleton instance
diff --git a/lib/db/schema.ts b/lib/db/schema.ts
index 68f84a3..0a5edf8 100644
--- a/lib/db/schema.ts
+++ b/lib/db/schema.ts
@@ -1,22 +1,189 @@
-import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
-import { sql } from "drizzle-orm";
+import { sqliteTable, text, integer, index } from "drizzle-orm/sqlite-core";
+import { sql, relations } from "drizzle-orm";
-export const calendars = sqliteTable("calendars", {
- id: text("id")
- .primaryKey()
- .$defaultFn(() => crypto.randomUUID()),
+// =====================================================
+// Better Auth Tables (generated by @better-auth/cli)
+// =====================================================
+
+export const user = sqliteTable("user", {
+ id: text("id").primaryKey(),
name: text("name").notNull(),
- color: text("color").notNull().default("#3b82f6"),
- passwordHash: text("password_hash"),
- isLocked: integer("is_locked", { mode: "boolean" }).notNull().default(false),
- createdAt: integer("created_at", { mode: "timestamp" })
- .notNull()
- .default(sql`CURRENT_TIMESTAMP`),
- updatedAt: integer("updated_at", { mode: "timestamp" })
- .notNull()
- .default(sql`CURRENT_TIMESTAMP`),
+ email: text("email").notNull().unique(),
+ emailVerified: integer("email_verified", { mode: "boolean" })
+ .default(false)
+ .notNull(),
+ image: text("image"),
+ createdAt: integer("created_at", { mode: "timestamp_ms" })
+ .default(sql`(cast(unixepoch('subsecond') * 1000 as integer))`)
+ .notNull(),
+ updatedAt: integer("updated_at", { mode: "timestamp_ms" })
+ .default(sql`(cast(unixepoch('subsecond') * 1000 as integer))`)
+ .$onUpdate(() => new Date())
+ .notNull(),
+ // Better Auth Admin Plugin fields
+ role: text("role"),
+ banned: integer("banned", { mode: "boolean" }).default(false),
+ banReason: text("ban_reason"),
+ banExpires: integer("ban_expires", { mode: "timestamp_ms" }),
});
+export const session = sqliteTable(
+ "session",
+ {
+ id: text("id").primaryKey(),
+ expiresAt: integer("expires_at", { mode: "timestamp_ms" }).notNull(),
+ token: text("token").notNull().unique(),
+ createdAt: integer("created_at", { mode: "timestamp_ms" })
+ .default(sql`(cast(unixepoch('subsecond') * 1000 as integer))`)
+ .notNull(),
+ updatedAt: integer("updated_at", { mode: "timestamp_ms" })
+ .$onUpdate(() => new Date())
+ .notNull(),
+ ipAddress: text("ip_address"),
+ userAgent: text("user_agent"),
+ userId: text("user_id")
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ // Better Auth Admin Plugin field
+ impersonatedBy: text("impersonated_by"),
+ },
+ (table) => [index("session_userId_idx").on(table.userId)]
+);
+
+export const account = sqliteTable(
+ "account",
+ {
+ id: text("id").primaryKey(),
+ accountId: text("account_id").notNull(),
+ providerId: text("provider_id").notNull(),
+ userId: text("user_id")
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ accessToken: text("access_token"),
+ refreshToken: text("refresh_token"),
+ idToken: text("id_token"),
+ accessTokenExpiresAt: integer("access_token_expires_at", {
+ mode: "timestamp_ms",
+ }),
+ refreshTokenExpiresAt: integer("refresh_token_expires_at", {
+ mode: "timestamp_ms",
+ }),
+ scope: text("scope"),
+ password: text("password"),
+ createdAt: integer("created_at", { mode: "timestamp_ms" })
+ .default(sql`(cast(unixepoch('subsecond') * 1000 as integer))`)
+ .notNull(),
+ updatedAt: integer("updated_at", { mode: "timestamp_ms" })
+ .$onUpdate(() => new Date())
+ .notNull(),
+ },
+ (table) => [index("account_userId_idx").on(table.userId)]
+);
+
+export const verification = sqliteTable("verification", {
+ id: text("id").primaryKey(),
+ identifier: text("identifier").notNull(),
+ value: text("value").notNull(),
+ expiresAt: integer("expires_at", { mode: "timestamp_ms" }).notNull(),
+ createdAt: integer("created_at", { mode: "timestamp_ms" })
+ .default(sql`(cast(unixepoch('subsecond') * 1000 as integer))`)
+ .notNull(),
+ updatedAt: integer("updated_at", { mode: "timestamp_ms" }).$onUpdate(
+ () => new Date()
+ ),
+});
+
+// =====================================================
+// BetterShift Application Tables
+// =====================================================
+
+export const calendars = sqliteTable(
+ "calendars",
+ {
+ id: text("id")
+ .primaryKey()
+ .$defaultFn(() => crypto.randomUUID()),
+ name: text("name").notNull(),
+ color: text("color").notNull().default("#3b82f6"),
+ ownerId: text("owner_id").references(() => user.id, {
+ onDelete: "set null",
+ }),
+ guestPermission: text("guest_permission", {
+ enum: ["none", "read", "write"],
+ })
+ .notNull()
+ .default("none"),
+ createdAt: integer("created_at", { mode: "timestamp" })
+ .notNull()
+ .default(sql`CURRENT_TIMESTAMP`),
+ updatedAt: integer("updated_at", { mode: "timestamp" })
+ .notNull()
+ .default(sql`CURRENT_TIMESTAMP`),
+ },
+ (table) => [index("calendars_ownerId_idx").on(table.ownerId)]
+);
+
+export const calendarShares = sqliteTable(
+ "calendar_shares",
+ {
+ id: text("id")
+ .primaryKey()
+ .$defaultFn(() => crypto.randomUUID()),
+ calendarId: text("calendar_id")
+ .notNull()
+ .references(() => calendars.id, { onDelete: "cascade" }),
+ userId: text("user_id")
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ permission: text("permission", { enum: ["admin", "write", "read"] })
+ .notNull()
+ .default("read"),
+ sharedBy: text("shared_by")
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ createdAt: integer("created_at", { mode: "timestamp" })
+ .notNull()
+ .default(sql`CURRENT_TIMESTAMP`),
+ },
+ (table) => [
+ index("calendar_shares_calendarId_idx").on(table.calendarId),
+ index("calendar_shares_userId_idx").on(table.userId),
+ ]
+);
+
+export const userCalendarSubscriptions = sqliteTable(
+ "user_calendar_subscriptions",
+ {
+ id: text("id")
+ .primaryKey()
+ .$defaultFn(() => crypto.randomUUID()),
+ userId: text("user_id")
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ calendarId: text("calendar_id")
+ .notNull()
+ .references(() => calendars.id, { onDelete: "cascade" }),
+ status: text("status", { enum: ["subscribed", "dismissed"] })
+ .notNull()
+ .default("subscribed"),
+ source: text("source", { enum: ["guest", "shared"] })
+ .notNull()
+ .default("guest"),
+ createdAt: integer("created_at", { mode: "timestamp" })
+ .notNull()
+ .default(sql`CURRENT_TIMESTAMP`),
+ updatedAt: integer("updated_at", { mode: "timestamp" })
+ .notNull()
+ .default(sql`CURRENT_TIMESTAMP`)
+ .$onUpdate(() => new Date()),
+ },
+ (table) => [
+ index("user_calendar_subscriptions_userId_idx").on(table.userId),
+ index("user_calendar_subscriptions_calendarId_idx").on(table.calendarId),
+ index("user_calendar_subscriptions_status_idx").on(table.status),
+ ]
+);
+
export const externalSyncs = sqliteTable("external_syncs", {
id: text("id")
.primaryKey()
@@ -153,10 +320,86 @@ export const syncLogs = sqliteTable("sync_logs", {
.default(sql`CURRENT_TIMESTAMP`),
});
+export const auditLogs = sqliteTable(
+ "audit_logs",
+ {
+ id: text("id")
+ .primaryKey()
+ .$defaultFn(() => crypto.randomUUID()),
+ userId: text("user_id").references(() => user.id, {
+ onDelete: "set null",
+ }),
+ action: text("action").notNull(),
+ resourceType: text("resource_type"),
+ resourceId: text("resource_id"),
+ metadata: text("metadata"), // JSON string
+ ipAddress: text("ip_address"),
+ userAgent: text("user_agent"),
+ severity: text("severity").notNull().default("info"), // info, warning, error, critical
+ isUserVisible: integer("is_user_visible", { mode: "boolean" })
+ .notNull()
+ .default(false),
+ timestamp: integer("timestamp", { mode: "timestamp" })
+ .notNull()
+ .default(sql`CURRENT_TIMESTAMP`),
+ },
+ (table) => [
+ index("audit_logs_userId_timestamp_idx").on(table.userId, table.timestamp),
+ index("audit_logs_action_timestamp_idx").on(table.action, table.timestamp),
+ index("audit_logs_userVisible_userId_timestamp_idx").on(
+ table.isUserVisible,
+ table.userId,
+ table.timestamp
+ ),
+ ]
+);
+
+export const calendarAccessTokens = sqliteTable(
+ "calendar_access_tokens",
+ {
+ id: text("id")
+ .primaryKey()
+ .$defaultFn(() => crypto.randomUUID()),
+ calendarId: text("calendar_id")
+ .notNull()
+ .references(() => calendars.id, { onDelete: "cascade" }),
+ token: text("token").notNull().unique(), // base64url encoded, 43 chars
+ name: text("name"), // Optional label (e.g., "Family Link")
+ permission: text("permission", { enum: ["read", "write"] })
+ .notNull()
+ .default("read"),
+ expiresAt: integer("expires_at", { mode: "timestamp" }), // null = never expires
+ createdBy: text("created_by")
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ createdAt: integer("created_at", { mode: "timestamp" })
+ .notNull()
+ .default(sql`CURRENT_TIMESTAMP`),
+ lastUsedAt: integer("last_used_at", { mode: "timestamp" }),
+ usageCount: integer("usage_count").notNull().default(0),
+ isActive: integer("is_active", { mode: "boolean" }).notNull().default(true),
+ },
+ (table) => [
+ index("calendar_access_tokens_token_idx").on(table.token),
+ index("calendar_access_tokens_calendarId_isActive_idx").on(
+ table.calendarId,
+ table.isActive
+ ),
+ index("calendar_access_tokens_createdBy_idx").on(table.createdBy),
+ ]
+);
+
export type Calendar = typeof calendars.$inferSelect;
export type NewCalendar = typeof calendars.$inferInsert;
+
+export type CalendarAccessToken = typeof calendarAccessTokens.$inferSelect;
+export type NewCalendarAccessToken = typeof calendarAccessTokens.$inferInsert;
+
export type ExternalSync = typeof externalSyncs.$inferSelect;
export type NewExternalSync = typeof externalSyncs.$inferInsert;
+
+export type AuditLog = typeof auditLogs.$inferSelect;
+export type NewAuditLog = typeof auditLogs.$inferInsert;
export type Shift = typeof shifts.$inferSelect;
export type NewShift = typeof shifts.$inferInsert;
export type ShiftPreset = typeof shiftPresets.$inferSelect;
@@ -165,3 +408,107 @@ export type CalendarNote = typeof calendarNotes.$inferSelect;
export type NewCalendarNote = typeof calendarNotes.$inferInsert;
export type SyncLog = typeof syncLogs.$inferSelect;
export type NewSyncLog = typeof syncLogs.$inferInsert;
+
+// Better Auth types
+export type User = typeof user.$inferSelect;
+export type NewUser = typeof user.$inferInsert;
+export type Session = typeof session.$inferSelect;
+export type Account = typeof account.$inferSelect;
+export type CalendarShare = typeof calendarShares.$inferSelect;
+export type NewCalendarShare = typeof calendarShares.$inferInsert;
+export type UserCalendarSubscription =
+ typeof userCalendarSubscriptions.$inferSelect;
+export type NewUserCalendarSubscription =
+ typeof userCalendarSubscriptions.$inferInsert;
+
+// =====================================================
+// Drizzle Relations (for experimental joins)
+// =====================================================
+
+export const userRelations = relations(user, ({ many }) => ({
+ sessions: many(session),
+ accounts: many(account),
+ ownedCalendars: many(calendars),
+ calendarShares: many(calendarShares),
+ calendarSubscriptions: many(userCalendarSubscriptions),
+ auditLogs: many(auditLogs),
+}));
+
+export const sessionRelations = relations(session, ({ one }) => ({
+ user: one(user, {
+ fields: [session.userId],
+ references: [user.id],
+ }),
+}));
+
+export const accountRelations = relations(account, ({ one }) => ({
+ user: one(user, {
+ fields: [account.userId],
+ references: [user.id],
+ }),
+}));
+
+export const calendarsRelations = relations(calendars, ({ one, many }) => ({
+ owner: one(user, {
+ fields: [calendars.ownerId],
+ references: [user.id],
+ }),
+ shares: many(calendarShares),
+ subscriptions: many(userCalendarSubscriptions),
+ accessTokens: many(calendarAccessTokens),
+ shifts: many(shifts),
+ presets: many(shiftPresets),
+ notes: many(calendarNotes),
+ externalSyncs: many(externalSyncs),
+ syncLogs: many(syncLogs),
+}));
+
+export const calendarSharesRelations = relations(calendarShares, ({ one }) => ({
+ calendar: one(calendars, {
+ fields: [calendarShares.calendarId],
+ references: [calendars.id],
+ }),
+ user: one(user, {
+ fields: [calendarShares.userId],
+ references: [user.id],
+ }),
+ sharedByUser: one(user, {
+ fields: [calendarShares.sharedBy],
+ references: [user.id],
+ }),
+}));
+
+export const userCalendarSubscriptionsRelations = relations(
+ userCalendarSubscriptions,
+ ({ one }) => ({
+ user: one(user, {
+ fields: [userCalendarSubscriptions.userId],
+ references: [user.id],
+ }),
+ calendar: one(calendars, {
+ fields: [userCalendarSubscriptions.calendarId],
+ references: [calendars.id],
+ }),
+ })
+);
+
+export const auditLogsRelations = relations(auditLogs, ({ one }) => ({
+ user: one(user, {
+ fields: [auditLogs.userId],
+ references: [user.id],
+ }),
+}));
+
+export const calendarAccessTokensRelations = relations(
+ calendarAccessTokens,
+ ({ one }) => ({
+ calendar: one(calendars, {
+ fields: [calendarAccessTokens.calendarId],
+ references: [calendars.id],
+ }),
+ createdByUser: one(user, {
+ fields: [calendarAccessTokens.createdBy],
+ references: [user.id],
+ }),
+ })
+);
diff --git a/lib/ip-utils.ts b/lib/ip-utils.ts
new file mode 100644
index 0000000..dfa6288
--- /dev/null
+++ b/lib/ip-utils.ts
@@ -0,0 +1,31 @@
+import { NextRequest } from "next/server";
+import RequestIp from "@supercharge/request-ip";
+
+/**
+ * Extract the real client IP address from a request.
+ * Uses @supercharge/request-ip which automatically handles:
+ * - Cloudflare (CF-Connecting-IP)
+ * - Standard proxies (X-Forwarded-For, X-Real-IP)
+ * - AWS/Azure/GCP load balancers
+ * - Direct connections
+ *
+ * @param request - Request object (NextRequest or standard Request)
+ * @returns Client IP address or null if not found
+ */
+export function getClientIp(request: NextRequest | Request): string | null {
+ // Create a minimal Express-like request object for the library
+ const expressLikeRequest = {
+ headers: Object.fromEntries(request.headers.entries()),
+ connection: {},
+ socket: {},
+ };
+
+ const ip = RequestIp.getClientIp(
+ expressLikeRequest as {
+ headers: Record<string, string>;
+ connection: Record<string, unknown>;
+ socket: Record<string, unknown>;
+ }
+ );
+ return ip || null;
+}
diff --git a/lib/password-cache.ts b/lib/password-cache.ts
deleted file mode 100644
index c85217a..0000000
--- a/lib/password-cache.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-/**
- * Centralized password caching and verification utility
- * Ensures consistent password handling across all components
- */
-
-/**
- * Get cached password from localStorage
- */
-export function getCachedPassword(
- calendarId: string | null | undefined
-): string | null {
- if (typeof window === "undefined" || !calendarId) return null;
- return localStorage.getItem(`calendar_password_${calendarId}`);
-}
-
-/**
- * Cache password in localStorage
- */
-export function setCachedPassword(calendarId: string, password: string): void {
- if (typeof window === "undefined") return;
- localStorage.setItem(`calendar_password_${calendarId}`, password);
-}
-
-/**
- * Remove cached password from localStorage
- */
-export function removeCachedPassword(calendarId: string): void {
- if (typeof window === "undefined") return;
- localStorage.removeItem(`calendar_password_${calendarId}`);
-}
-
-/**
- * Verify password with the server and cache if valid
- * Returns { valid: boolean, protected: boolean }
- */
-export async function verifyAndCachePassword(
- calendarId: string,
- password: string | null
-): Promise<{ valid: boolean; protected: boolean }> {
- try {
- const response = await fetch(
- `/api/calendars/${calendarId}/verify-password`,
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ password }),
- }
- );
-
- // Handle different HTTP status codes
- if (!response.ok) {
- // 401 Unauthorized or 403 Forbidden indicate wrong password
- if (response.status === 401 || response.status === 403) {
- removeCachedPassword(calendarId);
- return { valid: false, protected: true };
- }
-
- // Other errors (404, 500, etc.) - treat as temporary failure
- // Don't remove cached password as the error might be transient
- console.error(
- `Password verification failed with status ${response.status}`
- );
- return { valid: false, protected: true };
- }
-
- const data = await response.json();
-
- // If calendar is protected and password is invalid, remove from cache
- if (data.protected && !data.valid) {
- removeCachedPassword(calendarId);
- return { valid: false, protected: true };
- }
-
- // If valid and password was provided, cache it
- if (data.valid && password) {
- setCachedPassword(calendarId, password);
- }
-
- return {
- valid: data.valid,
- protected: data.protected,
- };
- } catch (error) {
- // Network errors or other exceptions
- // Don't remove cached password as this might be a temporary network issue
- console.error("Failed to verify password:", error);
- return { valid: false, protected: true };
- }
-}
-
-/**
- * Check if we have a valid cached password
- * This verifies the cached password with the server
- */
-export async function hasValidCachedPassword(
- calendarId: string
-): Promise<boolean> {
- const cachedPassword = getCachedPassword(calendarId);
- if (!cachedPassword) return false;
-
- const result = await verifyAndCachePassword(calendarId, cachedPassword);
- return result.valid;
-}
diff --git a/lib/password-utils.ts b/lib/password-utils.ts
deleted file mode 100644
index 4cedf38..0000000
--- a/lib/password-utils.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import crypto from "crypto";
-
-/**
- * Hashes a password using SHA-256
- */
-export function hashPassword(
- password: string | null | undefined
-): string | null {
- if (!password) return null;
- return crypto.createHash("sha256").update(password).digest("hex");
-}
-
-/**
- * Verifies if a password matches the stored hash
- */
-export function verifyPassword(
- password: string | null | undefined,
- hash: string | null
-): boolean {
- if (!password || !hash) return false;
- const inputHash = hashPassword(password);
- return inputHash === hash;
-}
diff --git a/lib/public-config.ts b/lib/public-config.ts
new file mode 100644
index 0000000..b90ea63
--- /dev/null
+++ b/lib/public-config.ts
@@ -0,0 +1,136 @@
+/**
+ * Public Configuration
+ *
+ * This module provides a centralized way to expose server-side environment
+ * variables to the client safely. Only values explicitly returned by
+ * getPublicConfig() are exposed to the browser.
+ *
+ * SECURITY: This file is server-only. Values are passed to the client via:
+ * 1. SSR injection (inline script in root layout) - zero latency
+ * 2. API fallback (/api/public-config) - for client-side navigation
+ *
+ * Usage:
+ * - Server Components: import { getPublicConfig } from '@/lib/public-config'
+ * - Client Components: use the usePublicConfig() hook
+ */
+
+/**
+ * Returns public configuration that can be safely exposed to the client.
+ * This function runs ONLY on the server and explicitly whitelists which
+ * environment variables are safe to expose.
+ *
+ * @returns Public configuration object
+ */
+export function getPublicConfig() {
+ return {
+ // =============================================================================
+ // Auth System Configuration
+ // =============================================================================
+ auth: {
+ /**
+ * Whether the authentication system is enabled
+ * @default false
+ */
+ enabled: process.env.AUTH_ENABLED === "true",
+
+ /**
+ * Better Auth base URL for callbacks and API endpoints
+ * @default "http://localhost:3000"
+ */
+ url: process.env.BETTER_AUTH_URL || "http://localhost:3000",
+
+ /**
+ * Allow new user registrations
+ * @default true
+ */
+ allowRegistration: process.env.ALLOW_USER_REGISTRATION !== "false",
+
+ /**
+ * Allow unauthenticated users to view calendars with guest permission
+ * @default false
+ */
+ allowGuestAccess: process.env.ALLOW_GUEST_ACCESS === "true",
+ },
+
+ // =============================================================================
+ // OAuth Providers (Social Login)
+ // =============================================================================
+ oauth: {
+ /**
+ * Google OAuth Client ID (needed for client-side button display)
+ */
+ google: process.env.GOOGLE_CLIENT_ID,
+
+ /**
+ * GitHub OAuth Client ID (needed for client-side button display)
+ */
+ github: process.env.GITHUB_CLIENT_ID,
+
+ /**
+ * Discord OAuth Client ID (needed for client-side button display)
+ */
+ discord: process.env.DISCORD_CLIENT_ID,
+ },
+
+ // =============================================================================
+ // Custom OIDC Provider
+ // =============================================================================
+ oidc: {
+ /**
+ * Whether custom OIDC provider is enabled
+ * @default false
+ */
+ enabled: process.env.CUSTOM_OIDC_ENABLED === "true",
+
+ /**
+ * Custom OIDC Client ID
+ */
+ clientId: process.env.CUSTOM_OIDC_CLIENT_ID,
+
+ /**
+ * Display name for the OIDC provider login button
+ * @default "Custom SSO"
+ */
+ name: process.env.CUSTOM_OIDC_NAME || "Custom SSO",
+
+ /**
+ * OIDC issuer URL (well-known configuration endpoint)
+ */
+ issuer: process.env.CUSTOM_OIDC_ISSUER,
+ },
+ } as const;
+}
+
+/**
+ * Type-safe public configuration object
+ */
+export type PublicConfig = ReturnType<typeof getPublicConfig>;
+
+/**
+ * Validates that the public configuration is properly set up.
+ * Called during build/startup to catch configuration errors early.
+ */
+export function validatePublicConfig(): void {
+ const config = getPublicConfig();
+
+ // Validate auth configuration
+ if (config.auth.enabled && !config.auth.url) {
+ console.warn(
+ "[PUBLIC_CONFIG] Auth is enabled but BETTER_AUTH_URL is not set"
+ );
+ }
+
+ // Validate OIDC configuration
+ if (config.oidc.enabled) {
+ if (!config.oidc.clientId) {
+ console.warn(
+ "[PUBLIC_CONFIG] OIDC is enabled but CUSTOM_OIDC_CLIENT_ID is not set"
+ );
+ }
+ if (!config.oidc.issuer) {
+ console.warn(
+ "[PUBLIC_CONFIG] OIDC is enabled but CUSTOM_OIDC_ISSUER is not set"
+ );
+ }
+ }
+}
diff --git a/lib/rate-limit-client.ts b/lib/rate-limit-client.ts
new file mode 100644
index 0000000..fc2a465
--- /dev/null
+++ b/lib/rate-limit-client.ts
@@ -0,0 +1,150 @@
+/**
+ * Rate Limit Error Handler for Client-Side
+ *
+ * Provides user-friendly error messages and toast notifications
+ * when rate limits are exceeded.
+ *
+ * Uses the app's existing i18n infrastructure (next-intl) for translations.
+ */
+
+import { toast } from "sonner";
+
+export interface RateLimitError {
+ error: string;
+ retryAfter?: number;
+}
+
+/**
+ * Translation function type (compatible with next-intl)
+ */
+type TranslateFn = (
+ key: string,
+ values?: Record<string, string | number | Date>
+) => string;
+
+/**
+ * Check if a response is a rate limit error (429)
+ */
+export function isRateLimitError(response: Response): boolean {
+ return response.status === 429;
+}
+
+/**
+ * Handle rate limit error with user-friendly toast
+ *
+ * @param response - Fetch response object
+ * @param t - Translation function from useTranslations()
+ * @param action - Optional description of the action that was rate-limited
+ *
+ * @example
+ * ```typescript
+ * const t = useTranslations();
+ * const response = await fetch('/api/auth/change-password', { ... });
+ * if (isRateLimitError(response)) {
+ * await handleRateLimitError(response, t, 'change your password');
+ * return;
+ * }
+ * ```
+ */
+export async function handleRateLimitError(
+ response: Response,
+ t: TranslateFn,
+ action?: string
+): Promise<void> {
+ try {
+ const data: RateLimitError = await response.json();
+ const retryAfter = data.retryAfter || 60;
+
+ // Format retry time with proper pluralization
+ let retryMessage = "";
+ if (retryAfter < 60) {
+ const unit =
+ retryAfter === 1 ? t("rateLimit.second") : t("rateLimit.seconds");
+ retryMessage = `${retryAfter} ${unit}`;
+ } else if (retryAfter < 3600) {
+ const minutes = Math.ceil(retryAfter / 60);
+ const unit =
+ minutes === 1 ? t("rateLimit.minute") : t("rateLimit.minutes");
+ retryMessage = `${minutes} ${unit}`;
+ } else {
+ const hours = Math.ceil(retryAfter / 3600);
+ const unit = hours === 1 ? t("rateLimit.hour") : t("rateLimit.hours");
+ retryMessage = `${hours} ${unit}`;
+ }
+
+ // Build localized message
+ const message = t("rateLimit.message", { time: retryMessage });
+ const title = t("rateLimit.title");
+
+ toast.error(title, {
+ description: action ? `${action}\n\n${message}` : message,
+ duration: 6000,
+ });
+ } catch {
+ // Fallback if JSON parsing fails
+ const title = t("rateLimit.title");
+ const fallback = t("rateLimit.fallback");
+
+ toast.error(title, {
+ description: fallback,
+ duration: 5000,
+ });
+ }
+}
+
+/**
+ * Extract rate limit headers from response
+ * Useful for displaying remaining requests in UI
+ */
+export function getRateLimitHeaders(response: Response): {
+ limit?: number;
+ remaining?: number;
+ reset?: number;
+ retryAfter?: number;
+} {
+ const headers = response.headers;
+
+ return {
+ limit: headers.get("X-RateLimit-Limit")
+ ? parseInt(headers.get("X-RateLimit-Limit")!, 10)
+ : undefined,
+ remaining: headers.get("X-RateLimit-Remaining")
+ ? parseInt(headers.get("X-RateLimit-Remaining")!, 10)
+ : undefined,
+ reset: headers.get("X-RateLimit-Reset")
+ ? parseInt(headers.get("X-RateLimit-Reset")!, 10)
+ : undefined,
+ retryAfter: headers.get("Retry-After")
+ ? parseInt(headers.get("Retry-After")!, 10)
+ : undefined,
+ };
+}
+
+/**
+ * Create a fetch wrapper that automatically handles rate limit errors
+ *
+ * @param t - Translation function from useTranslations()
+ * @param action - Optional description of the action that was rate-limited
+ *
+ * @example
+ * ```typescript
+ * const t = useTranslations();
+ * const rateLimitedFetch = createRateLimitedFetch(t, 'change your password');
+ * const response = await rateLimitedFetch('/api/auth/change-password', {
+ * method: 'POST',
+ * body: JSON.stringify({ ... }),
+ * });
+ * ```
+ */
+export function createRateLimitedFetch(t: TranslateFn, action?: string) {
+ return async (input: RequestInfo | URL, init?: RequestInit) => {
+ const response = await fetch(input, init);
+
+ if (isRateLimitError(response)) {
+ await handleRateLimitError(response.clone(), t, action);
+ throw new Error("Rate limit exceeded");
+ }
+
+ return response;
+ };
+}
diff --git a/lib/rate-limiter.ts b/lib/rate-limiter.ts
new file mode 100644
index 0000000..d21225e
--- /dev/null
+++ b/lib/rate-limiter.ts
@@ -0,0 +1,552 @@
+/**
+ * Rate Limiter Implementation
+ *
+ * In-memory rate limiting using Fixed Window algorithm with LRU-like cleanup.
+ * Tracks requests by IP address (unauthenticated) or User ID (authenticated).
+ *
+ * Configuration via Environment Variables:
+ * - RATE_LIMIT_AUTH_REQUESTS - Auth endpoints (login)
+ * - RATE_LIMIT_AUTH_WINDOW - Time window in seconds
+ * - RATE_LIMIT_REGISTER_REQUESTS - Registration endpoint (stricter)
+ * - RATE_LIMIT_REGISTER_WINDOW
+ * - RATE_LIMIT_PASSWORD_CHANGE_REQUESTS - Password change endpoint
+ * - RATE_LIMIT_PASSWORD_CHANGE_WINDOW
+ * - RATE_LIMIT_ACCOUNT_DELETE_REQUESTS - Account deletion endpoint
+ * - RATE_LIMIT_ACCOUNT_DELETE_WINDOW
+ * - RATE_LIMIT_UPLOAD_AVATAR_REQUESTS - Avatar upload endpoint
+ * - RATE_LIMIT_UPLOAD_AVATAR_WINDOW
+ * - RATE_LIMIT_SSE_CONNECTIONS - SSE connection limit per user
+ * - RATE_LIMIT_SSE_WINDOW
+ * - RATE_LIMIT_CALENDAR_CREATE_REQUESTS - Calendar creation
+ * - RATE_LIMIT_CALENDAR_CREATE_WINDOW
+ * - RATE_LIMIT_EXTERNAL_SYNC_REQUESTS - External sync execution (per calendar)
+ * - RATE_LIMIT_EXTERNAL_SYNC_WINDOW
+ * - RATE_LIMIT_EXPORT_PDF_REQUESTS - PDF export
+ * - RATE_LIMIT_EXPORT_PDF_WINDOW
+ * - RATE_LIMIT_TOKEN_VALIDATION_REQUESTS - Token validation (per IP)
+ * - RATE_LIMIT_TOKEN_VALIDATION_WINDOW
+ * - RATE_LIMIT_TOKEN_CREATION_REQUESTS - Token creation (per calendar)
+ * - RATE_LIMIT_TOKEN_CREATION_WINDOW
+ */
+
+import { NextRequest, NextResponse } from "next/server";
+import { logAuditEvent, type RateLimitHitMetadata } from "@/lib/audit-log";
+
+// =============================================================================
+// Configuration from Environment Variables
+// =============================================================================
+
+const config = {
+ auth: {
+ requests: parseInt(process.env.RATE_LIMIT_AUTH_REQUESTS || "5", 10),
+ windowMs: parseInt(process.env.RATE_LIMIT_AUTH_WINDOW || "60", 10) * 1000,
+ },
+ register: {
+ requests: parseInt(process.env.RATE_LIMIT_REGISTER_REQUESTS || "3", 10),
+ windowMs:
+ parseInt(process.env.RATE_LIMIT_REGISTER_WINDOW || "600", 10) * 1000, // 10 minutes
+ },
+ passwordChange: {
+ requests: parseInt(
+ process.env.RATE_LIMIT_PASSWORD_CHANGE_REQUESTS || "3",
+ 10
+ ),
+ windowMs:
+ parseInt(process.env.RATE_LIMIT_PASSWORD_CHANGE_WINDOW || "3600", 10) *
+ 1000,
+ },
+ accountDelete: {
+ requests: parseInt(
+ process.env.RATE_LIMIT_ACCOUNT_DELETE_REQUESTS || "1",
+ 10
+ ),
+ windowMs:
+ parseInt(process.env.RATE_LIMIT_ACCOUNT_DELETE_WINDOW || "3600", 10) *
+ 1000,
+ },
+ uploadAvatar: {
+ requests: parseInt(
+ process.env.RATE_LIMIT_UPLOAD_AVATAR_REQUESTS || "5",
+ 10
+ ),
+ windowMs:
+ parseInt(process.env.RATE_LIMIT_UPLOAD_AVATAR_WINDOW || "300", 10) * 1000,
+ },
+ sseConnection: {
+ requests: parseInt(process.env.RATE_LIMIT_SSE_CONNECTIONS || "10", 10),
+ windowMs: parseInt(process.env.RATE_LIMIT_SSE_WINDOW || "10", 10) * 1000,
+ },
+ calendarCreate: {
+ requests: parseInt(
+ process.env.RATE_LIMIT_CALENDAR_CREATE_REQUESTS || "10",
+ 10
+ ),
+ windowMs:
+ parseInt(process.env.RATE_LIMIT_CALENDAR_CREATE_WINDOW || "3600", 10) *
+ 1000, // 1 hour
+ },
+ externalSync: {
+ requests: parseInt(
+ process.env.RATE_LIMIT_EXTERNAL_SYNC_REQUESTS || "5",
+ 10
+ ),
+ windowMs:
+ parseInt(process.env.RATE_LIMIT_EXTERNAL_SYNC_WINDOW || "300", 10) * 1000, // 5 minutes
+ },
+ exportPdf: {
+ requests: parseInt(process.env.RATE_LIMIT_EXPORT_PDF_REQUESTS || "10", 10),
+ windowMs:
+ parseInt(process.env.RATE_LIMIT_EXPORT_PDF_WINDOW || "600", 10) * 1000, // 10 minutes
+ },
+ tokenValidation: {
+ requests: parseInt(
+ process.env.RATE_LIMIT_TOKEN_VALIDATION_REQUESTS || "10",
+ 10
+ ),
+ windowMs:
+ parseInt(process.env.RATE_LIMIT_TOKEN_VALIDATION_WINDOW || "60", 10) *
+ 1000, // 1 minute
+ },
+ tokenCreation: {
+ requests: parseInt(
+ process.env.RATE_LIMIT_TOKEN_CREATION_REQUESTS || "10",
+ 10
+ ),
+ windowMs:
+ parseInt(process.env.RATE_LIMIT_TOKEN_CREATION_WINDOW || "3600", 10) *
+ 1000, // 1 hour
+ },
+ // Admin Panel
+ adminUserMutations: {
+ requests: parseInt(process.env.RATE_LIMIT_ADMIN_USER_MUTATIONS || "10", 10),
+ windowMs:
+ parseInt(process.env.RATE_LIMIT_ADMIN_USER_MUTATIONS_WINDOW || "60", 10) *
+ 1000, // 1 minute
+ },
+ adminPasswordReset: {
+ requests: parseInt(process.env.RATE_LIMIT_ADMIN_PASSWORD_RESET || "5", 10),
+ windowMs:
+ parseInt(
+ process.env.RATE_LIMIT_ADMIN_PASSWORD_RESET_WINDOW || "300",
+ 10
+ ) * 1000, // 5 minutes
+ },
+ adminBulkOperations: {
+ requests: parseInt(process.env.RATE_LIMIT_ADMIN_BULK_OPERATIONS || "3", 10),
+ windowMs:
+ parseInt(
+ process.env.RATE_LIMIT_ADMIN_BULK_OPERATIONS_WINDOW || "300",
+ 10
+ ) * 1000, // 5 minutes
+ },
+ adminCalendarMutations: {
+ requests: parseInt(
+ process.env.RATE_LIMIT_ADMIN_CALENDAR_MUTATIONS || "10",
+ 10
+ ),
+ windowMs:
+ parseInt(
+ process.env.RATE_LIMIT_ADMIN_CALENDAR_MUTATIONS_WINDOW || "60",
+ 10
+ ) * 1000, // 1 minute
+ },
+};
+
+// =============================================================================
+// Types
+// =============================================================================
+
+interface RateLimitEntry {
+ count: number;
+ resetAt: number;
+}
+
+interface RateLimitOptions {
+ requests: number;
+ windowMs: number;
+}
+
+interface RateLimitResult {
+ success: boolean;
+ limit: number;
+ remaining: number;
+ resetAt: number;
+ retryAfter?: number;
+}
+
+// =============================================================================
+// In-Memory Storage
+// =============================================================================
+
+const store = new Map<string, RateLimitEntry>();
+
+/**
+ * Lazy cleanup: Remove expired entries when accessed
+ */
+function cleanupExpiredEntry(key: string, now: number): void {
+ const entry = store.get(key);
+ if (entry && entry.resetAt <= now) {
+ store.delete(key);
+ }
+}
+
+/**
+ * Get client identifier from request
+ * - Authenticated: User ID
+ * - Unauthenticated: IP Address
+ */
+function getClientIdentifier(req: NextRequest, userId?: string | null): string {
+ if (userId) {
+ return `user:${userId}`;
+ }
+
+ // Try to get real IP from headers (proxies)
+ const forwarded = req.headers.get("x-forwarded-for");
+ const realIp = req.headers.get("x-real-ip");
+ const ip = forwarded?.split(",")[0].trim() || realIp || "unknown";
+
+ return `ip:${ip}`;
+}
+
+/**
+ * Check rate limit for a request
+ */
+function checkRateLimit(
+ identifier: string,
+ options: RateLimitOptions
+): RateLimitResult {
+ const now = Date.now();
+ const key = `${identifier}:${options.windowMs}`;
+
+ // Clean up expired entry
+ cleanupExpiredEntry(key, now);
+
+ const entry = store.get(key);
+
+ if (!entry) {
+ // First request in window
+ store.set(key, {
+ count: 1,
+ resetAt: now + options.windowMs,
+ });
+
+ return {
+ success: true,
+ limit: options.requests,
+ remaining: options.requests - 1,
+ resetAt: now + options.windowMs,
+ };
+ }
+
+ // Check if within limit
+ if (entry.count < options.requests) {
+ entry.count++;
+ store.set(key, entry);
+
+ return {
+ success: true,
+ limit: options.requests,
+ remaining: options.requests - entry.count,
+ resetAt: entry.resetAt,
+ };
+ }
+
+ // Rate limit exceeded
+ const retryAfter = Math.ceil((entry.resetAt - now) / 1000);
+
+ return {
+ success: false,
+ limit: options.requests,
+ remaining: 0,
+ resetAt: entry.resetAt,
+ retryAfter,
+ };
+}
+
+/**
+ * Add rate limit headers to response
+ */
+function addRateLimitHeaders(
+ response: NextResponse,
+ result: RateLimitResult
+): void {
+ response.headers.set("X-RateLimit-Limit", result.limit.toString());
+ response.headers.set("X-RateLimit-Remaining", result.remaining.toString());
+ response.headers.set(
+ "X-RateLimit-Reset",
+ Math.floor(result.resetAt / 1000).toString()
+ );
+
+ if (result.retryAfter !== undefined) {
+ response.headers.set("Retry-After", result.retryAfter.toString());
+ }
+}
+
+// =============================================================================
+// Public API
+// =============================================================================
+
+/**
+ * Rate limit middleware for API routes
+ *
+ * @param req - Next.js request object
+ * @param userId - Optional user ID for authenticated requests
+ * @param type - Type of endpoint to determine limits
+ * @param resourceId - Optional resource ID (e.g., calendarId for token-creation)
+ * @returns NextResponse if rate limit exceeded, null otherwise
+ *
+ * @example
+ * ```typescript
+ * export async function POST(req: NextRequest) {
+ * const user = await getSessionUser(req.headers);
+ * const rateLimitResponse = await rateLimit(req, user?.id, "auth");
+ * if (rateLimitResponse) return rateLimitResponse;
+ *
+ * // ... handle request
+ * }
+ * ```
+ */
+export function rateLimit(
+ req: NextRequest,
+ userId?: string | null,
+ type:
+ | "auth"
+ | "register"
+ | "password-change"
+ | "account-delete"
+ | "upload-avatar"
+ | "sse"
+ | "calendar-create"
+ | "external-sync"
+ | "export-pdf"
+ | "token-validation"
+ | "token-creation"
+ | "admin-user-mutations"
+ | "admin-password-reset"
+ | "admin-bulk-operations"
+ | "admin-calendar-mutations" = "auth",
+ resourceId?: string
+): NextResponse | null {
+ // Special handling for resource-based limits (e.g., token-creation per calendar)
+ let identifier: string;
+ if (type === "token-creation" && resourceId) {
+ identifier = `calendar:${resourceId}`;
+ } else if (type === "external-sync" && resourceId) {
+ identifier = `calendar:${resourceId}`;
+ } else {
+ identifier = getClientIdentifier(req, userId);
+ }
+
+ // Select config based on type
+ let options: RateLimitOptions;
+ switch (type) {
+ case "auth":
+ options = config.auth;
+ break;
+ case "register":
+ options = config.register;
+ break;
+ case "password-change":
+ options = config.passwordChange;
+ break;
+ case "account-delete":
+ options = config.accountDelete;
+ break;
+ case "upload-avatar":
+ options = config.uploadAvatar;
+ break;
+ case "sse":
+ options = config.sseConnection;
+ break;
+ case "calendar-create":
+ options = config.calendarCreate;
+ break;
+ case "external-sync":
+ options = config.externalSync;
+ break;
+ case "export-pdf":
+ options = config.exportPdf;
+ break;
+ case "token-validation":
+ options = config.tokenValidation;
+ break;
+ case "token-creation":
+ options = config.tokenCreation;
+ break;
+ case "admin-user-mutations":
+ options = config.adminUserMutations;
+ break;
+ case "admin-password-reset":
+ options = config.adminPasswordReset;
+ break;
+ case "admin-bulk-operations":
+ options = config.adminBulkOperations;
+ break;
+ case "admin-calendar-mutations":
+ options = config.adminCalendarMutations;
+ break;
+ }
+
+ const result = checkRateLimit(identifier, options);
+
+ if (!result.success) {
+ // Rate limit exceeded
+ console.warn(
+ `[Rate Limit] ${type} - ${identifier} exceeded limit (${result.limit} requests per ${options.windowMs}ms)`
+ );
+
+ // Log rate limit event to audit logs (fire-and-forget)
+ logAuditEvent<RateLimitHitMetadata>({
+ action: "security.rate_limit.hit",
+ userId: userId || null,
+ resourceType: "rate_limit",
+ metadata: {
+ endpoint: type,
+ limit: result.limit,
+ resetTime: result.resetAt,
+ },
+ request: req,
+ severity: "warning",
+ isUserVisible: userId ? true : false, // Show in activity log only for authenticated users
+ }).catch((err) => console.error("Failed to log rate limit event:", err));
+
+ const response = NextResponse.json(
+ {
+ error: "Too many requests. Please try again later.",
+ retryAfter: result.retryAfter,
+ },
+ { status: 429 }
+ );
+
+ addRateLimitHeaders(response, result);
+ return response;
+ }
+
+ // Success - headers will be added by caller if needed
+ return null;
+}
+
+/**
+ * Get current rate limit status without incrementing counter
+ * Useful for checking limits without consuming a request
+ */
+export function getRateLimitStatus(
+ identifier: string,
+ type:
+ | "auth"
+ | "register"
+ | "password-change"
+ | "account-delete"
+ | "upload-avatar"
+ | "sse"
+ | "calendar-create"
+ | "external-sync"
+ | "export-pdf"
+ | "token-validation"
+ | "token-creation" = "auth"
+): RateLimitResult {
+ let options: RateLimitOptions;
+ switch (type) {
+ case "auth":
+ options = config.auth;
+ break;
+ case "register":
+ options = config.register;
+ break;
+ case "password-change":
+ options = config.passwordChange;
+ break;
+ case "account-delete":
+ options = config.accountDelete;
+ break;
+ case "upload-avatar":
+ options = config.uploadAvatar;
+ break;
+ case "sse":
+ options = config.sseConnection;
+ break;
+ case "calendar-create":
+ options = config.calendarCreate;
+ break;
+ case "external-sync":
+ options = config.externalSync;
+ break;
+ case "export-pdf":
+ options = config.exportPdf;
+ break;
+ case "token-validation":
+ options = config.tokenValidation;
+ break;
+ case "token-creation":
+ options = config.tokenCreation;
+ break;
+ }
+
+ const now = Date.now();
+ const key = `${identifier}:${options.windowMs}`;
+ cleanupExpiredEntry(key, now);
+
+ const entry = store.get(key);
+
+ if (!entry) {
+ return {
+ success: true,
+ limit: options.requests,
+ remaining: options.requests,
+ resetAt: now + options.windowMs,
+ };
+ }
+
+ const remaining = Math.max(0, options.requests - entry.count);
+
+ return {
+ success: remaining > 0,
+ limit: options.requests,
+ remaining,
+ resetAt: entry.resetAt,
+ retryAfter:
+ remaining === 0 ? Math.ceil((entry.resetAt - now) / 1000) : undefined,
+ };
+}
+
+/**
+ * Manually reset rate limit for a specific identifier
+ * Useful for testing or administrative purposes
+ */
+export function resetRateLimit(identifier: string): void {
+ // Remove all entries matching the identifier prefix
+ const keysToDelete: string[] = [];
+ for (const key of store.keys()) {
+ if (key.startsWith(identifier)) {
+ keysToDelete.push(key);
+ }
+ }
+ keysToDelete.forEach((key) => store.delete(key));
+}
+
+/**
+ * Get stats about the rate limiter (for monitoring/debugging)
+ */
+export function getRateLimiterStats(): {
+ totalEntries: number;
+ activeEntries: number;
+ expiredEntries: number;
+} {
+ const now = Date.now();
+ let activeEntries = 0;
+ let expiredEntries = 0;
+
+ for (const entry of store.values()) {
+ if (entry.resetAt > now) {
+ activeEntries++;
+ } else {
+ expiredEntries++;
+ }
+ }
+
+ return {
+ totalEntries: store.size,
+ activeEntries,
+ expiredEntries,
+ };
+}
diff --git a/lib/types.ts b/lib/types.ts
index a08b6cd..46088fe 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -5,11 +5,16 @@ export interface CalendarWithCount {
id: string;
name: string;
color: string;
- passwordHash?: string | null;
- isLocked?: boolean;
+ ownerId?: string | null;
+ guestPermission?: "none" | "read" | "write";
createdAt: Date | null;
updatedAt: Date | null;
_count?: number;
+ // Permission metadata (only for authenticated users)
+ sharePermission?: "owner" | "admin" | "write" | "read";
+ tokenPermission?: "read" | "write"; // Permission from access token
+ isSubscribed?: boolean;
+ subscriptionSource?: "guest" | "shared" | "token";
}
export interface ShiftWithCalendar {
diff --git a/messages/de.json b/messages/de.json
index 0d29525..fad085b 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -8,12 +8,17 @@
"cancel": "Abbrechen",
"save": "Speichern",
"saving": "Speichere...",
+ "close": "Schließen",
+ "optional": "(optional)",
"delete": "Löschen",
- "create": "Erstellen",
+ "deleteSelected": "Ausgewählte löschen",
"loading": "Lädt...",
- "required": "erforderlich",
- "unlock": "Entsperren",
"add": "Hinzufügen",
+ "adding": "Wird hinzugefügt...",
+ "or": "oder",
+ "next": "Weiter",
+ "previous": "Zurück",
+ "of": "von",
"unsavedChanges": "Ungespeicherte Änderungen",
"unsavedChangesDescription": "Du hast ungespeicherte Änderungen. Möchtest du wirklich schließen, ohne zu speichern?",
"closeWithoutSaving": "Schließen ohne Speichern",
@@ -24,13 +29,32 @@
"updateError": "{item} konnte nicht aktualisiert werden",
"deleteError": "{item} konnte nicht gelöscht werden",
"deleteConfirm": "{item} \"{name}\" wirklich löschen?",
- "deleteConfirmWithWarning": "{item} \"{name}\" wirklich löschen? {warning}",
"shifts": "Schichten",
"success": "Erfolgreich",
"error": "Fehler",
+ "fetchError": "{item} konnte nicht geladen werden",
+ "transferError": "{item} konnte nicht übertragen werden",
+ "banError": "{item} konnte nicht gesperrt werden",
+ "unbanError": "Sperre für {item} konnte nicht aufgehoben werden",
+ "banned": "{item} erfolgreich gesperrt",
+ "unbanned": "Sperre für {item} erfolgreich aufgehoben",
+ "transferred": "{item} erfolgreich übertragen",
+ "copyError": "{item} konnte nicht kopiert werden",
+ "copied": "{item} kopiert",
+ "revokeError": "{item} konnte nicht widerrufen werden",
+ "revoked": "{item} erfolgreich widerrufen",
+ "passwordReset": "Passwort erfolgreich zurückgesetzt",
+ "passwordResetError": "Fehler beim Zurücksetzen des Passworts",
+ "search": "Suchen...",
+ "noResults": "Keine Ergebnisse gefunden",
"createdCount": "{count} erstellt",
"updatedCount": "{count} aktualisiert",
"deletedCount": "{count} gelöscht",
+ "copy": "Kopieren",
+ "yes": "Ja",
+ "no": "Nein",
+ "viewAll": "Alle anzeigen",
+ "viewDetails": "Details anzeigen",
"weekday": {
"monday": "Mo",
"tuesday": "Di",
@@ -39,26 +63,86 @@
"friday": "Fr",
"saturday": "Sa",
"sunday": "So"
+ },
+ "labels": {
+ "name": "Name",
+ "email": "E-Mail",
+ "password": "Passwort",
+ "newPassword": "Neues Passwort",
+ "confirmPassword": "Passwort bestätigen",
+ "status": "Status",
+ "action": "Aktion",
+ "time": "Zeit",
+ "startDate": "Startdatum",
+ "endDate": "Enddatum",
+ "ipAddress": "IP-Adresse",
+ "severity": "Schweregrad",
+ "permission": "Berechtigung",
+ "permissions": {
+ "admin": "Admin",
+ "read": "Lesen",
+ "write": "Schreiben",
+ "none": "Keinen Zugriff"
+ },
+ "notes": "Notizen",
+ "calendar": "Kalender",
+ "shifts": "Schichten",
+ "presets": "Vorlagen",
+ "shares": "Freigaben",
+ "sharedCalendars": "Geteilte Kalender",
+ "user": "Benutzer",
+ "users": "Benutzer"
+ },
+ "status": {
+ "active": "Aktiv",
+ "inactive": "Inaktiv"
+ },
+ "roles": {
+ "admin": "Admin",
+ "superadmin": "Superadmin",
+ "user": "Benutzer"
+ },
+ "time": {
+ "never": "Niemals",
+ "lastActive": "Zuletzt aktiv"
+ },
+ "filters": {
+ "allSeverities": "Alle Schweregrade",
+ "clearFilters": "Filter löschen"
+ },
+ "severity": {
+ "info": "Info",
+ "warning": "Warnung",
+ "error": "Fehler",
+ "critical": "Kritisch"
+ },
+ "stats": {
+ "statistics": "Statistiken",
+ "created": "Erstellt"
+ },
+ "auth": {
+ "activeSessions": "Aktive Sitzungen",
+ "connectedAccounts": "Verbundene Konten"
+ },
+ "empty": {
+ "noUsersFound": "Keine Benutzer gefunden"
}
},
"validation": {
- "passwordMatch": "Passwörter stimmen nicht überein",
- "passwordIncorrect": "Falsches Passwort",
- "passwordRequired": "Passwort erforderlich",
"fileRequired": "Bitte wähle eine Datei aus",
"fileTooLarge": "Datei ist zu groß. Maximale Größe beträgt {maxSize}.",
"urlRequired": "Bitte gib eine URL ein",
"urlInvalid": "Ungültiges URL-Format",
- "urlAlreadyExists": "Diese URL wurde bereits hinzugefügt"
+ "urlAlreadyExists": "Diese URL wurde bereits hinzugefügt",
+ "passwordRequired": "Passwort ist erforderlich",
+ "passwordTooShort": "Passwort muss mindestens 8 Zeichen lang sein",
+ "passwordsNoMatch": "Passwörter stimmen nicht überein"
},
"form": {
"namePlaceholder": "z.B. {example}",
- "nameLabel": "Name",
"colorLabel": "Farbe",
"notesLabel": "Notizen (optional)",
"notesPlaceholder": "Zusätzliche Informationen...",
- "passwordLabel": "Passwort",
- "passwordPlaceholder": "Passwort eingeben",
"urlLabel": "URL",
"urlPlaceholder": "https://..."
},
@@ -72,17 +156,15 @@
"createDescription": "Erstelle einen neuen Kalender, um deine Schichten zu organisieren",
"selectDescription": "Wähle einen Kalender aus, um deine Schichten zu verwalten",
"name": "Kalendername",
+ "myCalendars": "Meine Kalender",
+ "sharedCalendars": "Geteilte Kalender",
+ "tokenCalendars": "Via Zugangslink",
+ "publicCalendars": "Öffentliche Kalender",
"select": "Dein BetterShift Kalender",
"deleteCalendar": "Kalender löschen",
"deleteWarning": "Alle Schichten, Presets und Notizen werden ebenfalls gelöscht.",
"settings": "Kalendereinstellungen für \"{name}\"",
- "settingsDescription": "Passe Name, Farbe und Passwortschutz an",
- "passwordProtected": "Kalender ist passwortgeschützt",
- "passwordRequiredToEdit": "Bitte gib dein aktuelles Passwort ein, um Einstellungen zu ändern.",
- "currentPasswordRequired": "Erforderlich, um Änderungen zu speichern",
- "lockCalendar": "Kalender komplett sperren",
- "lockCalendarHint": "Sperrt Kalender komplett - Passwort zum sehen und verwalten erforderlich",
- "lockRequiresPassword": "Kalendersperre erfordert ein Passwort",
+ "settingsDescription": "Passe Name und Farbe an",
"compare": "Vergleichen",
"compareMode": "Vergleichsmodus",
"exitCompare": "Vergleich beenden",
@@ -93,30 +175,28 @@
"mobileNotOptimized": "Die Vergleichsansicht ist nicht für Mobile optimiert. Für die beste Erfahrung nutze bitte einen größeren Bildschirm.",
"shareLink": "Link teilen",
"shareLinkDescription": "Kopiere den Link zur Vergleichsansicht",
- "linkCopied": "Link in Zwischenablage kopiert"
+ "browseCalendars": "Geteilte Kalender",
+ "browseCalendarsDescription": "Kalender-Abonnements entdecken und verwalten",
+ "subscribe": "Abonnieren",
+ "subscribed": "Abonniert",
+ "noPublicCalendars": "Keine öffentlichen Kalender verfügbar",
+ "subscriptionSuccess": "Abonniert: {name}",
+ "unsubscribeSuccess": "Deabonniert: {name}",
+ "subscribeTooltip": "Diesen Kalender abonnieren",
+ "unsubscribeTooltip": "Diesen Kalender deabonnieren",
+ "sharedTab": "Geteilt",
+ "publicTab": "Öffentlich",
+ "hiddenTab": "Ausgeblendet",
+ "publicBadge": "Öffentlich",
+ "showAgain": "Wieder anzeigen",
+ "noSharedCalendars": "Noch keine mit dir geteilten Kalender",
+ "noHiddenCalendars": "Keine ausgeblendeten Kalender"
},
"color": {
"custom": "Eigene Farbe",
"customTitle": "Eigene Farbe wählen",
"customDescription": "Wähle eine eigene Farbe mit dem Farbwähler"
},
- "password": {
- "optional": "Passwortschutz (optional)",
- "management": "Passwortverwaltung",
- "currentPassword": "Aktuelles Passwort",
- "currentPasswordPlaceholder": "Aktuelles Passwort eingeben",
- "newPassword": "Neues Passwort",
- "newPasswordPlaceholder": "Neues Passwort eingeben",
- "confirmPassword": "Passwort bestätigen",
- "confirmPasswordPlaceholder": "Passwort bestätigen",
- "removePassword": "Passwort entfernen",
- "enter": "Passwort für \"{name}\" eingeben",
- "enterCalendarPassword": "Kalenderpasswort eingeben",
- "currentlyLocked": "Dieser Kalender ist derzeit gesperrt.",
- "unlockRequired": "Kalender ist passwortgeschützt",
- "unlockRequiredDescription": "Dieser Kalender ist passwortgeschützt. Bitte entsperre den Kalender, um Vorlagen zu verwalten und Schichten zu erstellen.",
- "unlockCalendar": "Kalender entsperren"
- },
"note": {
"create": "{item} erstellen",
"edit": "{item} bearbeiten",
@@ -243,10 +323,7 @@
"radarDescription": "Vergleiche Top-Schichttypen nach Gesamtstunden und Durchschnitt"
},
"sync": {
- "refreshing": "Aktualisiere Daten...",
- "resyncing": "Synchronisiere nach Verbindungsunterbrechung...",
"reconnected": "Verbindung wiederhergestellt",
- "offline": "Keine Internetverbindung",
"disconnected": "Verbindung zum Server verloren"
},
"onboarding": {
@@ -254,6 +331,11 @@
"description": "Erstelle deinen ersten Kalender, um deine Schichten zu verwalten.",
"createCalendar": "Kalender erstellen"
},
+ "guestEmptyState": {
+ "title": "Keine öffentlichen Kalender verfügbar",
+ "description": "Es sind derzeit keine öffentlichen Kalender freigegeben. Bitte melde dich an, um eigene Kalender zu erstellen und zu verwalten.",
+ "loginButton": "Zur Anmeldung"
+ },
"footer": {
"version": "Version",
"github": "GitHub",
@@ -290,7 +372,6 @@
"hideFromStats": "Aus Statistik ausblenden",
"hideFromStatsHint": "Schichten dieses Kalenders aus der Statistik ausschließen",
"lastSynced": "Zuletzt synchronisiert",
- "syncError": "Kalender konnte nicht synchronisiert werden",
"delete": "Externen Kalender löschen",
"deleteConfirm": "Diesen externen Kalender löschen? Alle importierten Schichten werden entfernt.",
"hintsTitle": "Kalender-URL finden",
@@ -351,5 +432,359 @@
"available": "Update verfügbar",
"newVersion": "Version {version} ist verfügbar",
"viewChangelog": "Changelog anzeigen"
+ },
+ "auth": {
+ "login": "Anmelden",
+ "loginTitle": "Bei BetterShift anmelden",
+ "loginDescription": "Melde dich mit deinem Konto an oder verwende einen der Provider unten",
+ "register": "Registrieren",
+ "registerTitle": "Konto erstellen",
+ "registerDescription": "Erstelle ein neues Konto, um loszulegen",
+ "logout": "Abmelden",
+ "profile": "Profil",
+ "profileTitle": "Dein Profil",
+ "profileDescription": "Verwalte deine Kontoeinstellungen und Präferenzen",
+ "profileBasicInfoDescription": "Deine grundlegenden Kontoinformationen",
+ "changePasswordDescription": "Aktualisiere dein Passwort, um dein Konto sicher zu halten",
+ "connectedAccountsDescription": "Verwalte deine verbundenen OAuth-Anbieter",
+ "dangerZone": "Gefahrenzone",
+ "dangerZoneDescription": "Unwiderrufliche Aktionen, die dein Konto betreffen",
+ "logoutDescription": "Von deiner aktuellen Sitzung abmelden",
+ "deleteAccountDescription": "Lösche dein Konto und alle Daten dauerhaft",
+ "noConnectedAccounts": "Noch keine verbundenen Konten",
+ "emailPasswordAuth": "E-Mail/Passwort",
+ "emailPlaceholder": "[email protected]",
+ "passwordPlaceholder": "Dein Passwort",
+ "currentPassword": "Aktuelles Passwort",
+ "confirmPasswordLabel": "Passwortbestätigung",
+ "enterPassword": "Passwort eingeben",
+ "namePlaceholder": "Dein Name",
+ "continueWith": "Weiter mit {provider}",
+ "continueAsGuest": "Als Gast fortfahren",
+ "alreadyHaveAccount": "Hast du bereits ein Konto?",
+ "noAccountYet": "Noch kein Konto?",
+ "changePassword": "Passwort ändern",
+ "deleteAccount": "Konto löschen",
+ "editProfile": "Profil bearbeiten",
+ "editProfileDescription": "Aktualisiere deinen Namen, E-Mail und Profilbild",
+ "profileUpdated": "Profil erfolgreich aktualisiert",
+ "profilePicture": "Profilbild",
+ "avatarHint": "Max. 5MB. Unterstützte Formate: JPEG, PNG, GIF, WebP",
+ "invalidImageType": "Ungültiger Dateityp. Bitte wähle ein Bild aus.",
+ "imageTooLarge": "Bild ist zu groß. Maximale Größe ist 5MB.",
+ "avatarUploadFailed": "Fehler beim Hochladen des Profilbilds",
+ "uploadingImage": "Bild wird hochgeladen...",
+ "deleteAccountConfirm": "Bist du sicher, dass du dein Konto löschen möchtest? Diese Aktion kann nicht rückgängig gemacht werden.",
+ "loginSuccess": "Erfolgreich angemeldet",
+ "loginError": "Anmeldung fehlgeschlagen",
+ "registrationDisabled": "Registrierung deaktiviert",
+ "registrationDisabledDescription": "Die Registrierung neuer Benutzer ist derzeit deaktiviert. Bitte kontaktiere einen Administrator, wenn du ein Konto benötigst.",
+ "registerSuccess": "Konto erfolgreich erstellt",
+ "registerError": "Registrierung fehlgeschlagen",
+ "logoutSuccess": "Erfolgreich abgemeldet",
+ "passwordChanged": "Passwort erfolgreich geändert",
+ "accountDeleted": "Konto erfolgreich gelöscht",
+ "emailRequired": "E-Mail ist erforderlich",
+ "nameRequired": "Name ist erforderlich",
+ "emailAlreadyExists": "Diese E-Mail-Adresse wird bereits verwendet",
+ "provider": {
+ "google": "Google",
+ "github": "GitHub",
+ "discord": "Discord",
+ "customOidc": "SSO"
+ },
+ "activeSessionsDescription": "Verwalte deine angemeldeten Geräte und Sitzungen",
+ "noActiveSessions": "Keine aktiven Sitzungen",
+ "browser": "Browser",
+ "operatingSystem": "Betriebssystem",
+ "logoutAllDevices": "Von allen anderen Geräten abmelden",
+ "sessionsRevokedCount": "Von {count} Gerät(en) abgemeldet",
+ "accountBanned": "Konto gesperrt"
+ },
+ "guest": {
+ "viewingAsGuest": "Du betrachtest als Gast",
+ "bannerMessage": "Du betrachtest diesen Kalender als Gast. Melde dich an für vollen Zugriff.",
+ "loginForFullAccess": "Anmelden für vollen Zugriff",
+ "cannotEdit": "Du kannst im Nur-Lesen-Modus nicht bearbeiten"
+ },
+ "share": {
+ "manageSharing": "Freigaben verwalten",
+ "manageSharingDescription": "Bestimme, wer auf \"{name}\" zugreifen kann",
+ "userShares": "Benutzerfreigaben",
+ "publicAccess": "Öffentlicher Zugriff",
+ "accessLinks": "Zugangslinks",
+ "public": "Öffentlich",
+ "links": "Links",
+ "share": "Freigabe",
+ "sharedBy": "Geteilt von",
+ "sharedOn": "Geteilt am",
+ "addUser": "Benutzer hinzufügen",
+ "addUserDescription": "Suche nach einem Benutzer, um diesen Kalender zu teilen",
+ "searchUser": "Benutzer suchen",
+ "searchUserPlaceholder": "Name oder E-Mail eingeben...",
+ "selectedUser": "Ausgewählter Benutzer",
+ "noShares": "Noch keine Benutzer haben Zugriff",
+ "noSharesDescription": "Teile diesen Kalender mit anderen Benutzern zur Zusammenarbeit",
+ "userSharesDescription": "Verwalte, wer auf diesen Kalender zugreifen kann",
+ "publicAccessDescription": "Bestimme den öffentlichen Zugriff für authentifizierte und Gastbenutzer",
+ "publicPermissionNoneDesc": "Niemand kann ohne Freigabe auf diesen Kalender zugreifen",
+ "publicPermissionReadDesc": "Jeder authentifizierte Benutzer kann den Kalender ansehen",
+ "publicPermissionWriteDesc": "Jeder authentifizierte Benutzer kann den Kalender ansehen und bearbeiten",
+ "shareAdded": "Kalender erfolgreich geteilt",
+ "shareUpdated": "Berechtigung erfolgreich aktualisiert",
+ "shareRemoved": "Zugriff erfolgreich entfernt",
+ "removeAccess": "Zugriff entfernen",
+ "removeShareConfirmTitle": "Kalenderzugriff entfernen?",
+ "removeShareConfirmDesc": "Bist du sicher, dass du den Zugriff für {user} entfernen möchtest? Diese Person kann den Kalender dann nicht mehr sehen oder bearbeiten.",
+ "you": "Du",
+ "sharedWithYou": "Mit dir geteilt"
+ },
+ "token": {
+ "accessLinks": "Zugangslinks",
+ "accessLinksDescription": "Teile diesen Kalender über sichere Links",
+ "createLink": "Link erstellen",
+ "createFirstLink": "Ersten Link erstellen",
+ "noTokensYet": "Noch keine Zugangslinks",
+ "noTokensDescription": "Erstelle einen Freigabelink, um anderen Zugriff zu gewähren",
+ "unnamed": "Unbenannt",
+ "namePlaceholder": "z.B. Familien-Link, Arbeitsteam",
+ "token": "Token",
+ "tokenValue": "Token-Wert",
+ "readOnlyDescription": "Schichten und Notizen ansehen",
+ "editDescription": "Schichten erstellen und bearbeiten",
+ "expiration": "Ablauf",
+ "expires": "Läuft ab",
+ "expired": "Abgelaufen",
+ "expiration1Day": "1 Tag",
+ "expiration7Days": "7 Tage",
+ "expiration30Days": "30 Tage",
+ "expirationNever": "Niemals",
+ "expiresOn": "Läuft ab am",
+ "usage": "Nutzung",
+ "usedCount": "{count, plural, =0 {Nie verwendet} =1 {1x verwendet} other {#x verwendet}}",
+ "neverUsed": "Nie verwendet",
+ "enable": "Aktivieren",
+ "disable": "Deaktivieren",
+ "revoke": "Widerrufen",
+ "revokeConfirm": "Zugangslink widerrufen?",
+ "revokeConfirmDescription": "Bist du sicher, dass du \"{name}\" widerrufen möchtest? Jeder, der diesen Link verwendet, verliert sofort den Zugriff.",
+ "generate": "Link generieren",
+ "shareLink": "Freigabelink",
+ "linkCreated": "Link erstellt!",
+ "linkCreatedDescription": "Dein Freigabelink wurde erfolgreich erstellt",
+ "saveWarning": "Speichere diesen Link jetzt - er wird nicht erneut angezeigt!",
+ "shareInfo": "Jeder mit diesem Link kann auf deinen Kalender mit der angegebenen Berechtigungsstufe zugreifen",
+ "accessedViaLink": "Zugriff über Freigabelink",
+ "linkName": "Link-Name",
+ "createLinkDescription": "Erstelle einen Zugangslink, um diesen Kalender zu teilen"
+ },
+ "rateLimit": {
+ "title": "Zu viele Anfragen",
+ "message": "Bitte versuche es in {time} erneut.",
+ "fallback": "Bitte warte einen Moment, bevor du es erneut versuchst.",
+ "second": "Sekunde",
+ "seconds": "Sekunden",
+ "minute": "Minute",
+ "minutes": "Minuten",
+ "hour": "Stunde",
+ "hours": "Stunden"
+ },
+ "activityLog": {
+ "title": "Aktivitätsprotokoll",
+ "description": "Zeigt deine Kontoaktivität und Sicherheitsereignisse an",
+ "noLogs": "Noch keine Aktivität aufgezeichnet",
+ "eventType": "Ereignistyp",
+ "resource": "Ressource",
+ "details": "Details",
+ "clearAll": "Alle löschen",
+ "refresh": "Aktualisieren",
+ "refreshed": "Aktivitätsprotokoll aktualisiert",
+ "confirmClear": "Bist du sicher, dass du alle Aktivitätsprotokolle löschen möchtest? Dies kann nicht rückgängig gemacht werden.",
+ "totalLogs": "{count} Protokolle insgesamt",
+ "showingResults": "Zeige {start}-{end} von {total}",
+ "searchPlaceholder": "Suche nach Aktion, Ressource oder ID...",
+ "noMetadata": "Keine zusätzlichen Details verfügbar",
+ "allTypes": "Alle Typen",
+ "auth": "Authentifizierung",
+ "sync": "Synchronisation",
+ "security": "Sicherheit"
+ },
+ "admin": {
+ "title": "Admin-Panel",
+ "adminPanel": "Admin-Panel",
+ "dashboard": "Dashboard",
+ "usersMenu": "Benutzer",
+ "calendarsMenu": "Kalender",
+ "orphanedCalendars": "Verwaiste Kalender",
+ "auditLogs": "Audit-Logs",
+ "backToApp": "Zurück zur App",
+ "superadminBadge": "Superadmin",
+ "expandSidebar": "Seitenleiste ausklappen",
+ "collapseSidebar": "Seitenleiste einklappen",
+ "accessDenied": "Admin-Zugriff erforderlich",
+ "stats": {
+ "totalUsers": "Benutzer gesamt",
+ "totalCalendars": "Kalender gesamt",
+ "orphanedCalendars": "Verwaiste Kalender",
+ "totalShifts": "Schichten gesamt",
+ "activeShares": "Aktive Freigaben",
+ "recentActivity": "Letzte Admin Aktivitäten",
+ "usersByRole": "{superadmin} Superadmin, {admin} Admin, {user} Benutzer",
+ "calendarsDescription": "Kalender mit Besitzern",
+ "orphanedDescription": "Kalender ohne Besitzer",
+ "sharesDescription": "{user} Benutzerfreigaben, {token} Token-Freigaben",
+ "shiftsDescription": "Schichten über alle Kalender",
+ "last7Days": "Letzte 7 Tage",
+ "needsAttention": "Benötigt Aufmerksamkeit"
+ },
+ "dashboardDescription": "Willkommen im BetterShift Admin-Panel",
+ "orphanedCalendarsWarning": "Verwaiste Kalender erkannt",
+ "orphanedCalendarsWarningDescription": "{count, plural, =1 {Es gibt 1 Kalender ohne Besitzer} other {Es gibt # Kalender ohne Besitzer}}. Bitte weise diese(n) Benutzern zu.",
+ "manageOrphanedCalendars": "Verwaiste Kalender verwalten",
+ "recentActivityDescription": "Neueste Admin-Aktivitätsprotokolle",
+ "statsFetchError": "Fehler beim Laden der Statistiken",
+ "userManagement": "Benutzerverwaltung",
+ "userManagementDescription": "Benutzerkonten und Berechtigungen verwalten",
+ "searchUsers": "Nach Name oder E-Mail suchen...",
+ "allRoles": "Alle Rollen",
+ "allStatuses": "Alle Status",
+ "banned": "Gesperrt",
+ "role": "Rolle",
+ "calendarsCount": "Kalender",
+ "page": "Seite",
+ "usersCount": "{count, plural, =0 {Keine Benutzer} =1 {1 Benutzer} other {# Benutzer}}",
+ "neverActive": "Nie",
+ "editUser": "Benutzer bearbeiten",
+ "editUserDescription": "Benutzerinformationen und Berechtigungen aktualisieren",
+ "userDetails": "Benutzerdetails",
+ "userDetailsDescription": "Detaillierte Benutzerinformationen anzeigen",
+ "ownedCalendars": "Eigene Kalender",
+ "joined": "Beigetreten",
+ "banUser": "Benutzer sperren",
+ "banUserConfirm": "Benutzer {name} sperren?",
+ "banWarning": "Der Benutzer wird sofort abgemeldet und kann sich erst wieder anmelden, wenn die Sperre aufgehoben wird.",
+ "banReason": "Sperrgrund",
+ "banReasonPlaceholder": "Gebe den Grund für die Sperrung ein...",
+ "permanentBan": "Permanente Sperre",
+ "banExpires": "Sperre läuft ab",
+ "confirmBan": "Benutzer sperren",
+ "unbanUser": "Sperre aufheben",
+ "unbanUserConfirm": "Sperre für Benutzer {name} aufheben?",
+ "originalBanReason": "Ursprünglicher Sperrgrund",
+ "confirmUnban": "Sperre aufheben",
+ "deleteUser": "Benutzer löschen",
+ "deleteUserConfirm": "Benutzer {name} löschen?",
+ "deleteWarning": "Dies wird alle Kalender, Schichten, Notizen und Freigaben dieses Benutzers dauerhaft löschen.",
+ "deleteUnderstood": "Ich verstehe, dass diese Aktion nicht rückgängig gemacht werden kann",
+ "deleteConfirmation": "Gebe \"{name}\" ein, um zu bestätigen",
+ "deleteConfirmationHint": "Gebe den exakten Benutzernamen ein, um das Löschen zu bestätigen",
+ "confirmDelete": "Benutzer löschen",
+ "resetPassword": "Passwort zurücksetzen",
+ "resetPasswordFor": "Passwort für {name} zurücksetzen",
+ "passwordResetWarning": "Es wird keine E-Mail gesendet. Der User muss manuell über das neue Passwort informiert werden.",
+ "passwordResetSecurityNote": "Das Passwort wird nur in diesem Dialog angezeigt. Speichere es jetzt.",
+ "generatePassword": "Zufälliges Passwort generieren",
+ "passwordPlaceholder": "Mindestens 8 Zeichen",
+ "confirmPasswordPlaceholder": "Passwort erneut eingeben",
+ "copyPassword": "Passwort in Zwischenablage kopieren",
+ "setPassword": "Passwort setzen",
+ "bannedUntil": "Gesperrt bis {date}",
+ "bannedPermanently": "Dauerhaft gesperrt",
+ "userNotFound": "Benutzer nicht gefunden",
+ "namePlaceholder": "Vollständigen Namen eingeben",
+ "emailPlaceholder": "[email protected]",
+ "roleChangeWarning": "Eine Änderung der Benutzerrolle wirkt sich sofort auf die Berechtigungen aus",
+ "calendars": {
+ "title": "Kalenderverwaltung",
+ "description": "Verwalte alle Kalender im System",
+ "owner": "Besitzer",
+ "updated": "Aktualisiert",
+ "guestPermission": "Gastberechtigung",
+ "orphaned": "Verwaist",
+ "noOwner": "Kein Besitzer zugewiesen",
+ "currentOwner": "Aktueller Besitzer",
+ "allStatuses": "Alle Kalender",
+ "orphanedOnly": "Nur verwaiste",
+ "withOwner": "Mit Besitzer",
+ "searchPlaceholder": "Nach Name suchen...",
+ "calendarsCount": "{count, plural, =0 {Keine Kalender} =1 {1 Kalender} other {# Kalender}}",
+ "selectedCount": "{count, plural, =1 {1 Kalender ausgewählt} other {# Kalender ausgewählt}}",
+ "transferSelected": "Ausgewählte übertragen",
+ "clearSelection": "Auswahl löschen",
+ "noCalendarsFound": "Keine Kalender gefunden",
+ "noSearchResults": "Keine Kalender entsprechen Ihrer Suche",
+ "orphanedWarning": "{count, plural, =1 {1 verwaister Kalender} other {# verwaiste Kalender}} benötigen Besitzerzuweisung",
+ "orphanedWarningDescription": "Bitte weise diese Kalender Benutzern zu oder lösche sie.",
+ "editCalendar": "Kalender bearbeiten",
+ "transferOwnership": "Besitz übertragen",
+ "deleteCalendar": "Kalender löschen",
+ "calendarDetails": "Kalenderdetails",
+ "calendarDetailsDescription": "Detaillierte Kalenderinformationen anzeigen",
+ "userShares": "Benutzer",
+ "tokenShares": "Token",
+ "userSharesList": "Benutzer-Freigaben",
+ "tokenSharesList": "Token-Freigaben",
+ "externalSyncs": "Externe Synchronisationen",
+ "externalSyncsShort": "Syncs",
+ "lastSynced": "Zuletzt synchronisiert",
+ "quickActions": "Schnellaktionen",
+ "editCalendarDescription": "Kalenderinformationen aktualisieren",
+ "namePlaceholder": "Kalendername eingeben",
+ "guestPermissionHint": "Kontrolliert den öffentlichen Zugriff auf diesen Kalender",
+ "transferSingleDescription": "Besitz von \"{name}\" übertragen",
+ "transferMultipleDescription": "{count, plural, =1 {1 Kalender} other {# Kalender}} werden übertragen",
+ "calendarsToTransfer": "Zu übertragende Kalender",
+ "calendarToTransfer": "Zu übertragender Kalender",
+ "selectNewOwner": "Neuen Besitzer auswählen",
+ "searchUserPlaceholder": "Nach Name oder E-Mail suchen...",
+ "searchUserHint": "Gib mindestens 2 Zeichen ein, um zu suchen",
+ "newOwner": "Neuer Besitzer",
+ "transferButton": "Besitz übertragen",
+ "deleteCalendarConfirm": "Kalender \"{name}\" löschen?",
+ "deleteWarning": "Dadurch werden alle Schichten, Notizen, Vorlagen, Freigaben und externen Synchronisationen dieses Kalenders dauerhaft gelöscht.",
+ "deleteUnderstood": "Ich verstehe, dass diese Aktion nicht rückgängig gemacht werden kann",
+ "deleteConfirmation": "Gib \"{name}\" zur Bestätigung ein",
+ "deleteConfirmationHint": "Gib den genauen Kalendernamen ein, um das Löschen zu bestätigen",
+ "confirmDelete": "Kalender löschen",
+ "bulkDeleteConfirm": "{count, plural, =1 {1 Kalender löschen?} other {# Kalender löschen?}}",
+ "bulkDeleteWarning": "Dadurch werden alle Schichten, Notizen, Vorlagen, Freigaben und externen Synchronisationen dieser Kalender dauerhaft gelöscht.",
+ "calendarsToDelete": "Zu löschende Kalender",
+ "andMore": "... und {count} weitere",
+ "calendarsDeleted": "{count, plural, =1 {1 Kalender gelöscht} other {# Kalender gelöscht}}",
+ "calendarsTransferred": "{count, plural, =1 {1 Kalender übertragen} other {# Kalender übertragen}}"
+ },
+ "auditLogsDescription": "Alle Protokolle verwalten",
+ "allActions": "Alle Aktionen",
+ "adminActions": "Admin-Aktionen",
+ "calendarActions": "Kalender-Aktionen",
+ "authActions": "Authentifizierung",
+ "securityActions": "Sicherheit",
+ "searchLogs": "Aktion, Metadaten suchen...",
+ "showingLogs": "Zeige {from} bis {to} von {total} Protokollen",
+ "timestamp": "Zeitstempel",
+ "userAgent": "User Agent",
+ "metadata": "Metadaten",
+ "noLogsFound": "Keine Audit-Protokolle gefunden",
+ "deleteOldLogs": "Alte Protokolle löschen",
+ "deleteLogsDescription": "Audit-Protokolle löschen, die älter als ein bestimmtes Datum sind. Diese Aktion kann nicht rückgängig gemacht werden.",
+ "deleteLogsBefore": "Protokolle löschen älter als",
+ "deleteLogsBeforeHint": "Alle Protokolle vor diesem Datum werden dauerhaft gelöscht",
+ "deleteLogsWarning": "Diese Aktion ist permanent und kann nicht rückgängig gemacht werden. Alle Audit-Protokolle vor dem ausgewählten Datum werden aus der Datenbank gelöscht.",
+ "confirmPermanentDeletion": "Ich verstehe, dass Audit-Protokolle dauerhaft gelöscht werden",
+ "pleaseSelectDate": "Bitte wähle ein Datum",
+ "pleaseConfirmDeletion": "Bitte bestätige das Löschen",
+ "willDeleteLogsOlderThan": "Alle Protokolle älter als {date} werden gelöscht",
+ "preview": "Vorschau",
+ "auditLogDetails": "Audit-Log-Details",
+ "resourceType": "Ressourcentyp",
+ "resourceId": "Ressourcen-ID",
+ "logId": "Log-ID",
+ "userVisible": "Für Benutzer sichtbar",
+ "unknownUser": "Unbekannter Benutzer",
+ "systemAction": "System",
+ "selectedLogs": "{count} ausgewählt",
+ "clearSelection": "Auswahl aufheben",
+ "deleteSelectedLogsDescription": "{count, plural, one {# ausgewähltes Protokoll} other {# ausgewählte Protokolle}} löschen. Diese Aktion kann nicht rückgängig gemacht werden.",
+ "willDeleteSelectedLogs": "{count, plural, one {# Protokoll} other {# Protokolle}} werden dauerhaft gelöscht"
}
}
diff --git a/messages/en.json b/messages/en.json
index 1bc3a97..5c14c6c 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -8,12 +8,16 @@
"cancel": "Cancel",
"save": "Save",
"saving": "Saving...",
+ "close": "Close",
+ "optional": "(optional)",
"delete": "Delete",
- "create": "Create",
"loading": "Loading...",
- "required": "required",
- "unlock": "Unlock",
"add": "Add",
+ "adding": "Adding...",
+ "or": "or",
+ "next": "Next",
+ "previous": "Previous",
+ "of": "of",
"unsavedChanges": "Unsaved Changes",
"unsavedChangesDescription": "You have unsaved changes. Do you really want to close without saving?",
"closeWithoutSaving": "Close Without Saving",
@@ -24,13 +28,33 @@
"updateError": "Failed to update {item}",
"deleteError": "Failed to delete {item}",
"deleteConfirm": "Really delete {item} \"{name}\"?",
- "deleteConfirmWithWarning": "Really delete {item} \"{name}\"? {warning}",
"shifts": "Shifts",
"success": "Success",
"error": "Error",
+ "fetchError": "Failed to load {item}",
+ "transferError": "Failed to transfer {item}",
+ "banError": "Failed to ban {item}",
+ "unbanError": "Failed to unban {item}",
+ "banned": "{item} banned successfully",
+ "unbanned": "{item} unbanned successfully",
+ "transferred": "{item} transferred successfully",
+ "copyError": "Failed to copy {item}",
+ "copied": "{item} copied",
+ "revokeError": "Failed to revoke {item}",
+ "revoked": "{item} revoked successfully",
+ "passwordReset": "Password reset successfully",
+ "passwordResetError": "Failed to reset password",
+ "search": "Search...",
+ "noResults": "No results found",
"createdCount": "{count} created",
"updatedCount": "{count} updated",
"deletedCount": "{count} deleted",
+ "copy": "Copy",
+ "yes": "Yes",
+ "no": "No",
+ "deleteSelected": "Delete Selected",
+ "viewAll": "View All",
+ "viewDetails": "View Details",
"weekday": {
"monday": "Mon",
"tuesday": "Tue",
@@ -39,26 +63,86 @@
"friday": "Fri",
"saturday": "Sat",
"sunday": "Sun"
+ },
+ "labels": {
+ "name": "Name",
+ "email": "Email",
+ "password": "Password",
+ "newPassword": "New Password",
+ "confirmPassword": "Confirm Password",
+ "status": "Status",
+ "action": "Action",
+ "time": "Time",
+ "startDate": "Start Date",
+ "endDate": "End Date",
+ "ipAddress": "IP Address",
+ "severity": "Severity",
+ "permission": "Permission",
+ "permissions": {
+ "admin": "Admin",
+ "read": "Read",
+ "write": "Write",
+ "none": "No Access"
+ },
+ "notes": "Notes",
+ "calendar": "Calendar",
+ "shifts": "Shifts",
+ "presets": "Presets",
+ "shares": "Shares",
+ "sharedCalendars": "Shared Calendars",
+ "user": "User",
+ "users": "Users"
+ },
+ "status": {
+ "active": "Active",
+ "inactive": "Inactive"
+ },
+ "roles": {
+ "admin": "Admin",
+ "superadmin": "Superadmin",
+ "user": "User"
+ },
+ "time": {
+ "never": "Never",
+ "lastActive": "Last Active"
+ },
+ "filters": {
+ "allSeverities": "All Severities",
+ "clearFilters": "Clear Filters"
+ },
+ "severity": {
+ "info": "Info",
+ "warning": "Warning",
+ "error": "Error",
+ "critical": "Critical"
+ },
+ "stats": {
+ "statistics": "Statistics",
+ "created": "Created"
+ },
+ "auth": {
+ "activeSessions": "Active Sessions",
+ "connectedAccounts": "Connected Accounts"
+ },
+ "empty": {
+ "noUsersFound": "No users found"
}
},
"validation": {
- "passwordMatch": "Passwords do not match",
- "passwordIncorrect": "Incorrect password",
- "passwordRequired": "Password required",
"fileRequired": "Please select a file",
"fileTooLarge": "File is too large. Maximum size is {maxSize}.",
"urlRequired": "Please enter a URL",
"urlInvalid": "Invalid URL format",
- "urlAlreadyExists": "This URL has already been added"
+ "urlAlreadyExists": "This URL has already been added",
+ "passwordRequired": "Password is required",
+ "passwordTooShort": "Password must be at least 8 characters",
+ "passwordsNoMatch": "Passwords do not match"
},
"form": {
"namePlaceholder": "e.g., {example}",
- "nameLabel": "Name",
"colorLabel": "Color",
"notesLabel": "Notes (optional)",
"notesPlaceholder": "Additional information...",
- "passwordLabel": "Password",
- "passwordPlaceholder": "Enter password",
"urlLabel": "URL",
"urlPlaceholder": "https://..."
},
@@ -72,17 +156,15 @@
"createDescription": "Create a new calendar to organize your shifts",
"selectDescription": "Choose a calendar to manage your shifts",
"name": "Calendar Name",
+ "myCalendars": "My Calendars",
+ "sharedCalendars": "Shared Calendars",
+ "tokenCalendars": "Via Access Link",
+ "publicCalendars": "Public Calendars",
"select": "Your BetterShift Calendar",
"deleteCalendar": "Delete Calendar",
"deleteWarning": "All shifts, presets and notes will also be deleted.",
"settings": "Calendar Settings for \"{name}\"",
- "settingsDescription": "Customize name, color and password protection",
- "passwordProtected": "Calendar is password protected",
- "passwordRequiredToEdit": "Please enter your current password to change settings.",
- "currentPasswordRequired": "Required to save changes",
- "lockCalendar": "Lock calendar completely",
- "lockCalendarHint": "Locks calendar completely - password required to view and manage",
- "lockRequiresPassword": "Locking the calendar requires a password",
+ "settingsDescription": "Customize name and color",
"compare": "Compare Calendars",
"compareMode": "Comparison Mode",
"exitCompare": "Exit Comparison",
@@ -93,30 +175,28 @@
"mobileNotOptimized": "The comparison view is not optimized for mobile. Please use a larger screen for the best experience.",
"shareLink": "Share Link",
"shareLinkDescription": "Copy link to comparison view",
- "linkCopied": "Link copied to clipboard"
+ "browseCalendars": "Shared Calendars",
+ "browseCalendarsDescription": "Discover and manage calendar subscriptions",
+ "subscribe": "Subscribe",
+ "subscribed": "Subscribed",
+ "noPublicCalendars": "No public calendars available",
+ "noSharedCalendars": "No calendars shared with you yet",
+ "noHiddenCalendars": "No hidden calendars",
+ "subscriptionSuccess": "Subscribed to {name}",
+ "unsubscribeSuccess": "Unsubscribed from {name}",
+ "subscribeTooltip": "Subscribe to this calendar",
+ "unsubscribeTooltip": "Unsubscribe from this calendar",
+ "sharedTab": "Shared",
+ "publicTab": "Public",
+ "hiddenTab": "Hidden",
+ "publicBadge": "Public",
+ "showAgain": "Show Again"
},
"color": {
"custom": "Custom",
"customTitle": "Custom Color",
"customDescription": "Choose a custom color using the color picker"
},
- "password": {
- "optional": "Password Protection (optional)",
- "management": "Password Management",
- "currentPassword": "Current Password",
- "currentPasswordPlaceholder": "Enter current password",
- "newPassword": "New Password",
- "newPasswordPlaceholder": "Enter new password",
- "confirmPassword": "Confirm Password",
- "confirmPasswordPlaceholder": "Confirm password",
- "removePassword": "Remove Password",
- "enter": "Enter Password for \"{name}\"",
- "enterCalendarPassword": "Enter calendar password",
- "currentlyLocked": "This calendar is currently locked.",
- "unlockRequired": "Calendar is password protected",
- "unlockRequiredDescription": "This calendar is password protected. Please unlock the calendar to manage presets and create shifts.",
- "unlockCalendar": "Unlock Calendar"
- },
"note": {
"create": "Create {item}",
"edit": "Edit {item}",
@@ -243,10 +323,7 @@
"radarDescription": "Compare top shift types by total hours and average"
},
"sync": {
- "refreshing": "Refreshing data...",
- "resyncing": "Resyncing after disconnect...",
"reconnected": "Connection restored",
- "offline": "No internet connection",
"disconnected": "Connection to server lost"
},
"onboarding": {
@@ -254,6 +331,11 @@
"description": "Create your first calendar to manage your shifts.",
"createCalendar": "Create Calendar"
},
+ "guestEmptyState": {
+ "title": "No Public Calendars Available",
+ "description": "There are currently no public calendars shared. Please log in to create and manage your own calendars.",
+ "loginButton": "Go to Login"
+ },
"footer": {
"version": "Version",
"github": "GitHub",
@@ -290,7 +372,6 @@
"hideFromStats": "Hide from statistics",
"hideFromStatsHint": "Exclude shifts from this calendar from statistics",
"lastSynced": "Last synced",
- "syncError": "Failed to sync calendar",
"delete": "Delete External Calendar",
"deleteConfirm": "Delete this external calendar? All imported shifts will be removed.",
"hintsTitle": "Finding Your Calendar URL",
@@ -351,5 +432,359 @@
"available": "Update Available",
"newVersion": "Version {version} is available",
"viewChangelog": "View Changelog"
+ },
+ "auth": {
+ "login": "Sign In",
+ "loginTitle": "Sign in to BetterShift",
+ "loginDescription": "Sign in with your account or use one of the providers below",
+ "register": "Sign Up",
+ "registerTitle": "Create Account",
+ "registerDescription": "Create a new account to get started",
+ "logout": "Sign Out",
+ "profile": "Profile",
+ "profileTitle": "Your Profile",
+ "profileDescription": "Manage your account settings and preferences",
+ "profileBasicInfoDescription": "Your basic account information",
+ "changePasswordDescription": "Update your password to keep your account secure",
+ "connectedAccountsDescription": "Manage your connected OAuth providers",
+ "dangerZone": "Danger Zone",
+ "dangerZoneDescription": "Irreversible actions that affect your account",
+ "logoutDescription": "Sign out from your current session",
+ "deleteAccountDescription": "Permanently delete your account and all data",
+ "noConnectedAccounts": "No connected accounts yet",
+ "emailPasswordAuth": "Email/Password",
+ "emailPlaceholder": "[email protected]",
+ "passwordPlaceholder": "Your password",
+ "currentPassword": "Current Password",
+ "confirmPasswordLabel": "Password Confirmation",
+ "enterPassword": "Enter password",
+ "namePlaceholder": "Your name",
+ "continueWith": "Continue with {provider}",
+ "alreadyHaveAccount": "Already have an account?",
+ "noAccountYet": "Don't have an account yet?",
+ "changePassword": "Change Password",
+ "deleteAccount": "Delete Account",
+ "editProfile": "Edit Profile",
+ "editProfileDescription": "Update your name, email, and profile picture",
+ "profileUpdated": "Profile updated successfully",
+ "profilePicture": "Profile Picture",
+ "avatarHint": "Max 5MB. Supported formats: JPEG, PNG, GIF, WebP",
+ "invalidImageType": "Invalid file type. Please select an image.",
+ "imageTooLarge": "Image is too large. Maximum size is 5MB.",
+ "avatarUploadFailed": "Failed to upload profile picture",
+ "uploadingImage": "Uploading image...",
+ "deleteAccountConfirm": "Are you sure you want to delete your account? This action cannot be undone.",
+ "loginSuccess": "Signed in successfully",
+ "loginError": "Sign in failed",
+ "accountBanned": "Account Banned",
+ "continueAsGuest": "Continue as Guest",
+ "registrationDisabled": "Registration Disabled",
+ "registrationDisabledDescription": "New user registration is currently disabled. Please contact an administrator if you need an account.",
+ "registerSuccess": "Account created successfully",
+ "registerError": "Registration failed",
+ "logoutSuccess": "Signed out successfully",
+ "passwordChanged": "Password changed successfully",
+ "accountDeleted": "Account deleted successfully",
+ "emailRequired": "Email is required",
+ "nameRequired": "Name is required",
+ "emailAlreadyExists": "This email is already in use",
+ "provider": {
+ "google": "Google",
+ "github": "GitHub",
+ "discord": "Discord",
+ "customOidc": "SSO"
+ },
+ "activeSessionsDescription": "Manage your logged-in devices and sessions",
+ "noActiveSessions": "No active sessions",
+ "browser": "Browser",
+ "operatingSystem": "OS",
+ "logoutAllDevices": "Logout from all other devices",
+ "sessionsRevokedCount": "Logged out from {count} device(s)"
+ },
+ "guest": {
+ "viewingAsGuest": "You are viewing as guest",
+ "bannerMessage": "You are viewing this calendar as a guest. Sign in for full access.",
+ "loginForFullAccess": "Sign in for full access",
+ "cannotEdit": "You cannot edit in read-only mode"
+ },
+ "share": {
+ "manageSharing": "Manage Sharing",
+ "manageSharingDescription": "Control who can access \"{name}\"",
+ "userShares": "User Shares",
+ "publicAccess": "Public Access",
+ "accessLinks": "Access Links",
+ "public": "Public",
+ "links": "Links",
+ "share": "share",
+ "sharedBy": "Shared By",
+ "sharedOn": "Shared On",
+ "addUser": "Add User",
+ "addUserDescription": "Search for a user to share this calendar with",
+ "searchUser": "Search user",
+ "searchUserPlaceholder": "Enter name or email...",
+ "selectedUser": "Selected user",
+ "noShares": "No users have access yet",
+ "noSharesDescription": "Share this calendar with other users to collaborate",
+ "userSharesDescription": "Manage who can access this calendar",
+ "publicAccessDescription": "Control public access for authenticated and guest users",
+ "publicPermissionNoneDesc": "No one can access this calendar without being explicitly shared",
+ "publicPermissionReadDesc": "Any authenticated user can view the calendar",
+ "publicPermissionWriteDesc": "Any authenticated user can view and edit the calendar",
+ "shareAdded": "Calendar shared successfully",
+ "shareUpdated": "Permission updated successfully",
+ "shareRemoved": "Access removed successfully",
+ "removeAccess": "Remove Access",
+ "removeShareConfirmTitle": "Remove calendar access?",
+ "removeShareConfirmDesc": "Are you sure you want to remove access for {user}? They will no longer be able to view or edit this calendar.",
+ "you": "You",
+ "sharedWithYou": "Shared with you"
+ },
+ "token": {
+ "accessLinks": "Access Links",
+ "accessLinksDescription": "Share this calendar via secure links",
+ "createLink": "Create Link",
+ "createFirstLink": "Create First Link",
+ "noTokensYet": "No access links yet",
+ "noTokensDescription": "Create a share link to give other users access",
+ "unnamed": "Unnamed",
+ "namePlaceholder": "e.g., Family Link, Work Team",
+ "token": "Token",
+ "tokenValue": "Token Value",
+ "readOnlyDescription": "View shifts and notes",
+ "editDescription": "Create and edit shifts",
+ "expiration": "Expiration",
+ "expires": "Expires",
+ "expired": "Expired",
+ "expiration1Day": "1 Day",
+ "expiration7Days": "7 Days",
+ "expiration30Days": "30 Days",
+ "expirationNever": "Never",
+ "expiresOn": "Expires on",
+ "usage": "Usage",
+ "usedCount": "{count, plural, =0 {Never used} =1 {Used once} other {Used # times}}",
+ "neverUsed": "Never used",
+ "enable": "Enable",
+ "disable": "Disable",
+ "revoke": "Revoke",
+ "revokeConfirm": "Revoke Access Link?",
+ "revokeConfirmDescription": "Are you sure you want to revoke \"{name}\"? Anyone using this link will immediately lose access.",
+ "generate": "Generate Link",
+ "shareLink": "Share Link",
+ "linkCreated": "Link Created!",
+ "linkCreatedDescription": "Your share link has been created successfully",
+ "saveWarning": "Save this link now - it won't be shown again!",
+ "shareInfo": "Anyone with this link can access your calendar with the specified permission level",
+ "accessedViaLink": "Accessed via Share Link",
+ "linkName": "Link Name",
+ "createLinkDescription": "Create a shareable link to give others access to this calendar"
+ },
+ "rateLimit": {
+ "title": "Too Many Requests",
+ "message": "Please try again in {time}.",
+ "fallback": "Please wait a moment before trying again.",
+ "second": "second",
+ "seconds": "seconds",
+ "minute": "minute",
+ "minutes": "minutes",
+ "hour": "hour",
+ "hours": "hours"
+ },
+ "activityLog": {
+ "title": "Activity Log",
+ "description": "View your account activity and security events",
+ "noLogs": "No activity recorded yet",
+ "eventType": "Event Type",
+ "resource": "Resource",
+ "details": "Details",
+ "clearAll": "Clear All",
+ "refresh": "Refresh",
+ "refreshed": "Activity log refreshed",
+ "confirmClear": "Are you sure you want to clear all activity logs? This cannot be undone.",
+ "totalLogs": "{count} total logs",
+ "showingResults": "Showing {start}-{end} of {total}",
+ "searchPlaceholder": "Search by action, resource, or ID...",
+ "noMetadata": "No additional details available",
+ "allTypes": "All Types",
+ "auth": "Authentication",
+ "sync": "Sync",
+ "security": "Security"
+ },
+ "admin": {
+ "title": "Admin Panel",
+ "adminPanel": "Admin Panel",
+ "dashboard": "Dashboard",
+ "usersMenu": "Users",
+ "calendarsMenu": "Calendars",
+ "orphanedCalendars": "Orphaned Calendars",
+ "auditLogs": "Audit Logs",
+ "backToApp": "Back to App",
+ "superadminBadge": "Superadmin",
+ "expandSidebar": "Expand Sidebar",
+ "collapseSidebar": "Collapse Sidebar",
+ "accessDenied": "Admin access required",
+ "stats": {
+ "totalUsers": "Total Users",
+ "totalCalendars": "Total Calendars",
+ "orphanedCalendars": "Orphaned Calendars",
+ "totalShifts": "Total Shifts",
+ "activeShares": "Active Shares",
+ "recentActivity": "Recent Admin Activity",
+ "usersByRole": "{superadmin} superadmin, {admin} admin, {user} users",
+ "calendarsDescription": "Total calendars with owners",
+ "orphanedDescription": "Calendars without an owner",
+ "sharesDescription": "{user} user shares, {token} token shares",
+ "shiftsDescription": "Total shifts across all calendars",
+ "last7Days": "Last 7 days",
+ "needsAttention": "Needs Attention"
+ },
+ "dashboardDescription": "Welcome to the BetterShift Admin Panel",
+ "orphanedCalendarsWarning": "Orphaned Calendars Detected",
+ "orphanedCalendarsWarningDescription": "{count, plural, =1 {There is 1 calendar without an owner} other {There are # calendars without an owner}}. Please assign them to users.",
+ "manageOrphanedCalendars": "Manage Orphaned Calendars",
+ "recentActivityDescription": "Latest admin activity logs",
+ "statsFetchError": "Failed to load statistics",
+ "userManagement": "User Management",
+ "userManagementDescription": "Manage user accounts and permissions",
+ "searchUsers": "Search by name or email...",
+ "allRoles": "All Roles",
+ "allStatuses": "All Statuses",
+ "banned": "Banned",
+ "role": "Role",
+ "calendarsCount": "Calendars",
+ "page": "page",
+ "usersCount": "{count, plural, =0 {No users} =1 {1 user} other {# users}}",
+ "neverActive": "Never",
+ "editUser": "Edit User",
+ "editUserDescription": "Update user information and permissions",
+ "userDetails": "User Details",
+ "userDetailsDescription": "View detailed user information",
+ "ownedCalendars": "Owned Calendars",
+ "joined": "Joined",
+ "banUser": "Ban User",
+ "banUserConfirm": "Ban user {name}?",
+ "banWarning": "User will be logged out immediately and cannot sign in until unbanned.",
+ "banReason": "Ban Reason",
+ "banReasonPlaceholder": "Enter the reason for banning this user...",
+ "permanentBan": "Permanent ban",
+ "banExpires": "Ban Expires",
+ "confirmBan": "Ban User",
+ "unbanUser": "Unban User",
+ "unbanUserConfirm": "Unban user {name}?",
+ "originalBanReason": "Original Ban Reason",
+ "confirmUnban": "Unban User",
+ "deleteUser": "Delete User",
+ "deleteUserConfirm": "Delete user {name}?",
+ "deleteWarning": "This will permanently delete all calendars, shifts, notes, and shares owned by this user.",
+ "deleteUnderstood": "I understand this action cannot be undone",
+ "deleteConfirmation": "Type \"{name}\" to confirm",
+ "deleteConfirmationHint": "Type the exact username to confirm deletion",
+ "confirmDelete": "Delete User",
+ "resetPassword": "Reset Password",
+ "resetPasswordFor": "Reset password for {name}",
+ "passwordResetWarning": "No email will be sent. You must manually inform the user of their new password.",
+ "passwordResetSecurityNote": "This password will be saved immediately. Copy it before closing this dialog.",
+ "generatePassword": "Generate Random Password",
+ "passwordPlaceholder": "Minimum 8 characters",
+ "confirmPasswordPlaceholder": "Re-enter password",
+ "copyPassword": "Copy Password to Clipboard",
+ "setPassword": "Set Password",
+ "bannedUntil": "Banned until {date}",
+ "bannedPermanently": "Banned permanently",
+ "userNotFound": "User not found",
+ "namePlaceholder": "Enter user's full name",
+ "emailPlaceholder": "[email protected]",
+ "roleChangeWarning": "Changing a user's role will affect their permissions immediately",
+ "calendars": {
+ "title": "Calendar Management",
+ "description": "Manage all calendars in the system",
+ "owner": "Owner",
+ "updated": "Updated",
+ "guestPermission": "Guest Permission",
+ "orphaned": "Orphaned",
+ "noOwner": "No owner assigned",
+ "currentOwner": "Current Owner",
+ "allStatuses": "All Calendars",
+ "orphanedOnly": "Orphaned Only",
+ "withOwner": "With Owner",
+ "searchPlaceholder": "Search by name...",
+ "calendarsCount": "{count, plural, =0 {No calendars} =1 {1 calendar} other {# calendars}}",
+ "selectedCount": "{count, plural, =1 {1 calendar selected} other {# calendars selected}}",
+ "transferSelected": "Transfer Selected",
+ "clearSelection": "Clear Selection",
+ "noCalendarsFound": "No calendars found",
+ "noSearchResults": "No calendars match your search",
+ "orphanedWarning": "{count, plural, =1 {1 orphaned calendar} other {# orphaned calendars}} need owner assignment",
+ "orphanedWarningDescription": "Please assign these calendars to users or delete them.",
+ "editCalendar": "Edit Calendar",
+ "transferOwnership": "Transfer Ownership",
+ "deleteCalendar": "Delete Calendar",
+ "calendarDetails": "Calendar Details",
+ "calendarDetailsDescription": "View detailed calendar information",
+ "userShares": "user",
+ "tokenShares": "token",
+ "userSharesList": "User Shares",
+ "tokenSharesList": "Token Shares",
+ "externalSyncs": "External Syncs",
+ "externalSyncsShort": "Syncs",
+ "lastSynced": "Last synced",
+ "quickActions": "Quick Actions",
+ "editCalendarDescription": "Update calendar information",
+ "namePlaceholder": "Enter calendar name",
+ "guestPermissionHint": "Controls public access to this calendar",
+ "transferSingleDescription": "Transfer ownership of \"{name}\"",
+ "transferMultipleDescription": "{count, plural, =1 {1 calendar} other {# calendars}} will be transferred",
+ "calendarsToTransfer": "Calendars to Transfer",
+ "calendarToTransfer": "Calendar to Transfer",
+ "selectNewOwner": "Select New Owner",
+ "searchUserPlaceholder": "Search by name or email...",
+ "searchUserHint": "Type at least 2 characters to search",
+ "newOwner": "New Owner",
+ "transferButton": "Transfer Ownership",
+ "deleteCalendarConfirm": "Delete calendar \"{name}\"?",
+ "deleteWarning": "This will permanently delete all shifts, notes, presets, shares, and external syncs associated with this calendar.",
+ "deleteUnderstood": "I understand this action cannot be undone",
+ "deleteConfirmation": "Type \"{name}\" to confirm",
+ "deleteConfirmationHint": "Type the exact calendar name to confirm deletion",
+ "confirmDelete": "Delete Calendar",
+ "bulkDeleteConfirm": "{count, plural, =1 {Delete 1 calendar?} other {Delete # calendars?}}",
+ "bulkDeleteWarning": "This will permanently delete all shifts, notes, presets, shares, and external syncs for these calendars.",
+ "calendarsToDelete": "Calendars to delete",
+ "andMore": "... and {count} more",
+ "calendarsDeleted": "{count, plural, =1 {1 calendar deleted} other {# calendars deleted}}",
+ "calendarsTransferred": "{count, plural, =1 {1 calendar transferred} other {# calendars transferred}}"
+ },
+ "auditLogsDescription": "Manage all logs",
+ "allActions": "All Actions",
+ "adminActions": "Admin Actions",
+ "calendarActions": "Calendar Actions",
+ "authActions": "Authentication",
+ "securityActions": "Security",
+ "searchLogs": "Search action, metadata...",
+ "showingLogs": "Showing {from} to {to} of {total} logs",
+ "timestamp": "Timestamp",
+ "userAgent": "User Agent",
+ "metadata": "Metadata",
+ "noLogsFound": "No audit logs found",
+ "deleteOldLogs": "Delete Old Logs",
+ "deleteLogsDescription": "Delete audit logs older than a specific date. This action cannot be undone.",
+ "deleteLogsBefore": "Delete logs older than",
+ "deleteLogsBeforeHint": "All logs before this date will be permanently deleted",
+ "deleteLogsWarning": "This action is permanent and cannot be undone. All audit logs before the selected date will be deleted from the database.",
+ "confirmPermanentDeletion": "I understand that audit logs will be permanently deleted",
+ "pleaseSelectDate": "Please select a date",
+ "pleaseConfirmDeletion": "Please confirm the deletion",
+ "willDeleteLogsOlderThan": "All logs older than {date} will be deleted",
+ "preview": "Preview",
+ "auditLogDetails": "Audit Log Details",
+ "resourceType": "Resource Type",
+ "resourceId": "Resource ID",
+ "logId": "Log ID",
+ "userVisible": "User Visible",
+ "unknownUser": "Unknown User",
+ "systemAction": "System",
+ "selectedLogs": "{count} selected",
+ "clearSelection": "Clear Selection",
+ "deleteSelectedLogsDescription": "Delete {count, plural, one {# selected log} other {# selected logs}}. This action cannot be undone.",
+ "willDeleteSelectedLogs": "{count, plural, one {# log} other {# logs}} will be permanently deleted"
}
}
diff --git a/messages/it.json b/messages/it.json
index f64e8eb..76b5458 100644
--- a/messages/it.json
+++ b/messages/it.json
@@ -8,12 +8,16 @@
"cancel": "Annulla",
"save": "Salva",
"saving": "Salvataggio...",
+ "close": "Chiudi",
+ "optional": "(opzionale)",
"delete": "Elimina",
- "create": "Crea",
"loading": "Caricamento...",
- "required": "obbligatorio",
- "unlock": "Sblocca",
"add": "Aggiungi",
+ "adding": "Aggiunta...",
+ "or": "o",
+ "next": "Avanti",
+ "previous": "Precedente",
+ "of": "di",
"unsavedChanges": "Modifiche Non Salvate",
"unsavedChangesDescription": "Hai modifiche non salvate. Vuoi davvero chiudere senza salvare?",
"closeWithoutSaving": "Chiudi Senza Salvare",
@@ -24,13 +28,33 @@
"updateError": "Impossibile aggiornare {item}",
"deleteError": "Impossibile eliminare {item}",
"deleteConfirm": "Eliminare davvero {item} \"{name}\"?",
- "deleteConfirmWithWarning": "Eliminare davvero {item} \"{name}\"? {warning}",
"shifts": "Turni",
"success": "Successo",
"error": "Errore",
+ "fetchError": "Impossibile caricare {item}",
+ "transferError": "Impossibile trasferire {item}",
+ "banError": "Impossibile bannare {item}",
+ "unbanError": "Impossibile rimuovere il ban per {item}",
+ "banned": "{item} bannato con successo",
+ "unbanned": "Ban per {item} rimosso con successo",
+ "transferred": "{item} trasferito con successo",
+ "copyError": "Impossibile copiare {item}",
+ "copied": "{item} copiato",
+ "revokeError": "Impossibile revocare {item}",
+ "revoked": "{item} revocato con successo",
+ "passwordReset": "Password reimpostata con successo",
+ "passwordResetError": "Impossibile reimpostare la password",
+ "search": "Cerca...",
+ "noResults": "Nessun risultato trovato",
"createdCount": "{count} creati",
"updatedCount": "{count} aggiornati",
"deletedCount": "{count} eliminati",
+ "copy": "Copia",
+ "yes": "Sì",
+ "no": "No",
+ "deleteSelected": "Elimina Selezionati",
+ "viewAll": "Mostra Tutto",
+ "viewDetails": "Visualizza Dettagli",
"weekday": {
"monday": "Lun",
"tuesday": "Mar",
@@ -39,26 +63,86 @@
"friday": "Ven",
"saturday": "Sab",
"sunday": "Dom"
+ },
+ "labels": {
+ "name": "Nome",
+ "email": "Email",
+ "password": "Password",
+ "newPassword": "Nuova Password",
+ "confirmPassword": "Conferma Password",
+ "status": "Stato",
+ "action": "Azione",
+ "time": "Ora",
+ "startDate": "Data Inizio",
+ "endDate": "Data Fine",
+ "ipAddress": "Indirizzo IP",
+ "severity": "Gravità",
+ "permission": "Permesso",
+ "permissions": {
+ "admin": "Admin",
+ "read": "Lettura",
+ "write": "Scrittura",
+ "none": "Nessun Accesso"
+ },
+ "notes": "Note",
+ "calendar": "Calendario",
+ "shifts": "Turni",
+ "presets": "Modelli",
+ "shares": "Condivisioni",
+ "sharedCalendars": "Calendari Condivisi",
+ "user": "Utente",
+ "users": "Utenti"
+ },
+ "status": {
+ "active": "Attivo",
+ "inactive": "Inattivo"
+ },
+ "roles": {
+ "admin": "Admin",
+ "superadmin": "Superadmin",
+ "user": "Utente"
+ },
+ "time": {
+ "never": "Mai",
+ "lastActive": "Ultima Attività"
+ },
+ "filters": {
+ "allSeverities": "Tutte le Gravità",
+ "clearFilters": "Cancella Filtri"
+ },
+ "severity": {
+ "info": "Info",
+ "warning": "Avviso",
+ "error": "Errore",
+ "critical": "Critico"
+ },
+ "stats": {
+ "statistics": "Statistiche",
+ "created": "Creato"
+ },
+ "auth": {
+ "activeSessions": "Sessioni Attive",
+ "connectedAccounts": "Account Collegati"
+ },
+ "empty": {
+ "noUsersFound": "Nessun utente trovato"
}
},
"validation": {
- "passwordMatch": "Le password non corrispondono",
- "passwordIncorrect": "Password errata",
- "passwordRequired": "Password obbligatoria",
"fileRequired": "Seleziona un file",
"fileTooLarge": "Il file è troppo grande. La dimensione massima è {maxSize}.",
"urlRequired": "Inserisci un URL",
"urlInvalid": "Formato URL non valido",
- "urlAlreadyExists": "Questo URL è già stato aggiunto"
+ "urlAlreadyExists": "Questo URL è già stato aggiunto",
+ "passwordRequired": "La password è obbligatoria",
+ "passwordTooShort": "La password deve contenere almeno 8 caratteri",
+ "passwordsNoMatch": "Le password non corrispondono"
},
"form": {
"namePlaceholder": "es., {example}",
- "nameLabel": "Nome",
"colorLabel": "Colore",
"notesLabel": "Note (opzionale)",
"notesPlaceholder": "Informazioni aggiuntive...",
- "passwordLabel": "Password",
- "passwordPlaceholder": "Inserisci password",
"urlLabel": "URL",
"urlPlaceholder": "https://..."
},
@@ -72,17 +156,15 @@
"createDescription": "Crea un nuovo calendario per organizzare i tuoi turni",
"selectDescription": "Scegli un calendario per gestire i tuoi turni",
"name": "Nome Calendario",
+ "myCalendars": "I Miei Calendari",
+ "sharedCalendars": "Calendari Condivisi",
+ "tokenCalendars": "Tramite Link di Accesso",
+ "publicCalendars": "Calendari Pubblici",
"select": "Il tuo Calendario BetterShift",
"deleteCalendar": "Elimina Calendario",
"deleteWarning": "Anche tutti i turni, i preset e le note verranno eliminati.",
"settings": "Impostazioni Calendario per \"{name}\"",
- "settingsDescription": "Personalizza nome, colore e protezione password",
- "passwordProtected": "Il calendario è protetto da password",
- "passwordRequiredToEdit": "Inserisci la tua password attuale per modificare le impostazioni.",
- "currentPasswordRequired": "Richiesto per salvare le modifiche",
- "lockCalendar": "Blocca calendario completamente",
- "lockCalendarHint": "Blocca il calendario completamente - è necessaria la password per visualizzare e gestire",
- "lockRequiresPassword": "Il blocco del calendario richiede una password",
+ "settingsDescription": "Personalizza nome e colore",
"compare": "Confronta Calendari",
"compareMode": "Modalità Confronto",
"exitCompare": "Esci dal Confronto",
@@ -93,30 +175,28 @@
"mobileNotOptimized": "La vista confronto non è ottimizzata per dispositivi mobili. Utilizza uno schermo più grande per un'esperienza migliore.",
"shareLink": "Condividi Link",
"shareLinkDescription": "Copia link alla vista confronto",
- "linkCopied": "Link copiato negli appunti"
+ "browseCalendars": "Calendari Condivisi",
+ "browseCalendarsDescription": "Scopri e gestisci gli abbonamenti ai calendari",
+ "subscribe": "Iscriviti",
+ "subscribed": "Iscritto",
+ "noPublicCalendars": "Nessun calendario pubblico disponibile",
+ "subscriptionSuccess": "Iscritto a {name}",
+ "unsubscribeSuccess": "Disiscritto da {name}",
+ "subscribeTooltip": "Iscriviti a questo calendario",
+ "unsubscribeTooltip": "Disiscriviti da questo calendario",
+ "sharedTab": "Condivisi",
+ "publicTab": "Pubblici",
+ "hiddenTab": "Nascosti",
+ "publicBadge": "Pubblico",
+ "showAgain": "Mostra di Nuovo",
+ "noSharedCalendars": "Nessun calendario condiviso ancora",
+ "noHiddenCalendars": "Nessun calendario nascosto"
},
"color": {
"custom": "Personalizzato",
"customTitle": "Colore Personalizzato",
"customDescription": "Scegli un colore personalizzato usando il selettore di colori"
},
- "password": {
- "optional": "Protezione Password (opzionale)",
- "management": "Gestione Password",
- "currentPassword": "Password Attuale",
- "currentPasswordPlaceholder": "Inserisci la password attuale",
- "newPassword": "Nuova Password",
- "newPasswordPlaceholder": "Inserisci la nuova password",
- "confirmPassword": "Conferma Password",
- "confirmPasswordPlaceholder": "Conferma password",
- "removePassword": "Rimuovi Password",
- "enter": "Inserisci Password per \"{name}\"",
- "enterCalendarPassword": "Inserisci la password del calendario",
- "currentlyLocked": "Questo calendario è attualmente bloccato.",
- "unlockRequired": "Il calendario è protetto da password",
- "unlockRequiredDescription": "Questo calendario è protetto da password. Sblocca il calendario per gestire i preset e creare turni.",
- "unlockCalendar": "Sblocca Calendario"
- },
"note": {
"create": "Crea {item}",
"edit": "Modifica {item}",
@@ -243,10 +323,7 @@
"radarDescription": "Confronta i tipi di turno principali per ore totali e media"
},
"sync": {
- "refreshing": "Aggiornamento dati...",
- "resyncing": "Risincronizzazione dopo disconnessione...",
"reconnected": "Connessione ripristinata",
- "offline": "Nessuna connessione internet",
"disconnected": "Connessione al server persa"
},
"onboarding": {
@@ -254,6 +331,11 @@
"description": "Crea il tuo primo calendario per gestire i tuoi turni.",
"createCalendar": "Crea Calendario"
},
+ "guestEmptyState": {
+ "title": "Nessun Calendario Pubblico Disponibile",
+ "description": "Al momento non ci sono calendari pubblici condivisi. Effettua il login per creare e gestire i tuoi calendari.",
+ "loginButton": "Vai al Login"
+ },
"footer": {
"version": "Versione",
"github": "GitHub",
@@ -290,7 +372,6 @@
"hideFromStats": "Nascondi dalle statistiche",
"hideFromStatsHint": "Escludi i turni da questo calendario dalle statistiche",
"lastSynced": "Ultima sincronizzazione",
- "syncError": "Impossibile sincronizzare il calendario",
"delete": "Elimina Calendario Esterno",
"deleteConfirm": "Eliminare questo calendario esterno? Tutti i turni importati verranno rimossi.",
"hintsTitle": "Trovare l'URL del Calendario",
@@ -351,5 +432,359 @@
"available": "Aggiornamento disponibile",
"newVersion": "Versione {version} è disponibile",
"viewChangelog": "Visualizza changelog"
+ },
+ "auth": {
+ "login": "Accedi",
+ "loginTitle": "Accedi a BetterShift",
+ "loginDescription": "Accedi con il tuo account o usa uno dei provider sotto",
+ "register": "Registrati",
+ "registerTitle": "Crea Account",
+ "registerDescription": "Crea un nuovo account per iniziare",
+ "logout": "Disconnetti",
+ "profile": "Profilo",
+ "profileTitle": "Il Tuo Profilo",
+ "profileDescription": "Gestisci le impostazioni e le preferenze del tuo account",
+ "profileBasicInfoDescription": "Le tue informazioni di base dell'account",
+ "changePasswordDescription": "Aggiorna la tua password per mantenere il tuo account sicuro",
+ "connectedAccountsDescription": "Gestisci i tuoi provider OAuth connessi",
+ "dangerZone": "Zona Pericolosa",
+ "dangerZoneDescription": "Azioni irreversibili che influenzano il tuo account",
+ "logoutDescription": "Disconnettiti dalla tua sessione corrente",
+ "deleteAccountDescription": "Elimina permanentemente il tuo account e tutti i dati",
+ "noConnectedAccounts": "Nessun account connesso ancora",
+ "emailPasswordAuth": "Email/Password",
+ "emailPlaceholder": "[email protected]",
+ "passwordPlaceholder": "La tua password",
+ "currentPassword": "Password Attuale",
+ "confirmPasswordLabel": "Conferma Password",
+ "enterPassword": "Inserisci password",
+ "namePlaceholder": "Il tuo nome",
+ "continueWith": "Continua con {provider}",
+ "continueAsGuest": "Continua come Ospite",
+ "alreadyHaveAccount": "Hai già un account?",
+ "noAccountYet": "Non hai ancora un account?",
+ "changePassword": "Cambia Password",
+ "deleteAccount": "Elimina Account",
+ "editProfile": "Modifica Profilo",
+ "editProfileDescription": "Aggiorna il tuo nome, email e immagine del profilo",
+ "profileUpdated": "Profilo aggiornato con successo",
+ "profilePicture": "Immagine del Profilo",
+ "avatarHint": "Max 5MB. Formati supportati: JPEG, PNG, GIF, WebP",
+ "invalidImageType": "Tipo di file non valido. Seleziona un'immagine.",
+ "imageTooLarge": "L'immagine è troppo grande. Dimensione massima 5MB.",
+ "avatarUploadFailed": "Caricamento dell'immagine del profilo non riuscito",
+ "uploadingImage": "Caricamento immagine...",
+ "deleteAccountConfirm": "Sei sicuro di voler eliminare il tuo account? Questa azione non può essere annullata.",
+ "loginSuccess": "Accesso effettuato con successo",
+ "loginError": "Accesso fallito",
+ "accountBanned": "Account bannato",
+ "registrationDisabled": "Registrazione disabilitata",
+ "registrationDisabledDescription": "La registrazione di nuovi utenti è attualmente disabilitata. Contatta un amministratore se hai bisogno di un account.",
+ "registerSuccess": "Account creato con successo",
+ "registerError": "Registrazione fallita",
+ "logoutSuccess": "Disconnesso con successo",
+ "passwordChanged": "Password cambiata con successo",
+ "accountDeleted": "Account eliminato con successo",
+ "emailRequired": "Email è richiesta",
+ "nameRequired": "Nome è richiesto",
+ "emailAlreadyExists": "Questa email è già in uso",
+ "provider": {
+ "google": "Google",
+ "github": "GitHub",
+ "discord": "Discord",
+ "customOidc": "SSO"
+ },
+ "activeSessionsDescription": "Gestisci i tuoi dispositivi e sessioni attive",
+ "noActiveSessions": "Nessuna sessione attiva",
+ "browser": "Browser",
+ "operatingSystem": "Sistema Operativo",
+ "logoutAllDevices": "Disconnetti da tutti gli altri dispositivi",
+ "sessionsRevokedCount": "Disconnesso da {count} dispositivo/i"
+ },
+ "guest": {
+ "viewingAsGuest": "Stai visualizzando come ospite",
+ "bannerMessage": "Stai visualizzando questo calendario come ospite. Accedi per l'accesso completo.",
+ "loginForFullAccess": "Accedi per l'accesso completo",
+ "cannotEdit": "Non puoi modificare in modalità sola lettura"
+ },
+ "share": {
+ "manageSharing": "Gestisci Condivisione",
+ "manageSharingDescription": "Controlla chi può accedere a \"{name}\"",
+ "userShares": "Condivisioni Utente",
+ "publicAccess": "Accesso Pubblico",
+ "accessLinks": "Link di Accesso",
+ "public": "Pubblico",
+ "links": "Link",
+ "share": "condivisione",
+ "sharedBy": "Condiviso Da",
+ "sharedOn": "Condiviso Il",
+ "addUser": "Aggiungi Utente",
+ "addUserDescription": "Cerca un utente per condividere questo calendario",
+ "searchUser": "Cerca utente",
+ "searchUserPlaceholder": "Inserisci nome o email...",
+ "selectedUser": "Utente selezionato",
+ "noShares": "Nessun utente ha ancora accesso",
+ "noSharesDescription": "Condividi questo calendario con altri utenti per collaborare",
+ "userSharesDescription": "Gestisci chi può accedere a questo calendario",
+ "publicAccessDescription": "Controlla l'accesso pubblico per utenti autenticati e ospiti",
+ "publicPermissionNoneDesc": "Nessuno può accedere a questo calendario senza condivisione esplicita",
+ "publicPermissionReadDesc": "Qualsiasi utente autenticato può visualizzare il calendario",
+ "publicPermissionWriteDesc": "Qualsiasi utente autenticato può visualizzare e modificare il calendario",
+ "shareAdded": "Calendario condiviso con successo",
+ "shareUpdated": "Permesso aggiornato con successo",
+ "shareRemoved": "Accesso rimosso con successo",
+ "removeAccess": "Rimuovi Accesso",
+ "removeShareConfirmTitle": "Rimuovere l'accesso al calendario?",
+ "removeShareConfirmDesc": "Sei sicuro di voler rimuovere l'accesso per {user}? Non potrà più visualizzare o modificare questo calendario.",
+ "you": "Tu",
+ "sharedWithYou": "Condiviso con te"
+ },
+ "token": {
+ "accessLinks": "Link di Accesso",
+ "accessLinksDescription": "Condividi questo calendario tramite link sicuri",
+ "createLink": "Crea Link",
+ "createFirstLink": "Crea Primo Link",
+ "noTokensYet": "Nessun link di accesso ancora",
+ "noTokensDescription": "Crea link di accesso per condividere questo calendario senza richiedere un account",
+ "unnamed": "Senza Nome",
+ "namePlaceholder": "es. Link Famiglia, Team Lavoro",
+ "token": "Token",
+ "tokenValue": "Valore Token",
+ "readOnlyDescription": "Visualizza turni e note",
+ "editDescription": "Crea e modifica turni",
+ "expiration": "Scadenza",
+ "expires": "Scade",
+ "expired": "Scaduto",
+ "expiration1Day": "1 Giorno",
+ "expiration7Days": "7 Giorni",
+ "expiration30Days": "30 Giorni",
+ "expirationNever": "Mai",
+ "expiresOn": "Scade il",
+ "usage": "Utilizzo",
+ "usedCount": "{count, plural, =0 {Mai usato} =1 {Usato una volta} other {Usato # volte}}",
+ "neverUsed": "Mai usato",
+ "enable": "Attiva",
+ "disable": "Disattiva",
+ "revoke": "Revoca",
+ "revokeConfirm": "Revocare Link di Accesso?",
+ "revokeConfirmDescription": "Sei sicuro di voler revocare \"{name}\"? Chiunque usi questo link perderà immediatamente l'accesso.",
+ "generate": "Genera Link",
+ "shareLink": "Link di Condivisione",
+ "linkCreated": "Link Creato!",
+ "linkCreatedDescription": "Il tuo link di condivisione è stato creato con successo",
+ "saveWarning": "Salva questo link ora - non verrà mostrato di nuovo!",
+ "shareInfo": "Chiunque abbia questo link può accedere al tuo calendario con il livello di permesso specificato",
+ "accessedViaLink": "Accesso tramite Link di Condivisione",
+ "linkName": "Nome Link",
+ "createLinkDescription": "Crea un link di accesso per condividere questo calendario senza richiedere un account"
+ },
+ "rateLimit": {
+ "title": "Troppe richieste",
+ "message": "Riprova tra {time}.",
+ "fallback": "Attendi un momento prima di riprovare.",
+ "second": "secondo",
+ "seconds": "secondi",
+ "minute": "minuto",
+ "minutes": "minuti",
+ "hour": "ora",
+ "hours": "ore"
+ },
+ "activityLog": {
+ "title": "Registro Attività",
+ "description": "Visualizza l'attività del tuo account e gli eventi di sicurezza",
+ "noLogs": "Nessuna attività registrata ancora",
+ "eventType": "Tipo Evento",
+ "resource": "Risorsa",
+ "details": "Dettagli",
+ "clearAll": "Cancella tutto",
+ "refresh": "Aggiorna",
+ "refreshed": "Registro attività aggiornato",
+ "confirmClear": "Sei sicuro di voler cancellare tutti i registri di attività? Questa azione non può essere annullata.",
+ "totalLogs": "{count} registri totali",
+ "showingResults": "Mostrando {start}-{end} di {total}",
+ "searchPlaceholder": "Cerca per azione, risorsa o ID...",
+ "noMetadata": "Nessun dettaglio aggiuntivo disponibile",
+ "allTypes": "Tutti i Tipi",
+ "auth": "Autenticazione",
+ "sync": "Sincronizzazione",
+ "security": "Sicurezza"
+ },
+ "admin": {
+ "title": "Pannello Admin",
+ "adminPanel": "Pannello Admin",
+ "dashboard": "Dashboard",
+ "usersMenu": "Utenti",
+ "calendarsMenu": "Calendari",
+ "orphanedCalendars": "Calendari Orfani",
+ "auditLogs": "Log di Audit",
+ "backToApp": "Torna all'App",
+ "superadminBadge": "Superadmin",
+ "expandSidebar": "Espandi Barra Laterale",
+ "collapseSidebar": "Comprimi Barra Laterale",
+ "accessDenied": "Accesso admin richiesto",
+ "stats": {
+ "totalUsers": "Utenti Totali",
+ "totalCalendars": "Calendari Totali",
+ "orphanedCalendars": "Calendari Orfani",
+ "totalShifts": "Turni Totali",
+ "activeShares": "Condivisioni Attive",
+ "recentActivity": "Attività Admin Recente",
+ "usersByRole": "{superadmin} superadmin, {admin} admin, {user} utenti",
+ "calendarsDescription": "Calendari con proprietari",
+ "orphanedDescription": "Calendari senza proprietario",
+ "sharesDescription": "{user} condivisioni utente, {token} condivisioni token",
+ "shiftsDescription": "Turni totali in tutti i calendari",
+ "last7Days": "Ultimi 7 giorni",
+ "needsAttention": "Richiede Attenzione"
+ },
+ "dashboardDescription": "Benvenuto nel Pannello Admin di BetterShift",
+ "orphanedCalendarsWarning": "Calendari Orfani Rilevati",
+ "orphanedCalendarsWarningDescription": "{count, plural, =1 {C'è 1 calendario senza proprietario} other {Ci sono # calendari senza proprietario}}. Si prega di assegnarli agli utenti.",
+ "manageOrphanedCalendars": "Gestisci Calendari Orfani",
+ "recentActivityDescription": "Log delle ultime attività admin",
+ "statsFetchError": "Impossibile caricare le statistiche",
+ "userManagement": "Gestione Utenti",
+ "userManagementDescription": "Gestisci account utente e permessi",
+ "searchUsers": "Cerca per nome o email...",
+ "allRoles": "Tutti i Ruoli",
+ "allStatuses": "Tutti gli Stati",
+ "banned": "Bannato",
+ "role": "Ruolo",
+ "calendarsCount": "Calendari",
+ "page": "pagina",
+ "usersCount": "{count, plural, =0 {Nessun utente} =1 {1 utente} other {# utenti}}",
+ "neverActive": "Mai",
+ "editUser": "Modifica Utente",
+ "editUserDescription": "Aggiorna informazioni utente e permessi",
+ "userDetails": "Dettagli Utente",
+ "userDetailsDescription": "Visualizza informazioni dettagliate utente",
+ "ownedCalendars": "Calendari Proprietari",
+ "joined": "Iscritto",
+ "banUser": "Banna Utente",
+ "banUserConfirm": "Bannare utente {name}?",
+ "banWarning": "L'utente verrà disconnesso immediatamente e non potrà accedere fino alla rimozione del ban.",
+ "banReason": "Motivo Ban",
+ "banReasonPlaceholder": "Inserisci il motivo del ban...",
+ "permanentBan": "Ban permanente",
+ "banExpires": "Scadenza Ban",
+ "confirmBan": "Banna Utente",
+ "unbanUser": "Rimuovi Ban",
+ "unbanUserConfirm": "Rimuovere ban per utente {name}?",
+ "originalBanReason": "Motivo Ban Originale",
+ "confirmUnban": "Rimuovi Ban",
+ "deleteUser": "Elimina Utente",
+ "deleteUserConfirm": "Eliminare utente {name}?",
+ "deleteWarning": "Questo eliminerà permanentemente tutti i calendari, i turni, le note e le condivisioni di proprietà di questo utente.",
+ "deleteUnderstood": "Comprendo che questa azione non può essere annullata",
+ "deleteConfirmation": "Digita \"{name}\" per confermare",
+ "deleteConfirmationHint": "Digita il nome utente esatto per confermare l'eliminazione",
+ "confirmDelete": "Elimina Utente",
+ "resetPassword": "Reimposta Password",
+ "resetPasswordFor": "Reimposta password per {name}",
+ "passwordResetWarning": "Non verrà inviata alcuna email. Devi informare manualmente l'utente della nuova password.",
+ "passwordResetSecurityNote": "Questa password verrà salvata immediatamente. Copiala prima di chiudere questo dialogo.",
+ "generatePassword": "Genera Password Casuale",
+ "passwordPlaceholder": "Minimo 8 caratteri",
+ "confirmPasswordPlaceholder": "Reinserisci password",
+ "copyPassword": "Copia Password negli Appunti",
+ "setPassword": "Imposta Password",
+ "bannedUntil": "Bannato fino al {date}",
+ "bannedPermanently": "Bannato permanentemente",
+ "userNotFound": "Utente non trovato",
+ "namePlaceholder": "Inserisci nome completo",
+ "emailPlaceholder": "[email protected]",
+ "roleChangeWarning": "La modifica del ruolo utente influenzerà immediatamente i permessi",
+ "calendars": {
+ "title": "Gestione Calendari",
+ "description": "Gestisci tutti i calendari nel sistema",
+ "owner": "Proprietario",
+ "updated": "Aggiornato",
+ "guestPermission": "Permesso Ospite",
+ "orphaned": "Orfano",
+ "noOwner": "Nessun proprietario assegnato",
+ "currentOwner": "Proprietario Attuale",
+ "allStatuses": "Tutti i Calendari",
+ "orphanedOnly": "Solo Orfani",
+ "withOwner": "Con Proprietario",
+ "searchPlaceholder": "Cerca per nome...",
+ "calendarsCount": "{count, plural, =0 {Nessun calendario} =1 {1 calendario} other {# calendari}}",
+ "selectedCount": "{count, plural, =1 {1 calendario selezionato} other {# calendari selezionati}}",
+ "transferSelected": "Trasferisci Selezionati",
+ "clearSelection": "Cancella Selezione",
+ "noCalendarsFound": "Nessun calendario trovato",
+ "noSearchResults": "Nessun calendario corrisponde alla tua ricerca",
+ "orphanedWarning": "{count, plural, =1 {1 calendario orfano} other {# calendari orfani}} necessitano assegnazione proprietario",
+ "orphanedWarningDescription": "Si prega di assegnare questi calendari agli utenti o eliminarli.",
+ "editCalendar": "Modifica Calendario",
+ "transferOwnership": "Trasferisci Proprietà",
+ "deleteCalendar": "Elimina Calendario",
+ "calendarDetails": "Dettagli Calendario",
+ "calendarDetailsDescription": "Visualizza informazioni dettagliate del calendario",
+ "userShares": "utente",
+ "tokenShares": "token",
+ "userSharesList": "Condivisioni Utente",
+ "tokenSharesList": "Condivisioni Token",
+ "externalSyncs": "Sincronizzazioni Esterne",
+ "externalSyncsShort": "Sincronizzazioni",
+ "lastSynced": "Ultima sincronizzazione",
+ "quickActions": "Azioni Rapide",
+ "editCalendarDescription": "Aggiorna informazioni calendario",
+ "namePlaceholder": "Inserisci nome calendario",
+ "guestPermissionHint": "Controlla l'accesso pubblico a questo calendario",
+ "transferSingleDescription": "Trasferisci proprietà di \"{name}\"",
+ "transferMultipleDescription": "{count, plural, =1 {1 calendario} other {# calendari}} saranno trasferiti",
+ "calendarsToTransfer": "Calendari da Trasferire",
+ "calendarToTransfer": "Calendario da Trasferire",
+ "selectNewOwner": "Seleziona Nuovo Proprietario",
+ "searchUserPlaceholder": "Cerca per nome o email...",
+ "searchUserHint": "Digita almeno 2 caratteri per cercare",
+ "newOwner": "Nuovo Proprietario",
+ "transferButton": "Trasferisci Proprietà",
+ "deleteCalendarConfirm": "Eliminare il calendario \"{name}\"?",
+ "deleteWarning": "Questo eliminerà permanentemente tutti i turni, note, preset, condivisioni e sincronizzazioni esterne associati a questo calendario.",
+ "deleteUnderstood": "Comprendo che questa azione non può essere annullata",
+ "deleteConfirmation": "Digita \"{name}\" per confermare",
+ "deleteConfirmationHint": "Digita il nome esatto del calendario per confermare l'eliminazione",
+ "confirmDelete": "Elimina Calendario",
+ "bulkDeleteConfirm": "{count, plural, =1 {Eliminare 1 calendario?} other {Eliminare # calendari?}}",
+ "bulkDeleteWarning": "Questo eliminerà permanentemente tutti i turni, note, preset, condivisioni e sincronizzazioni esterne per questi calendari.",
+ "calendarsToDelete": "Calendari da eliminare",
+ "andMore": "... e altri {count}",
+ "calendarsDeleted": "{count, plural, =1 {1 calendario eliminato} other {# calendari eliminati}}",
+ "calendarsTransferred": "{count, plural, =1 {1 calendario trasferito} other {# calendari trasferiti}}"
+ },
+ "auditLogsDescription": "Gestisci tutti i log",
+ "allActions": "Tutte le Azioni",
+ "adminActions": "Azioni Admin",
+ "calendarActions": "Azioni Calendario",
+ "authActions": "Autenticazione",
+ "securityActions": "Sicurezza",
+ "searchLogs": "Cerca azione, metadati...",
+ "showingLogs": "Mostrando da {from} a {to} di {total} log",
+ "timestamp": "Timestamp",
+ "userAgent": "User Agent",
+ "metadata": "Metadati",
+ "noLogsFound": "Nessun log di audit trovato",
+ "deleteOldLogs": "Elimina Vecchi Log",
+ "deleteLogsDescription": "Elimina i log di audit più vecchi di una data specifica. Questa azione non può essere annullata.",
+ "deleteLogsBefore": "Elimina log più vecchi di",
+ "deleteLogsBeforeHint": "Tutti i log prima di questa data verranno eliminati permanentemente",
+ "deleteLogsWarning": "Questa azione è permanente e non può essere annullata. Tutti i log di audit prima della data selezionata verranno eliminati dal database.",
+ "confirmPermanentDeletion": "Comprendo che i log di audit verranno eliminati permanentemente",
+ "pleaseSelectDate": "Seleziona una data",
+ "pleaseConfirmDeletion": "Conferma l'eliminazione",
+ "willDeleteLogsOlderThan": "Tutti i log più vecchi di {date} verranno eliminati",
+ "preview": "Anteprima",
+ "auditLogDetails": "Dettagli Log di Audit",
+ "resourceType": "Tipo Risorsa",
+ "resourceId": "ID Risorsa",
+ "logId": "ID Log",
+ "userVisible": "Visibile all'Utente",
+ "unknownUser": "Utente Sconosciuto",
+ "systemAction": "Sistema",
+ "selectedLogs": "{count} selezionati",
+ "clearSelection": "Cancella Selezione",
+ "deleteSelectedLogsDescription": "Elimina {count, plural, one {# log selezionato} other {# log selezionati}}. Questa azione non può essere annullata.",
+ "willDeleteSelectedLogs": "{count, plural, one {# log} other {# log}} verranno eliminati permanentemente"
}
}
diff --git a/next-pwa.d.ts b/next-pwa.d.ts
deleted file mode 100644
index a73a2f1..0000000
--- a/next-pwa.d.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-declare module "next-pwa" {
- import { NextConfig } from "next";
-
- interface PWAConfig {
- dest?: string;
- register?: boolean;
- skipWaiting?: boolean;
- disable?: boolean;
- sw?: string;
- runtimeCaching?: Array<{
- urlPattern: RegExp;
- handler:
- | "CacheFirst"
- | "NetworkFirst"
- | "StaleWhileRevalidate"
- | "NetworkOnly"
- | "CacheOnly";
- options?: {
- cacheName?: string;
- expiration?: {
- maxEntries?: number;
- maxAgeSeconds?: number;
- };
- networkTimeoutSeconds?: number;
- };
- }>;
- }
-
- export default function withPWA(
- config: PWAConfig
- ): (nextConfig: NextConfig) => NextConfig;
-}
diff --git a/next.config.ts b/next.config.ts
index bd9ad2d..251b49e 100644
--- a/next.config.ts
+++ b/next.config.ts
@@ -6,6 +6,12 @@ const withNextIntl = createNextIntlPlugin("./lib/i18n.ts");
const nextConfig: NextConfig = {
/* config options here */
output: "standalone",
+
+ // Build optimizations
+ compiler: {
+ removeConsole: process.env.NODE_ENV === "production",
+ },
+
async headers() {
return [
{
diff --git a/package-lock.json b/package-lock.json
index 6072df2..fe4ff95 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -12,13 +12,23 @@
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@radix-ui/react-alert-dialog": "^1.1.15",
+ "@radix-ui/react-avatar": "^1.1.11",
"@radix-ui/react-checkbox": "^1.3.3",
"@radix-ui/react-dialog": "^1.1.15",
+ "@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-label": "^2.1.8",
+ "@radix-ui/react-popover": "^1.1.15",
"@radix-ui/react-radio-group": "^1.3.8",
+ "@radix-ui/react-scroll-area": "^1.2.10",
"@radix-ui/react-select": "^2.2.6",
+ "@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slider": "^1.3.6",
"@radix-ui/react-slot": "^1.2.4",
+ "@radix-ui/react-switch": "^1.2.6",
+ "@radix-ui/react-tabs": "^1.1.13",
+ "@radix-ui/react-tooltip": "^1.2.8",
+ "@supercharge/request-ip": "^1.2.0",
+ "better-auth": "^1.4.7",
"better-sqlite3": "^12.5.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
@@ -37,9 +47,11 @@
"react-colorful": "^5.6.1",
"react-day-picker": "^9.11.3",
"react-dom": "^19.2.1",
+ "react-is": "^19.2.3",
"recharts": "^3.6.0",
"sonner": "^2.0.7",
- "tailwind-merge": "^3.4.0"
+ "tailwind-merge": "^3.4.0",
+ "ua-parser-js": "^2.0.7"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
@@ -50,6 +62,7 @@
"eslint": "^9",
"eslint-config-next": "^16.0.7",
"tailwindcss": "^4",
+ "tsx": "^4.21.0",
"tw-animate-css": "^1.4.0",
"typescript": "^5"
}
@@ -316,6 +329,46 @@
"node": ">=6.9.0"
}
},
+ "node_modules/@better-auth/core": {
+ "version": "1.4.9",
+ "resolved": "https://registry.npmjs.org/@better-auth/core/-/core-1.4.9.tgz",
+ "integrity": "sha512-JT2q4NDkQzN22KclUEoZ7qU6tl9HUTfK1ctg2oWlT87SEagkwJcnrUwS9VznL+u9ziOIfY27P0f7/jSnmvLcoQ==",
+ "dependencies": {
+ "@standard-schema/spec": "^1.0.0",
+ "zod": "^4.1.12"
+ },
+ "peerDependencies": {
+ "@better-auth/utils": "0.3.0",
+ "@better-fetch/fetch": "1.1.21",
+ "better-call": "1.1.7",
+ "jose": "^6.1.0",
+ "kysely": "^0.28.5",
+ "nanostores": "^1.0.1"
+ }
+ },
+ "node_modules/@better-auth/telemetry": {
+ "version": "1.4.9",
+ "resolved": "https://registry.npmjs.org/@better-auth/telemetry/-/telemetry-1.4.9.tgz",
+ "integrity": "sha512-Tthy1/Gmx+pYlbvRQPBTKfVei8+pJwvH1NZp+5SbhwA6K2EXIaoonx/K6N/AXYs2aKUpyR4/gzqDesDjL7zd6A==",
+ "dependencies": {
+ "@better-auth/utils": "0.3.0",
+ "@better-fetch/fetch": "1.1.21"
+ },
+ "peerDependencies": {
+ "@better-auth/core": "1.4.9"
+ }
+ },
+ "node_modules/@better-auth/utils": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/@better-auth/utils/-/utils-0.3.0.tgz",
+ "integrity": "sha512-W+Adw6ZA6mgvnSnhOki270rwJ42t4XzSK6YWGF//BbVXL6SwCLWfyzBc1lN2m/4RM28KubdBKQ4X5VMoLRNPQw==",
+ "license": "MIT"
+ },
+ "node_modules/@better-fetch/fetch": {
+ "version": "1.1.21",
+ "resolved": "https://registry.npmjs.org/@better-fetch/fetch/-/fetch-1.1.21.tgz",
+ "integrity": "sha512-/ImESw0sskqlVR94jB+5+Pxjf+xBwDZF/N5+y2/q4EqD7IARUTSpPfIo8uf39SYpCxyOCtbyYpUrZ3F/k0zT4A=="
+ },
"node_modules/@date-fns/tz": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@date-fns/tz/-/tz-1.4.1.tgz",
@@ -2071,9 +2124,9 @@
"license": "MIT"
},
"node_modules/@next/eslint-plugin-next": {
- "version": "16.1.0",
- "resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-16.1.0.tgz",
- "integrity": "sha512-sooC/k0LCF4/jLXYHpgfzJot04lZQqsttn8XJpTguP8N3GhqXN3wSkh68no2OcZzS/qeGwKDFTqhZ8WofdXmmQ==",
+ "version": "16.1.1",
+ "resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-16.1.1.tgz",
+ "integrity": "sha512-Ovb/6TuLKbE1UiPcg0p39Ke3puyTCIKN9hGbNItmpQsp+WX3qrjO3WaMVSi6JHr9X1NrmthqIguVHodMJbh/dw==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -2208,6 +2261,30 @@
"node": ">= 10"
}
},
+ "node_modules/@noble/ciphers": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-2.1.1.tgz",
+ "integrity": "sha512-bysYuiVfhxNJuldNXlFEitTVdNnYUc+XNJZd7Qm2a5j1vZHgY+fazadNFWFaMK/2vye0JVlxV3gHmC0WDfAOQw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 20.19.0"
+ },
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
+ "node_modules/@noble/hashes": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.0.1.tgz",
+ "integrity": "sha512-XlOlEbQcE9fmuXxrVTXCTlG2nlRXa9Rj3rr5Ue/+tX+nmkgbX720YHh0VR3hBF9xDvwnb8D2shVGOwNx+ulArw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 20.19.0"
+ },
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
"node_modules/@nodelib/fs.scandir": {
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
@@ -2644,6 +2721,71 @@
}
}
},
+ "node_modules/@radix-ui/react-avatar": {
+ "version": "1.1.11",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-avatar/-/react-avatar-1.1.11.tgz",
+ "integrity": "sha512-0Qk603AHGV28BOBO34p7IgD5m+V5Sg/YovfayABkoDDBM5d3NCx0Mp4gGrjzLGes1jV5eNOE1r3itqOR33VC6Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/react-context": "1.1.3",
+ "@radix-ui/react-primitive": "2.1.4",
+ "@radix-ui/react-use-callback-ref": "1.1.1",
+ "@radix-ui/react-use-is-hydrated": "0.1.0",
+ "@radix-ui/react-use-layout-effect": "1.1.1"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-avatar/node_modules/@radix-ui/react-context": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.1.3.tgz",
+ "integrity": "sha512-ieIFACdMpYfMEjF0rEf5KLvfVyIkOz6PDGyNnP+u+4xQ6jny3VCgA4OgXOwNx2aUkxn8zx9fiVcM8CfFYv9Lxw==",
+ "license": "MIT",
+ "peerDependencies": {
+ "@types/react": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-avatar/node_modules/@radix-ui/react-primitive": {
+ "version": "2.1.4",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.4.tgz",
+ "integrity": "sha512-9hQc4+GNVtJAIEPEqlYqW5RiYdrr8ea5XQ0ZOnD6fgru+83kqT15mq2OCcbe8KnjRZl5vF3ks69AKz3kh1jrhg==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/react-slot": "1.2.4"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-checkbox": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@radix-ui/react-checkbox/-/react-checkbox-1.3.3.tgz",
@@ -2844,6 +2986,35 @@
}
}
},
+ "node_modules/@radix-ui/react-dropdown-menu": {
+ "version": "2.1.16",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-dropdown-menu/-/react-dropdown-menu-2.1.16.tgz",
+ "integrity": "sha512-1PLGQEynI/3OX/ftV54COn+3Sud/Mn8vALg2rWnBLnRaGtJDduNW/22XjlGgPdpcIbiQxjKtb7BkcjP00nqfJw==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-id": "1.1.1",
+ "@radix-ui/react-menu": "2.1.16",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-use-controllable-state": "1.2.2"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-focus-guards": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/@radix-ui/react-focus-guards/-/react-focus-guards-1.1.3.tgz",
@@ -2948,6 +3119,119 @@
}
}
},
+ "node_modules/@radix-ui/react-menu": {
+ "version": "2.1.16",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-menu/-/react-menu-2.1.16.tgz",
+ "integrity": "sha512-72F2T+PLlphrqLcAotYPp0uJMr5SjP5SL01wfEspJbru5Zs5vQaSHb4VB3ZMJPimgHHCHG7gMOeOB9H3Hdmtxg==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-collection": "1.1.7",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-direction": "1.1.1",
+ "@radix-ui/react-dismissable-layer": "1.1.11",
+ "@radix-ui/react-focus-guards": "1.1.3",
+ "@radix-ui/react-focus-scope": "1.1.7",
+ "@radix-ui/react-id": "1.1.1",
+ "@radix-ui/react-popper": "1.2.8",
+ "@radix-ui/react-portal": "1.1.9",
+ "@radix-ui/react-presence": "1.1.5",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-roving-focus": "1.1.11",
+ "@radix-ui/react-slot": "1.2.3",
+ "@radix-ui/react-use-callback-ref": "1.1.1",
+ "aria-hidden": "^1.2.4",
+ "react-remove-scroll": "^2.6.3"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-slot": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.3.tgz",
+ "integrity": "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/react-compose-refs": "1.1.2"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-popover": {
+ "version": "1.1.15",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-popover/-/react-popover-1.1.15.tgz",
+ "integrity": "sha512-kr0X2+6Yy/vJzLYJUPCZEc8SfQcf+1COFoAqauJm74umQhta9M7lNJHP7QQS3vkvcGLQUbWpMzwrXYwrYztHKA==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-dismissable-layer": "1.1.11",
+ "@radix-ui/react-focus-guards": "1.1.3",
+ "@radix-ui/react-focus-scope": "1.1.7",
+ "@radix-ui/react-id": "1.1.1",
+ "@radix-ui/react-popper": "1.2.8",
+ "@radix-ui/react-portal": "1.1.9",
+ "@radix-ui/react-presence": "1.1.5",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-slot": "1.2.3",
+ "@radix-ui/react-use-controllable-state": "1.2.2",
+ "aria-hidden": "^1.2.4",
+ "react-remove-scroll": "^2.6.3"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-popover/node_modules/@radix-ui/react-slot": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.3.tgz",
+ "integrity": "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/react-compose-refs": "1.1.2"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-popper": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/@radix-ui/react-popper/-/react-popper-1.2.8.tgz",
@@ -3132,6 +3416,37 @@
}
}
},
+ "node_modules/@radix-ui/react-scroll-area": {
+ "version": "1.2.10",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-scroll-area/-/react-scroll-area-1.2.10.tgz",
+ "integrity": "sha512-tAXIa1g3sM5CGpVT0uIbUx/U3Gs5N8T52IICuCtObaos1S8fzsrPXG5WObkQN3S6NVl6wKgPhAIiBGbWnvc97A==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/number": "1.1.1",
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-direction": "1.1.1",
+ "@radix-ui/react-presence": "1.1.5",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-use-callback-ref": "1.1.1",
+ "@radix-ui/react-use-layout-effect": "1.1.1"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-select": {
"version": "2.2.6",
"resolved": "https://registry.npmjs.org/@radix-ui/react-select/-/react-select-2.2.6.tgz",
@@ -3193,23 +3508,69 @@
}
}
},
- "node_modules/@radix-ui/react-slider": {
- "version": "1.3.6",
- "resolved": "https://registry.npmjs.org/@radix-ui/react-slider/-/react-slider-1.3.6.tgz",
- "integrity": "sha512-JPYb1GuM1bxfjMRlNLE+BcmBC8onfCi60Blk7OBqi2MLTFdS+8401U4uFjnwkOr49BLmXxLC6JHkvAsx5OJvHw==",
+ "node_modules/@radix-ui/react-separator": {
+ "version": "1.1.8",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-separator/-/react-separator-1.1.8.tgz",
+ "integrity": "sha512-sDvqVY4itsKwwSMEe0jtKgfTh+72Sy3gPmQpjqcQneqQ4PFmr/1I0YA+2/puilhggCe2gJcx5EBAYFkWkdpa5g==",
"license": "MIT",
"dependencies": {
- "@radix-ui/number": "1.1.1",
- "@radix-ui/primitive": "1.1.3",
- "@radix-ui/react-collection": "1.1.7",
- "@radix-ui/react-compose-refs": "1.1.2",
- "@radix-ui/react-context": "1.1.2",
- "@radix-ui/react-direction": "1.1.1",
- "@radix-ui/react-primitive": "2.1.3",
- "@radix-ui/react-use-controllable-state": "1.2.2",
- "@radix-ui/react-use-layout-effect": "1.1.1",
- "@radix-ui/react-use-previous": "1.1.1",
- "@radix-ui/react-use-size": "1.1.1"
+ "@radix-ui/react-primitive": "2.1.4"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-separator/node_modules/@radix-ui/react-primitive": {
+ "version": "2.1.4",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.4.tgz",
+ "integrity": "sha512-9hQc4+GNVtJAIEPEqlYqW5RiYdrr8ea5XQ0ZOnD6fgru+83kqT15mq2OCcbe8KnjRZl5vF3ks69AKz3kh1jrhg==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/react-slot": "1.2.4"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-slider": {
+ "version": "1.3.6",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-slider/-/react-slider-1.3.6.tgz",
+ "integrity": "sha512-JPYb1GuM1bxfjMRlNLE+BcmBC8onfCi60Blk7OBqi2MLTFdS+8401U4uFjnwkOr49BLmXxLC6JHkvAsx5OJvHw==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/number": "1.1.1",
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-collection": "1.1.7",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-direction": "1.1.1",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-use-controllable-state": "1.2.2",
+ "@radix-ui/react-use-layout-effect": "1.1.1",
+ "@radix-ui/react-use-previous": "1.1.1",
+ "@radix-ui/react-use-size": "1.1.1"
},
"peerDependencies": {
"@types/react": "*",
@@ -3244,6 +3605,117 @@
}
}
},
+ "node_modules/@radix-ui/react-switch": {
+ "version": "1.2.6",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-switch/-/react-switch-1.2.6.tgz",
+ "integrity": "sha512-bByzr1+ep1zk4VubeEVViV592vu2lHE2BZY5OnzehZqOOgogN80+mNtCqPkhn2gklJqOpxWgPoYTSnhBCqpOXQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-use-controllable-state": "1.2.2",
+ "@radix-ui/react-use-previous": "1.1.1",
+ "@radix-ui/react-use-size": "1.1.1"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-tabs": {
+ "version": "1.1.13",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-tabs/-/react-tabs-1.1.13.tgz",
+ "integrity": "sha512-7xdcatg7/U+7+Udyoj2zodtI9H/IIopqo+YOIcZOq1nJwXWBZ9p8xiu5llXlekDbZkca79a/fozEYQXIA4sW6A==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-direction": "1.1.1",
+ "@radix-ui/react-id": "1.1.1",
+ "@radix-ui/react-presence": "1.1.5",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-roving-focus": "1.1.11",
+ "@radix-ui/react-use-controllable-state": "1.2.2"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-tooltip": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-tooltip/-/react-tooltip-1.2.8.tgz",
+ "integrity": "sha512-tY7sVt1yL9ozIxvmbtN5qtmH2krXcBCfjEiCgKGLqunJHvgvZG2Pcl2oQ3kbcZARb1BGEHdkLzcYGO8ynVlieg==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-dismissable-layer": "1.1.11",
+ "@radix-ui/react-id": "1.1.1",
+ "@radix-ui/react-popper": "1.2.8",
+ "@radix-ui/react-portal": "1.1.9",
+ "@radix-ui/react-presence": "1.1.5",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-slot": "1.2.3",
+ "@radix-ui/react-use-controllable-state": "1.2.2",
+ "@radix-ui/react-visually-hidden": "1.2.3"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-slot": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.3.tgz",
+ "integrity": "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/react-compose-refs": "1.1.2"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-use-callback-ref": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.1.tgz",
@@ -3314,6 +3786,24 @@
}
}
},
+ "node_modules/@radix-ui/react-use-is-hydrated": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-is-hydrated/-/react-use-is-hydrated-0.1.0.tgz",
+ "integrity": "sha512-U+UORVEq+cTnRIaostJv9AGdV3G6Y+zbVd+12e18jQ5A3c0xL03IhnHuiU4UV69wolOQp5GfR58NW/EgdQhwOA==",
+ "license": "MIT",
+ "dependencies": {
+ "use-sync-external-store": "^1.5.0"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-use-layout-effect": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.1.tgz",
@@ -3436,9 +3926,9 @@
}
},
"node_modules/@reduxjs/toolkit/node_modules/immer": {
- "version": "11.0.1",
- "resolved": "https://registry.npmjs.org/immer/-/immer-11.0.1.tgz",
- "integrity": "sha512-naDCyggtcBWANtIrjQEajhhBEuL9b0Zg4zmlWK2CzS6xCWSE39/vvf4LqnMjUAWHBhot4m9MHCM/Z+mfWhUkiA==",
+ "version": "11.1.0",
+ "resolved": "https://registry.npmjs.org/immer/-/immer-11.1.0.tgz",
+ "integrity": "sha512-dlzb07f5LDY+tzs+iLCSXV2yuhaYfezqyZQc+n6baLECWkOMEWxkECAOnXL0ba7lsA25fM9b2jtzpu/uxo1a7g==",
"license": "MIT",
"funding": {
"type": "opencollective",
@@ -3470,6 +3960,12 @@
"integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",
"license": "MIT"
},
+ "node_modules/@supercharge/request-ip": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/@supercharge/request-ip/-/request-ip-1.2.0.tgz",
+ "integrity": "sha512-wlt6JW69MHqLY2M6Sm/jVyCojNRKq2CBvwH0Hbx24SFhDQQGkgEjeKxVutDxHSyrWixFaOSLXC27euzxijhyMQ==",
+ "license": "MIT"
+ },
"node_modules/@swc/core": {
"version": "1.15.7",
"resolved": "https://registry.npmjs.org/@swc/core/-/core-1.15.7.tgz",
@@ -4125,17 +4621,17 @@
"license": "MIT"
},
"node_modules/@typescript-eslint/eslint-plugin": {
- "version": "8.50.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.50.0.tgz",
- "integrity": "sha512-O7QnmOXYKVtPrfYzMolrCTfkezCJS9+ljLdKW/+DCvRsc3UAz+sbH6Xcsv7p30+0OwUbeWfUDAQE0vpabZ3QLg==",
+ "version": "8.50.1",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.50.1.tgz",
+ "integrity": "sha512-PKhLGDq3JAg0Jk/aK890knnqduuI/Qj+udH7wCf0217IGi4gt+acgCyPVe79qoT+qKUvHMDQkwJeKW9fwl8Cyw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@eslint-community/regexpp": "^4.10.0",
- "@typescript-eslint/scope-manager": "8.50.0",
- "@typescript-eslint/type-utils": "8.50.0",
- "@typescript-eslint/utils": "8.50.0",
- "@typescript-eslint/visitor-keys": "8.50.0",
+ "@typescript-eslint/scope-manager": "8.50.1",
+ "@typescript-eslint/type-utils": "8.50.1",
+ "@typescript-eslint/utils": "8.50.1",
+ "@typescript-eslint/visitor-keys": "8.50.1",
"ignore": "^7.0.0",
"natural-compare": "^1.4.0",
"ts-api-utils": "^2.1.0"
@@ -4148,7 +4644,7 @@
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
- "@typescript-eslint/parser": "^8.50.0",
+ "@typescript-eslint/parser": "^8.50.1",
"eslint": "^8.57.0 || ^9.0.0",
"typescript": ">=4.8.4 <6.0.0"
}
@@ -4164,16 +4660,16 @@
}
},
"node_modules/@typescript-eslint/parser": {
- "version": "8.50.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.50.0.tgz",
- "integrity": "sha512-6/cmF2piao+f6wSxUsJLZjck7OQsYyRtcOZS02k7XINSNlz93v6emM8WutDQSXnroG2xwYlEVHJI+cPA7CPM3Q==",
+ "version": "8.50.1",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.50.1.tgz",
+ "integrity": "sha512-hM5faZwg7aVNa819m/5r7D0h0c9yC4DUlWAOvHAtISdFTc8xB86VmX5Xqabrama3wIPJ/q9RbGS1worb6JfnMg==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@typescript-eslint/scope-manager": "8.50.0",
- "@typescript-eslint/types": "8.50.0",
- "@typescript-eslint/typescript-estree": "8.50.0",
- "@typescript-eslint/visitor-keys": "8.50.0",
+ "@typescript-eslint/scope-manager": "8.50.1",
+ "@typescript-eslint/types": "8.50.1",
+ "@typescript-eslint/typescript-estree": "8.50.1",
+ "@typescript-eslint/visitor-keys": "8.50.1",
"debug": "^4.3.4"
},
"engines": {
@@ -4189,14 +4685,14 @@
}
},
"node_modules/@typescript-eslint/project-service": {
- "version": "8.50.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.50.0.tgz",
- "integrity": "sha512-Cg/nQcL1BcoTijEWyx4mkVC56r8dj44bFDvBdygifuS20f3OZCHmFbjF34DPSi07kwlFvqfv/xOLnJ5DquxSGQ==",
+ "version": "8.50.1",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.50.1.tgz",
+ "integrity": "sha512-E1ur1MCVf+YiP89+o4Les/oBAVzmSbeRB0MQLfSlYtbWU17HPxZ6Bhs5iYmKZRALvEuBoXIZMOIRRc/P++Ortg==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@typescript-eslint/tsconfig-utils": "^8.50.0",
- "@typescript-eslint/types": "^8.50.0",
+ "@typescript-eslint/tsconfig-utils": "^8.50.1",
+ "@typescript-eslint/types": "^8.50.1",
"debug": "^4.3.4"
},
"engines": {
@@ -4211,14 +4707,14 @@
}
},
"node_modules/@typescript-eslint/scope-manager": {
- "version": "8.50.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.50.0.tgz",
- "integrity": "sha512-xCwfuCZjhIqy7+HKxBLrDVT5q/iq7XBVBXLn57RTIIpelLtEIZHXAF/Upa3+gaCpeV1NNS5Z9A+ID6jn50VD4A==",
+ "version": "8.50.1",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.50.1.tgz",
+ "integrity": "sha512-mfRx06Myt3T4vuoHaKi8ZWNTPdzKPNBhiblze5N50//TSHOAQQevl/aolqA/BcqqbJ88GUnLqjjcBc8EWdBcVw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@typescript-eslint/types": "8.50.0",
- "@typescript-eslint/visitor-keys": "8.50.0"
+ "@typescript-eslint/types": "8.50.1",
+ "@typescript-eslint/visitor-keys": "8.50.1"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
@@ -4229,9 +4725,9 @@
}
},
"node_modules/@typescript-eslint/tsconfig-utils": {
- "version": "8.50.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.50.0.tgz",
- "integrity": "sha512-vxd3G/ybKTSlm31MOA96gqvrRGv9RJ7LGtZCn2Vrc5htA0zCDvcMqUkifcjrWNNKXHUU3WCkYOzzVSFBd0wa2w==",
+ "version": "8.50.1",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.50.1.tgz",
+ "integrity": "sha512-ooHmotT/lCWLXi55G4mvaUF60aJa012QzvLK0Y+Mp4WdSt17QhMhWOaBWeGTFVkb2gDgBe19Cxy1elPXylslDw==",
"dev": true,
"license": "MIT",
"engines": {
@@ -4246,15 +4742,15 @@
}
},
"node_modules/@typescript-eslint/type-utils": {
- "version": "8.50.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.50.0.tgz",
- "integrity": "sha512-7OciHT2lKCewR0mFoBrvZJ4AXTMe/sYOe87289WAViOocEmDjjv8MvIOT2XESuKj9jp8u3SZYUSh89QA4S1kQw==",
+ "version": "8.50.1",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.50.1.tgz",
+ "integrity": "sha512-7J3bf022QZE42tYMO6SL+6lTPKFk/WphhRPe9Tw/el+cEwzLz1Jjz2PX3GtGQVxooLDKeMVmMt7fWpYRdG5Etg==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@typescript-eslint/types": "8.50.0",
- "@typescript-eslint/typescript-estree": "8.50.0",
- "@typescript-eslint/utils": "8.50.0",
+ "@typescript-eslint/types": "8.50.1",
+ "@typescript-eslint/typescript-estree": "8.50.1",
+ "@typescript-eslint/utils": "8.50.1",
"debug": "^4.3.4",
"ts-api-utils": "^2.1.0"
},
@@ -4271,9 +4767,9 @@
}
},
"node_modules/@typescript-eslint/types": {
- "version": "8.50.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.50.0.tgz",
- "integrity": "sha512-iX1mgmGrXdANhhITbpp2QQM2fGehBse9LbTf0sidWK6yg/NE+uhV5dfU1g6EYPlcReYmkE9QLPq/2irKAmtS9w==",
+ "version": "8.50.1",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.50.1.tgz",
+ "integrity": "sha512-v5lFIS2feTkNyMhd7AucE/9j/4V9v5iIbpVRncjk/K0sQ6Sb+Np9fgYS/63n6nwqahHQvbmujeBL7mp07Q9mlA==",
"dev": true,
"license": "MIT",
"engines": {
@@ -4285,16 +4781,16 @@
}
},
"node_modules/@typescript-eslint/typescript-estree": {
- "version": "8.50.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.50.0.tgz",
- "integrity": "sha512-W7SVAGBR/IX7zm1t70Yujpbk+zdPq/u4soeFSknWFdXIFuWsBGBOUu/Tn/I6KHSKvSh91OiMuaSnYp3mtPt5IQ==",
+ "version": "8.50.1",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.50.1.tgz",
+ "integrity": "sha512-woHPdW+0gj53aM+cxchymJCrh0cyS7BTIdcDxWUNsclr9VDkOSbqC13juHzxOmQ22dDkMZEpZB+3X1WpUvzgVQ==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@typescript-eslint/project-service": "8.50.0",
- "@typescript-eslint/tsconfig-utils": "8.50.0",
- "@typescript-eslint/types": "8.50.0",
- "@typescript-eslint/visitor-keys": "8.50.0",
+ "@typescript-eslint/project-service": "8.50.1",
+ "@typescript-eslint/tsconfig-utils": "8.50.1",
+ "@typescript-eslint/types": "8.50.1",
+ "@typescript-eslint/visitor-keys": "8.50.1",
"debug": "^4.3.4",
"minimatch": "^9.0.4",
"semver": "^7.6.0",
@@ -4352,16 +4848,16 @@
}
},
"node_modules/@typescript-eslint/utils": {
- "version": "8.50.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.50.0.tgz",
- "integrity": "sha512-87KgUXET09CRjGCi2Ejxy3PULXna63/bMYv72tCAlDJC3Yqwln0HiFJ3VJMst2+mEtNtZu5oFvX4qJGjKsnAgg==",
+ "version": "8.50.1",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.50.1.tgz",
+ "integrity": "sha512-lCLp8H1T9T7gPbEuJSnHwnSuO9mDf8mfK/Nion5mZmiEaQD9sWf9W4dfeFqRyqRjF06/kBuTmAqcs9sewM2NbQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@eslint-community/eslint-utils": "^4.7.0",
- "@typescript-eslint/scope-manager": "8.50.0",
- "@typescript-eslint/types": "8.50.0",
- "@typescript-eslint/typescript-estree": "8.50.0"
+ "@typescript-eslint/scope-manager": "8.50.1",
+ "@typescript-eslint/types": "8.50.1",
+ "@typescript-eslint/typescript-estree": "8.50.1"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
@@ -4376,13 +4872,13 @@
}
},
"node_modules/@typescript-eslint/visitor-keys": {
- "version": "8.50.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.50.0.tgz",
- "integrity": "sha512-Xzmnb58+Db78gT/CCj/PVCvK+zxbnsw6F+O1oheYszJbBSdEjVhQi3C/Xttzxgi/GLmpvOggRs1RFpiJ8+c34Q==",
+ "version": "8.50.1",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.50.1.tgz",
+ "integrity": "sha512-IrDKrw7pCRUR94zeuCSUWQ+w8JEf5ZX5jl/e6AHGSLi1/zIr0lgutfn/7JpfCey+urpgQEdrZVYzCaVVKiTwhQ==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@typescript-eslint/types": "8.50.0",
+ "@typescript-eslint/types": "8.50.1",
"eslint-visitor-keys": "^4.2.1"
},
"engines": {
@@ -5007,6 +5503,122 @@
"baseline-browser-mapping": "dist/cli.js"
}
},
+ "node_modules/better-auth": {
+ "version": "1.4.9",
+ "resolved": "https://registry.npmjs.org/better-auth/-/better-auth-1.4.9.tgz",
+ "integrity": "sha512-usSdjuyTzZwIvM8fjF8YGhPncxV3MAg3dHUO9uPUnf0yklXUSYISiH1+imk6/Z+UBqsscyyPRnbIyjyK97p7YA==",
+ "license": "MIT",
+ "dependencies": {
+ "@better-auth/core": "1.4.9",
+ "@better-auth/telemetry": "1.4.9",
+ "@better-auth/utils": "0.3.0",
+ "@better-fetch/fetch": "1.1.21",
+ "@noble/ciphers": "^2.0.0",
+ "@noble/hashes": "^2.0.0",
+ "better-call": "1.1.7",
+ "defu": "^6.1.4",
+ "jose": "^6.1.0",
+ "kysely": "^0.28.5",
+ "nanostores": "^1.0.1",
+ "zod": "^4.1.12"
+ },
+ "peerDependencies": {
+ "@lynx-js/react": "*",
+ "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0",
+ "@sveltejs/kit": "^2.0.0",
+ "@tanstack/react-start": "^1.0.0",
+ "better-sqlite3": "^12.0.0",
+ "drizzle-kit": ">=0.31.4",
+ "drizzle-orm": ">=0.41.0",
+ "mongodb": "^6.0.0 || ^7.0.0",
+ "mysql2": "^3.0.0",
+ "next": "^14.0.0 || ^15.0.0 || ^16.0.0",
+ "pg": "^8.0.0",
+ "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0",
+ "react": "^18.0.0 || ^19.0.0",
+ "react-dom": "^18.0.0 || ^19.0.0",
+ "solid-js": "^1.0.0",
+ "svelte": "^4.0.0 || ^5.0.0",
+ "vitest": "^2.0.0 || ^3.0.0 || ^4.0.0",
+ "vue": "^3.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@lynx-js/react": {
+ "optional": true
+ },
+ "@prisma/client": {
+ "optional": true
+ },
+ "@sveltejs/kit": {
+ "optional": true
+ },
+ "@tanstack/react-start": {
+ "optional": true
+ },
+ "better-sqlite3": {
+ "optional": true
+ },
+ "drizzle-kit": {
+ "optional": true
+ },
+ "drizzle-orm": {
+ "optional": true
+ },
+ "mongodb": {
+ "optional": true
+ },
+ "mysql2": {
+ "optional": true
+ },
+ "next": {
+ "optional": true
+ },
+ "pg": {
+ "optional": true
+ },
+ "prisma": {
+ "optional": true
+ },
+ "react": {
+ "optional": true
+ },
+ "react-dom": {
+ "optional": true
+ },
+ "solid-js": {
+ "optional": true
+ },
+ "svelte": {
+ "optional": true
+ },
+ "vitest": {
+ "optional": true
+ },
+ "vue": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/better-call": {
+ "version": "1.1.7",
+ "resolved": "https://registry.npmjs.org/better-call/-/better-call-1.1.7.tgz",
+ "integrity": "sha512-6gaJe1bBIEgVebQu/7q9saahVzvBsGaByEnE8aDVncZEDiJO7sdNB28ot9I6iXSbR25egGmmZ6aIURXyQHRraQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@better-auth/utils": "^0.3.0",
+ "@better-fetch/fetch": "^1.1.4",
+ "rou3": "^0.7.10",
+ "set-cookie-parser": "^2.7.1"
+ },
+ "peerDependencies": {
+ "zod": "^4.0.0"
+ },
+ "peerDependenciesMeta": {
+ "zod": {
+ "optional": true
+ }
+ }
+ },
"node_modules/better-sqlite3": {
"version": "12.5.0",
"resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.5.0.tgz",
@@ -5650,6 +6262,32 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/defu": {
+ "version": "6.1.4",
+ "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.4.tgz",
+ "integrity": "sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg==",
+ "license": "MIT"
+ },
+ "node_modules/detect-europe-js": {
+ "version": "0.1.2",
+ "resolved": "https://registry.npmjs.org/detect-europe-js/-/detect-europe-js-0.1.2.tgz",
+ "integrity": "sha512-lgdERlL3u0aUdHocoouzT10d9I89VVhk0qNRmll7mXdGfJT1/wqZ2ZLA4oJAjeACPY5fT1wsbq2AT+GkuInsow==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/faisalman"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/ua-parser-js"
+ },
+ {
+ "type": "paypal",
+ "url": "https://paypal.me/faisalman"
+ }
+ ],
+ "license": "MIT"
+ },
"node_modules/detect-libc": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
@@ -6216,13 +6854,13 @@
}
},
"node_modules/eslint-config-next": {
- "version": "16.1.0",
- "resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-16.1.0.tgz",
- "integrity": "sha512-RlPb8E2uO/Ix/w3kizxz6+6ogw99WqtNzTG0ArRZ5NEkIYcsfRb8U0j7aTG7NjRvcrsak5QtUSuxGNN2UcA58g==",
+ "version": "16.1.1",
+ "resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-16.1.1.tgz",
+ "integrity": "sha512-55nTpVWm3qeuxoQKLOjQVciKZJUphKrNM0fCcQHAIOGl6VFXgaqeMfv0aKJhs7QtcnlAPhNVqsqRfRjeKBPIUA==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@next/eslint-plugin-next": "16.1.0",
+ "@next/eslint-plugin-next": "16.1.1",
"eslint-import-resolver-node": "^0.3.6",
"eslint-import-resolver-typescript": "^3.5.2",
"eslint-plugin-import": "^2.32.0",
@@ -6657,9 +7295,9 @@
}
},
"node_modules/fastq": {
- "version": "1.19.1",
- "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.1.tgz",
- "integrity": "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==",
+ "version": "1.20.1",
+ "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz",
+ "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==",
"dev": true,
"license": "ISC",
"dependencies": {
@@ -6790,14 +7428,29 @@
"integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
"license": "MIT"
},
- "node_modules/function-bind": {
- "version": "1.1.2",
- "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
- "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
"dev": true,
+ "hasInstallScript": true,
"license": "MIT",
- "funding": {
- "url": "https://github.com/sponsors/ljharb"
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/function-bind": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/function.prototype.name": {
@@ -7565,6 +8218,26 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/is-standalone-pwa": {
+ "version": "0.1.1",
+ "resolved": "https://registry.npmjs.org/is-standalone-pwa/-/is-standalone-pwa-0.1.1.tgz",
+ "integrity": "sha512-9Cbovsa52vNQCjdXOzeQq5CnCbAcRk05aU62K20WO372NrTv0NxibLFCK6lQ4/iZEFdEA3p3t2VNOn8AJ53F5g==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/faisalman"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/ua-parser-js"
+ },
+ {
+ "type": "paypal",
+ "url": "https://paypal.me/faisalman"
+ }
+ ],
+ "license": "MIT"
+ },
"node_modules/is-string": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/is-string/-/is-string-1.1.1.tgz",
@@ -7704,6 +8377,15 @@
"jiti": "lib/jiti-cli.mjs"
}
},
+ "node_modules/jose": {
+ "version": "6.1.3",
+ "resolved": "https://registry.npmjs.org/jose/-/jose-6.1.3.tgz",
+ "integrity": "sha512-0TpaTfihd4QMNwrz/ob2Bp7X04yuxJkjRGi4aKmOqwhov54i6u79oCv7T+C7lo70MKH6BesI3vscD1yb/yzKXQ==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/panva"
+ }
+ },
"node_modules/js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
@@ -7814,6 +8496,15 @@
"json-buffer": "3.0.1"
}
},
+ "node_modules/kysely": {
+ "version": "0.28.9",
+ "resolved": "https://registry.npmjs.org/kysely/-/kysely-0.28.9.tgz",
+ "integrity": "sha512-3BeXMoiOhpOwu62CiVpO6lxfq4eS6KMYfQdMsN/2kUCRNuF2YiEr7u0HLHaQU+O4Xu8YXE3bHVkwaQ85i72EuA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
"node_modules/language-subtag-registry": {
"version": "0.3.23",
"resolved": "https://registry.npmjs.org/language-subtag-registry/-/language-subtag-registry-0.3.23.tgz",
@@ -8312,6 +9003,21 @@
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
+ "node_modules/nanostores": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/nanostores/-/nanostores-1.1.0.tgz",
+ "integrity": "sha512-yJBmDJr18xy47dbNVlHcgdPrulSn1nhSE6Ns9vTG+Nx9VPT6iV1MD6aQFp/t52zpf82FhLLTXAXr30NuCnxvwA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": "^20.0.0 || >=22.0.0"
+ }
+ },
"node_modules/napi-build-utils": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz",
@@ -9016,8 +9722,7 @@
"version": "19.2.3",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.3.tgz",
"integrity": "sha512-qJNJfu81ByyabuG7hPFEbXqNcWSU3+eVus+KJs+0ncpGfMyYdvSmxiJxbWR65lYi1I+/0HBcliO029gc4F+PnA==",
- "license": "MIT",
- "peer": true
+ "license": "MIT"
},
"node_modules/react-redux": {
"version": "9.2.0",
@@ -9288,6 +9993,12 @@
"node": ">= 0.8.15"
}
},
+ "node_modules/rou3": {
+ "version": "0.7.12",
+ "resolved": "https://registry.npmjs.org/rou3/-/rou3-0.7.12.tgz",
+ "integrity": "sha512-iFE4hLDuloSWcD7mjdCDhx2bKcIsYbtOTpfH5MHHLSKMOUyjqQXTeZVa289uuwEGEKFoE/BAPbhaU4B774nceg==",
+ "license": "MIT"
+ },
"node_modules/run-parallel": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",
@@ -9403,6 +10114,12 @@
"semver": "bin/semver.js"
}
},
+ "node_modules/set-cookie-parser": {
+ "version": "2.7.2",
+ "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz",
+ "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==",
+ "license": "MIT"
+ },
"node_modules/set-function-length": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz",
@@ -10107,6 +10824,510 @@
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
+ "node_modules/tsx": {
+ "version": "4.21.0",
+ "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz",
+ "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "esbuild": "~0.27.0",
+ "get-tsconfig": "^4.7.5"
+ },
+ "bin": {
+ "tsx": "dist/cli.mjs"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/aix-ppc64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.2.tgz",
+ "integrity": "sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/android-arm": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.2.tgz",
+ "integrity": "sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/android-arm64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.2.tgz",
+ "integrity": "sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/android-x64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.2.tgz",
+ "integrity": "sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/darwin-arm64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.2.tgz",
+ "integrity": "sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/darwin-x64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.2.tgz",
+ "integrity": "sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.2.tgz",
+ "integrity": "sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/freebsd-x64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.2.tgz",
+ "integrity": "sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/linux-arm": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.2.tgz",
+ "integrity": "sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/linux-arm64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.2.tgz",
+ "integrity": "sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/linux-ia32": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.2.tgz",
+ "integrity": "sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/linux-loong64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.2.tgz",
+ "integrity": "sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/linux-mips64el": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.2.tgz",
+ "integrity": "sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/linux-ppc64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.2.tgz",
+ "integrity": "sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/linux-riscv64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.2.tgz",
+ "integrity": "sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/linux-s390x": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.2.tgz",
+ "integrity": "sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/linux-x64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.2.tgz",
+ "integrity": "sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.2.tgz",
+ "integrity": "sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/netbsd-x64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.2.tgz",
+ "integrity": "sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.2.tgz",
+ "integrity": "sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/openbsd-x64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.2.tgz",
+ "integrity": "sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.2.tgz",
+ "integrity": "sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/sunos-x64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.2.tgz",
+ "integrity": "sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/win32-arm64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.2.tgz",
+ "integrity": "sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/win32-ia32": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.2.tgz",
+ "integrity": "sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/@esbuild/win32-x64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.2.tgz",
+ "integrity": "sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tsx/node_modules/esbuild": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.2.tgz",
+ "integrity": "sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.27.2",
+ "@esbuild/android-arm": "0.27.2",
+ "@esbuild/android-arm64": "0.27.2",
+ "@esbuild/android-x64": "0.27.2",
+ "@esbuild/darwin-arm64": "0.27.2",
+ "@esbuild/darwin-x64": "0.27.2",
+ "@esbuild/freebsd-arm64": "0.27.2",
+ "@esbuild/freebsd-x64": "0.27.2",
+ "@esbuild/linux-arm": "0.27.2",
+ "@esbuild/linux-arm64": "0.27.2",
+ "@esbuild/linux-ia32": "0.27.2",
+ "@esbuild/linux-loong64": "0.27.2",
+ "@esbuild/linux-mips64el": "0.27.2",
+ "@esbuild/linux-ppc64": "0.27.2",
+ "@esbuild/linux-riscv64": "0.27.2",
+ "@esbuild/linux-s390x": "0.27.2",
+ "@esbuild/linux-x64": "0.27.2",
+ "@esbuild/netbsd-arm64": "0.27.2",
+ "@esbuild/netbsd-x64": "0.27.2",
+ "@esbuild/openbsd-arm64": "0.27.2",
+ "@esbuild/openbsd-x64": "0.27.2",
+ "@esbuild/openharmony-arm64": "0.27.2",
+ "@esbuild/sunos-x64": "0.27.2",
+ "@esbuild/win32-arm64": "0.27.2",
+ "@esbuild/win32-ia32": "0.27.2",
+ "@esbuild/win32-x64": "0.27.2"
+ }
+ },
"node_modules/tunnel-agent": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
@@ -10235,16 +11456,16 @@
}
},
"node_modules/typescript-eslint": {
- "version": "8.50.0",
- "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.50.0.tgz",
- "integrity": "sha512-Q1/6yNUmCpH94fbgMUMg2/BSAr/6U7GBk61kZTv1/asghQOWOjTlp9K8mixS5NcJmm2creY+UFfGeW/+OcA64A==",
+ "version": "8.50.1",
+ "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.50.1.tgz",
+ "integrity": "sha512-ytTHO+SoYSbhAH9CrYnMhiLx8To6PSSvqnvXyPUgPETCvB6eBKmTI9w6XMPS3HsBRGkwTVBX+urA8dYQx6bHfQ==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@typescript-eslint/eslint-plugin": "8.50.0",
- "@typescript-eslint/parser": "8.50.0",
- "@typescript-eslint/typescript-estree": "8.50.0",
- "@typescript-eslint/utils": "8.50.0"
+ "@typescript-eslint/eslint-plugin": "8.50.1",
+ "@typescript-eslint/parser": "8.50.1",
+ "@typescript-eslint/typescript-estree": "8.50.1",
+ "@typescript-eslint/utils": "8.50.1"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
@@ -10258,6 +11479,57 @@
"typescript": ">=4.8.4 <6.0.0"
}
},
+ "node_modules/ua-is-frozen": {
+ "version": "0.1.2",
+ "resolved": "https://registry.npmjs.org/ua-is-frozen/-/ua-is-frozen-0.1.2.tgz",
+ "integrity": "sha512-RwKDW2p3iyWn4UbaxpP2+VxwqXh0jpvdxsYpZ5j/MLLiQOfbsV5shpgQiw93+KMYQPcteeMQ289MaAFzs3G9pw==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/faisalman"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/ua-parser-js"
+ },
+ {
+ "type": "paypal",
+ "url": "https://paypal.me/faisalman"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/ua-parser-js": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/ua-parser-js/-/ua-parser-js-2.0.7.tgz",
+ "integrity": "sha512-CFdHVHr+6YfbktNZegH3qbYvYgC7nRNEUm2tk7nSFXSODUu4tDBpaFpP1jdXBUOKKwapVlWRfTtS8bCPzsQ47w==",
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/ua-parser-js"
+ },
+ {
+ "type": "paypal",
+ "url": "https://paypal.me/faisalman"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/faisalman"
+ }
+ ],
+ "license": "AGPL-3.0-or-later",
+ "dependencies": {
+ "detect-europe-js": "^0.1.2",
+ "is-standalone-pwa": "^0.1.1",
+ "ua-is-frozen": "^0.1.2"
+ },
+ "bin": {
+ "ua-parser-js": "script/cli.js"
+ },
+ "engines": {
+ "node": "*"
+ }
+ },
"node_modules/unbox-primitive": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.1.0.tgz",
@@ -10609,7 +11881,6 @@
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.2.1.tgz",
"integrity": "sha512-0wZ1IRqGGhMP76gLqz8EyfBXKk0J2qo2+H3fi4mcUP/KtTocoX08nmIAHl1Z2kJIZbZee8KOpBCSNPRgauucjw==",
- "dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
diff --git a/package.json b/package.json
index f141bee..db3da24 100644
--- a/package.json
+++ b/package.json
@@ -7,12 +7,13 @@
"build": "next build",
"start": "next start",
"lint": "eslint",
- "test": "npm run lint && npm run build",
- "test:ci": "npm run lint && npm run build && npm run db:generate && npm run db:migrate",
+ "test": "npm run lint && npm run build && npm run i18n",
+ "test:ci": "npm run lint && npm run build && npm run i18n && npm run db:generate && npm run db:migrate",
"db:generate": "drizzle-kit generate",
"db:migrate": "drizzle-kit migrate",
"db:studio": "drizzle-kit studio",
"db:push": "drizzle-kit push",
+ "i18n": "tsx scripts/i18n-checks.ts",
"release:patch": "npm version patch && git push && git push --tags",
"release:minor": "npm version minor && git push && git push --tags",
"release:major": "npm version major && git push && git push --tags"
@@ -22,13 +23,23 @@
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@radix-ui/react-alert-dialog": "^1.1.15",
+ "@radix-ui/react-avatar": "^1.1.11",
"@radix-ui/react-checkbox": "^1.3.3",
"@radix-ui/react-dialog": "^1.1.15",
+ "@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-label": "^2.1.8",
+ "@radix-ui/react-popover": "^1.1.15",
"@radix-ui/react-radio-group": "^1.3.8",
+ "@radix-ui/react-scroll-area": "^1.2.10",
"@radix-ui/react-select": "^2.2.6",
+ "@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slider": "^1.3.6",
"@radix-ui/react-slot": "^1.2.4",
+ "@radix-ui/react-switch": "^1.2.6",
+ "@radix-ui/react-tabs": "^1.1.13",
+ "@radix-ui/react-tooltip": "^1.2.8",
+ "@supercharge/request-ip": "^1.2.0",
+ "better-auth": "^1.4.7",
"better-sqlite3": "^12.5.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
@@ -47,9 +58,11 @@
"react-colorful": "^5.6.1",
"react-day-picker": "^9.11.3",
"react-dom": "^19.2.1",
+ "react-is": "^19.2.3",
"recharts": "^3.6.0",
"sonner": "^2.0.7",
- "tailwind-merge": "^3.4.0"
+ "tailwind-merge": "^3.4.0",
+ "ua-parser-js": "^2.0.7"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
@@ -60,6 +73,7 @@
"eslint": "^9",
"eslint-config-next": "^16.0.7",
"tailwindcss": "^4",
+ "tsx": "^4.21.0",
"tw-animate-css": "^1.4.0",
"typescript": "^5"
},
diff --git a/proxy.ts b/proxy.ts
new file mode 100644
index 0000000..7cae7f2
--- /dev/null
+++ b/proxy.ts
@@ -0,0 +1,240 @@
+import { NextResponse } from "next/server";
+import type { NextRequest } from "next/server";
+import { isAuthEnabled, allowGuestAccess } from "@/lib/auth/feature-flags";
+import {
+ validateAccessToken,
+ storeTokenInCookie,
+ updateTokenUsage,
+} from "@/lib/auth/token-auth";
+import { logAuditEvent } from "@/lib/audit-log";
+import { rateLimit } from "@/lib/rate-limiter";
+import { auth } from "@/lib/auth";
+import { isAdmin } from "@/lib/auth/admin";
+
+/**
+ * Proxy for authentication and route protection (Next.js 16)
+ *
+ * Features:
+ * - Protects routes when auth is enabled
+ * - Redirects unauthenticated users to login (unless guest access enabled)
+ * - Allows public routes (login, register, API)
+ * - Stores return URL for post-login redirect
+ * - Supports guest access for viewing calendars
+ * - Handles access token sharing (/share/token/xyz)
+ */
+export async function proxy(request: NextRequest) {
+ const { pathname } = request.nextUrl;
+
+ // =====================================================
+ // Access Token Handling (/share/token/[token])
+ // =====================================================
+ if (pathname.startsWith("/share/token/")) {
+ const token = pathname.split("/share/token/")[1];
+
+ if (token) {
+ // Rate limit: 10 requests per minute per IP
+ const rateLimitResponse = rateLimit(request, null, "token-validation");
+ if (rateLimitResponse) return rateLimitResponse;
+
+ // Validate the token
+ const validation = await validateAccessToken(token);
+
+ if (validation) {
+ // Token is valid - store in cookie and redirect to calendar
+ const response = NextResponse.redirect(
+ new URL(`/?id=${validation.calendarId}`, request.url)
+ );
+
+ storeTokenInCookie(
+ token,
+ validation.calendarId,
+ validation.permission,
+ response,
+ request // Pass request to read existing tokens
+ );
+
+ // Update usage stats (non-blocking)
+ void updateTokenUsage(validation.id);
+
+ // Audit log: Token used
+ void logAuditEvent({
+ userId: null, // Token access is anonymous
+ action: "calendar_token_used",
+ resourceType: "calendar",
+ resourceId: validation.calendarId,
+ metadata: {
+ tokenId: validation.id,
+ calendarName: validation.calendarName,
+ permission: validation.permission,
+ },
+ request,
+ severity: "info",
+ isUserVisible: false,
+ });
+
+ return response;
+ } else {
+ // Invalid token - audit log and redirect to home with error
+ void logAuditEvent({
+ userId: null,
+ action: "calendar_token_invalid",
+ resourceType: "calendar",
+ resourceId: null,
+ metadata: {
+ tokenPreview: `${token.slice(0, 6)}...`,
+ },
+ request,
+ severity: "warning",
+ isUserVisible: false,
+ });
+
+ const response = NextResponse.redirect(new URL("/", request.url));
+ // Could set a query param to show error toast on client
+ return response;
+ }
+ }
+ }
+
+ // If auth is disabled, allow all routes
+ if (!isAuthEnabled()) {
+ return NextResponse.next();
+ }
+
+ // Public routes that don't require authentication
+ const publicRoutes = [
+ "/login",
+ "/register",
+ "/api/auth", // Better Auth API routes
+ "/api/version", // Version info (always public)
+ "/api/releases", // Changelog/releases (always public)
+ ];
+
+ // Check if the current route is public
+ const isPublicRoute = publicRoutes.some((route) =>
+ pathname.startsWith(route)
+ );
+
+ // Allow public routes
+ if (isPublicRoute) {
+ return NextResponse.next();
+ }
+
+ // =====================================================
+ // Admin Panel Protection (/admin/*)
+ // =====================================================
+ if (pathname.startsWith("/admin")) {
+ // Admin panel requires authentication (no guest access)
+ // Check both secure and non-secure cookie names
+ const sessionToken =
+ request.cookies.get("__Secure-better-auth.session_token") ||
+ request.cookies.get("better-auth.session_token");
+
+ if (!sessionToken) {
+ // Not authenticated - redirect to login
+ const loginUrl = new URL("/login", request.url);
+ loginUrl.searchParams.set("returnUrl", pathname);
+ return NextResponse.redirect(loginUrl);
+ }
+
+ // Validate session and check admin role
+ try {
+ const session = await auth.api.getSession({ headers: request.headers });
+
+ if (!session?.user) {
+ // Invalid session - redirect to login
+ const loginUrl = new URL("/login", request.url);
+ loginUrl.searchParams.set("returnUrl", pathname);
+ return NextResponse.redirect(loginUrl);
+ }
+
+ // Check if user is admin
+ if (!isAdmin(session.user)) {
+ // Not an admin - redirect to home with error
+ const homeUrl = new URL("/", request.url);
+ homeUrl.searchParams.set("error", "admin_access_required");
+
+ // Audit log: Unauthorized admin access attempt
+ void logAuditEvent({
+ userId: session.user.id,
+ action: "admin_access_denied",
+ resourceType: "admin",
+ resourceId: null,
+ metadata: {
+ attemptedPath: pathname,
+ userRole: session.user.role || "user",
+ },
+ request,
+ severity: "warning",
+ isUserVisible: false,
+ });
+
+ return NextResponse.redirect(homeUrl);
+ }
+ } catch (error) {
+ console.error("[Proxy] Admin access check failed:", error);
+ // Session validation failed - redirect to login
+ const loginUrl = new URL("/login", request.url);
+ loginUrl.searchParams.set("returnUrl", pathname);
+ return NextResponse.redirect(loginUrl);
+ }
+ }
+
+ // Check for session cookie (Better Auth uses "better-auth.session_token")
+ // When useSecureCookies is enabled, it adds __Secure- prefix
+ const sessionToken =
+ request.cookies.get("__Secure-better-auth.session_token") ||
+ request.cookies.get("better-auth.session_token");
+
+ // If no session token, check guest access
+ if (!sessionToken) {
+ // If guest access is enabled, allow viewing without login
+ if (allowGuestAccess()) {
+ return NextResponse.next();
+ }
+
+ // Otherwise, redirect to login with return URL
+ const loginUrl = new URL("/login", request.url);
+ loginUrl.searchParams.set("returnUrl", pathname);
+ return NextResponse.redirect(loginUrl);
+ }
+
+ // Session token validation happens in API routes via getSessionUser()
+ // Middleware only checks for cookie presence (fast routing decision)
+
+ // Add security headers to response
+ const response = NextResponse.next();
+
+ // Security Headers (Defense in Depth)
+ response.headers.set("X-Content-Type-Options", "nosniff");
+ response.headers.set("X-Frame-Options", "DENY");
+ response.headers.set("X-XSS-Protection", "1; mode=block");
+ response.headers.set("Referrer-Policy", "strict-origin-when-cross-origin");
+
+ // Content Security Policy (strict but allows inline scripts for Next.js hydration)
+ const csp = [
+ "default-src 'self'",
+ "script-src 'self' 'unsafe-inline' 'unsafe-eval'", // Required for Next.js
+ "style-src 'self' 'unsafe-inline'", // Required for Tailwind
+ "img-src 'self' data: https:",
+ "font-src 'self' data:",
+ "connect-src 'self'",
+ "frame-ancestors 'none'",
+ ].join("; ");
+ response.headers.set("Content-Security-Policy", csp);
+
+ return response;
+}
+
+// Configure which routes to run proxy on
+export const config = {
+ matcher: [
+ /*
+ * Match all request paths except:
+ * - _next/static (static files)
+ * - _next/image (image optimization files)
+ * - favicon.ico (favicon file)
+ * - public files (images, etc.)
+ */
+ "/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
+ ],
+};
diff --git a/scripts/i18n-checks.ts b/scripts/i18n-checks.ts
new file mode 100644
index 0000000..f62f6e0
--- /dev/null
+++ b/scripts/i18n-checks.ts
@@ -0,0 +1,544 @@
+#!/usr/bin/env tsx
+
+/**
+ * Find unused translation keys in the project
+ *
+ * This script:
+ * 1. Reads all translation keys from messages/*.json files
+ * 2. Searches for usage of t("key") in the codebase
+ * 3. Reports keys that are never used
+ * 4. Reports keys that are used in code but missing in de.json
+ * 5. Checks if en.json and it.json are synchronized with de.json
+ */
+
+import fs from "fs";
+import path from "path";
+import { fileURLToPath } from "url";
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+const rootDir = path.resolve(__dirname, "..");
+
+// Directories to search for translations usage
+const searchDirs = ["app", "components", "hooks", "lib"];
+
+// Extensions to search in
+const extensions = [".ts", ".tsx", ".js", ".jsx"];
+
+/**
+ * Flatten nested JSON object to dot-notation keys
+ * Example: { common: { save: "Save" } } -> ["common.save"]
+ */
+function flattenKeys(obj: Record<string, unknown>, prefix = ""): string[] {
+ const keys: string[] = [];
+
+ for (const [key, value] of Object.entries(obj)) {
+ const fullKey = prefix ? `${prefix}.${key}` : key;
+
+ if (value && typeof value === "object" && !Array.isArray(value)) {
+ keys.push(...flattenKeys(value as Record<string, unknown>, fullKey));
+ } else {
+ keys.push(fullKey);
+ }
+ }
+
+ return keys;
+}
+
+/**
+ * Read all translation keys from a specific locale file
+ */
+function getTranslationKeys(locale: string): string[] {
+ const messagesPath = path.join(rootDir, "messages", `${locale}.json`);
+ const content = fs.readFileSync(messagesPath, "utf-8");
+ const messages = JSON.parse(content) as Record<string, unknown>;
+ return flattenKeys(messages);
+}
+
+/**
+ * Read all translation keys from messages/de.json (source of truth)
+ */
+function getAllTranslationKeys(): string[] {
+ return getTranslationKeys("de");
+}
+
+/**
+ * Recursively find all files with given extensions in a directory
+ */
+function findFiles(dir: string, exts: string[]): string[] {
+ const results: string[] = [];
+
+ if (!fs.existsSync(dir)) {
+ return results;
+ }
+
+ const items = fs.readdirSync(dir, { withFileTypes: true });
+
+ for (const item of items) {
+ const fullPath = path.join(dir, item.name);
+
+ if (item.isDirectory()) {
+ // Skip node_modules and hidden directories
+ if (item.name === "node_modules" || item.name.startsWith(".")) {
+ continue;
+ }
+ results.push(...findFiles(fullPath, exts));
+ } else if (item.isFile() && exts.some((ext) => item.name.endsWith(ext))) {
+ results.push(fullPath);
+ }
+ }
+
+ return results;
+}
+
+/**
+ * Find all files to search in
+ */
+function getSearchFiles(): string[] {
+ const files: string[] = [];
+
+ for (const dir of searchDirs) {
+ const fullPath = path.join(rootDir, dir);
+ files.push(...findFiles(fullPath, extensions));
+ }
+
+ return files;
+}
+
+/**
+ * Check if a key contains dynamic template syntax
+ */
+function isDynamicKey(key: string): boolean {
+ return key.includes("${");
+}
+
+/**
+ * Extract static prefix and original pattern from a dynamic key
+ * Example: "language.${locale}" -> { prefix: "language", pattern: "language.${locale}" }
+ * Example: "admin.role${role}" -> { prefix: "admin.role", pattern: "admin.role${role}" }
+ */
+function extractDynamicKeyInfo(key: string): {
+ prefix: string;
+ pattern: string;
+} | null {
+ // Find the position of the first ${
+ const dollarIndex = key.indexOf("${");
+ if (dollarIndex === -1) return null;
+
+ // Get everything before ${ - this is our prefix
+ // For "admin.role${...}", beforeDollar = "admin.role"
+ // For "language.${...}", beforeDollar = "language"
+ const beforeDollar = key.substring(0, dollarIndex);
+
+ // The prefix is everything before ${, which represents the static part
+ // This allows matching keys like:
+ // - "admin.role" + "User" = "admin.roleUser"
+ // - "admin.role" + "Admin" = "admin.roleAdmin"
+ // - "language" + ".de" = "language.de"
+ const prefix = beforeDollar;
+
+ return {
+ prefix,
+ pattern: key,
+ };
+}
+
+/**
+ * Store for dynamic patterns with their original code representation
+ */
+const dynamicPatterns = new Map<string, string>();
+
+/**
+ * Extract translation key usage patterns from file content
+ * Matches: t("key"), t('key'), t(`key`)
+ * Also matches: t("key", ...), t.rich("key"), etc.
+ * Handles both static keys and dynamic template patterns
+ */
+function extractUsedKeys(content: string): Set<string> {
+ const keys = new Set<string>();
+
+ // Match t("key"), t('key')
+ // Also handles t.rich(), t.raw(), etc.
+ const stringPatterns = [
+ /\bt(?:\.\w+)?\s*\(\s*["']([^"']+)["']/g, // t("key") or t.rich("key")
+ ];
+
+ for (const pattern of stringPatterns) {
+ let match;
+ while ((match = pattern.exec(content)) !== null) {
+ const key = match[1];
+ keys.add(key);
+ }
+ }
+
+ // Special handling for template literals: t(`key`) and t(`key${var}`)
+ // Use 's' flag to match across newlines (dotall mode)
+ // Match opening backtick, capture everything until closing backtick
+ const templatePattern = /\bt(?:\.\w+)?\s*\(\s*`([^`]+)`/gs;
+ let templateMatch;
+ while ((templateMatch = templatePattern.exec(content)) !== null) {
+ // Normalize whitespace in the captured template string
+ const fullTemplate = templateMatch[1].replace(/\s+/g, " ").trim();
+
+ // Check if it contains ${...} template expressions
+ if (isDynamicKey(fullTemplate)) {
+ const info = extractDynamicKeyInfo(fullTemplate);
+ if (info) {
+ // Store the original pattern for later display
+ dynamicPatterns.set(info.prefix, fullTemplate);
+ // Store the prefix as a marker
+ keys.add(`${info.prefix}.*`);
+ }
+ } else {
+ // Static template literal (no ${})
+ keys.add(fullTemplate);
+ }
+ }
+
+ return keys;
+}
+
+/**
+ * Find all used translation keys in the codebase
+ */
+function findUsedKeys(files: string[]): Set<string> {
+ const usedKeys = new Set<string>();
+
+ for (const file of files) {
+ const content = fs.readFileSync(file, "utf-8");
+ const fileKeys = extractUsedKeys(content);
+
+ for (const key of fileKeys) {
+ usedKeys.add(key);
+ }
+ }
+
+ return usedKeys;
+}
+
+/**
+ * Check if a key or any of its parent keys are used
+ * Example: If "common" is used, then "common.save" is considered used too
+ * Also handles wildcard patterns like "admin.role.*" matching "admin.roleUser"
+ */
+function isKeyOrParentUsed(key: string, usedKeys: Set<string>): boolean {
+ // Check exact match
+ if (usedKeys.has(key)) {
+ return true;
+ }
+
+ // Check if any wildcard pattern matches
+ // Wildcard patterns like "admin.role.*" should match keys like "admin.roleUser"
+ // BUT NOT "admin.role" itself or "admin.roleSettings.foo"
+ for (const usedKey of usedKeys) {
+ if (usedKey.endsWith(".*")) {
+ const prefix = usedKey.slice(0, -2); // Remove ".*" -> "admin.role"
+
+ // Check if key starts with prefix + "."
+ if (key.startsWith(prefix)) {
+ // Get the part after the prefix
+ const afterPrefix = key.substring(prefix.length);
+
+ // Only match if:
+ // 1. There's exactly one more segment (e.g., "admin.role" + "User" = "admin.roleUser")
+ // 2. No dots in the remaining part (not "admin.roleSettings.foo")
+ if (afterPrefix.length > 0 && !afterPrefix.includes(".")) {
+ return true;
+ }
+ }
+ }
+ }
+
+ // Check if any parent key is used
+ // Example: If "common" is used, "common.save" is considered used
+ const parts = key.split(".");
+ for (let i = parts.length - 1; i > 0; i--) {
+ const parentKey = parts.slice(0, i).join(".");
+ if (usedKeys.has(parentKey)) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+/**
+ * Compare translation files and find missing/extra keys
+ */
+function compareTranslationFiles(): {
+ missingInEn: string[];
+ missingInIt: string[];
+ extraInEn: string[];
+ extraInIt: string[];
+} {
+ const deKeys = new Set(getTranslationKeys("de"));
+ const enKeys = new Set(getTranslationKeys("en"));
+ const itKeys = new Set(getTranslationKeys("it"));
+
+ const missingInEn: string[] = [];
+ const missingInIt: string[] = [];
+ const extraInEn: string[] = [];
+ const extraInIt: string[] = [];
+
+ // Find keys missing in en.json and it.json
+ for (const key of deKeys) {
+ if (!enKeys.has(key)) {
+ missingInEn.push(key);
+ }
+ if (!itKeys.has(key)) {
+ missingInIt.push(key);
+ }
+ }
+
+ // Find extra keys in en.json and it.json
+ for (const key of enKeys) {
+ if (!deKeys.has(key)) {
+ extraInEn.push(key);
+ }
+ }
+
+ for (const key of itKeys) {
+ if (!deKeys.has(key)) {
+ extraInIt.push(key);
+ }
+ }
+
+ return { missingInEn, missingInIt, extraInEn, extraInIt };
+}
+
+/**
+ * Find keys that are used in code but missing in de.json
+ */
+function findMissingKeys(
+ usedKeys: Set<string>,
+ allKeys: string[]
+): Array<{ key: string; pattern?: string; existingKeys?: string[] }> {
+ const allKeysSet = new Set(allKeys);
+ const missingKeys: Array<{
+ key: string;
+ pattern?: string;
+ existingKeys?: string[];
+ }> = [];
+
+ for (const usedKey of usedKeys) {
+ // Handle wildcard patterns
+ if (usedKey.endsWith(".*")) {
+ const prefix = usedKey.slice(0, -2); // Remove ".*"
+ const originalPattern = dynamicPatterns.get(prefix);
+
+ // Find all keys that match this prefix
+ // Two possible patterns:
+ // 1. prefix + "." + something (e.g., "language." + "de" = "language.de")
+ // 2. prefix + something (e.g., "admin.role" + "User" = "admin.roleUser")
+ const matchingKeys = allKeys.filter((key) => {
+ if (key.startsWith(prefix + ".")) {
+ return true; // Pattern 1: language.${locale} -> language.de
+ }
+ if (key.startsWith(prefix) && key.length > prefix.length) {
+ const afterPrefix = key.substring(prefix.length);
+ // Check if there's no dot in the remaining part
+ // This catches: admin.roleUser but not admin.role.something
+ return !afterPrefix.includes(".");
+ }
+ return false;
+ });
+
+ if (matchingKeys.length === 0) {
+ // No keys found with this prefix at all
+ missingKeys.push({
+ key: `${prefix}.*`,
+ pattern: originalPattern,
+ existingKeys: [],
+ });
+ }
+ // If some keys exist with this prefix, we assume it's OK
+ // (we can't know which specific keys are needed at runtime)
+ } else {
+ // Static key - check if it exists
+ if (!isKeyOrParentUsed(usedKey, allKeysSet)) {
+ missingKeys.push({ key: usedKey });
+ }
+ }
+ }
+
+ return missingKeys.sort((a, b) => a.key.localeCompare(b.key));
+}
+
+/**
+ * Main function
+ */
+function main() {
+ console.log("🔍 Analyzing translation keys...\n");
+ let hasIssues = false;
+
+ // Get all translation keys
+ console.log("📖 Reading translation keys from messages/de.json...");
+ const allKeys = getAllTranslationKeys();
+ console.log(` Found ${allKeys.length} translation keys\n`);
+
+ // Get all files to search
+ console.log("📁 Finding source files...");
+ const files = getSearchFiles();
+ console.log(` Found ${files.length} files to search\n`);
+
+ // Find used keys
+ console.log("🔎 Searching for translation key usage...");
+ const usedKeys = findUsedKeys(files);
+ const staticKeys = Array.from(usedKeys).filter((k) => !k.endsWith(".*"));
+ const wildcardPatterns = Array.from(usedKeys).filter((k) => k.endsWith(".*"));
+ console.log(
+ ` Found ${staticKeys.length} static keys + ${wildcardPatterns.length} dynamic patterns\n`
+ );
+
+ // 1. Find unused keys
+ console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
+ console.log("1️⃣ UNUSED KEYS (in de.json but not used in code)");
+ console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
+
+ const unusedKeys = allKeys.filter((key) => !isKeyOrParentUsed(key, usedKeys));
+
+ if (unusedKeys.length === 0) {
+ console.log("✅ No unused translation keys found!\n");
+ } else {
+ hasIssues = true;
+ // Group unused keys by top-level namespace
+ const groupedKeys = new Map<string, string[]>();
+
+ for (const key of unusedKeys) {
+ const namespace = key.split(".")[0];
+ if (!groupedKeys.has(namespace)) {
+ groupedKeys.set(namespace, []);
+ }
+ groupedKeys.get(namespace)!.push(key);
+ }
+
+ console.log(`❌ Found ${unusedKeys.length} unused translation keys:\n`);
+
+ for (const [namespace, keys] of Array.from(groupedKeys.entries()).sort()) {
+ console.log(`📦 ${namespace} (${keys.length} unused):`);
+ for (const key of keys.sort()) {
+ console.log(` - ${key}`);
+ }
+ console.log();
+ }
+ }
+
+ // 2. Find missing keys
+ console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
+ console.log("2️⃣ MISSING KEYS (used in code but not in de.json)");
+ console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
+
+ const missingKeys = findMissingKeys(usedKeys, allKeys);
+
+ if (missingKeys.length === 0) {
+ console.log("✅ No missing translation keys found!\n");
+ } else {
+ hasIssues = true;
+ console.log(`❌ Found ${missingKeys.length} missing translation keys:\n`);
+ for (const item of missingKeys) {
+ if (item.pattern) {
+ // Dynamic pattern
+ console.log(
+ ` - ${
+ item.pattern
+ } (dynamic key - no keys with prefix '${item.key.replace(
+ ".*",
+ ""
+ )}' found)`
+ );
+ } else {
+ // Static key
+ console.log(` - ${item.key}`);
+ }
+ }
+ console.log();
+ }
+
+ // 3. Compare translation files
+ console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
+ console.log("3️⃣ FILE SYNCHRONIZATION (de.json vs en.json vs it.json)");
+ console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
+
+ const { missingInEn, missingInIt, extraInEn, extraInIt } =
+ compareTranslationFiles();
+
+ const syncIssues =
+ missingInEn.length +
+ missingInIt.length +
+ extraInEn.length +
+ extraInIt.length;
+
+ if (syncIssues === 0) {
+ console.log("✅ All translation files are synchronized!\n");
+ } else {
+ hasIssues = true;
+
+ if (missingInEn.length > 0) {
+ console.log(`❌ Missing in en.json (${missingInEn.length} keys):`);
+ for (const key of missingInEn.sort()) {
+ console.log(` - ${key}`);
+ }
+ console.log();
+ }
+
+ if (missingInIt.length > 0) {
+ console.log(`❌ Missing in it.json (${missingInIt.length} keys):`);
+ for (const key of missingInIt.sort()) {
+ console.log(` - ${key}`);
+ }
+ console.log();
+ }
+
+ if (extraInEn.length > 0) {
+ console.log(
+ `⚠️ Extra in en.json (${extraInEn.length} keys not in de.json):`
+ );
+ for (const key of extraInEn.sort()) {
+ console.log(` - ${key}`);
+ }
+ console.log();
+ }
+
+ if (extraInIt.length > 0) {
+ console.log(
+ `⚠️ Extra in it.json (${extraInIt.length} keys not in de.json):`
+ );
+ for (const key of extraInIt.sort()) {
+ console.log(` - ${key}`);
+ }
+ console.log();
+ }
+ }
+
+ // Summary
+ console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
+ console.log("📊 SUMMARY");
+ console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
+ console.log(` Total keys in de.json: ${allKeys.length}`);
+ console.log(` Static keys used in code: ${staticKeys.length}`);
+ console.log(` Dynamic patterns (wildcards): ${wildcardPatterns.length}`);
+ console.log(` Unused keys: ${unusedKeys.length}`);
+ console.log(` Missing keys: ${missingKeys.length}`);
+ console.log(
+ ` Usage rate: ${((1 - unusedKeys.length / allKeys.length) * 100).toFixed(
+ 1
+ )}%`
+ );
+ console.log();
+ console.log(` en.json missing: ${missingInEn.length}`);
+ console.log(` en.json extra: ${extraInEn.length}`);
+ console.log(` it.json missing: ${missingInIt.length}`);
+ console.log(` it.json extra: ${extraInIt.length}`);
+ console.log();
+
+ if (!hasIssues) {
+ console.log("✅ All checks passed!");
+ } else {
+ console.log("❌ Issues found. Please review the report above.");
+ }
+
+ // Exit with error code if any issues found
+ process.exit(hasIssues ? 1 : 0);
+}
+
+main();
diff --git a/tsconfig.json b/tsconfig.json
index 3a13f90..15c7b97 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -1,6 +1,6 @@
{
"compilerOptions": {
- "target": "ES2017",
+ "target": "ES2020",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,