Skip to content

Your favorite shift management application!

feat: two-tier calendar password protection (#40)

panteL372f04065bf9
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index 71ad1d5..224d3ad 100644
--- a/.github/copilot-instructions.md
+++ b/.github/copilot-instructions.md
@@ -64,33 +64,73 @@ export async function PUT(
### Password Protection
-Calendars can be password-protected. Implementation flow:
+Calendars support two-tier password protection via `passwordHash` and `isLocked` fields:
-1. Check localStorage via `getCachedPassword(calendarId)` from `lib/password-cache.ts`
-2. Verify via `verifyAndCachePassword(calendarId, password)` - automatically caches valid passwords
-3. On invalid password: Show `PasswordDialog`, which automatically caches on success
-4. Use `pendingAction` state to retry operation after authentication
+**Two-Tier Protection System**:
-**Important**: Always use the utilities from `lib/password-cache.ts` instead of direct localStorage access:
+- **Write-Only Protection** (`passwordHash` set, `isLocked=false`): Password required for mutations (POST/PUT/PATCH/DELETE), but read access (GET) is allowed without password
+- **Full Protection** (`passwordHash` set, `isLocked=true`): Password required for all operations including read access
-- `getCachedPassword(calendarId)` - Get cached password
-- `setCachedPassword(calendarId, password)` - Cache password after verification
-- `removeCachedPassword(calendarId)` - Remove cached password
-- `verifyAndCachePassword(calendarId, password)` - Verify and auto-cache if valid
-- `hasValidCachedPassword(calendarId)` - Check if cached password is still valid
+**API Route Implementation**:
```typescript
-// Example: Password check before action
-const password = getCachedPassword(calendarId);
-const result = await verifyAndCachePassword(calendarId, password);
-
-if (result.protected && !result.valid) {
- setPendingAction({ type: "edit", shiftId: id, formData });
- setShowPasswordDialog(true);
- return;
+// GET endpoints - check both passwordHash AND isLocked
+if (calendar.passwordHash && calendar.isLocked) {
+ const { searchParams } = new URL(request.url);
+ const password = searchParams.get("password");
+
+ if (!password || !verifyPassword(password, calendar.passwordHash)) {
+ return NextResponse.json({ error: "Invalid password" }, { status: 401 });
+ }
+}
+
+// POST/PUT/PATCH/DELETE endpoints - check only passwordHash
+if (calendar.passwordHash) {
+ const { password } = await request.json();
+
+ if (!password || !verifyPassword(password, calendar.passwordHash)) {
+ return NextResponse.json({ error: "Invalid password" }, { status: 401 });
+ }
}
```
+**Client-Side Password Flow**:
+
+1. **Password Caching**: Use utilities from `lib/password-cache.ts`:
+
+ - `getCachedPassword(calendarId)` - Retrieve password from localStorage
+ - `verifyAndCachePassword(calendarId, password)` - Verify with server and cache if valid
+ - `setCachedPassword(calendarId, password)` - Manually cache password
+ - `removeCachedPassword(calendarId)` - Clear cached password
+
+2. **Hooks Auto-Include Password**: All data-fetching hooks (`useShifts`, `usePresets`, `useNotes`) automatically:
+
+ - Call `getCachedPassword(calendarId)` before each fetch
+ - Append password as query parameter if present
+ - Return empty arrays on 401 responses (graceful degradation)
+
+3. **Locked Calendar UX**:
+
+ - When `isLocked=true` and no valid cached password: Show integrated password form in main UI
+ - After successful password entry: Call `handlePasswordSuccess(password)` which triggers:
+ - `refetchShifts()`, `refetchPresets()`, `refetchNotes()`
+ - `fetchExternalSyncs()`, `fetchSyncErrorStatus()`
+ - `setStatsRefreshTrigger((prev) => prev + 1)`
+ - All data loads immediately after unlock - no page reload needed
+
+4. **Mutation Password Protection**:
+ - Check cached password before mutation: `const result = await verifyAndCachePassword(calendarId, password)`
+ - If `result.protected && !result.valid`: Set `pendingAction` and show `PasswordDialog`
+ - On successful password entry: Execute pending action automatically
+
+**Important Implementation Notes**:
+
+- Never require password input twice - the integrated "Currently Locked" form is sufficient
+- All hooks handle 401 gracefully by returning empty arrays (prevents UI crashes)
+- Calendar list (GET `/api/calendars`) never requires password (allows calendar switching)
+- Password verification is asynchronous - always await `verifyAndCachePassword`
+- Cached passwords persist across sessions via localStorage
+
### State Management
Main page (`app/page.tsx`) patterns:
diff --git a/app/api/calendars/[id]/route.ts b/app/api/calendars/[id]/route.ts
index e7f90d4..fe85bbe 100644
--- a/app/api/calendars/[id]/route.ts
+++ b/app/api/calendars/[id]/route.ts
@@ -11,6 +11,9 @@ export async function GET(
) {
try {
const { id } = await params;
+ const { searchParams } = new URL(request.url);
+ const password = searchParams.get("password");
+
const [calendar] = await db
.select()
.from(calendars)
@@ -23,6 +26,16 @@ 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 }
+ );
+ }
+ }
+
const calendarShifts = await db
.select()
.from(shifts)
diff --git a/app/api/external-syncs/[id]/route.ts b/app/api/external-syncs/[id]/route.ts
index ee4b058..d55de50 100644
--- a/app/api/external-syncs/[id]/route.ts
+++ b/app/api/external-syncs/[id]/route.ts
@@ -1,7 +1,8 @@
import { NextResponse } from "next/server";
import { db } from "@/lib/db";
-import { externalSyncs, shifts } from "@/lib/db/schema";
+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 {
isValidCalendarUrl,
@@ -15,6 +16,8 @@ export async function GET(
) {
try {
const { id } = await params;
+ const { searchParams } = new URL(request.url);
+ const password = searchParams.get("password");
const [externalSync] = await db
.select()
@@ -29,6 +32,29 @@ export async function GET(
);
}
+ // Fetch calendar to check password
+ const [calendar] = await db
+ .select()
+ .from(calendars)
+ .where(eq(calendars.id, externalSync.calendarId));
+
+ if (!calendar) {
+ return NextResponse.json(
+ { error: "Calendar not found" },
+ { status: 404 }
+ );
+ }
+
+ // 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(externalSync);
} catch (error) {
console.error("Failed to fetch external sync:", error);
@@ -71,6 +97,30 @@ export async function PATCH(
);
}
+ // Fetch calendar to check password
+ const [calendar] = await db
+ .select()
+ .from(calendars)
+ .where(eq(calendars.id, existingSync.calendarId));
+
+ if (!calendar) {
+ return NextResponse.json(
+ { error: "Calendar not found" },
+ { status: 404 }
+ );
+ }
+
+ // 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 }
+ );
+ }
+ }
+
// Validate calendar URL if provided
if (calendarUrl !== undefined) {
if (
@@ -179,6 +229,55 @@ 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 (e) {
+ // If body parsing fails, continue with null password
+ }
+ }
+
+ // Fetch external sync to get calendar ID
+ const [existingSync] = await db
+ .select()
+ .from(externalSyncs)
+ .where(eq(externalSyncs.id, id));
+
+ if (!existingSync) {
+ return NextResponse.json(
+ { error: "External sync not found" },
+ { status: 404 }
+ );
+ }
+
+ // Fetch calendar to check password
+ const [calendar] = await db
+ .select()
+ .from(calendars)
+ .where(eq(calendars.id, existingSync.calendarId));
+
+ if (!calendar) {
+ return NextResponse.json(
+ { error: "Calendar not found" },
+ { status: 404 }
+ );
+ }
+
+ // 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(externalSyncs).where(eq(externalSyncs.id, id));
return NextResponse.json({ success: true });
diff --git a/app/api/external-syncs/[id]/sync/route.ts b/app/api/external-syncs/[id]/sync/route.ts
index 7704c82..44d016a 100644
--- a/app/api/external-syncs/[id]/sync/route.ts
+++ b/app/api/external-syncs/[id]/sync/route.ts
@@ -1,7 +1,8 @@
import { NextResponse } from "next/server";
import { db } from "@/lib/db";
-import { externalSyncs, shifts, syncLogs } from "@/lib/db/schema";
+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 {
expandRecurringEvents,
@@ -343,6 +344,56 @@ export async function POST(
) {
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 (e) {
+ // If body parsing fails, continue with null password
+ }
+ }
+
+ // Fetch external sync to get calendar ID
+ const [externalSync] = await db
+ .select()
+ .from(externalSyncs)
+ .where(eq(externalSyncs.id, syncId));
+
+ if (!externalSync) {
+ return NextResponse.json(
+ { error: "External sync not found" },
+ { status: 404 }
+ );
+ }
+
+ // Fetch calendar to check password
+ const [calendar] = await db
+ .select()
+ .from(calendars)
+ .where(eq(calendars.id, externalSync.calendarId));
+
+ if (!calendar) {
+ return NextResponse.json(
+ { error: "Calendar not found" },
+ { status: 404 }
+ );
+ }
+
+ // Verify password if calendar is protected
+ if (calendar.passwordHash) {
+ if (!password || !verifyPassword(password, calendar.passwordHash)) {
+ return NextResponse.json(
+ { error: "Invalid password" },
+ { status: 401 }
+ );
+ }
+ }
+
const stats = await syncExternalCalendar(syncId, "manual");
return NextResponse.json({
diff --git a/app/api/external-syncs/route.ts b/app/api/external-syncs/route.ts
index 37c6901..072a1ff 100644
--- a/app/api/external-syncs/route.ts
+++ b/app/api/external-syncs/route.ts
@@ -1,7 +1,8 @@
import { NextResponse } from "next/server";
import { db } from "@/lib/db";
-import { externalSyncs } from "@/lib/db/schema";
+import { externalSyncs, calendars } from "@/lib/db/schema";
import { eq, desc } from "drizzle-orm";
+import { verifyPassword } from "@/lib/password-utils";
import {
isValidCalendarUrl,
detectCalendarSyncType,
@@ -22,6 +23,31 @@ export async function GET(request: Request) {
);
}
+ const password = searchParams.get("password");
+
+ // Fetch calendar to check password
+ const [calendar] = await db
+ .select()
+ .from(calendars)
+ .where(eq(calendars.id, calendarId));
+
+ if (!calendar) {
+ return NextResponse.json(
+ { error: "Calendar not found" },
+ { status: 404 }
+ );
+ }
+
+ // 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 }
+ );
+ }
+ }
+
const syncs = await db
.select()
.from(externalSyncs)
@@ -63,6 +89,30 @@ export async function POST(request: Request) {
);
}
+ // Fetch calendar to check password
+ const [calendar] = await db
+ .select()
+ .from(calendars)
+ .where(eq(calendars.id, calendarId));
+
+ if (!calendar) {
+ return NextResponse.json(
+ { error: "Calendar not found" },
+ { status: 404 }
+ );
+ }
+
+ // 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 }
+ );
+ }
+ }
+
let finalCalendarUrl;
let isOneTimeImport = false;
let syncType: CalendarSyncType;
diff --git a/app/api/notes/[id]/route.ts b/app/api/notes/[id]/route.ts
index ad33402..4bf17dc 100644
--- a/app/api/notes/[id]/route.ts
+++ b/app/api/notes/[id]/route.ts
@@ -12,6 +12,9 @@ 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()
.from(calendarNotes)
@@ -24,6 +27,29 @@ export async function GET(
);
}
+ // Fetch calendar to check password
+ const [calendar] = await db
+ .select()
+ .from(calendars)
+ .where(eq(calendars.id, result[0].calendarId));
+
+ if (!calendar) {
+ return NextResponse.json(
+ { error: "Calendar not found" },
+ { status: 404 }
+ );
+ }
+
+ // 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 calendar note:", error);
diff --git a/app/api/notes/route.ts b/app/api/notes/route.ts
index cfa920d..91c6d8f 100644
--- a/app/api/notes/route.ts
+++ b/app/api/notes/route.ts
@@ -19,6 +19,31 @@ export async function GET(request: Request) {
);
}
+ const password = searchParams.get("password");
+
+ // Fetch calendar to check password
+ const [calendar] = await db
+ .select()
+ .from(calendars)
+ .where(eq(calendars.id, calendarId));
+
+ if (!calendar) {
+ return NextResponse.json(
+ { error: "Calendar not found" },
+ { status: 404 }
+ );
+ }
+
+ // 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 }
+ );
+ }
+ }
+
let query = db
.select()
.from(calendarNotes)
diff --git a/app/api/presets/[id]/route.ts b/app/api/presets/[id]/route.ts
index 927979d..b752028 100644
--- a/app/api/presets/[id]/route.ts
+++ b/app/api/presets/[id]/route.ts
@@ -5,6 +5,58 @@ import { eq } from "drizzle-orm";
import { verifyPassword } from "@/lib/password-utils";
import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";
+// GET single preset
+export async function GET(
+ request: NextRequest,
+ { params }: { params: Promise<{ id: string }> }
+) {
+ try {
+ const { id } = await params;
+ const { searchParams } = new URL(request.url);
+ const password = searchParams.get("password");
+
+ const [preset] = await db
+ .select()
+ .from(shiftPresets)
+ .where(eq(shiftPresets.id, id));
+
+ if (!preset) {
+ return NextResponse.json({ error: "Preset not found" }, { status: 404 });
+ }
+
+ // Fetch calendar to check password
+ const [calendar] = await db
+ .select()
+ .from(calendars)
+ .where(eq(calendars.id, preset.calendarId));
+
+ if (!calendar) {
+ return NextResponse.json(
+ { error: "Calendar not found" },
+ { status: 404 }
+ );
+ }
+
+ // 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(preset);
+ } catch (error) {
+ console.error("Failed to fetch preset:", error);
+ return NextResponse.json(
+ { error: "Failed to fetch preset" },
+ { status: 500 }
+ );
+ }
+}
+
// PATCH update a preset
export async function PATCH(
request: NextRequest,
diff --git a/app/api/presets/route.ts b/app/api/presets/route.ts
index 67f92c0..cfab8c1 100644
--- a/app/api/presets/route.ts
+++ b/app/api/presets/route.ts
@@ -18,6 +18,31 @@ export async function GET(request: NextRequest) {
);
}
+ const password = searchParams.get("password");
+
+ // Fetch calendar to check password
+ const [calendar] = await db
+ .select()
+ .from(calendars)
+ .where(eq(calendars.id, calendarId));
+
+ if (!calendar) {
+ return NextResponse.json(
+ { error: "Calendar not found" },
+ { status: 404 }
+ );
+ }
+
+ // 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 }
+ );
+ }
+ }
+
const presets = await db
.select()
.from(shiftPresets)
diff --git a/app/api/shifts/[id]/route.ts b/app/api/shifts/[id]/route.ts
index 09ec4cb..8c62e59 100644
--- a/app/api/shifts/[id]/route.ts
+++ b/app/api/shifts/[id]/route.ts
@@ -12,6 +12,9 @@ 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({
id: shifts.id,
@@ -40,6 +43,29 @@ 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) {
+ return NextResponse.json(
+ { error: "Calendar not found" },
+ { status: 404 }
+ );
+ }
+
+ // 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);
diff --git a/app/api/shifts/route.ts b/app/api/shifts/route.ts
index 276d03c..9e946d2 100644
--- a/app/api/shifts/route.ts
+++ b/app/api/shifts/route.ts
@@ -2,6 +2,7 @@ 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";
// GET shifts for a calendar (with optional date filter)
@@ -18,6 +19,31 @@ export async function GET(request: Request) {
);
}
+ const password = searchParams.get("password");
+
+ // Fetch calendar to check password
+ const [calendar] = await db
+ .select()
+ .from(calendars)
+ .where(eq(calendars.id, calendarId));
+
+ if (!calendar) {
+ return NextResponse.json(
+ { error: "Calendar not found" },
+ { status: 404 }
+ );
+ }
+
+ // 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 }
+ );
+ }
+ }
+
let query = db
.select({
id: shifts.id,
@@ -93,6 +119,7 @@ export async function POST(request: Request) {
presetId,
isAllDay,
isSecondary,
+ password,
} = body;
if (!calendarId || !date || !title) {
@@ -102,6 +129,29 @@ export async function POST(request: Request) {
);
}
+ // Fetch calendar to check password
+ const [calendar] = await db
+ .select()
+ .from(calendars)
+ .where(eq(calendars.id, calendarId));
+
+ if (!calendar) {
+ return NextResponse.json(
+ { error: "Calendar not found" },
+ { status: 404 }
+ );
+ }
+
+ // Verify password if calendar is protected
+ if (calendar.passwordHash) {
+ if (!password || !verifyPassword(password, calendar.passwordHash)) {
+ return NextResponse.json(
+ { error: "Invalid password" },
+ { status: 401 }
+ );
+ }
+ }
+
const [shift] = await db
.insert(shifts)
.values({
@@ -118,12 +168,6 @@ export async function POST(request: Request) {
})
.returning();
- // Fetch calendar info
- const [calendar] = await db
- .select()
- .from(calendars)
- .where(eq(calendars.id, calendarId));
-
// Emit event for SSE
eventEmitter.emit("calendar-change", {
type: "shift",
diff --git a/app/api/shifts/stats/route.ts b/app/api/shifts/stats/route.ts
index 762fea8..d094b85 100644
--- a/app/api/shifts/stats/route.ts
+++ b/app/api/shifts/stats/route.ts
@@ -1,7 +1,13 @@
import { NextResponse } from "next/server";
import { db } from "@/lib/db";
-import { shifts, externalSyncs, shiftPresets } from "@/lib/db/schema";
+import {
+ shifts,
+ externalSyncs,
+ shiftPresets,
+ calendars,
+} from "@/lib/db/schema";
import { eq, and, gte, lte, sql, or, isNull } from "drizzle-orm";
+import { verifyPassword } from "@/lib/password-utils";
import {
startOfWeek,
endOfWeek,
@@ -26,6 +32,31 @@ export async function GET(request: Request) {
);
}
+ const password = searchParams.get("password");
+
+ // Fetch calendar to check password
+ const [calendar] = await db
+ .select()
+ .from(calendars)
+ .where(eq(calendars.id, calendarId));
+
+ if (!calendar) {
+ return NextResponse.json(
+ { error: "Calendar not found" },
+ { status: 404 }
+ );
+ }
+
+ // 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 }
+ );
+ }
+ }
+
const referenceDate = date ? new Date(date) : new Date();
let startDate: Date;
diff --git a/app/api/sync-logs/route.ts b/app/api/sync-logs/route.ts
index d8ffc09..8fe873a 100644
--- a/app/api/sync-logs/route.ts
+++ b/app/api/sync-logs/route.ts
@@ -1,12 +1,14 @@
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
-import { syncLogs } from "@/lib/db/schema";
+import { syncLogs, calendars } from "@/lib/db/schema";
import { eq, desc, and } from "drizzle-orm";
+import { verifyPassword } from "@/lib/password-utils";
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(
@@ -16,6 +18,29 @@ export async function GET(request: NextRequest) {
}
try {
+ // Fetch calendar to check password
+ const [calendar] = await db
+ .select()
+ .from(calendars)
+ .where(eq(calendars.id, calendarId));
+
+ if (!calendar) {
+ return NextResponse.json(
+ { error: "Calendar not found" },
+ { status: 404 }
+ );
+ }
+
+ // 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 }
+ );
+ }
+ }
+
const logs = await db
.select()
.from(syncLogs)
@@ -46,6 +71,42 @@ 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 (e) {
+ // If body parsing fails, continue with null password
+ }
+ }
+
+ // Fetch calendar to check password
+ const [calendar] = await db
+ .select()
+ .from(calendars)
+ .where(eq(calendars.id, calendarId));
+
+ if (!calendar) {
+ return NextResponse.json(
+ { error: "Calendar not found" },
+ { status: 404 }
+ );
+ }
+
+ // Verify password if calendar is protected
+ if (calendar.passwordHash) {
+ if (!password || !verifyPassword(password, calendar.passwordHash)) {
+ return NextResponse.json(
+ { error: "Invalid password" },
+ { status: 401 }
+ );
+ }
+ }
+
if (action === "markErrorsAsRead") {
// Mark all error logs as read for this calendar
await db
@@ -80,6 +141,42 @@ 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 (e) {
+ // If body parsing fails, continue with null password
+ }
+ }
+
+ // Fetch calendar to check password
+ const [calendar] = await db
+ .select()
+ .from(calendars)
+ .where(eq(calendars.id, calendarId));
+
+ if (!calendar) {
+ return NextResponse.json(
+ { error: "Calendar not found" },
+ { status: 404 }
+ );
+ }
+
+ // 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(syncLogs).where(eq(syncLogs.calendarId, calendarId));
return NextResponse.json({ success: true });
} catch (error) {
diff --git a/app/page.tsx b/app/page.tsx
index bf759bf..5015d57 100644
--- a/app/page.tsx
+++ b/app/page.tsx
@@ -110,9 +110,13 @@ function HomeContent() {
}
try {
- const response = await fetch(
- `/api/external-syncs?calendarId=${selectedCalendar}`
- );
+ 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) {
const data = await response.json();
setExternalSyncs(data);
@@ -130,9 +134,16 @@ function HomeContent() {
}
try {
- const response = await fetch(
- `/api/sync-logs?calendarId=${selectedCalendar}&limit=50`
- );
+ 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) {
const logs = await response.json();
// Only show errors that are not read
@@ -198,12 +209,25 @@ function HomeContent() {
const [isCalendarUnlocked, setIsCalendarUnlocked] = useState(true);
const [isVerifyingCalendarPassword, setIsVerifyingCalendarPassword] =
useState(false);
+ const [passwordCacheTrigger, setPasswordCacheTrigger] = useState(0);
const [versionInfo, setVersionInfo] = useState<{
version: string;
githubUrl: string;
commitHash?: string;
} | null>(null);
+ // Check if UI elements should be hidden (password required but not cached)
+ 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;
+ }, [selectedCalendar, selectedCalendarData, passwordCacheTrigger]);
+
// SSE Connection for real-time updates
useSSEConnection({
calendarId: selectedCalendar,
@@ -263,6 +287,10 @@ function HomeContent() {
verifyAndCachePassword(selectedCalendar, cachedPassword)
.then((result) => {
setIsCalendarUnlocked(result.valid);
+ if (result.valid) {
+ // Password is valid, refetch all data
+ handlePasswordSuccess(cachedPassword);
+ }
})
.catch(() => {
// On error, keep calendar locked
@@ -341,6 +369,18 @@ function HomeContent() {
};
const handlePasswordSuccess = async (password: string) => {
+ // Refetch all data now that password is available
+ await Promise.all([
+ refetchShifts(),
+ refetchPresets(),
+ refetchNotes(),
+ fetchExternalSyncs(),
+ fetchSyncErrorStatus(),
+ ]);
+
+ setStatsRefreshTrigger((prev) => prev + 1);
+ setPasswordCacheTrigger((prev) => prev + 1);
+
if (!pendingAction) return;
try {
@@ -872,6 +912,8 @@ function HomeContent() {
password
);
setIsCalendarUnlocked(true);
+ // Trigger data refetch after successful password entry
+ handlePasswordSuccess(password);
} else {
toast.error(t("password.errorIncorrect"));
}
@@ -955,42 +997,50 @@ function HomeContent() {
togglingDates={togglingDates}
externalSyncs={externalSyncs}
onDayClick={handleDayClick}
- onDayRightClick={handleDayRightClick}
- onNoteIconClick={handleNoteIconClick}
- onLongPress={handleLongPressDay}
+ onDayRightClick={
+ shouldHideUIElements ? undefined : handleDayRightClick
+ }
+ onNoteIconClick={
+ shouldHideUIElements ? undefined : handleNoteIconClick
+ }
+ onLongPress={
+ shouldHideUIElements ? undefined : handleLongPressDay
+ }
onShowAllShifts={handleShowAllShifts}
onShowSyncedShifts={handleShowSyncedShifts}
/>
{/* Note Hint */}
- <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>
+ {!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>
</div>
</div>
- </div>
- </motion.div>
+ </motion.div>
+ )}
{/* Shifts List */}
<div className="space-y-3 sm:space-y-4 px-2 sm:px-0">
@@ -1003,7 +1053,9 @@ function HomeContent() {
<ShiftsList
shifts={shifts}
currentDate={currentDate}
- onDeleteShift={handleDeleteShift}
+ onDeleteShift={
+ shouldHideUIElements ? undefined : handleDeleteShift
+ }
/>
</div>
</>
@@ -1011,7 +1063,7 @@ function HomeContent() {
</div>
{/* Floating Action Button for Manual Shift Creation - Desktop Only */}
- {selectedCalendar && (
+ {selectedCalendar && !shouldHideUIElements && (
<motion.div
className="hidden sm:block fixed bottom-6 right-6 z-50"
initial={{ scale: 0, opacity: 0 }}
diff --git a/components/calendar-grid.tsx b/components/calendar-grid.tsx
index 31248b9..e18fba4 100644
--- a/components/calendar-grid.tsx
+++ b/components/calendar-grid.tsx
@@ -16,9 +16,9 @@ interface CalendarGridProps {
togglingDates: Set<string>;
externalSyncs: ExternalSync[];
onDayClick: (date: Date) => void;
- onDayRightClick: (e: React.MouseEvent, date: Date) => void;
- onNoteIconClick: (e: React.MouseEvent, date: Date) => void;
- onLongPress: (date: Date) => void;
+ onDayRightClick?: (e: React.MouseEvent, date: Date) => void;
+ onNoteIconClick?: (e: React.MouseEvent, date: Date) => void;
+ onLongPress?: (date: Date) => void;
onShowAllShifts?: (date: Date, shifts: ShiftWithCalendar[]) => void;
onShowSyncedShifts?: (date: Date, shifts: ShiftWithCalendar[]) => void;
}
@@ -96,10 +96,12 @@ export function CalendarGrid({
const isToggling = togglingDates.has(dayKey);
const handleTouchStart = (e: React.TouchEvent) => {
- pressTimerRef.current[dayKey] = setTimeout(
- () => onLongPress(day),
- 500
- );
+ if (onLongPress) {
+ pressTimerRef.current[dayKey] = setTimeout(
+ () => onLongPress(day),
+ 500
+ );
+ }
};
const handleTouchEnd = () => {
if (pressTimerRef.current[dayKey]) {
@@ -114,7 +116,9 @@ export function CalendarGrid({
onClick={() => onDayClick(day)}
onContextMenu={(e) => {
e.preventDefault();
- onDayRightClick(e, day);
+ if (onDayRightClick) {
+ onDayRightClick(e, day);
+ }
}}
onTouchStart={handleTouchStart}
onTouchEnd={handleTouchEnd}
@@ -151,7 +155,7 @@ export function CalendarGrid({
}`}
>
<span>{day.getDate()}</span>
- {dayNote && (
+ {dayNote && onNoteIconClick && (
<motion.div
className="group/note relative"
onClick={(e) => onNoteIconClick(e, day)}
diff --git a/components/calendar-selector.tsx b/components/calendar-selector.tsx
index 4b2e00a..aeed262 100644
--- a/components/calendar-selector.tsx
+++ b/components/calendar-selector.tsx
@@ -41,10 +41,10 @@ export function CalendarSelector({
const t = useTranslations();
const selectedCalendar = calendars.find((c) => c.id === selectedId);
- // Hide external sync buttons if calendar is locked AND no valid password is cached
- const isCalendarLocked = selectedCalendar?.isLocked === true;
+ // 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 = isCalendarLocked && !hasPassword;
+ const shouldHideSyncButtons = requiresPassword && !hasPassword;
// Desktop: Compact icon-based layout
if (variant === "desktop") {
diff --git a/components/external-sync-manage-dialog.tsx b/components/external-sync-manage-dialog.tsx
index 60a49f2..d3dd53b 100644
--- a/components/external-sync-manage-dialog.tsx
+++ b/components/external-sync-manage-dialog.tsx
@@ -33,6 +33,7 @@ import {
} from "lucide-react";
import { toast } from "sonner";
import { PRESET_COLORS } from "@/lib/constants";
+import { getCachedPassword } from "@/lib/password-cache";
import {
isValidCalendarUrl,
detectCalendarSyncType,
@@ -95,17 +96,24 @@ export function ExternalSyncManageDialog({
setIsLoading(true);
}
try {
- const response = await fetch(
- `/api/external-syncs?calendarId=${calendarId}`
- );
+ 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) {
const data = await response.json();
setSyncs(data);
// Fetch last sync logs to check for errors
- const logsResponse = await fetch(
- `/api/sync-logs?calendarId=${calendarId}&limit=50`
- );
+ const logsParams = new URLSearchParams({ calendarId, limit: "50" });
+ if (password) {
+ logsParams.append("password", password);
+ }
+
+ const logsResponse = await fetch(`/api/sync-logs?${logsParams}`);
if (logsResponse.ok) {
const logs = await logsResponse.json();
const errors: Record<string, string> = {};
@@ -230,6 +238,8 @@ export function ExternalSyncManageDialog({
icsContent = await icsFile.text();
}
+ const password = getCachedPassword(calendarId);
+
const response = await fetch("/api/external-syncs", {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -243,6 +253,7 @@ export function ExternalSyncManageDialog({
icsContent,
isHidden: formIsHidden,
hideFromStats: formHideFromStats,
+ password,
}),
});
@@ -280,6 +291,8 @@ export function ExternalSyncManageDialog({
setIsLoading(true);
try {
+ const password = getCachedPassword(calendarId);
+
const response = await fetch(`/api/external-syncs/${editingSync.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
@@ -289,6 +302,7 @@ export function ExternalSyncManageDialog({
color: formColor,
displayMode: formDisplayMode,
autoSyncInterval: formAutoSyncInterval,
+ password,
}),
});
@@ -317,8 +331,12 @@ export function ExternalSyncManageDialog({
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 }),
});
const data = await response.json();
@@ -354,8 +372,12 @@ export function ExternalSyncManageDialog({
setIsDeleting(syncId);
try {
+ const password = getCachedPassword(calendarId);
+
const response = await fetch(`/api/external-syncs/${syncId}`, {
method: "DELETE",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ password }),
});
if (response.ok) {
@@ -426,11 +448,14 @@ export function ExternalSyncManageDialog({
}
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,
}),
});
@@ -484,6 +509,8 @@ export function ExternalSyncManageDialog({
if (!editingSync) return false;
try {
+ const password = getCachedPassword(calendarId);
+
const response = await fetch(`/api/external-syncs/${editingSync.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
@@ -495,6 +522,7 @@ export function ExternalSyncManageDialog({
color: formColor,
displayMode: formDisplayMode,
autoSyncInterval: formAutoSyncInterval,
+ password,
}),
});
diff --git a/components/preset-list.tsx b/components/preset-list.tsx
index c6558a6..efbd485 100644
--- a/components/preset-list.tsx
+++ b/components/preset-list.tsx
@@ -12,8 +12,9 @@ interface PresetListProps {
presets: ShiftPreset[];
selectedPresetId?: string;
onSelectPreset: (presetId: string | undefined) => void;
- onCreateNew: () => void;
- onManageClick: () => void;
+ onCreateNew?: () => void;
+ onManageClick?: () => void;
+ onUnlock?: () => void;
loading?: boolean;
}
@@ -25,16 +26,19 @@ export function PresetList({
onSelectPreset,
onCreateNew,
onManageClick,
+ onUnlock,
loading = false,
}: PresetListProps) {
const t = useTranslations();
const [showSecondary, setShowSecondary] = React.useState(false);
- // Hide preset buttons if calendar is locked AND no valid password is cached
+ // Hide preset buttons if calendar requires password AND no valid password is cached
const selectedCalendar = calendars.find((c) => c.id === calendarId);
- const isCalendarLocked = selectedCalendar?.isLocked === true;
+ const requiresPassword = !!selectedCalendar?.passwordHash;
const hasPassword = calendarId ? !!getCachedPassword(calendarId) : false;
- const shouldHidePresetButtons = isCalendarLocked && !hasPassword;
+ const isLocked = selectedCalendar?.isLocked === true;
+ const shouldHidePresetButtons = requiresPassword && !hasPassword;
+ const shouldShowUnlockHint = shouldHidePresetButtons && !isLocked;
const primaryPresets = presets.filter((p) => !p.isSecondary);
const secondaryPresets = presets.filter((p) => p.isSecondary);
@@ -53,7 +57,56 @@ export function PresetList({
);
}
- // Hide everything if calendar is locked and no password is cached
+ // 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;
}
@@ -70,7 +123,12 @@ export function PresetList({
<p className="text-[10px] sm:text-xs text-muted-foreground max-w-md mx-auto">
{t("preset.createFirstDescription")}
</p>
- <Button onClick={onCreateNew} size="sm" className="gap-2">
+ <Button
+ onClick={onCreateNew}
+ size="sm"
+ className="gap-2"
+ disabled={!onCreateNew}
+ >
<Plus className="h-4 w-4" />
<span className="text-xs sm:text-sm">
{t("preset.createYourFirst")}
@@ -100,6 +158,7 @@ export function PresetList({
variant="outline"
size="sm"
onClick={onCreateNew}
+ disabled={!onCreateNew}
className="gap-1 text-xs sm:text-sm px-2 sm:px-3 h-8 sm:h-9"
>
<Plus className="h-3 sm:h-4 w-3 sm:w-4" />
@@ -111,6 +170,7 @@ export function PresetList({
variant="ghost"
size="sm"
onClick={onManageClick}
+ disabled={!onManageClick}
className="h-8 sm:h-9 w-8 sm:w-9 p-0"
>
<Settings className="h-3 sm:h-4 w-3 sm:w-4" />
diff --git a/components/preset-selector.tsx b/components/preset-selector.tsx
index de6cedb..23f17f0 100644
--- a/components/preset-selector.tsx
+++ b/components/preset-selector.tsx
@@ -176,6 +176,7 @@ export function PresetSelector({
onSelectPreset={onSelectPreset}
onCreateNew={handleCreateNew}
onManageClick={() => setShowManageDialog(true)}
+ onUnlock={() => onPasswordRequired(async () => {})}
loading={loading}
/>
diff --git a/components/shift-card.tsx b/components/shift-card.tsx
index ea92dd4..2e881f6 100644
--- a/components/shift-card.tsx
+++ b/components/shift-card.tsx
@@ -9,7 +9,7 @@ import { motion } from "motion/react";
interface ShiftCardProps {
shift: ShiftWithCalendar;
- onDelete: (id: string) => void;
+ onDelete?: (id: string) => void;
}
export function ShiftCard({ shift, onDelete }: ShiftCardProps) {
@@ -49,7 +49,7 @@ export function ShiftCard({ shift, onDelete }: ShiftCardProps) {
</p>
)}
</div>
- {!shift.externalSyncId && (
+ {!shift.externalSyncId && onDelete && (
<Button
variant="ghost"
size="icon"
diff --git a/components/shift-stats.tsx b/components/shift-stats.tsx
index e3d4bf2..d61202f 100644
--- a/components/shift-stats.tsx
+++ b/components/shift-stats.tsx
@@ -4,6 +4,7 @@ import { useState, useEffect } from "react";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { BarChart3, ChevronDown, ChevronUp } from "lucide-react";
+import { getCachedPassword } from "@/lib/password-cache";
interface ShiftStats {
period: string;
@@ -44,9 +45,20 @@ export function ShiftStats({
}
try {
- const response = await fetch(
- `/api/shifts/stats?calendarId=${calendarId}&period=${period}&date=${currentDate.toISOString()}`
- );
+ 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
+ }
const data = await response.json();
setStats(data);
} catch (error) {
@@ -60,9 +72,10 @@ export function ShiftStats({
if (!calendarId) return null;
- const totalShifts = stats
- ? Object.values(stats.stats).reduce((sum, count) => sum + count, 0)
- : 0;
+ const totalShifts =
+ stats && stats.stats
+ ? Object.values(stats.stats).reduce((sum, count) => sum + count, 0)
+ : 0;
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">
diff --git a/components/shifts-list.tsx b/components/shifts-list.tsx
index f4ca399..d5c5d23 100644
--- a/components/shifts-list.tsx
+++ b/components/shifts-list.tsx
@@ -10,7 +10,7 @@ import { ChevronUp, ChevronDown, Calendar as CalendarIcon } from "lucide-react";
interface ShiftsListProps {
shifts: ShiftWithCalendar[];
currentDate: Date;
- onDeleteShift: (id: string) => void;
+ onDeleteShift?: (id: string) => void;
}
export function ShiftsList({
diff --git a/components/sync-notification-dialog.tsx b/components/sync-notification-dialog.tsx
index 3e8350f..275b0cc 100644
--- a/components/sync-notification-dialog.tsx
+++ b/components/sync-notification-dialog.tsx
@@ -2,6 +2,7 @@
import { useCallback, useEffect, useState } from "react";
import { useLocale, useTranslations } from "next-intl";
+import { getCachedPassword } from "@/lib/password-cache";
import {
Dialog,
DialogContent,
@@ -61,9 +62,13 @@ export function SyncNotificationDialog({
setLoading(true);
}
try {
- const response = await fetch(
- `/api/sync-logs?calendarId=${calendarId}&limit=20`
- );
+ 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) {
const data = await response.json();
setLogs(data);
@@ -133,8 +138,12 @@ export function SyncNotificationDialog({
setIsDeleting(true);
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 }),
});
if (response.ok) {
@@ -156,9 +165,15 @@ export function SyncNotificationDialog({
setIsMarkingRead(true);
try {
+ const password = getCachedPassword(calendarId);
+
const response = await fetch(
`/api/sync-logs?calendarId=${calendarId}&action=markErrorsAsRead`,
- { method: "PATCH" }
+ {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ password }),
+ }
);
if (response.ok) {
diff --git a/hooks/useNotes.ts b/hooks/useNotes.ts
index b281a6c..7eff6d5 100644
--- a/hooks/useNotes.ts
+++ b/hooks/useNotes.ts
@@ -13,17 +13,30 @@ export function useNotes(calendarId: string | undefined) {
if (!calendarId) return;
try {
- const response = await fetch(`/api/notes?calendarId=${calendarId}`);
+ 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) {
- throw new Error(
- `Failed to fetch notes: ${response.status} ${response.statusText}`
- );
+ // Only clear notes for unauthorized responses (locked calendar)
+ if (response.status === 401 || response.status === 403) {
+ setNotes([]);
+ } else {
+ // For other errors (server errors, etc.), log but don't clear existing notes
+ console.error(
+ `Failed to fetch notes: ${response.status} ${response.statusText}`
+ );
+ }
+ return;
}
const data = await response.json();
setNotes(data);
} catch (error) {
+ // Network errors or other exceptions - don't clear existing notes
console.error("Failed to fetch notes:", error);
- setNotes([]);
}
};
@@ -80,7 +93,7 @@ export function useNotes(calendarId: string | undefined) {
onPasswordRequired?: () => void
) => {
try {
- const password = calendarId ? getCachedPassword(calendarId) : null;
+ const password = getCachedPassword(calendarId);
const response = await fetch(`/api/notes/${noteId}`, {
method: "PUT",
@@ -119,7 +132,7 @@ export function useNotes(calendarId: string | undefined) {
onPasswordRequired?: () => void
) => {
try {
- const password = calendarId ? getCachedPassword(calendarId) : null;
+ const password = getCachedPassword(calendarId);
const response = await fetch(`/api/notes/${noteId}`, {
method: "DELETE",
diff --git a/hooks/usePresets.ts b/hooks/usePresets.ts
index fb42003..2a2f543 100644
--- a/hooks/usePresets.ts
+++ b/hooks/usePresets.ts
@@ -1,5 +1,6 @@
import { useState, useEffect } 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[]>([]);
@@ -14,11 +15,18 @@ export function usePresets(calendarId: string | undefined) {
setLoading(true);
try {
- const response = await fetch(`/api/presets?calendarId=${calendarId}`);
+ 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) {
- throw new Error(
- `Failed to fetch presets: ${response.status} ${response.statusText}`
- );
+ // Calendar is locked and no valid password - return empty array
+ setPresets([]);
+ setLoading(false);
+ return;
}
const data = await response.json();
setPresets(data);
diff --git a/hooks/useShifts.ts b/hooks/useShifts.ts
index 82807f9..902dec3 100644
--- a/hooks/useShifts.ts
+++ b/hooks/useShifts.ts
@@ -13,11 +13,23 @@ export function useShifts(calendarId: string | undefined) {
if (!calendarId) return;
try {
- const response = await fetch(`/api/shifts?calendarId=${calendarId}`);
+ 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);
} catch (error) {
console.error("Failed to fetch shifts:", error);
+ setShifts([]);
}
};
@@ -42,12 +54,15 @@ 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,
}),
});
@@ -82,7 +97,7 @@ export function useShifts(calendarId: string | undefined) {
onPasswordRequired?: () => void
) => {
try {
- const password = calendarId ? getCachedPassword(calendarId) : null;
+ const password = getCachedPassword(calendarId);
const response = await fetch(`/api/shifts/${id}`, {
method: "PATCH",
@@ -118,7 +133,7 @@ export function useShifts(calendarId: string | undefined) {
const deleteShift = async (id: string, onPasswordRequired?: () => void) => {
try {
- const password = calendarId ? getCachedPassword(calendarId) : null;
+ const password = getCachedPassword(calendarId);
const response = await fetch(`/api/shifts/${id}`, {
method: "DELETE",
diff --git a/lib/password-cache.ts b/lib/password-cache.ts
index 6571596..c85217a 100644
--- a/lib/password-cache.ts
+++ b/lib/password-cache.ts
@@ -6,8 +6,10 @@
/**
* Get cached password from localStorage
*/
-export function getCachedPassword(calendarId: string): string | null {
- if (typeof window === "undefined") return null;
+export function getCachedPassword(
+ calendarId: string | null | undefined
+): string | null {
+ if (typeof window === "undefined" || !calendarId) return null;
return localStorage.getItem(`calendar_password_${calendarId}`);
}
diff --git a/messages/de.json b/messages/de.json
index 4083431..9ad7124 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -60,7 +60,10 @@
"errorMatch": "Passwörter stimmen nicht überein",
"errorIncorrect": "Falsches Passwort",
"errorRequired": "Passwort erforderlich",
- "unlock": "Entsperren"
+ "unlock": "Entsperren",
+ "unlockRequired": "Kalender ist passwortgeschützt",
+ "unlockRequiredDescription": "Dieser Kalender ist passwortgeschützt. Bitte entsperren Sie den Kalender, um Vorlagen zu verwalten und Schichten zu erstellen.",
+ "unlockCalendar": "Kalender entsperren"
},
"note": {
"create": "Neue Notiz",
diff --git a/messages/en.json b/messages/en.json
index 56ee275..8869953 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -60,7 +60,10 @@
"errorMatch": "Passwords do not match",
"errorIncorrect": "Incorrect password",
"errorRequired": "Password required",
- "unlock": "Unlock"
+ "unlock": "Unlock",
+ "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": "New Note",