Your favorite shift management application!
feat: add password protection for calendars and shifts
panteLx1ea9909be4a0
diff --git a/app/api/calendars/[id]/route.ts b/app/api/calendars/[id]/route.tsindex 154cfbf..68662d6 100644--- a/app/api/calendars/[id]/route.ts+++ b/app/api/calendars/[id]/route.ts@@ -2,6 +2,7 @@ import { 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";// GET single calendarexport async function GET(@@ -46,11 +47,40 @@ export async function PATCH(try {const { id } = await params;const body = await request.json();- const { name, color } = body;+ const { name, color, password, currentPassword } = body;++ // Fetch current calendar to check password+ const [existingCalendar] = await db+ .select()+ .from(calendars)+ .where(eq(calendars.id, id));++ if (!existingCalendar) {+ return NextResponse.json(+ { error: "Calendar not found" },+ { status: 404 }+ );+ }++ // Verify password if calendar is protected+ if (existingCalendar.passwordHash) {+ if (+ !currentPassword ||+ !verifyPassword(currentPassword, existingCalendar.passwordHash)+ ) {+ return NextResponse.json(+ { error: "Invalid password" },+ { status: 401 }+ );+ }+ }const updateData: any = {};if (name) updateData.name = name;if (color) updateData.color = color;+ if (password !== undefined) {+ updateData.passwordHash = password ? hashPassword(password) : null;+ }const [calendar] = await db.update(calendars)@@ -75,6 +105,32 @@ export async function DELETE() {try {const { id } = await params;+ const { searchParams } = new URL(request.url);+ const password = searchParams.get("password");++ // Fetch calendar to check password+ const [calendar] = await db+ .select()+ .from(calendars)+ .where(eq(calendars.id, id));++ 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(calendars).where(eq(calendars.id, id));return NextResponse.json({ success: true });diff --git a/app/api/calendars/[id]/verify-password/route.ts b/app/api/calendars/[id]/verify-password/route.tsnew file mode 100644index 0000000..0b7dc1c--- /dev/null+++ b/app/api/calendars/[id]/verify-password/route.ts@@ -0,0 +1,51 @@+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.tsindex 338b3b0..1fd298e 100644--- a/app/api/calendars/route.ts+++ b/app/api/calendars/route.ts@@ -2,6 +2,7 @@ import { 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";// GET all calendarsexport async function GET() {@@ -11,6 +12,7 @@ export async function GET() {id: calendars.id,name: calendars.name,color: calendars.color,+ passwordHash: calendars.passwordHash,createdAt: calendars.createdAt,updatedAt: calendars.updatedAt,_count:@@ -35,7 +37,7 @@ export async function GET() {export async function POST(request: Request) {try {const body = await request.json();- const { name, color } = body;+ const { name, color, password } = body;if (!name) {return NextResponse.json(@@ -49,6 +51,7 @@ export async function POST(request: Request) {.values({name,color: color || "#3b82f6",+ passwordHash: password ? hashPassword(password) : null,}).returning();diff --git a/app/api/presets/[id]/route.ts b/app/api/presets/[id]/route.tsindex eefbd2f..4b67d9a 100644--- a/app/api/presets/[id]/route.ts+++ b/app/api/presets/[id]/route.ts@@ -1,7 +1,8 @@import { NextRequest, NextResponse } from "next/server";import { db } from "@/lib/db";-import { shiftPresets, shifts } from "@/lib/db/schema";+import { shiftPresets, shifts, calendars } from "@/lib/db/schema";import { eq } from "drizzle-orm";+import { verifyPassword } from "@/lib/password-utils";// PATCH update a presetexport async function PATCH(@@ -11,8 +12,49 @@ export async function PATCH(try {const { id } = await params;const body = await request.json();- const { title, startTime, endTime, color, notes, isSecondary, isAllDay } =- body;+ const {+ title,+ startTime,+ endTime,+ color,+ notes,+ isSecondary,+ isAllDay,+ password,+ } = body;++ // Fetch preset to get calendar ID+ const [existingPreset] = await db+ .select()+ .from(shiftPresets)+ .where(eq(shiftPresets.id, id));++ if (!existingPreset) {+ 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, existingPreset.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 [updatedPreset] = await db.update(shiftPresets)@@ -60,6 +102,41 @@ export async function DELETE() {try {const { id } = await params;+ const { searchParams } = new URL(request.url);+ const password = searchParams.get("password");++ // Fetch preset to get calendar ID+ 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+ if (calendar.passwordHash) {+ if (!password || !verifyPassword(password, calendar.passwordHash)) {+ return NextResponse.json(+ { error: "Invalid password" },+ { status: 401 }+ );+ }+ }// Delete all shifts that were created from this presetawait db.delete(shifts).where(eq(shifts.presetId, id));diff --git a/app/api/presets/route.ts b/app/api/presets/route.tsindex 74f037a..9b80703 100644--- a/app/api/presets/route.ts+++ b/app/api/presets/route.ts@@ -1,7 +1,8 @@import { NextRequest, NextResponse } from "next/server";import { db } from "@/lib/db";-import { shiftPresets } from "@/lib/db/schema";+import { shiftPresets, calendars } from "@/lib/db/schema";import { eq } from "drizzle-orm";+import { verifyPassword } from "@/lib/password-utils";// GET all presets for a calendarexport async function GET(request: NextRequest) {@@ -43,6 +44,7 @@ export async function POST(request: NextRequest) {notes,isSecondary,isAllDay,+ password,} = body;if (!calendarId || !title) {@@ -52,6 +54,29 @@ export async function POST(request: NextRequest) {);}+ // 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 [preset] = await db.insert(shiftPresets).values({diff --git a/app/api/shifts/[id]/route.ts b/app/api/shifts/[id]/route.tsindex 263f645..e0d5620 100644--- a/app/api/shifts/[id]/route.ts+++ b/app/api/shifts/[id]/route.ts@@ -2,6 +2,7 @@ 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";// GET single shiftexport async function GET(@@ -65,8 +66,42 @@ export async function PATCH(notes,isAllDay,isSecondary,+ password,} = body;+ // Fetch shift to get calendar ID+ const [existingShift] = await db+ .select()+ .from(shifts)+ .where(eq(shifts.id, id));++ if (!existingShift) {+ 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, existingShift.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 updateData: any = {};if (date) updateData.date = new Date(date);if (startTime !== undefined) updateData.startTime = startTime;@@ -83,12 +118,6 @@ export async function PATCH(.where(eq(shifts.id, id)).returning();- // Fetch calendar info- const [calendar] = await db- .select()- .from(calendars)- .where(eq(calendars.id, shift.calendarId));-return NextResponse.json({ ...shift, calendar });} catch (error) {console.error("Failed to update shift:", error);@@ -106,6 +135,39 @@ export async function DELETE() {try {const { id } = await params;+ const { searchParams } = new URL(request.url);+ const password = searchParams.get("password");++ // Fetch shift to get calendar ID+ const [shift] = await db.select().from(shifts).where(eq(shifts.id, id));++ if (!shift) {+ 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) {+ 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(shifts).where(eq(shifts.id, id));return NextResponse.json({ success: true });diff --git a/app/page.tsx b/app/page.tsxindex fa188d3..922df74 100644--- a/app/page.tsx+++ b/app/page.tsx@@ -8,6 +8,8 @@ import { CalendarDialog } from "@/components/calendar-dialog";import { ShiftDialog, ShiftFormData } from "@/components/shift-dialog";import { ShiftCard } from "@/components/shift-card";import { PresetSelector } from "@/components/preset-selector";+import { PasswordDialog } from "@/components/password-dialog";+import { ManagePasswordDialog } from "@/components/manage-password-dialog";import { Button } from "@/components/ui/button";import {Plus,@@ -46,6 +48,15 @@ function HomeContent() {const [selectedDate, setSelectedDate] = useState<Date | undefined>();const [showCalendarDialog, setShowCalendarDialog] = useState(false);const [showShiftDialog, setShowShiftDialog] = useState(false);+ const [showPasswordDialog, setShowPasswordDialog] = useState(false);+ const [showManagePasswordDialog, setShowManagePasswordDialog] =+ useState(false);+ const [pendingAction, setPendingAction] = useState<{+ type: "delete" | "edit";+ shiftId?: string;+ formData?: ShiftFormData;+ presetAction?: () => Promise<void>;+ } | null>(null);const [loading, setLoading] = useState(true);// Fetch calendars on mount@@ -125,12 +136,16 @@ function HomeContent() {}};- const createCalendar = async (name: string, color: string) => {+ const createCalendar = async (+ name: string,+ color: string,+ password?: string+ ) => {try {const response = await fetch("/api/calendars", {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name, color }),+ body: JSON.stringify({ name, color, password }),});const newCalendar = await response.json();setCalendars([...calendars, newCalendar]);@@ -161,11 +176,24 @@ function HomeContent() {const updateShift = async (id: string, formData: ShiftFormData) => {try {+ // Get stored password from localStorage+ const password = selectedCalendar+ ? localStorage.getItem(`calendar_password_${selectedCalendar}`)+ : null;+const response = await fetch(`/api/shifts/${id}`, {method: "PATCH",headers: { "Content-Type": "application/json" },- body: JSON.stringify(formData),+ body: JSON.stringify({ ...formData, password }),});++ if (response.status === 401) {+ // Password required or invalid+ setPendingAction({ type: "edit", shiftId: id, formData });+ setShowPasswordDialog(true);+ return;+ }+const updatedShift = await response.json();setShifts(shifts.map((s) => (s.id === id ? updatedShift : s)));} catch (error) {@@ -175,13 +203,78 @@ function HomeContent() {const deleteShift = async (id: string) => {try {- await fetch(`/api/shifts/${id}`, { method: "DELETE" });+ // Get stored password from localStorage+ const password = selectedCalendar+ ? localStorage.getItem(`calendar_password_${selectedCalendar}`)+ : null;++ const url = password+ ? `/api/shifts/${id}?password=${encodeURIComponent(password)}`+ : `/api/shifts/${id}`;++ const response = await fetch(url, { method: "DELETE" });++ if (response.status === 401) {+ // Password required or invalid+ setPendingAction({ type: "delete", shiftId: id });+ setShowPasswordDialog(true);+ return;+ }+setShifts(shifts.filter((s) => s.id !== id));} catch (error) {console.error("Failed to delete shift:", error);}};+ const handlePasswordSuccess = async (password: string) => {+ if (!pendingAction) return;++ try {+ if (pendingAction.type === "delete" && pendingAction.shiftId) {+ const response = await fetch(+ `/api/shifts/${pendingAction.shiftId}?password=${encodeURIComponent(+ password+ )}`,+ { method: "DELETE" }+ );+ if (response.ok) {+ setShifts(shifts.filter((s) => s.id !== pendingAction.shiftId));+ }+ } else if (+ pendingAction.type === "edit" &&+ pendingAction.shiftId &&+ pendingAction.formData+ ) {+ const response = await fetch(`/api/shifts/${pendingAction.shiftId}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ ...pendingAction.formData, password }),+ });+ if (response.ok) {+ const updatedShift = await response.json();+ setShifts(+ shifts.map((s) =>+ s.id === pendingAction.shiftId ? updatedShift : s+ )+ );+ }+ } else if (pendingAction.presetAction) {+ // Execute the pending preset action+ await pendingAction.presetAction();+ }+ } catch (error) {+ console.error("Failed to execute pending action:", error);+ } finally {+ setPendingAction(null);+ }+ };++ const handlePresetPasswordRequired = async (action: () => Promise<void>) => {+ setPendingAction({ type: "edit", presetAction: action });+ setShowPasswordDialog(true);+ };+const handleShiftSubmit = (formData: ShiftFormData) => {createShift(formData);};@@ -193,33 +286,68 @@ function HomeContent() {const preset = presets.find((p) => p.id === selectedPresetId);if (!preset) return;- // Check if a shift with the same preset already exists on this date- const existingShift = shifts.find(- (shift) =>- shift.date &&- isSameDay(new Date(shift.date), date) &&- shift.title === preset.title &&- shift.startTime === preset.startTime &&- shift.endTime === preset.endTime- );+ // Check password before adding/deleting shift+ const checkAndToggle = async () => {+ const password = selectedCalendar+ ? localStorage.getItem(`calendar_password_${selectedCalendar}`)+ : null;++ // Verify password if calendar is protected+ if (selectedCalendar) {+ const response = await fetch(+ `/api/calendars/${selectedCalendar}/verify-password`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ password }),+ }+ );++ const data = await response.json();++ if (data.protected && !data.valid) {+ // Password required or invalid+ localStorage.removeItem(`calendar_password_${selectedCalendar}`);+ setPendingAction({+ type: "edit",+ presetAction: () => handleAddShift(date),+ });+ setShowPasswordDialog(true);+ return;+ }+ }- if (existingShift) {- // Toggle: remove the existing shift- await deleteShift(existingShift.id);- } else {- // Toggle: add the shift- const shiftData: ShiftFormData = {- date: formatDateToLocal(date),- startTime: preset.startTime,- endTime: preset.endTime,- title: preset.title,- color: preset.color,- notes: preset.notes || "",- presetId: preset.id,- isAllDay: preset.isAllDay || false,- };- createShift(shiftData);- }+ // Password valid or not required, proceed with toggle+ // Check if a shift with the same preset already exists on this date+ const existingShift = shifts.find(+ (shift) =>+ shift.date &&+ isSameDay(new Date(shift.date), date) &&+ shift.title === preset.title &&+ shift.startTime === preset.startTime &&+ shift.endTime === preset.endTime+ );++ if (existingShift) {+ // Toggle: remove the existing shift+ await deleteShift(existingShift.id);+ } else {+ // Toggle: add the shift+ const shiftData: ShiftFormData = {+ date: formatDateToLocal(date),+ startTime: preset.startTime,+ endTime: preset.endTime,+ title: preset.title,+ color: preset.color,+ notes: preset.notes || "",+ presetId: preset.id,+ isAllDay: preset.isAllDay || false,+ };+ createShift(shiftData);+ }+ };++ await checkAndToggle();};// Calendar grid calculations@@ -280,6 +408,7 @@ function HomeContent() {selectedId={selectedCalendar}onSelect={setSelectedCalendar}onCreateNew={() => setShowCalendarDialog(true)}+ onManagePassword={() => setShowManagePasswordDialog(true)}/><PresetSelectorpresets={presets}@@ -288,6 +417,7 @@ function HomeContent() {onPresetsChange={fetchPresets}onShiftsChange={fetchShifts}calendarId={selectedCalendar || ""}+ onPasswordRequired={handlePresetPasswordRequired}/></div></div>@@ -522,6 +652,33 @@ function HomeContent() {onPresetsChange={fetchPresets}calendarId={selectedCalendar}/>+ {selectedCalendar && (+ <PasswordDialog+ open={showPasswordDialog}+ onOpenChange={setShowPasswordDialog}+ calendarId={selectedCalendar}+ calendarName={+ calendars.find((c) => c.id === selectedCalendar)?.name || ""+ }+ onSuccess={handlePasswordSuccess}+ />+ )}+ {selectedCalendar && (+ <ManagePasswordDialog+ open={showManagePasswordDialog}+ onOpenChange={setShowManagePasswordDialog}+ calendarId={selectedCalendar}+ calendarName={+ calendars.find((c) => c.id === selectedCalendar)?.name || ""+ }+ hasPassword={+ !!calendars.find((c) => c.id === selectedCalendar)?.passwordHash+ }+ onSuccess={() => {+ fetchCalendars();+ }}+ />+ )}</div>);}diff --git a/components/calendar-dialog.tsx b/components/calendar-dialog.tsxindex eb6f5b3..8d3f1da 100644--- a/components/calendar-dialog.tsx+++ b/components/calendar-dialog.tsx@@ -10,11 +10,12 @@ 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";interface CalendarDialogProps {open: boolean;onOpenChange: (open: boolean) => void;- onSubmit: (name: string, color: string) => void;+ onSubmit: (name: string, color: string, password?: string) => void;}const PRESET_COLORS = [@@ -35,13 +36,21 @@ export function CalendarDialog({}: CalendarDialogProps) {const [name, setName] = useState("");const [selectedColor, setSelectedColor] = useState(PRESET_COLORS[0]);+ const [password, setPassword] = useState("");+ const [usePassword, setUsePassword] = useState(false);const handleSubmit = (e: React.FormEvent) => {e.preventDefault();if (name.trim()) {- onSubmit(name.trim(), selectedColor);+ onSubmit(+ name.trim(),+ selectedColor,+ usePassword && password ? password : undefined+ );setName("");setSelectedColor(PRESET_COLORS[0]);+ setPassword("");+ setUsePassword(false);onOpenChange(false);}};@@ -81,6 +90,36 @@ export function CalendarDialog({))}</div></div>+ <div className="space-y-3 pt-2 border-t">+ <div className="flex items-center space-x-2">+ <Checkbox+ id="usePassword"+ checked={usePassword}+ onCheckedChange={(checked) => setUsePassword(!!checked)}+ />+ <Label+ htmlFor="usePassword"+ className="text-sm font-normal cursor-pointer"+ >+ Protect with password (optional)+ </Label>+ </div>+ {usePassword && (+ <div className="space-y-2">+ <Label htmlFor="password">Password</Label>+ <Input+ id="password"+ type="password"+ placeholder="Enter password"+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ />+ <p className="text-xs text-muted-foreground">+ Password will be required to edit or delete shifts+ </p>+ </div>+ )}+ </div><div className="flex justify-end gap-3"><Buttontype="button"diff --git a/components/calendar-selector.tsx b/components/calendar-selector.tsxindex 9ce337f..f56f29f 100644--- a/components/calendar-selector.tsx+++ b/components/calendar-selector.tsx@@ -9,13 +9,14 @@ import {SelectValue,} from "@/components/ui/select";import { Button } from "@/components/ui/button";-import { Plus } from "lucide-react";+import { Plus, Settings } from "lucide-react";interface CalendarSelectorProps {calendars: CalendarWithCount[];selectedId?: string;onSelect: (id: string) => void;onCreateNew: () => void;+ onManagePassword?: () => void;}export function CalendarSelector({@@ -23,6 +24,7 @@ export function CalendarSelector({selectedId,onSelect,onCreateNew,+ onManagePassword,}: CalendarSelectorProps) {return (<div className="flex gap-2 items-center">@@ -44,6 +46,17 @@ export function CalendarSelector({))}</SelectContent></Select>+ {onManagePassword && selectedId && (+ <Button+ onClick={onManagePassword}+ size="icon"+ variant="outline"+ className="h-9 w-9 sm:h-10 sm:w-10"+ title="Manage password"+ >+ <Settings className="h-4 w-4" />+ </Button>+ )}<ButtononClick={onCreateNew}size="icon"diff --git a/components/manage-password-dialog.tsx b/components/manage-password-dialog.tsxnew file mode 100644index 0000000..b26d919--- /dev/null+++ b/components/manage-password-dialog.tsx@@ -0,0 +1,202 @@+"use client";++import { useState, useEffect } from "react";+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 { Checkbox } from "@/components/ui/checkbox";++interface ManagePasswordDialogProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ calendarId: string;+ calendarName: string;+ hasPassword: boolean;+ onSuccess: () => void;+}++export function ManagePasswordDialog({+ open,+ onOpenChange,+ calendarId,+ calendarName,+ hasPassword,+ onSuccess,+}: ManagePasswordDialogProps) {+ const [currentPassword, setCurrentPassword] = useState("");+ const [newPassword, setNewPassword] = useState("");+ const [confirmPassword, setConfirmPassword] = useState("");+ const [removePassword, setRemovePassword] = useState(false);+ const [error, setError] = useState("");+ const [loading, setLoading] = useState(false);++ useEffect(() => {+ if (open) {+ setCurrentPassword("");+ setNewPassword("");+ setConfirmPassword("");+ setRemovePassword(false);+ setError("");+ }+ }, [open]);++ const handleSubmit = async (e: React.FormEvent) => {+ e.preventDefault();+ setError("");++ // Validate inputs+ if (hasPassword && !currentPassword) {+ setError("Current password is required");+ return;+ }++ if (!removePassword) {+ if (!newPassword) {+ setError("New password is required");+ return;+ }+ if (newPassword !== confirmPassword) {+ setError("Passwords do not match");+ return;+ }+ }++ setLoading(true);++ try {+ const response = await fetch(`/api/calendars/${calendarId}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ currentPassword: hasPassword ? currentPassword : undefined,+ password: removePassword ? null : newPassword,+ }),+ });++ if (response.status === 401) {+ setError("Current password is incorrect");+ setLoading(false);+ return;+ }++ if (!response.ok) {+ setError("Failed to update password");+ setLoading(false);+ return;+ }++ // Clear cached password from localStorage+ localStorage.removeItem(`calendar_password_${calendarId}`);++ // If new password was set, cache it+ if (!removePassword && newPassword) {+ localStorage.setItem(`calendar_password_${calendarId}`, newPassword);+ }++ onSuccess();+ onOpenChange(false);+ } catch (error) {+ console.error("Failed to update password:", error);+ setError("Failed to update password");+ } finally {+ setLoading(false);+ }+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-[425px]">+ <DialogHeader>+ <DialogTitle>Manage Password</DialogTitle>+ <DialogDescription>+ {hasPassword+ ? `Update or remove password for "${calendarName}"`+ : `Set a password for "${calendarName}"`}+ </DialogDescription>+ </DialogHeader>+ <form onSubmit={handleSubmit} className="space-y-4">+ {hasPassword && (+ <div className="space-y-2">+ <Label htmlFor="currentPassword">Current Password</Label>+ <Input+ id="currentPassword"+ type="password"+ value={currentPassword}+ onChange={(e) => setCurrentPassword(e.target.value)}+ placeholder="Enter current password"+ autoFocus+ />+ </div>+ )}++ {hasPassword && (+ <div className="flex items-center space-x-2">+ <Checkbox+ id="removePassword"+ checked={removePassword}+ onCheckedChange={(checked) => setRemovePassword(!!checked)}+ />+ <Label+ htmlFor="removePassword"+ className="text-sm font-normal cursor-pointer"+ >+ Remove password protection+ </Label>+ </div>+ )}++ {!removePassword && (+ <>+ <div className="space-y-2">+ <Label htmlFor="newPassword">+ {hasPassword ? "New Password" : "Password"}+ </Label>+ <Input+ id="newPassword"+ type="password"+ value={newPassword}+ onChange={(e) => setNewPassword(e.target.value)}+ placeholder="Enter new password"+ autoFocus={!hasPassword}+ />+ </div>++ <div className="space-y-2">+ <Label htmlFor="confirmPassword">Confirm Password</Label>+ <Input+ id="confirmPassword"+ type="password"+ value={confirmPassword}+ onChange={(e) => setConfirmPassword(e.target.value)}+ placeholder="Confirm new password"+ />+ </div>+ </>+ )}++ {error && <p className="text-sm text-red-500">{error}</p>}++ <div className="flex justify-end gap-2">+ <Button+ type="button"+ variant="outline"+ onClick={() => onOpenChange(false)}+ >+ Cancel+ </Button>+ <Button type="submit" disabled={loading}>+ {loading ? "Saving..." : "Save Changes"}+ </Button>+ </div>+ </form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/components/password-dialog.tsx b/components/password-dialog.tsxnew file mode 100644index 0000000..d52e728--- /dev/null+++ b/components/password-dialog.tsx@@ -0,0 +1,113 @@+"use client";++import { useState, useEffect } from "react";+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";++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 [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 response = await fetch(+ `/api/calendars/${calendarId}/verify-password`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ password }),+ }+ );++ const data = await response.json();++ if (data.valid) {+ // Store password in localStorage+ localStorage.setItem(`calendar_password_${calendarId}`, password);+ onSuccess(password);+ onOpenChange(false);+ } else {+ setError("Invalid password");+ }+ } catch (error) {+ console.error("Failed to verify password:", error);+ setError("Failed to verify password");+ } finally {+ setLoading(false);+ }+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-[425px]">+ <DialogHeader>+ <DialogTitle>Password Required</DialogTitle>+ <DialogDescription>+ Please enter the password for calendar "{calendarName}" to+ edit or delete shifts.+ </DialogDescription>+ </DialogHeader>+ <form onSubmit={handleSubmit} className="space-y-4">+ <div className="space-y-2">+ <Label htmlFor="password">Password</Label>+ <Input+ id="password"+ type="password"+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ placeholder="Enter calendar password"+ autoFocus+ />+ {error && <p className="text-sm text-red-500">{error}</p>}+ </div>+ <div className="flex justify-end gap-2">+ <Button+ type="button"+ variant="outline"+ onClick={() => onOpenChange(false)}+ >+ Cancel+ </Button>+ <Button type="submit" disabled={loading || !password}>+ {loading ? "Verifying..." : "Submit"}+ </Button>+ </div>+ </form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/components/preset-selector.tsx b/components/preset-selector.tsxindex b4a575b..078edda 100644--- a/components/preset-selector.tsx+++ b/components/preset-selector.tsx@@ -23,6 +23,7 @@ interface PresetSelectorProps {onPresetsChange: () => void;onShiftsChange?: () => void;calendarId: string;+ onPasswordRequired: (action: () => Promise<void>) => void;}const PRESET_COLORS = [@@ -43,6 +44,7 @@ export function PresetSelector({onPresetsChange,onShiftsChange,calendarId,+ onPasswordRequired,}: PresetSelectorProps) {const [showManageDialog, setShowManageDialog] = useState(false);const [editingPreset, setEditingPreset] = useState<ShiftPreset | null>(null);@@ -70,28 +72,85 @@ export function PresetSelector({});};- const handleCreateNew = () => {- resetForm();- setIsCreatingNew(true);- setEditingPreset(null);+ const handleCreateNew = async () => {+ // Check password before opening dialog+ const password = localStorage.getItem(`calendar_password_${calendarId}`);++ const checkAndCreate = async () => {+ const pwd = localStorage.getItem(`calendar_password_${calendarId}`);+ // Verify password by trying to fetch presets with it+ const response = await fetch(+ `/api/calendars/${calendarId}/verify-password`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ password: pwd }),+ }+ );++ const data = await response.json();++ if (data.protected && !data.valid) {+ // Password required or invalid+ localStorage.removeItem(`calendar_password_${calendarId}`);+ await onPasswordRequired(checkAndCreate);+ return;+ }++ // Password valid or not required, open dialog+ resetForm();+ setIsCreatingNew(true);+ setEditingPreset(null);+ };++ await checkAndCreate();};- const handleEditPreset = (preset: ShiftPreset) => {- setIsCreatingNew(false);- setEditingPreset(preset);- setFormData({- title: preset.title,- startTime: preset.startTime,- endTime: preset.endTime,- color: preset.color,- notes: preset.notes || "",- isSecondary: preset.isSecondary || false,- isAllDay: preset.isAllDay || false,- });+ const handleEditPreset = async (preset: ShiftPreset) => {+ // Check password before opening dialog+ const checkAndEdit = async () => {+ const password = localStorage.getItem(`calendar_password_${calendarId}`);+ // Verify password+ const response = await fetch(+ `/api/calendars/${calendarId}/verify-password`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ password }),+ }+ );++ const data = await response.json();++ if (data.protected && !data.valid) {+ // Password required or invalid+ localStorage.removeItem(`calendar_password_${calendarId}`);+ await onPasswordRequired(checkAndEdit);+ return;+ }++ // Password valid or not required, open dialog+ setIsCreatingNew(false);+ setEditingPreset(preset);+ setFormData({+ title: preset.title,+ startTime: preset.startTime,+ endTime: preset.endTime,+ color: preset.color,+ notes: preset.notes || "",+ isSecondary: preset.isSecondary || false,+ isAllDay: preset.isAllDay || false,+ });+ };++ await checkAndEdit();};const handleSave = async () => {try {+ // Get stored password from localStorage (already verified)+ const password = localStorage.getItem(`calendar_password_${calendarId}`);+if (isCreatingNew) {// Create new presetawait fetch("/api/presets", {@@ -100,6 +159,7 @@ export function PresetSelector({body: JSON.stringify({calendarId,...formData,+ password,}),});} else if (editingPreset) {@@ -107,8 +167,9 @@ export function PresetSelector({await fetch(`/api/presets/${editingPreset.id}`, {method: "PATCH",headers: { "Content-Type": "application/json" },- body: JSON.stringify(formData),+ body: JSON.stringify({ ...formData, password }),});+// Refresh shifts as they may have been updatedif (onShiftsChange) onShiftsChange();}@@ -122,24 +183,55 @@ export function PresetSelector({};const handleDeletePreset = async (id: string) => {- if (- !confirm(- "Delete this preset? This will also delete all shifts created from this preset."+ // Check password first+ const checkAndDelete = async () => {+ const password = localStorage.getItem(`calendar_password_${calendarId}`);+ // Verify password+ const verifyResponse = await fetch(+ `/api/calendars/${calendarId}/verify-password`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ password }),+ }+ );++ const data = await verifyResponse.json();++ if (data.protected && !data.valid) {+ // Password required or invalid+ localStorage.removeItem(`calendar_password_${calendarId}`);+ await onPasswordRequired(() => handleDeletePreset(id));+ return;+ }++ // Password valid, confirm deletion+ if (+ !confirm(+ "Delete this preset? This will also delete all shifts created from this preset."+ ))- )- return;+ return;- try {- await fetch(`/api/presets/${id}`, { method: "DELETE" });- if (selectedPresetId === id) {- onSelectPreset(undefined);+ try {+ const url = password+ ? `/api/presets/${id}?password=${encodeURIComponent(password)}`+ : `/api/presets/${id}`;++ await fetch(url, { method: "DELETE" });++ if (selectedPresetId === id) {+ onSelectPreset(undefined);+ }+ onPresetsChange();+ // Refresh shifts as they may have been deleted+ if (onShiftsChange) onShiftsChange();+ } catch (error) {+ console.error("Failed to delete preset:", error);}- onPresetsChange();- // Refresh shifts as they may have been deleted- if (onShiftsChange) onShiftsChange();- } catch (error) {- console.error("Failed to delete preset:", error);- }+ };++ await checkAndDelete();};return (diff --git a/drizzle/0002_illegal_purple_man.sql b/drizzle/0002_illegal_purple_man.sqlnew file mode 100644index 0000000..011f0b9--- /dev/null+++ b/drizzle/0002_illegal_purple_man.sql@@ -0,0 +1 @@+ALTER TABLE `calendars` ADD `password_hash` text;\ No newline at end of filediff --git a/drizzle/meta/0002_snapshot.json b/drizzle/meta/0002_snapshot.jsonnew file mode 100644index 0000000..44162b8--- /dev/null+++ b/drizzle/meta/0002_snapshot.json@@ -0,0 +1,312 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "dff81306-32b6-4fc5-b401-c8be4259b65f",+ "prevId": "3c04e502-20c3-4cd1-8331-df0a2aabad5d",+ "tables": {+ "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'"+ },+ "password_hash": {+ "name": "password_hash",+ "type": "text",+ "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": {},+ "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+ },+ "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+ },+ "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"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ }+ },+ "views": {},+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "internal": {+ "indexes": {}+ }+}\ No newline at end of filediff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.jsonindex 85a7408..2ec17fb 100644--- a/drizzle/meta/_journal.json+++ b/drizzle/meta/_journal.json@@ -15,6 +15,13 @@"when": 1763767949322,"tag": "0001_marvelous_gunslinger","breakpoints": true+ },+ {+ "idx": 2,+ "version": "6",+ "when": 1763776413411,+ "tag": "0002_illegal_purple_man",+ "breakpoints": true}]-}+}\ No newline at end of filediff --git a/lib/db/schema.ts b/lib/db/schema.tsindex ef25fa0..ca68180 100644--- a/lib/db/schema.ts+++ b/lib/db/schema.ts@@ -7,6 +7,7 @@ export const calendars = sqliteTable("calendars", {.$defaultFn(() => crypto.randomUUID()),name: text("name").notNull(),color: text("color").notNull().default("#3b82f6"),+ passwordHash: text("password_hash"),createdAt: integer("created_at", { mode: "timestamp" }).notNull().default(sql`CURRENT_TIMESTAMP`),diff --git a/lib/password-utils.ts b/lib/password-utils.tsnew file mode 100644index 0000000..8953010--- /dev/null+++ b/lib/password-utils.ts@@ -0,0 +1,30 @@+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;+}++/**+ * Generates a random salt (optional, for future enhancements)+ */+export function generateSalt(): string {+ return crypto.randomBytes(16).toString("hex");+}diff --git a/lib/types.ts b/lib/types.tsindex cf0966b..223cd23 100644--- a/lib/types.ts+++ b/lib/types.ts@@ -5,6 +5,7 @@ export interface CalendarWithCount {id: string;name: string;color: string;+ passwordHash?: string | null;createdAt: Date | null;updatedAt: Date | null;_count?: number;