Your favorite shift management application!
feat(admin): add guest-access toggle and admin-created users (#202)
panteL0d241a303176
diff --git a/.env.example b/.env.exampleindex da8d043..9f9c53f 100644--- a/.env.example+++ b/.env.example@@ -63,7 +63,8 @@ DEFAULT_LOCALE=en # Options: cs, de, en, es, fr, it# ==============================================================================ALLOW_USER_REGISTRATION=true # Enable/disable new user signups-ALLOW_GUEST_ACCESS=false # Allow viewing calendars without login+# Guest access (viewing calendars without login) is controlled live from the+# admin panel under System Settings -- there is no env var for it anymore.# Origins accepted for CSRF-protected requests, comma-separated.# Defaults to BETTER_AUTH_URL alone, which is correct for most deployments.@@ -235,6 +236,8 @@ ALLOW_GUEST_ACCESS=false # Allow viewing calendars without login# RATE_LIMIT_ADMIN_USER_MUTATIONS_WINDOW=60 # 1 minute# RATE_LIMIT_ADMIN_PASSWORD_RESET=5 # Password reset for users# RATE_LIMIT_ADMIN_PASSWORD_RESET_WINDOW=300 # 5 minutes+# RATE_LIMIT_ADMIN_USER_CREATE=5 # Creating new users+# RATE_LIMIT_ADMIN_USER_CREATE_WINDOW=300 # 5 minutes# RATE_LIMIT_ADMIN_BULK_OPERATIONS=3 # Bulk delete/transfer calendars# RATE_LIMIT_ADMIN_BULK_OPERATIONS_WINDOW=300 # 5 minutes# RATE_LIMIT_ADMIN_CALENDAR_MUTATIONS=10 # Calendar delete/transfer/editdiff --git a/app/admin/page.tsx b/app/admin/page.tsxindex 533a584..5cc68a5 100644--- a/app/admin/page.tsx+++ b/app/admin/page.tsx@@ -234,6 +234,15 @@ export default function AdminDashboardPage() {]}/></Field>+ <div className="h-px bg-line-subtle" />+ <ToggleRow+ id="allow-guest-access"+ title={t("admin.systemSettings.guestAccess")}+ description={t("admin.systemSettings.guestAccessHint")}+ checked={settings?.allowGuestAccess ?? false}+ onCheckedChange={(checked) => updateSettings({ allowGuestAccess: checked })}+ disabled={!settings || isUpdating}+ /></div></section>diff --git a/app/admin/users/page.tsx b/app/admin/users/page.tsxindex 96f4a09..3eead66 100644--- a/app/admin/users/page.tsx+++ b/app/admin/users/page.tsx@@ -2,6 +2,7 @@import { useMemo, useState } from "react";import { useTranslations } from "next-intl";+import { UserPlus } from "lucide-react";import {DropdownMenu,DropdownMenuContent,@@ -11,12 +12,14 @@ import {DropdownMenuSeparator,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";+import { Button } from "@/components/ui/button";import { FullscreenLoader } from "@/components/fullscreen-loader";import { SegmentedControl } from "@/components/segmented-control";import { ChoiceChips } from "@/components/form-kit";import { AdminPageHeader, AdminSearch } from "@/components/admin/admin-kit";import { FilterMenuButton, type SortState } from "@/components/admin/admin-table-controls";import { UserTable } from "@/components/admin/user-table";+import { UserCreateSheet } from "@/components/admin/user-create-sheet";import { UserEditSheet } from "@/components/admin/user-edit-sheet";import { UserDetailsSheet } from "@/components/admin/user-details-sheet";import { UserBanDialog } from "@/components/admin/user-ban-dialog";@@ -24,6 +27,7 @@ import { UserUnbanDialog } from "@/components/admin/user-unban-dialog";import { UserDeleteDialog } from "@/components/admin/user-delete-dialog";import { UserPasswordResetDialog } from "@/components/admin/user-password-reset-dialog";import { useAdminUserActions, useAdminUsers, type AdminUser } from "@/hooks/useAdminUsers";+import { useCanCreateUser } from "@/hooks/useAdminAccess";import { useDebouncedSearch, useResettableState } from "@/hooks/useAdminList";import {ADMIN_PAGE_SIZE,@@ -62,6 +66,7 @@ export default function AdminUsersPage() {const { users, total, counts, page, isLoading, isPlaceholderData } = useAdminUsers(params);const { banUser, unbanUser, deleteUser, resetPassword } = useAdminUserActions();+ const canCreateUser = useCanCreateUser();// The segments cover the common cases; anything else lives in the filter menu.const preset: Preset | "custom" =@@ -86,6 +91,7 @@ export default function AdminUsersPage() {const [showUnbanDialog, setShowUnbanDialog] = useState(false);const [showDeleteDialog, setShowDeleteDialog] = useState(false);const [showPasswordDialog, setShowPasswordDialog] = useState(false);+ const [showCreateSheet, setShowCreateSheet] = useState(false);const openFor = (setter: (open: boolean) => void) => (user: AdminUser) => {setSelectedUser(user);@@ -159,6 +165,30 @@ export default function AdminUsersPage() {subtitle={counts ? t("adminUsers.subtitle", { count: counts.total, banned: counts.banned }) : undefined}+ actions={+ canCreateUser && (+ <Button+ variant="outline"+ onClick={() => setShowCreateSheet(true)}+ className="h-[38px] gap-2 rounded-[9px] font-semibold"+ >+ <UserPlus className="size-4" />+ {t("admin.createUser")}+ </Button>+ )+ }+ mobileActions={+ canCreateUser && (+ <button+ type="button"+ onClick={() => setShowCreateSheet(true)}+ aria-label={t("admin.createUser")}+ className="flex size-[34px] items-center justify-center rounded-[9px] border border-line text-fg-secondary"+ >+ <UserPlus className="size-[17px]" />+ </button>+ )+ }/><div className="flex flex-col gap-[11px] lg:flex-row lg:items-center lg:gap-[9px]">@@ -215,6 +245,8 @@ export default function AdminUsersPage() {/></div>+ <UserCreateSheet open={showCreateSheet} onOpenChange={setShowCreateSheet} />+{selectedUser && (<><UserEditSheetdiff --git a/app/api/admin/system-settings/route.ts b/app/api/admin/system-settings/route.tsindex 2dd4596..9782d5c 100644--- a/app/api/admin/system-settings/route.ts+++ b/app/api/admin/system-settings/route.ts@@ -57,7 +57,11 @@ export async function PATCH(request: NextRequest) {return NextResponse.json({ error: "Invalid request body" }, { status: 400 });}- const patch: { updateCheckEnabled?: boolean; updateBannerVisibility?: UpdateBannerVisibility } = {};+ const patch: {+ updateCheckEnabled?: boolean;+ updateBannerVisibility?: UpdateBannerVisibility;+ allowGuestAccess?: boolean;+ } = {};if ("updateCheckEnabled" in body) {if (typeof body.updateCheckEnabled !== "boolean") {@@ -76,6 +80,13 @@ export async function PATCH(request: NextRequest) {patch.updateBannerVisibility = body.updateBannerVisibility;}+ if ("allowGuestAccess" in body) {+ if (typeof body.allowGuestAccess !== "boolean") {+ return NextResponse.json({ error: "allowGuestAccess must be a boolean" }, { status: 400 });+ }+ patch.allowGuestAccess = body.allowGuestAccess;+ }+const { before, after } = await updateSystemSettings(patch);await logAdminAction({diff --git a/app/api/admin/users/route.ts b/app/api/admin/users/route.tsindex 0f3a762..fa0c8dc 100644--- a/app/api/admin/users/route.ts+++ b/app/api/admin/users/route.ts@@ -1,8 +1,8 @@import { NextRequest, NextResponse } from "next/server";import { db } from "@/lib/db";import { user, calendars, session, calendarShares } from "@/lib/db/schema";-import { and, asc, count, desc, getTableColumns, getTableName, or, sql, type SQL } from "drizzle-orm";-import { isAdmin } from "@/lib/auth/admin";+import { and, asc, count, desc, eq, getTableColumns, getTableName, or, sql, type SQL } from "drizzle-orm";+import { isAdmin, canCreateUser, ADMIN_ROLES } from "@/lib/auth/admin";import {getValidatedAdminUser,isErrorResponse,@@ -18,6 +18,11 @@ import {pickParam,type UserListCounts,} from "@/lib/admin-list";+import { auth } from "@/lib/auth";+import { rateLimit } from "@/lib/rate-limiter";+import { logAuditEvent, type AdminUserCreateMetadata } from "@/lib/audit-log";+import { MIN_PASSWORD_LENGTH } from "@/lib/password-utils";+import { APIError } from "better-auth/api";/*** Admin User Management API@@ -166,3 +171,136 @@ export async function GET(request: NextRequest) {);}}++const CREATABLE_ROLES = ["user", ...ADMIN_ROLES] as const;++/**+ * POST /api/admin/users+ * Creates a user directly from the admin panel -- works even when public+ * self-registration (ALLOW_USER_REGISTRATION) is disabled, see lib/auth.ts.+ *+ * Body: { name: string, email: string, password: string, role?: "user" | "admin" | "superadmin" }+ * A `role` other than "user" is only honored for superadmin callers.+ *+ * Permission: Admin or Superadmin+ */+export async function POST(request: NextRequest) {+ try {+ const currentUser = await getValidatedAdminUser(request);+ if (isErrorResponse(currentUser)) return currentUser;++ if (!canCreateUser(currentUser)) {+ return NextResponse.json(+ { error: "Admin access required" },+ { status: 403 }+ );+ }++ const rateLimitResponse = rateLimit(+ request,+ currentUser.id,+ "admin-user-create"+ );+ if (rateLimitResponse) return rateLimitResponse;++ const body = await request.json().catch(() => null);+ if (!body || typeof body !== "object") {+ return NextResponse.json({ error: "Invalid request body" }, { status: 400 });+ }++ const { name, email, password, role } = body as Record<string, unknown>;++ if (typeof name !== "string" || !name.trim()) {+ return NextResponse.json({ error: "Name is required" }, { status: 400 });+ }+ if (typeof email !== "string" || !email.trim()) {+ return NextResponse.json({ error: "Email is required" }, { status: 400 });+ }+ if (typeof password !== "string" || password.length < MIN_PASSWORD_LENGTH) {+ return NextResponse.json(+ { error: `Password must be at least ${MIN_PASSWORD_LENGTH} characters long` },+ { status: 400 }+ );+ }++ let resolvedRole: (typeof CREATABLE_ROLES)[number] = "user";+ if (role !== undefined) {+ if (!CREATABLE_ROLES.includes(role as (typeof CREATABLE_ROLES)[number])) {+ return NextResponse.json(+ { error: `role must be one of: ${CREATABLE_ROLES.join(", ")}` },+ { status: 400 }+ );+ }+ if (!canCreateUser(currentUser, role as (typeof CREATABLE_ROLES)[number])) {+ return NextResponse.json(+ { error: "Insufficient permissions to assign this role" },+ { status: 403 }+ );+ }+ resolvedRole = role as (typeof CREATABLE_ROLES)[number];+ }++ const [existing] = await db+ .select({ id: user.id })+ .from(user)+ .where(eq(user.email, email))+ .limit(1);+ if (existing) {+ return NextResponse.json(+ { error: "A user with this email already exists" },+ { status: 409 }+ );+ }++ let createdUserId: string;+ try {+ const result = await auth.api.createUser({+ headers: request.headers,+ body: {+ email,+ name,+ password,+ // "user" is the admin plugin's defaultRole already; its role type+ // only accepts the configured custom roles ("admin"/"superadmin").+ ...(resolvedRole !== "user" ? { role: resolvedRole } : {}),+ data: { mustChangePassword: true },+ },+ });+ createdUserId = result.user.id;+ } catch (error) {+ if (error instanceof APIError) {+ return NextResponse.json(+ { error: error.message || "Failed to create user" },+ { status: 400 }+ );+ }+ throw error;+ }++ await logAuditEvent<AdminUserCreateMetadata>({+ action: "admin.user.create",+ userId: currentUser.id,+ resourceType: "user",+ resourceId: createdUserId,+ metadata: {+ createdUser: email,+ role: resolvedRole,+ createdBy: currentUser.email,+ },+ request,+ severity: "warning",+ isUserVisible: false,+ });++ return NextResponse.json({+ success: true,+ user: { id: createdUserId, email, role: resolvedRole },+ });+ } catch (error) {+ console.error("Failed to create user:", error);+ return NextResponse.json(+ { error: "Failed to create user" },+ { status: 500 }+ );+ }+}diff --git a/app/api/auth/change-password/route.ts b/app/api/auth/change-password/route.tsindex 33d64c3..e125855 100644--- a/app/api/auth/change-password/route.ts+++ b/app/api/auth/change-password/route.ts@@ -4,6 +4,7 @@ import { db } from "@/lib/db";import {account as accountTable,session as sessionTable,+ user as userTable,} from "@/lib/db/schema";import { eq, and, ne } from "drizzle-orm";import { hashPassword, verifyPassword } from "better-auth/crypto";@@ -98,6 +99,12 @@ export async function POST(req: NextRequest) {));+ // Clears the forced-change flag set on admin-created accounts+ await db+ .update(userTable)+ .set({ mustChangePassword: false })+ .where(eq(userTable.id, session.user.id));+// Revoke all other sessions (keep current session active)const revokedSessions = await db.delete(sessionTable)diff --git a/app/layout.tsx b/app/layout.tsxindex e5018d8..ed17f4a 100644--- a/app/layout.tsx+++ b/app/layout.tsx@@ -69,10 +69,13 @@ export default async function RootLayout({}: Readonly<{children: React.ReactNode;}>) {- const locale = await getLocale();- const messages = await getMessages();- const publicConfig = getPublicConfig();- const nonce = (await headers()).get("x-nonce") || undefined;+ const [locale, messages, publicConfig, requestHeaders] = await Promise.all([+ getLocale(),+ getMessages(),+ getPublicConfig(),+ headers(),+ ]);+ const nonce = requestHeaders.get("x-nonce") || undefined;return (<html lang={locale} suppressHydrationWarning>diff --git a/app/profile/page.tsx b/app/profile/page.tsxindex 273822e..1c9554d 100644--- a/app/profile/page.tsx+++ b/app/profile/page.tsx@@ -169,7 +169,18 @@ function ProfileContent() {<ProfileDetailsSection form={profileForm} canEdit={hasPasswordAuth} accounts={accounts} />);case "password":- return <PasswordSection />;+ return (+ <>+ {user.mustChangePassword && (+ <div className={cn(accountContentClass, "pt-[18px]")}>+ <StatusBanner tone="warning" icon={TriangleAlert} title={t("profile.mustChangePasswordTitle")}>+ {t("profile.mustChangePasswordDescription")}+ </StatusBanner>+ </div>+ )}+ <PasswordSection onChanged={refetch} />+ </>+ );case "accounts":return <ConnectedAccountsSection accounts={accounts} />;case "sessions":diff --git a/components/admin/password-fields.tsx b/components/admin/password-fields.tsxnew file mode 100644index 0000000..b9b3ac7--- /dev/null+++ b/components/admin/password-fields.tsx@@ -0,0 +1,168 @@+"use client";++import { useState } from "react";+import { useTranslations } from "next-intl";+import { Copy, Eye, EyeOff, RefreshCw } from "lucide-react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Field, inputClass } from "@/components/form-kit";+import { randomPassword, MIN_PASSWORD_LENGTH } from "@/lib/password-utils";+import { cn } from "@/lib/utils";++export function PasswordInput({+ id,+ value,+ onChange,+ visible,+ onToggle,+ placeholder,+}: {+ id: string;+ value: string;+ onChange: (value: string) => void;+ visible: boolean;+ onToggle: () => void;+ placeholder: string;+}) {+ const t = useTranslations();+ const Icon = visible ? EyeOff : Eye;+ return (+ <div className="relative">+ <Input+ id={id}+ type={visible ? "text" : "password"}+ value={value}+ onChange={(e) => onChange(e.target.value)}+ placeholder={placeholder}+ autoComplete="new-password"+ className={cn(inputClass, "pr-10", visible && value && "font-mono")}+ />+ <button+ type="button"+ onClick={onToggle}+ aria-label={visible ? t("adminUsers.hidePassword") : t("adminUsers.showPassword")}+ className="absolute right-2 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-fg-tertiary transition-colors hover:text-fg-strong"+ >+ <Icon className="size-4" />+ </button>+ </div>+ );+}++/** Password + confirm-password state shared by the create and reset-password forms. */+export function usePasswordFields() {+ const t = useTranslations();+ const [password, setPassword] = useState("");+ const [confirmPassword, setConfirmPassword] = useState("");+ const [showPassword, setShowPassword] = useState(false);+ const [showConfirmPassword, setShowConfirmPassword] = useState(false);++ const passwordsMatch = password === confirmPassword;+ const isValid = password.length >= MIN_PASSWORD_LENGTH && passwordsMatch;++ const generate = () => {+ const newPassword = randomPassword();+ setPassword(newPassword);+ setConfirmPassword(newPassword);+ setShowPassword(true);+ setShowConfirmPassword(true);+ };++ const copy = () => {+ navigator.clipboard.writeText(password);+ toast.success(t("common.copied", { item: t("common.labels.password") }));+ };++ const reset = () => {+ setPassword("");+ setConfirmPassword("");+ setShowPassword(false);+ setShowConfirmPassword(false);+ };++ return {+ password,+ setPassword,+ confirmPassword,+ setConfirmPassword,+ showPassword,+ setShowPassword,+ showConfirmPassword,+ setShowConfirmPassword,+ passwordsMatch,+ isValid,+ generate,+ copy,+ reset,+ };+}++/** Generate/reveal/confirm/copy UI for a password, shared by the create and reset-password forms. */+export function PasswordFieldsGroup({+ idPrefix,+ passwordLabel,+ passwordHint,+ fields,+}: {+ idPrefix: string;+ passwordLabel: string;+ passwordHint?: string;+ fields: ReturnType<typeof usePasswordFields>;+}) {+ const t = useTranslations();++ return (+ <>+ <Button+ type="button"+ variant="outline"+ onClick={fields.generate}+ className="h-10 w-full rounded-[9px] font-semibold"+ >+ <RefreshCw className="size-4 text-fg-secondary" />+ {t("admin.generatePassword")}+ </Button>++ <Field label={passwordLabel} htmlFor={`${idPrefix}-password`} hint={passwordHint}>+ <PasswordInput+ id={`${idPrefix}-password`}+ value={fields.password}+ onChange={fields.setPassword}+ visible={fields.showPassword}+ onToggle={() => fields.setShowPassword(!fields.showPassword)}+ placeholder={t("admin.passwordPlaceholder")}+ />+ {fields.password && fields.password.length < MIN_PASSWORD_LENGTH && (+ <p className="text-[12px] text-danger">{t("validation.passwordTooShort")}</p>+ )}+ </Field>++ <Field label={t("common.labels.confirmPassword")} htmlFor={`${idPrefix}-password-confirm`}>+ <PasswordInput+ id={`${idPrefix}-password-confirm`}+ value={fields.confirmPassword}+ onChange={fields.setConfirmPassword}+ visible={fields.showConfirmPassword}+ onToggle={() => fields.setShowConfirmPassword(!fields.showConfirmPassword)}+ placeholder={t("admin.confirmPasswordPlaceholder")}+ />+ {fields.confirmPassword && !fields.passwordsMatch && (+ <p className="text-[12px] text-danger">{t("validation.passwordsNoMatch")}</p>+ )}+ </Field>++ {fields.isValid && (+ <Button+ type="button"+ variant="secondary"+ onClick={fields.copy}+ className="h-10 w-full rounded-[9px] font-semibold"+ >+ <Copy className="size-4" />+ {t("admin.copyPassword")}+ </Button>+ )}+ </>+ );+}diff --git a/components/admin/role-select.tsx b/components/admin/role-select.tsxnew file mode 100644index 0000000..73fb041--- /dev/null+++ b/components/admin/role-select.tsx@@ -0,0 +1,29 @@+"use client";++import { useTranslations } from "next-intl";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";++/** User/admin/superadmin role picker shared by the create and edit user forms. */+export function RoleSelect({+ id,+ value,+ onValueChange,+}: {+ id: string;+ value: string;+ onValueChange: (value: string) => void;+}) {+ const t = useTranslations();+ return (+ <Select value={value} onValueChange={onValueChange}>+ <SelectTrigger id={id} className="h-10 w-full rounded-[9px] px-3 text-[14px] data-[size=default]:h-10">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="user">{t("common.roles.user")}</SelectItem>+ <SelectItem value="admin">{t("common.roles.admin")}</SelectItem>+ <SelectItem value="superadmin">{t("common.roles.superadmin")}</SelectItem>+ </SelectContent>+ </Select>+ );+}diff --git a/components/admin/user-create-sheet.tsx b/components/admin/user-create-sheet.tsxnew file mode 100644index 0000000..ea79531--- /dev/null+++ b/components/admin/user-create-sheet.tsx@@ -0,0 +1,103 @@+"use client";++import { useState } from "react";+import { useTranslations } from "next-intl";+import { Input } from "@/components/ui/input";+import { Field, inputClass } from "@/components/form-kit";+import { AdminFormPanel } from "@/components/admin/admin-form-panel";+import { RoleSelect } from "@/components/admin/role-select";+import { PasswordFieldsGroup, usePasswordFields } from "@/components/admin/password-fields";+import { useAdminUserActions } from "@/hooks/useAdminUsers";+import { useIsSuperAdmin } from "@/hooks/useAdminAccess";++interface UserCreateSheetProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+}++export function UserCreateSheet({ open, onOpenChange }: UserCreateSheetProps) {+ const t = useTranslations();+ const { createUser, isCreating } = useAdminUserActions();+ const isSuperAdmin = useIsSuperAdmin();+ const passwordFields = usePasswordFields();++ const [name, setName] = useState("");+ const [email, setEmail] = useState("");+ const [role, setRole] = useState("user");++ const isValid =+ name.trim().length > 0 && email.trim().length > 0 && passwordFields.isValid;+ const hasChanges = !!(name || email || passwordFields.password || passwordFields.confirmPassword);++ const reset = () => {+ setName("");+ setEmail("");+ setRole("user");+ passwordFields.reset();+ };++ const handleSave = async () => {+ if (!isValid) return;+ const success = await createUser({+ name,+ email,+ password: passwordFields.password,+ role: isSuperAdmin ? role : undefined,+ });+ if (success) {+ reset();+ onOpenChange(false);+ }+ };++ return (+ <AdminFormPanel+ open={open}+ onOpenChange={(next) => {+ if (!next) reset();+ onOpenChange(next);+ }}+ title={t("admin.createUser")}+ subtitle={t("admin.createUserSubtitle")}+ onSave={handleSave}+ isSaving={isCreating}+ saveDisabled={!isValid}+ saveLabel={t("common.create")}+ hasUnsavedChanges={hasChanges}+ >+ <Field label={t("common.labels.name")} htmlFor="admin-create-user-name">+ <Input+ id="admin-create-user-name"+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder={t("admin.namePlaceholder")}+ className={inputClass}+ />+ </Field>++ <Field label={t("common.labels.email")} htmlFor="admin-create-user-email">+ <Input+ id="admin-create-user-email"+ type="email"+ value={email}+ onChange={(e) => setEmail(e.target.value)}+ placeholder={t("admin.emailPlaceholder")}+ className={inputClass}+ />+ </Field>++ {isSuperAdmin && (+ <Field label={t("admin.role")} htmlFor="admin-create-user-role">+ <RoleSelect id="admin-create-user-role" value={role} onValueChange={setRole} />+ </Field>+ )}++ <PasswordFieldsGroup+ idPrefix="admin-create-user"+ passwordLabel={t("common.labels.password")}+ passwordHint={t("admin.mustChangePasswordHint")}+ fields={passwordFields}+ />+ </AdminFormPanel>+ );+}diff --git a/components/admin/user-edit-sheet.tsx b/components/admin/user-edit-sheet.tsxindex 64a6aa2..7a31df8 100644--- a/components/admin/user-edit-sheet.tsx+++ b/components/admin/user-edit-sheet.tsx@@ -3,9 +3,9 @@import { useState } from "react";import { useTranslations } from "next-intl";import { Input } from "@/components/ui/input";-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { Field, inputClass } from "@/components/form-kit";import { AdminFormPanel } from "@/components/admin/admin-form-panel";+import { RoleSelect } from "@/components/admin/role-select";import { useAdminUserActions, type AdminUser } from "@/hooks/useAdminUsers";import { useCanEditUser, useCanChangeUserRole } from "@/hooks/useAdminAccess";@@ -77,16 +77,7 @@ export function UserEditSheet({ open, onOpenChange, user }: UserEditSheetProps){canChangeRole && (<Field label={t("admin.role")} htmlFor="admin-user-role" hint={t("admin.roleChangeWarning")}>- <Select value={role} onValueChange={setRole}>- <SelectTrigger id="admin-user-role" className="h-10 w-full rounded-[9px] px-3 text-[14px] data-[size=default]:h-10">- <SelectValue />- </SelectTrigger>- <SelectContent>- <SelectItem value="user">{t("common.roles.user")}</SelectItem>- <SelectItem value="admin">{t("common.roles.admin")}</SelectItem>- <SelectItem value="superadmin">{t("common.roles.superadmin")}</SelectItem>- </SelectContent>- </Select>+ <RoleSelect id="admin-user-role" value={role} onValueChange={setRole} /></Field>)}</AdminFormPanel>diff --git a/components/admin/user-password-reset-dialog.tsx b/components/admin/user-password-reset-dialog.tsxindex e4c38d6..d199376 100644--- a/components/admin/user-password-reset-dialog.tsx+++ b/components/admin/user-password-reset-dialog.tsx@@ -2,14 +2,11 @@import { useState } from "react";import { useTranslations } from "next-intl";-import { Copy, Eye, EyeOff, RefreshCw, TriangleAlert } from "lucide-react";-import { toast } from "sonner";+import { TriangleAlert } from "lucide-react";import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";import { PanelDialog } from "@/components/panel-dialog";-import { Field, inputClass } from "@/components/form-kit";import { StatusBanner } from "@/components/status-banner";-import { cn } from "@/lib/utils";+import { PasswordFieldsGroup, usePasswordFields } from "@/components/admin/password-fields";import type { AdminUser } from "@/hooks/useAdminUsers";interface UserPasswordResetDialogProps {@@ -19,53 +16,6 @@ interface UserPasswordResetDialogProps {onConfirm: (newPassword: string) => Promise<void>;}-const CHARSET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*";--function randomPassword(length = 16) {- const values = crypto.getRandomValues(new Uint32Array(length));- return Array.from(values, (v) => CHARSET[v % CHARSET.length]).join("");-}--function PasswordInput({- id,- value,- onChange,- visible,- onToggle,- placeholder,-}: {- id: string;- value: string;- onChange: (value: string) => void;- visible: boolean;- onToggle: () => void;- placeholder: string;-}) {- const t = useTranslations();- const Icon = visible ? EyeOff : Eye;- return (- <div className="relative">- <Input- id={id}- type={visible ? "text" : "password"}- value={value}- onChange={(e) => onChange(e.target.value)}- placeholder={placeholder}- autoComplete="new-password"- className={cn(inputClass, "pr-10", visible && value && "font-mono")}- />- <button- type="button"- onClick={onToggle}- aria-label={visible ? t("adminUsers.hidePassword") : t("adminUsers.showPassword")}- className="absolute right-2 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-fg-tertiary transition-colors hover:text-fg-strong"- >- <Icon className="size-4" />- </button>- </div>- );-}-export function UserPasswordResetDialog({open,onOpenChange,@@ -73,42 +23,16 @@ export function UserPasswordResetDialog({onConfirm,}: UserPasswordResetDialogProps) {const t = useTranslations();- const [password, setPassword] = useState("");- const [confirmPassword, setConfirmPassword] = useState("");- const [showPassword, setShowPassword] = useState(false);- const [showConfirmPassword, setShowConfirmPassword] = useState(false);+ const passwordFields = usePasswordFields();const [isSubmitting, setIsSubmitting] = useState(false);- const passwordsMatch = password === confirmPassword;- const isValid = password.length >= 8 && passwordsMatch;-- const generateRandomPassword = () => {- const newPassword = randomPassword();- setPassword(newPassword);- setConfirmPassword(newPassword);- setShowPassword(true);- setShowConfirmPassword(true);- };-- const copyPassword = () => {- navigator.clipboard.writeText(password);- toast.success(t("common.copied", { item: t("common.labels.password") }));- };-- const reset = () => {- setPassword("");- setConfirmPassword("");- setShowPassword(false);- setShowConfirmPassword(false);- };-const handleConfirm = async () => {- if (!isValid) return;+ if (!passwordFields.isValid) return;setIsSubmitting(true);try {- await onConfirm(password);- reset();+ await onConfirm(passwordFields.password);+ passwordFields.reset();onOpenChange(false);} finally {setIsSubmitting(false);@@ -116,7 +40,7 @@ export function UserPasswordResetDialog({};const handleCancel = () => {- reset();+ passwordFields.reset();onOpenChange(false);};@@ -140,7 +64,7 @@ export function UserPasswordResetDialog({</Button><ButtononClick={handleConfirm}- disabled={!isValid || isSubmitting}+ disabled={!passwordFields.isValid || isSubmitting}className="h-10 flex-1 font-semibold">{isSubmitting ? t("common.saving") : t("admin.setPassword")}@@ -152,55 +76,11 @@ export function UserPasswordResetDialog({{t("admin.passwordResetSecurityNote")}</StatusBanner>- <Button- type="button"- variant="outline"- onClick={generateRandomPassword}- className="h-10 w-full rounded-[9px] font-semibold"- >- <RefreshCw className="size-4 text-fg-secondary" />- {t("admin.generatePassword")}- </Button>-- <Field label={t("common.labels.newPassword")} htmlFor="reset-password">- <PasswordInput- id="reset-password"- value={password}- onChange={setPassword}- visible={showPassword}- onToggle={() => setShowPassword(!showPassword)}- placeholder={t("admin.passwordPlaceholder")}- />- {password && password.length < 8 && (- <p className="text-[12px] text-danger">{t("validation.passwordTooShort")}</p>- )}- </Field>-- <Field label={t("common.labels.confirmPassword")} htmlFor="reset-password-confirm">- <PasswordInput- id="reset-password-confirm"- value={confirmPassword}- onChange={setConfirmPassword}- visible={showConfirmPassword}- onToggle={() => setShowConfirmPassword(!showConfirmPassword)}- placeholder={t("admin.confirmPasswordPlaceholder")}- />- {confirmPassword && !passwordsMatch && (- <p className="text-[12px] text-danger">{t("validation.passwordsNoMatch")}</p>- )}- </Field>-- {isValid && (- <Button- type="button"- variant="secondary"- onClick={copyPassword}- className="h-10 w-full rounded-[9px] font-semibold"- >- <Copy className="size-4" />- {t("admin.copyPassword")}- </Button>- )}+ <PasswordFieldsGroup+ idPrefix="reset"+ passwordLabel={t("common.labels.newPassword")}+ fields={passwordFields}+ /></PanelDialog>);}diff --git a/components/auth-provider.tsx b/components/auth-provider.tsxindex b069dfb..8b89b26 100644--- a/components/auth-provider.tsx+++ b/components/auth-provider.tsx@@ -15,7 +15,7 @@ import { usePublicConfig } from "@/hooks/usePublicConfig";* - Respects auth and guest access feature flags*/export function AuthProvider({ children }: { children: React.ReactNode }) {- const { isAuthenticated, isLoading } = useAuth();+ const { user, isAuthenticated, isLoading } = useAuth();const router = useRouter();const pathname = usePathname();const [mounted, setMounted] = useState(false);@@ -59,9 +59,18 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {if (!isPublicRoute && !isAuthenticated && !auth.allowGuestAccess) {const loginUrl = `/login?returnUrl=${encodeURIComponent(pathname + window.location.search)}`;router.replace(loginUrl);+ return;+ }++ // Admin-created accounts must change their password before doing anything+ // else. Client-side only, same trust level as the guest-access gating+ // above -- this app's threat model doesn't require an API-layer block too.+ if (isAuthenticated && user?.mustChangePassword && pathname !== "/profile") {+ router.replace("/profile?section=password");}}, [mounted,+ user,isAuthenticated,isLoading,auth.enabled,diff --git a/components/profile/password-section.tsx b/components/profile/password-section.tsxindex 24ead82..e47a2b9 100644--- a/components/profile/password-section.tsx+++ b/components/profile/password-section.tsx@@ -9,9 +9,9 @@ import { accountContentClass } from "@/components/profile/account-layout";import { usePasswordForm } from "@/hooks/useProfileForm";import { cn } from "@/lib/utils";-export function PasswordSection() {+export function PasswordSection({ onChanged }: { onChanged?: () => void }) {const t = useTranslations();- const form = usePasswordForm();+ const form = usePasswordForm(onChanged);return (<formdiff --git a/docs/AUTH_SETUP.md b/docs/AUTH_SETUP.mdindex 9552c1f..d2607d5 100644--- a/docs/AUTH_SETUP.md+++ b/docs/AUTH_SETUP.md@@ -49,11 +49,10 @@ BETTER_AUTH_URL=http://localhost:3000```bash# Allow new user registration (default: true)ALLOW_USER_REGISTRATION=true--# Allow viewing calendars without login (default: false)-ALLOW_GUEST_ACCESS=false```+Guest access (viewing calendars without login) is not an environment variable — it's a live toggle in the admin panel under **System Settings**, off by default.+### First User SetupThe first user to register becomes the **superadmin** with full system access. This happens automatically - no manual configuration required.diff --git a/docs/ENABLING_AUTH.md b/docs/ENABLING_AUTH.mdindex 0cd13e7..1df52ee 100644--- a/docs/ENABLING_AUTH.md+++ b/docs/ENABLING_AUTH.md@@ -73,11 +73,12 @@ BETTER_AUTH_SECRET=your-generated-secret-here# Set your application URLBETTER_AUTH_URL=https://your-domain.com-# Optional: Configure registration and guest access+# Optional: Configure registrationALLOW_USER_REGISTRATION=true-ALLOW_GUEST_ACCESS=false```+Guest access (viewing calendars without login) is a live toggle in the admin panel under System Settings, not an environment variable.+### Step 4: Restart the Application```bash@@ -165,7 +166,7 @@ Yes, after assigning an owner:1. Open calendar settings2. Set "Guest Permission" to "Read" or "Write"-3. Enable `ALLOW_GUEST_ACCESS=true` in environment+3. Turn on Guest Access globally in the admin panel under System Settings### How do I add more admins?diff --git a/docs/PERMISSIONS.md b/docs/PERMISSIONS.mdindex 92cbc21..814be9f 100644--- a/docs/PERMISSIONS.md+++ b/docs/PERMISSIONS.md@@ -84,7 +84,7 @@ From calendar settings, you can:## Access Tokens (Share Links)-Access tokens provide a way to share calendars via a URL. With `ALLOW_GUEST_ACCESS=true` the recipient needs no account; otherwise they sign in first and the token applies afterwards.+Access tokens provide a way to share calendars via a URL. With Guest Access enabled globally (admin panel → System Settings) the recipient needs no account; otherwise they sign in first and the token applies afterwards.### Creating Access Tokens@@ -116,7 +116,7 @@ Access tokens provide a way to share calendars via a URL. With `ALLOW_GUEST_ACCE### Security Considerations- Tokens are stored in cookies after first validation-- Users with tokens can access the calendar without logging in when `ALLOW_GUEST_ACCESS=true`+- Users with tokens can access the calendar without logging in when Guest Access is enabled globally- Treat share links like passwords - anyone with the link has access- Set expiration dates for temporary access- Monitor usage in token management@@ -139,10 +139,10 @@ Guest access allows unauthenticated users to view or edit calendars without any### Configuration-1. Enable globally: Set `ALLOW_GUEST_ACCESS=true` in environment+1. Enable globally: Turn on Guest Access in the admin panel under System Settings2. Enable per-calendar: Set public access in calendar settings, "Sharing" section, "Public" tab-The per-calendar level applies to visitors without an account only while `ALLOW_GUEST_ACCESS=true`; otherwise they are sent to the login page. Signed-in users get it through [Calendar Discovery](#calendar-discovery), whatever the flag says. Access links work even with public access set to `none`, but with `ALLOW_GUEST_ACCESS=false` a recipient without a session is sent to the login page first; the link's grant applies once they sign in.+The per-calendar level applies to visitors without an account only while Guest Access is enabled globally; otherwise they are sent to the login page. Signed-in users get it through [Calendar Discovery](#calendar-discovery), whatever the setting says. Access links work even with public access set to `none`, but with Guest Access disabled a recipient without a session is sent to the login page first; the link's grant applies once they sign in.### Guest Permission Levels@@ -166,7 +166,7 @@ The per-calendar level applies to visitors without an account only while `ALLOW_## Calendar Discovery-Signed-in users can discover and subscribe to any calendar whose public access is `read` or `write`. This does not depend on `ALLOW_GUEST_ACCESS`, which only governs visitors without an account.+Signed-in users can discover and subscribe to any calendar whose public access is `read` or `write`. This does not depend on the global Guest Access setting, which only governs visitors without an account.### Finding Public Calendars@@ -214,4 +214,4 @@ The first matching rule determines the permission level.3. **Set token expiration**: Don't leave tokens valid indefinitely4. **Review shares periodically**: Remove access that's no longer needed5. **Use read permission by default**: Only grant write when editing is required-6. **Consider public access carefully**: Public calendars are open to every signed-in user, and to everyone when `ALLOW_GUEST_ACCESS=true`+6. **Consider public access carefully**: Public calendars are open to every signed-in user, and to everyone when Guest Access is enabled globallydiff --git a/drizzle/0019_peaceful_peter_parker.sql b/drizzle/0019_peaceful_peter_parker.sqlnew file mode 100644index 0000000..4f60a61--- /dev/null+++ b/drizzle/0019_peaceful_peter_parker.sql@@ -0,0 +1,2 @@+ALTER TABLE `system_settings` ADD `allow_guest_access` integer;--> statement-breakpoint+ALTER TABLE `user` ADD `must_change_password` integer DEFAULT false NOT NULL;\ No newline at end of filediff --git a/drizzle/meta/0019_snapshot.json b/drizzle/meta/0019_snapshot.jsonnew file mode 100644index 0000000..a5dac52--- /dev/null+++ b/drizzle/meta/0019_snapshot.json@@ -0,0 +1,1883 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "20a88346-8085-45af-901f-ced11a89ebcf",+ "prevId": "46c43bf1-957b-48a6-80b6-8bb2d5c9ac6c",+ "tables": {+ "account": {+ "name": "account",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "account_userId_idx": {+ "name": "account_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "audit_logs": {+ "name": "audit_logs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "action": {+ "name": "action",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "resource_type": {+ "name": "resource_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "resource_id": {+ "name": "resource_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "severity": {+ "name": "severity",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'info'"+ },+ "is_user_visible": {+ "name": "is_user_visible",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "timestamp": {+ "name": "timestamp",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "audit_logs_userId_timestamp_idx": {+ "name": "audit_logs_userId_timestamp_idx",+ "columns": [+ "user_id",+ "timestamp"+ ],+ "isUnique": false+ },+ "audit_logs_action_timestamp_idx": {+ "name": "audit_logs_action_timestamp_idx",+ "columns": [+ "action",+ "timestamp"+ ],+ "isUnique": false+ },+ "audit_logs_userVisible_userId_timestamp_idx": {+ "name": "audit_logs_userVisible_userId_timestamp_idx",+ "columns": [+ "is_user_visible",+ "user_id",+ "timestamp"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "audit_logs_user_id_user_id_fk": {+ "name": "audit_logs_user_id_user_id_fk",+ "tableFrom": "audit_logs",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "calendar_access_tokens": {+ "name": "calendar_access_tokens",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "calendar_id": {+ "name": "calendar_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "permission": {+ "name": "permission",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'read'"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "last_used_at": {+ "name": "last_used_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "usage_count": {+ "name": "usage_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "is_active": {+ "name": "is_active",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ }+ },+ "indexes": {+ "calendar_access_tokens_token_unique": {+ "name": "calendar_access_tokens_token_unique",+ "columns": [+ "token"+ ],+ "isUnique": true+ },+ "calendar_access_tokens_token_idx": {+ "name": "calendar_access_tokens_token_idx",+ "columns": [+ "token"+ ],+ "isUnique": false+ },+ "calendar_access_tokens_calendarId_isActive_idx": {+ "name": "calendar_access_tokens_calendarId_isActive_idx",+ "columns": [+ "calendar_id",+ "is_active"+ ],+ "isUnique": false+ },+ "calendar_access_tokens_createdBy_idx": {+ "name": "calendar_access_tokens_createdBy_idx",+ "columns": [+ "created_by"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "calendar_access_tokens_calendar_id_calendars_id_fk": {+ "name": "calendar_access_tokens_calendar_id_calendars_id_fk",+ "tableFrom": "calendar_access_tokens",+ "tableTo": "calendars",+ "columnsFrom": [+ "calendar_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "calendar_access_tokens_created_by_user_id_fk": {+ "name": "calendar_access_tokens_created_by_user_id_fk",+ "tableFrom": "calendar_access_tokens",+ "tableTo": "user",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "calendar_notes": {+ "name": "calendar_notes",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "calendar_id": {+ "name": "calendar_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "date": {+ "name": "date",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "note": {+ "name": "note",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'note'"+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "recurring_pattern": {+ "name": "recurring_pattern",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'none'"+ },+ "recurring_interval": {+ "name": "recurring_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "calendar_notes_calendar_id_calendars_id_fk": {+ "name": "calendar_notes_calendar_id_calendars_id_fk",+ "tableFrom": "calendar_notes",+ "tableTo": "calendars",+ "columnsFrom": [+ "calendar_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "calendar_shares": {+ "name": "calendar_shares",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "calendar_id": {+ "name": "calendar_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "permission": {+ "name": "permission",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'read'"+ },+ "shared_by": {+ "name": "shared_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "calendar_shares_calendarId_idx": {+ "name": "calendar_shares_calendarId_idx",+ "columns": [+ "calendar_id"+ ],+ "isUnique": false+ },+ "calendar_shares_userId_idx": {+ "name": "calendar_shares_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "calendar_shares_calendar_id_calendars_id_fk": {+ "name": "calendar_shares_calendar_id_calendars_id_fk",+ "tableFrom": "calendar_shares",+ "tableTo": "calendars",+ "columnsFrom": [+ "calendar_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "calendar_shares_user_id_user_id_fk": {+ "name": "calendar_shares_user_id_user_id_fk",+ "tableFrom": "calendar_shares",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "calendar_shares_shared_by_user_id_fk": {+ "name": "calendar_shares_shared_by_user_id_fk",+ "tableFrom": "calendar_shares",+ "tableTo": "user",+ "columnsFrom": [+ "shared_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "calendars": {+ "name": "calendars",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'#3b82f6'"+ },+ "owner_id": {+ "name": "owner_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "guest_permission": {+ "name": "guest_permission",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'none'"+ },+ "allow_self_signup": {+ "name": "allow_self_signup",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "signups_enabled": {+ "name": "signups_enabled",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "view_settings": {+ "name": "view_settings",+ "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": {+ "calendars_ownerId_idx": {+ "name": "calendars_ownerId_idx",+ "columns": [+ "owner_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "calendars_owner_id_user_id_fk": {+ "name": "calendars_owner_id_user_id_fk",+ "tableFrom": "calendars",+ "tableTo": "user",+ "columnsFrom": [+ "owner_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "external_syncs": {+ "name": "external_syncs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "calendar_id": {+ "name": "calendar_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "sync_type": {+ "name": "sync_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'icloud'"+ },+ "calendar_url": {+ "name": "calendar_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'#3b82f6'"+ },+ "display_mode": {+ "name": "display_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'normal'"+ },+ "is_hidden": {+ "name": "is_hidden",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "hide_from_stats": {+ "name": "hide_from_stats",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "auto_sync_interval": {+ "name": "auto_sync_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "is_one_time_import": {+ "name": "is_one_time_import",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "last_synced_at": {+ "name": "last_synced_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "external_syncs_calendar_id_calendars_id_fk": {+ "name": "external_syncs_calendar_id_calendars_id_fk",+ "tableFrom": "external_syncs",+ "tableTo": "calendars",+ "columnsFrom": [+ "calendar_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "session": {+ "name": "session",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "impersonated_by": {+ "name": "impersonated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "session_token_unique": {+ "name": "session_token_unique",+ "columns": [+ "token"+ ],+ "isUnique": true+ },+ "session_userId_idx": {+ "name": "session_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "shift_presets": {+ "name": "shift_presets",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "calendar_id": {+ "name": "calendar_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "start_time": {+ "name": "start_time",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "end_time": {+ "name": "end_time",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'#3b82f6'"+ },+ "notes": {+ "name": "notes",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "group_name": {+ "name": "group_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "is_secondary": {+ "name": "is_secondary",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "is_all_day": {+ "name": "is_all_day",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "hide_from_stats": {+ "name": "hide_from_stats",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "default_signup_capacity": {+ "name": "default_signup_capacity",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "order": {+ "name": "order",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "shift_presets_calendar_id_calendars_id_fk": {+ "name": "shift_presets_calendar_id_calendars_id_fk",+ "tableFrom": "shift_presets",+ "tableTo": "calendars",+ "columnsFrom": [+ "calendar_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "shift_signups": {+ "name": "shift_signups",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "shift_id": {+ "name": "shift_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "signed_up_by": {+ "name": "signed_up_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "shift_signups_shiftId_idx": {+ "name": "shift_signups_shiftId_idx",+ "columns": [+ "shift_id"+ ],+ "isUnique": false+ },+ "shift_signups_userId_idx": {+ "name": "shift_signups_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ },+ "shift_signups_shiftId_userId_idx": {+ "name": "shift_signups_shiftId_userId_idx",+ "columns": [+ "shift_id",+ "user_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "shift_signups_shift_id_shifts_id_fk": {+ "name": "shift_signups_shift_id_shifts_id_fk",+ "tableFrom": "shift_signups",+ "tableTo": "shifts",+ "columnsFrom": [+ "shift_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "shift_signups_user_id_user_id_fk": {+ "name": "shift_signups_user_id_user_id_fk",+ "tableFrom": "shift_signups",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "shift_signups_signed_up_by_user_id_fk": {+ "name": "shift_signups_signed_up_by_user_id_fk",+ "tableFrom": "shift_signups",+ "tableTo": "user",+ "columnsFrom": [+ "signed_up_by"+ ],+ "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+ },+ "signup_capacity": {+ "name": "signup_capacity",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "external_event_id": {+ "name": "external_event_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "external_sync_id": {+ "name": "external_sync_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "synced_from_external": {+ "name": "synced_from_external",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "shifts_calendar_id_calendars_id_fk": {+ "name": "shifts_calendar_id_calendars_id_fk",+ "tableFrom": "shifts",+ "tableTo": "calendars",+ "columnsFrom": [+ "calendar_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "shifts_preset_id_shift_presets_id_fk": {+ "name": "shifts_preset_id_shift_presets_id_fk",+ "tableFrom": "shifts",+ "tableTo": "shift_presets",+ "columnsFrom": [+ "preset_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "shifts_external_sync_id_external_syncs_id_fk": {+ "name": "shifts_external_sync_id_external_syncs_id_fk",+ "tableFrom": "shifts",+ "tableTo": "external_syncs",+ "columnsFrom": [+ "external_sync_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "sync_logs": {+ "name": "sync_logs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "calendar_id": {+ "name": "calendar_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "external_sync_id": {+ "name": "external_sync_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "external_sync_name": {+ "name": "external_sync_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "error_message": {+ "name": "error_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "shifts_created": {+ "name": "shifts_created",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "shifts_updated": {+ "name": "shifts_updated",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "shifts_deleted": {+ "name": "shifts_deleted",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "sync_type": {+ "name": "sync_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'auto'"+ },+ "is_read": {+ "name": "is_read",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "synced_at": {+ "name": "synced_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "sync_logs_calendar_id_calendars_id_fk": {+ "name": "sync_logs_calendar_id_calendars_id_fk",+ "tableFrom": "sync_logs",+ "tableTo": "calendars",+ "columnsFrom": [+ "calendar_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "sync_logs_external_sync_id_external_syncs_id_fk": {+ "name": "sync_logs_external_sync_id_external_syncs_id_fk",+ "tableFrom": "sync_logs",+ "tableTo": "external_syncs",+ "columnsFrom": [+ "external_sync_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "system_settings": {+ "name": "system_settings",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false,+ "default": "'default'"+ },+ "update_check_enabled": {+ "name": "update_check_enabled",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "update_banner_visibility": {+ "name": "update_banner_visibility",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'all'"+ },+ "allow_guest_access": {+ "name": "allow_guest_access",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "user": {+ "name": "user",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email_verified": {+ "name": "email_verified",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "banned": {+ "name": "banned",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "ban_reason": {+ "name": "ban_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ban_expires": {+ "name": "ban_expires",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "must_change_password": {+ "name": "must_change_password",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ }+ },+ "indexes": {+ "user_email_unique": {+ "name": "user_email_unique",+ "columns": [+ "email"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "user_calendar_subscriptions": {+ "name": "user_calendar_subscriptions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "calendar_id": {+ "name": "calendar_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'subscribed'"+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'guest'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "user_calendar_subscriptions_userId_idx": {+ "name": "user_calendar_subscriptions_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ },+ "user_calendar_subscriptions_calendarId_idx": {+ "name": "user_calendar_subscriptions_calendarId_idx",+ "columns": [+ "calendar_id"+ ],+ "isUnique": false+ },+ "user_calendar_subscriptions_status_idx": {+ "name": "user_calendar_subscriptions_status_idx",+ "columns": [+ "status"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "user_calendar_subscriptions_user_id_user_id_fk": {+ "name": "user_calendar_subscriptions_user_id_user_id_fk",+ "tableFrom": "user_calendar_subscriptions",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_calendar_subscriptions_calendar_id_calendars_id_fk": {+ "name": "user_calendar_subscriptions_calendar_id_calendars_id_fk",+ "tableFrom": "user_calendar_subscriptions",+ "tableTo": "calendars",+ "columnsFrom": [+ "calendar_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "user_preferences": {+ "name": "user_preferences",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "view_settings": {+ "name": "view_settings",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "user_preferences_user_id_user_id_fk": {+ "name": "user_preferences_user_id_user_id_fk",+ "tableFrom": "user_preferences",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "verification": {+ "name": "verification",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ }+ },+ "views": {},+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "internal": {+ "indexes": {}+ }+}\ No newline at end of filediff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.jsonindex e57992d..9b06f78 100644--- a/drizzle/meta/_journal.json+++ b/drizzle/meta/_journal.json@@ -134,6 +134,13 @@"when": 1789303001140,"tag": "0018_skinny_goblin_queen","breakpoints": true+ },+ {+ "idx": 19,+ "version": "6",+ "when": 1789388420861,+ "tag": "0019_peaceful_peter_parker",+ "breakpoints": true}]}\ No newline at end of filediff --git a/hooks/useAdminAccess.ts b/hooks/useAdminAccess.tsindex f9378fe..092bbb3 100644--- a/hooks/useAdminAccess.ts+++ b/hooks/useAdminAccess.ts@@ -16,6 +16,7 @@ import {canViewAuditLogs,canDeleteAuditLogs,canResetPassword,+ canCreateUser,} from "@/lib/auth/admin";import type { User } from "@/lib/auth";@@ -162,6 +163,16 @@ export function useCanDeleteAuditLogs(): boolean {return useMemo(() => canDeleteAuditLogs(user), [user]);}+/**+ * Hook to check if current admin can create new users from the admin panel+ *+ * @returns boolean - true if current admin can create users+ */+export function useCanCreateUser(): boolean {+ const { user } = useAuth();+ return useMemo(() => canCreateUser(user), [user]);+}+/*** Hook to check if current admin can reset user passwords*diff --git a/hooks/useAdminUsers.ts b/hooks/useAdminUsers.tsindex 99d8503..bb2a0b6 100644--- a/hooks/useAdminUsers.ts+++ b/hooks/useAdminUsers.ts@@ -111,6 +111,33 @@ export async function fetchAdminUserDetails(userId: string): Promise<UserDetails};}+/**+ * Create user via API+ */+async function createUserApi(+ data: { name: string; email: string; password: string; role?: string },+ t: ReturnType<typeof useTranslations>,+): Promise<void> {+ const response = await fetch("/api/admin/users", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify(data),+ });++ if (!response.ok) {+ const body = await response.json().catch(() => null);+ if (response.status === 409) {+ throw new Error(t("admin.emailAlreadyExists"));+ }+ if (response.status === 403) {+ throw new Error(t("admin.accessDenied"));+ }+ throw new Error(body?.error || t("common.createError", { item: t("common.labels.user") }));+ }+}+/*** Update user via API*/@@ -398,6 +425,24 @@ export function useAdminUserActions() {onSettled,});+ // No optimistic update: the list is server-paginated/sorted/filtered with+ // separate aggregate counts, so there's no well-defined slot to insert into+ const createMutation = useMutation({+ mutationFn: (data: { name: string; email: string; password: string; role?: string }) =>+ createUserApi(data, t),+ onError: (err) => {+ toast.error(+ err instanceof Error+ ? err.message+ : t("common.createError", { item: t("common.labels.user") }),+ );+ },+ onSuccess: () => {+ toast.success(t("common.created", { item: t("common.labels.user") }));+ },+ onSettled,+ });+// No optimistic update: nothing in the list changesconst resetPasswordMutation = useMutation({mutationFn: ({@@ -419,6 +464,9 @@ export function useAdminUserActions() {return {isUpdating: updateMutation.isPending,+ isCreating: createMutation.isPending,+ createUser: (data: { name: string; email: string; password: string; role?: string }) =>+ run(createMutation.mutateAsync, data),updateUser: (userId: string, data: { name?: string; email?: string; role?: string }) =>run(updateMutation.mutateAsync, { userId, data }),banUser: (userId: string, reason: string, expiresAt?: Date) =>diff --git a/hooks/useProfileForm.ts b/hooks/useProfileForm.tsindex 787f0df..792264c 100644--- a/hooks/useProfileForm.ts+++ b/hooks/useProfileForm.ts@@ -179,7 +179,7 @@ export function useProfileForm(export type ProfileForm = ReturnType<typeof useProfileForm>;-export function usePasswordForm() {+export function usePasswordForm(onSuccess?: () => void) {const t = useTranslations();const [currentPassword, setCurrentPassword] = useState("");const [newPassword, setNewPassword] = useState("");@@ -237,6 +237,7 @@ export function usePasswordForm() {toast.success(t("auth.passwordChanged"));reset();+ onSuccess?.();} catch (error) {console.error("Password change error:", error);toast.error(t("common.error"));diff --git a/lib/audit-log.ts b/lib/audit-log.tsindex 22433f9..c17f5f4 100644--- a/lib/audit-log.ts+++ b/lib/audit-log.ts@@ -144,8 +144,14 @@ export interface AdminPasswordResetMetadata {}export interface AdminSystemSettingsUpdatedMetadata {- before: { updateCheckEnabled: boolean; updateBannerVisibility: string };- after: { updateCheckEnabled: boolean; updateBannerVisibility: string };+ before: { updateCheckEnabled: boolean; updateBannerVisibility: string; allowGuestAccess: boolean };+ after: { updateCheckEnabled: boolean; updateBannerVisibility: string; allowGuestAccess: boolean };+}++export interface AdminUserCreateMetadata {+ createdUser: string;+ role: string;+ createdBy: string;}// Union type for all metadata@@ -166,6 +172,7 @@ export type AuditLogMetadata =| SyncExecutedMetadata| RateLimitHitMetadata| AdminUserDeleteMetadata+ | AdminUserCreateMetadata| AdminCalendarTransferMetadata| AdminPasswordResetMetadata| AdminSystemSettingsUpdatedMetadata;diff --git a/lib/auth.ts b/lib/auth.tsindex 05dcc1b..196a8e5 100644--- a/lib/auth.ts+++ b/lib/auth.ts@@ -134,13 +134,31 @@ export const auth = betterAuth({deleteUser: {enabled: true,},+ additionalFields: {+ // Set on admin-created accounts (see POST /api/admin/users); input: false+ // blocks self-signup from setting it, but not the admin plugin's `data`+ // passthrough on /admin/create-user.+ mustChangePassword: {+ type: "boolean",+ defaultValue: false,+ input: false,+ },+ },},// Database hooks for user creation controldatabaseHooks: {user: {create: {- before: async () => {+ before: async (_user, context) => {+ // Admin-created users always work, even when self-registration is+ // disabled -- see docs/ADMIN_PANEL.md. Checked via the acting+ // session's role (mirrors isAdmin's rule) rather than matching+ // better-auth's internal /admin/create-user route, which is an+ // implementation detail.+ const actorRole = context?.context?.session?.user?.role;+ if (actorRole === "admin" || actorRole === "superadmin") return;+// Block OAuth/OIDC registration when ALLOW_USER_REGISTRATION is false// This hook runs for ALL user creation attempts (email + OAuth/OIDC)// Email registration is already blocked by disableSignUp configdiff --git a/lib/auth/admin.ts b/lib/auth/admin.tsindex 96ac415..b896cc2 100644--- a/lib/auth/admin.ts+++ b/lib/auth/admin.ts@@ -11,7 +11,7 @@ import { APIError } from "better-auth/api";/*** Valid admin roles in the system*/-const ADMIN_ROLES = ["admin", "superadmin"] as const;+export const ADMIN_ROLES = ["admin", "superadmin"] as const;export type AdminRole = (typeof ADMIN_ROLES)[number];/**@@ -321,6 +321,27 @@ export function canDeleteAuditLogs(return isSuperAdmin(adminUser);}+/**+ * Check if admin can create new users from the admin panel.+ *+ * Rules:+ * - Both admin and superadmin can create users+ * - Only superadmin may assign a role other than "user" at creation time+ * (mirrors canChangeUserRole's superadmin-only restriction)+ *+ * @param adminUser - The admin performing the action+ * @param role - The role to assign to the new user, if any (omit to just check base access)+ * @returns boolean - true if admin can create a user with the given role+ */+export function canCreateUser(+ adminUser: User | null | undefined,+ role?: string+): boolean {+ if (!isAdmin(adminUser)) return false;+ if (role !== undefined && role !== "user") return isSuperAdmin(adminUser);+ return true;+}+/*** Check if admin can view or change instance-wide system settings* (e.g. whether the update check runs and who sees its banner).diff --git a/lib/auth/feature-flags.ts b/lib/auth/feature-flags.tsindex 8f891e1..90d9de1 100644--- a/lib/auth/feature-flags.ts+++ b/lib/auth/feature-flags.ts@@ -11,11 +11,11 @@import {AUTH_ENABLED,ALLOW_USER_REGISTRATION,- ALLOW_GUEST_ACCESS,CUSTOM_OIDC_NAME,hasSocialProviders as hasSocialProvidersEnv,getEnabledProviders as getEnabledProvidersEnv,} from "./env";+import { getSystemSettings } from "@/lib/system-settings";/*** Server-side: Check if auth system is enabled@@ -36,12 +36,13 @@ export const allowUserRegistration = (): boolean => {* Server-side: Check if guest access is allowed* Returns true if auth is disabled (entire system public) OR if guest access is explicitly enabled*/-export const allowGuestAccess = (): boolean => {+export const allowGuestAccess = async (): Promise<boolean> => {// If auth is disabled, everything is public (backward compatibility)if (!isAuthEnabled()) return true;- // If auth is enabled, check explicit guest access flag- return ALLOW_GUEST_ACCESS;+ // If auth is enabled, check the live, admin-configurable guest access setting+ const settings = await getSystemSettings();+ return settings.allowGuestAccess;};/**diff --git a/lib/auth/permissions.ts b/lib/auth/permissions.tsindex 05d0457..d0a0c52 100644--- a/lib/auth/permissions.ts+++ b/lib/auth/permissions.ts@@ -96,7 +96,7 @@ async function getUserCalendarPermissionWithCalendar(}// Guest access only works when explicitly enabled- if (allowGuestAccess() && calendar.guestPermission !== "none") {+ if ((await allowGuestAccess()) && calendar.guestPermission !== "none") {return {permission: calendar.guestPermission as CalendarPermission,calendar,@@ -281,8 +281,14 @@ export async function getUserAccessibleCalendars(const results: Array<{ id: string; permission: CalendarPermission }> = [];const existingIds = new Set<string>();+ // Token-based access and the guest-access flag don't depend on each+ // other, so resolve them concurrently instead of one after another.+ const [tokens, guestAccessEnabled] = await Promise.all([+ getTokensFromCookie(),+ allowGuestAccess(),+ ]);+// First, check for token-based access (always works, regardless of allowGuestAccess)- const tokens = await getTokensFromCookie();for (const tokenData of tokens) {// Validate token is still validconst validation = await validateAccessToken(tokenData.token);@@ -296,7 +302,7 @@ export async function getUserAccessibleCalendars(}// Then, check for guest permissions (only if guest access is enabled)- if (allowGuestAccess()) {+ if (guestAccessEnabled) {const guestAccessibleCalendars = await db.query.calendars.findMany({where: (calendars, { ne }) => ne(calendars.guestPermission, "none"),});diff --git a/lib/db/schema.ts b/lib/db/schema.tsindex be79be6..33f4923 100644--- a/lib/db/schema.ts+++ b/lib/db/schema.ts@@ -35,6 +35,10 @@ export const user = sqliteTable("user", {banned: integer("banned", { mode: "boolean" }).default(false),banReason: text("ban_reason"),banExpires: integer("ban_expires", { mode: "timestamp_ms" }),+ // Set on admin-created accounts; cleared once the user changes their password+ mustChangePassword: integer("must_change_password", { mode: "boolean" })+ .notNull()+ .default(false),});export const session = sqliteTable(@@ -232,6 +236,10 @@ export const systemSettings = sqliteTable("system_settings", {}).notNull().default("all"),+ // Nullable: existing rows from before this column existed must fall back+ // to ALLOW_GUEST_ACCESS (see lib/system-settings.ts), not silently to+ // false -- a NOT NULL DEFAULT would force that on every upgrade.+ allowGuestAccess: integer("allow_guest_access", { mode: "boolean" }),updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().default(sql`CURRENT_TIMESTAMP`)diff --git a/lib/password-utils.ts b/lib/password-utils.tsnew file mode 100644index 0000000..cf67b7c--- /dev/null+++ b/lib/password-utils.ts@@ -0,0 +1,10 @@+export const MIN_PASSWORD_LENGTH = 8;++const CHARSET =+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*";++/** Cryptographically random password for admin-facing "generate password" actions. */+export function randomPassword(length = 16): string {+ const values = crypto.getRandomValues(new Uint32Array(length));+ return Array.from(values, (v) => CHARSET[v % CHARSET.length]).join("");+}diff --git a/lib/public-config.ts b/lib/public-config.tsindex 6e7c98c..6e4a66a 100644--- a/lib/public-config.ts+++ b/lib/public-config.ts@@ -14,6 +14,8 @@* - Client Components: use the usePublicConfig() hook*/+import { allowGuestAccess } from "@/lib/auth/feature-flags";+/*** Returns public configuration that can be safely exposed to the client.* This function runs ONLY on the server and explicitly whitelists which@@ -21,7 +23,9 @@** @returns Public configuration object*/-export function getPublicConfig() {+export async function getPublicConfig() {+ const guestAccess = await allowGuestAccess();+return {// =============================================================================// Auth System Configuration@@ -49,10 +53,12 @@ export function getPublicConfig() {allowRegistration: process.env.ALLOW_USER_REGISTRATION !== "false",/**- * Allow unauthenticated users to view calendars with guest permission+ * Allow unauthenticated users to view calendars with guest permission.+ * Live, admin-configurable via /admin (see lib/system-settings.ts);+ * ALLOW_GUEST_ACCESS is only the seed value for the first DB row.* @default false*/- allowGuestAccess: process.env.ALLOW_GUEST_ACCESS === "true",+ allowGuestAccess: guestAccess,},// =============================================================================@@ -107,14 +113,14 @@ export function getPublicConfig() {/*** Type-safe public configuration object*/-export type PublicConfig = ReturnType<typeof getPublicConfig>;+export type PublicConfig = Awaited<ReturnType<typeof getPublicConfig>>;/*** Validates that the public configuration is properly set up.* Called during build/startup to catch configuration errors early.*/-export function validatePublicConfig(): void {- const config = getPublicConfig();+export async function validatePublicConfig(): Promise<void> {+ const config = await getPublicConfig();// Validate auth configurationif (config.auth.enabled && !config.auth.url) {diff --git a/lib/rate-limiter.ts b/lib/rate-limiter.tsindex c3a4890..645dbce 100644--- a/lib/rate-limiter.ts+++ b/lib/rate-limiter.ts@@ -149,6 +149,15 @@ const config = {10) * 1000, // 5 minutes},+ // Separate from adminUserMutations: creating a real account (with a working+ // password) is at least as sensitive as a password reset, so it gets the+ // same stricter bucket instead of the general mutations budget.+ adminUserCreate: {+ requests: parseInt(process.env.RATE_LIMIT_ADMIN_USER_CREATE || "5", 10),+ windowMs:+ parseInt(process.env.RATE_LIMIT_ADMIN_USER_CREATE_WINDOW || "300", 10) *+ 1000, // 5 minutes+ },adminBulkOperations: {requests: parseInt(process.env.RATE_LIMIT_ADMIN_BULK_OPERATIONS || "3", 10),windowMs:@@ -191,6 +200,7 @@ const limitsByType = {"user-search": config.userSearch,"admin-user-mutations": config.adminUserMutations,"admin-password-reset": config.adminPasswordReset,+ "admin-user-create": config.adminUserCreate,"admin-bulk-operations": config.adminBulkOperations,"admin-calendar-mutations": config.adminCalendarMutations,} as const;diff --git a/lib/system-settings.ts b/lib/system-settings.tsindex dfad0fd..625311d 100644--- a/lib/system-settings.ts+++ b/lib/system-settings.ts@@ -1,6 +1,7 @@import { eq } from "drizzle-orm";import { db } from "@/lib/db";import { systemSettings } from "@/lib/db/schema";+import { ALLOW_GUEST_ACCESS } from "@/lib/auth/env";const SETTINGS_ID = "default";@@ -9,11 +10,17 @@ export type UpdateBannerVisibility = "all" | "admins";export interface SystemSettings {updateCheckEnabled: boolean;updateBannerVisibility: UpdateBannerVisibility;+ allowGuestAccess: boolean;}+// Neither the row nor (on upgrade) this specific column may exist yet, so+// both fallbacks have to mirror ALLOW_GUEST_ACCESS -- otherwise every+// self-hosted instance would silently lose guest access until an admin+// re-enables it here.export const DEFAULT_SYSTEM_SETTINGS: SystemSettings = {updateCheckEnabled: true,updateBannerVisibility: "all",+ allowGuestAccess: ALLOW_GUEST_ACCESS,};// Settings are read on every /api/version request; a short cache avoids a DB@@ -32,12 +39,15 @@ export async function getSystemSettings(): Promise<SystemSettings> {.select({updateCheckEnabled: systemSettings.updateCheckEnabled,updateBannerVisibility: systemSettings.updateBannerVisibility,+ allowGuestAccess: systemSettings.allowGuestAccess,}).from(systemSettings).where(eq(systemSettings.id, SETTINGS_ID)).limit(1);- cachedSettings = row ?? DEFAULT_SYSTEM_SETTINGS;+ cachedSettings = row+ ? { ...row, allowGuestAccess: row.allowGuestAccess ?? ALLOW_GUEST_ACCESS }+ : DEFAULT_SYSTEM_SETTINGS;cachedSettingsExpiresAt = Date.now() + CACHE_DURATION;return cachedSettings;}diff --git a/messages/cs.json b/messages/cs.jsonindex 69e4420..51404fa 100644--- a/messages/cs.json+++ b/messages/cs.json@@ -10,6 +10,7 @@"common": {"cancel": "Zrušit","save": "Uložit",+ "create": "Vytvořit","saving": "Ukládání...","close": "Zavřít","delete": "Smazat",@@ -525,7 +526,9 @@"visibility": "Banner viditelný pro","visibilityAll": "Všechny","visibilityAdmins": "Pouze administrátory",- "updateError": "Nastavení se nepodařilo uložit"+ "updateError": "Nastavení se nepodařilo uložit",+ "guestAccess": "Přístup pro hosty",+ "guestAccessHint": "Umožňuje zobrazit kalendáře bez přihlášení, pokud to kalendář povoluje."},"orphanedCalendarsWarning": "Zjištěny osiřelé kalendáře","orphanedCalendarsWarningDescription": "{count, plural, =1 {Existuje 1 kalendář bez vlastníka} few {Existují # kalendáře bez vlastníka} other {Existuje # kalendářů bez vlastníka}}. Přiřaďte je prosím uživatelům.",@@ -654,7 +657,11 @@"selectedLogs": "{count} vybráno","clearSelection": "Zrušit výběr","deleteSelectedLogsDescription": "Smazat {count, plural, one {# vybraný protokol} few {# vybrané protokoly} other {# vybraných protokolů}}. Tuto akci nelze vrátit zpět.",- "willDeleteSelectedLogs": "{count, plural, one {# protokol} few {# protokoly} other {# protokolů}} bude trvale smazáno"+ "willDeleteSelectedLogs": "{count, plural, one {# protokol} few {# protokoly} other {# protokolů}} bude trvale smazáno",+ "createUser": "Vytvořit uživatele",+ "createUserSubtitle": "Vytvoří nový účet i při vypnuté registraci.",+ "mustChangePasswordHint": "Uživatel bude muset toto heslo změnit při prvním přihlášení.",+ "emailAlreadyExists": "Uživatel s touto e-mailovou adresou již existuje"},"appearance": {"title": "Vzhled",@@ -964,7 +971,9 @@"unknownBrowser": "Neznámý prohlížeč","unknownOs": "Neznámý systém","deleteImpact": "Smažou se i kalendáře, směny a sdílení.",- "deleteNeedsPassword": "Vyžaduje vaše heslo."+ "deleteNeedsPassword": "Vyžaduje vaše heslo.",+ "mustChangePasswordTitle": "Je vyžadována změna hesla",+ "mustChangePasswordDescription": "Tento účet vytvořil administrátor. Nastavte si nyní nové heslo, abyste mohli pokračovat."},"adminKit": {"banned": "Zablokován",diff --git a/messages/de.json b/messages/de.jsonindex 0b93ec3..84151f4 100644--- a/messages/de.json+++ b/messages/de.json@@ -10,6 +10,7 @@"common": {"cancel": "Abbrechen","save": "Speichern",+ "create": "Erstellen","saving": "Speichere...","close": "Schließen","delete": "Löschen",@@ -525,7 +526,9 @@"visibility": "Banner sichtbar für","visibilityAll": "Alle","visibilityAdmins": "Nur Admins",- "updateError": "Einstellungen konnten nicht gespeichert werden"+ "updateError": "Einstellungen konnten nicht gespeichert werden",+ "guestAccess": "Gastzugang",+ "guestAccessHint": "Erlaubt das Ansehen von Kalendern ohne Anmeldung, sofern der Kalender das zulässt."},"orphanedCalendarsWarning": "Verwaiste Kalender erkannt","orphanedCalendarsWarningDescription": "{count, plural, =1 {Es gibt 1 Kalender ohne Besitzer} other {Es gibt # Kalender ohne Besitzer}}. Bitte weise diese(n) Benutzern zu.",@@ -654,7 +657,11 @@"selectedLogs": "{count} ausgewählt","clearSelection": "Auswahl aufheben","deleteSelectedLogsDescription": "{count, plural, one {# ausgewähltes Protokoll} other {# ausgewählte Protokolle}} löschen. Diese Aktion kann nicht rückgängig gemacht werden.",- "willDeleteSelectedLogs": "{count, plural, one {# Protokoll} other {# Protokolle}} werden dauerhaft gelöscht"+ "willDeleteSelectedLogs": "{count, plural, one {# Protokoll} other {# Protokolle}} werden dauerhaft gelöscht",+ "createUser": "Benutzer erstellen",+ "createUserSubtitle": "Legt ein neues Konto an, auch wenn die Registrierung deaktiviert ist.",+ "mustChangePasswordHint": "Der Benutzer muss dieses Passwort beim ersten Login ändern.",+ "emailAlreadyExists": "Ein Benutzer mit dieser E-Mail-Adresse existiert bereits"},"appearance": {"title": "Erscheinungsbild",@@ -964,7 +971,9 @@"unknownBrowser": "Unbekannter Browser","unknownOs": "Unbekanntes System","deleteImpact": "Kalender, Schichten und Freigaben werden mitgelöscht.",- "deleteNeedsPassword": "Verlangt dein Passwort."+ "deleteNeedsPassword": "Verlangt dein Passwort.",+ "mustChangePasswordTitle": "Passwortänderung erforderlich",+ "mustChangePasswordDescription": "Ein Administrator hat dieses Konto erstellt. Bitte lege jetzt ein neues Passwort fest, um fortzufahren."},"adminKit": {"banned": "Gesperrt",diff --git a/messages/en.json b/messages/en.jsonindex c4a8be8..9c1aa6c 100644--- a/messages/en.json+++ b/messages/en.json@@ -10,6 +10,7 @@"common": {"cancel": "Cancel","save": "Save",+ "create": "Create","saving": "Saving...","close": "Close","delete": "Delete",@@ -525,7 +526,9 @@"visibility": "Banner visible to","visibilityAll": "Everyone","visibilityAdmins": "Admins only",- "updateError": "Failed to save settings"+ "updateError": "Failed to save settings",+ "guestAccess": "Guest access",+ "guestAccessHint": "Allows viewing calendars without logging in, where the calendar permits it."},"orphanedCalendarsWarning": "Orphaned Calendars Detected","orphanedCalendarsWarningDescription": "{count, plural, =1 {There is 1 calendar without an owner} other {There are # calendars without an owner}}. Please assign them to users.",@@ -654,7 +657,11 @@"selectedLogs": "{count} selected","clearSelection": "Clear Selection","deleteSelectedLogsDescription": "Delete {count, plural, one {# selected log} other {# selected logs}}. This action cannot be undone.",- "willDeleteSelectedLogs": "{count, plural, one {# log} other {# logs}} will be permanently deleted"+ "willDeleteSelectedLogs": "{count, plural, one {# log} other {# logs}} will be permanently deleted",+ "createUser": "Create user",+ "createUserSubtitle": "Creates a new account, even while registration is disabled.",+ "mustChangePasswordHint": "The user will be required to change this password on first login.",+ "emailAlreadyExists": "A user with this email address already exists"},"appearance": {"title": "Appearance",@@ -964,7 +971,9 @@"unknownBrowser": "Unknown browser","unknownOs": "Unknown system","deleteImpact": "Calendars, shifts and shares are deleted as well.",- "deleteNeedsPassword": "Requires your password."+ "deleteNeedsPassword": "Requires your password.",+ "mustChangePasswordTitle": "Password change required",+ "mustChangePasswordDescription": "An administrator created this account. Please set a new password now to continue."},"adminKit": {"banned": "Banned",diff --git a/messages/es.json b/messages/es.jsonindex 73b0d1b..3656926 100644--- a/messages/es.json+++ b/messages/es.json@@ -10,6 +10,7 @@"common": {"cancel": "Cancelar","save": "Guardar",+ "create": "Crear","saving": "Guardando...","close": "Cerrar","delete": "Eliminar",@@ -525,7 +526,9 @@"visibility": "Banner visible para","visibilityAll": "Todos","visibilityAdmins": "Solo administradores",- "updateError": "No se pudieron guardar los ajustes"+ "updateError": "No se pudieron guardar los ajustes",+ "guestAccess": "Acceso de invitado",+ "guestAccessHint": "Permite ver calendarios sin iniciar sesión, si el calendario lo permite."},"orphanedCalendarsWarning": "Se han detectado calendarios huérfanos","orphanedCalendarsWarningDescription": "{count, plural, =1 {Hay 1 calendario sin propietario} other {Hay # calendarios sin propietario}}. Por favor, asígnalos a usuarios.",@@ -654,7 +657,11 @@"selectedLogs": "{count} seleccionados","clearSelection": "Limpiar selección","deleteSelectedLogsDescription": "Eliminar {count, plural, one {# registro seleccionado} other {# registros seleccionados}}. Esta acción no se puede deshacer.",- "willDeleteSelectedLogs": "{count, plural, one {# registro} other {# registros}} se borrarán permanentemente"+ "willDeleteSelectedLogs": "{count, plural, one {# registro} other {# registros}} se borrarán permanentemente",+ "createUser": "Crear usuario",+ "createUserSubtitle": "Crea una nueva cuenta, incluso con el registro desactivado.",+ "mustChangePasswordHint": "El usuario deberá cambiar esta contraseña en el primer inicio de sesión.",+ "emailAlreadyExists": "Ya existe un usuario con esta dirección de correo electrónico"},"appearance": {"title": "Apariencia",@@ -964,7 +971,9 @@"unknownBrowser": "Navegador desconocido","unknownOs": "Sistema desconocido","deleteImpact": "También se eliminan los calendarios, turnos y compartidos.",- "deleteNeedsPassword": "Requiere tu contraseña."+ "deleteNeedsPassword": "Requiere tu contraseña.",+ "mustChangePasswordTitle": "Cambio de contraseña requerido",+ "mustChangePasswordDescription": "Un administrador creó esta cuenta. Establece una nueva contraseña ahora para continuar."},"adminKit": {"banned": "Bloqueado",diff --git a/messages/fr.json b/messages/fr.jsonindex 02152f3..7311423 100755--- a/messages/fr.json+++ b/messages/fr.json@@ -10,6 +10,7 @@"common": {"cancel": "Annuler","save": "Enregistrer",+ "create": "Créer","saving": "Enregistrement...","close": "Fermer","delete": "Supprimer",@@ -525,7 +526,9 @@"visibility": "Bannière visible pour","visibilityAll": "Tout le monde","visibilityAdmins": "Administrateurs uniquement",- "updateError": "Échec de l'enregistrement des paramètres"+ "updateError": "Échec de l'enregistrement des paramètres",+ "guestAccess": "Accès invité",+ "guestAccessHint": "Permet de consulter les calendriers sans connexion, si le calendrier l'autorise."},"orphanedCalendarsWarning": "Calendriers orphelins détectés","orphanedCalendarsWarningDescription": "{count, plural, =1 {1 calendrier n'a pas de propriétaire} other {# calendriers n'ont pas de propriétaire}}. Veuillez les attribuer à des utilisateurs.",@@ -654,7 +657,11 @@"selectedLogs": "{count} sélectionné(s)","clearSelection": "Effacer la sélection","deleteSelectedLogsDescription": "Supprimer {count, plural, one {# journal sélectionné} other {# journaux sélectionnés}}. Cette action est irréversible.",- "willDeleteSelectedLogs": "{count, plural, one {# journal} other {# journaux}} sera/seront supprimé(s) définitivement"+ "willDeleteSelectedLogs": "{count, plural, one {# journal} other {# journaux}} sera/seront supprimé(s) définitivement",+ "createUser": "Créer un utilisateur",+ "createUserSubtitle": "Crée un nouveau compte, même si l'inscription est désactivée.",+ "mustChangePasswordHint": "L'utilisateur devra changer ce mot de passe lors de sa première connexion.",+ "emailAlreadyExists": "Un utilisateur avec cette adresse e-mail existe déjà"},"appearance": {"title": "Apparence",@@ -964,7 +971,9 @@"unknownBrowser": "Navigateur inconnu","unknownOs": "Système inconnu","deleteImpact": "Les calendriers, créneaux et partages sont également supprimés.",- "deleteNeedsPassword": "Nécessite votre mot de passe."+ "deleteNeedsPassword": "Nécessite votre mot de passe.",+ "mustChangePasswordTitle": "Changement de mot de passe requis",+ "mustChangePasswordDescription": "Un administrateur a créé ce compte. Définissez un nouveau mot de passe maintenant pour continuer."},"adminKit": {"banned": "Bloqué",diff --git a/messages/it.json b/messages/it.jsonindex 454b07c..3517c21 100644--- a/messages/it.json+++ b/messages/it.json@@ -10,6 +10,7 @@"common": {"cancel": "Annulla","save": "Salva",+ "create": "Crea","saving": "Salvataggio...","close": "Chiudi","delete": "Elimina",@@ -525,7 +526,9 @@"visibility": "Banner visibile a","visibilityAll": "Tutti","visibilityAdmins": "Solo amministratori",- "updateError": "Impossibile salvare le impostazioni"+ "updateError": "Impossibile salvare le impostazioni",+ "guestAccess": "Accesso ospite",+ "guestAccessHint": "Consente di visualizzare i calendari senza accedere, se il calendario lo consente."},"orphanedCalendarsWarning": "Calendari Orfani Rilevati","orphanedCalendarsWarningDescription": "{count, plural, =1 {C'è 1 calendario senza proprietario} other {Ci sono # calendari senza proprietario}}. Si prega di assegnarli agli utenti.",@@ -654,7 +657,11 @@"selectedLogs": "{count} selezionati","clearSelection": "Cancella Selezione","deleteSelectedLogsDescription": "Elimina {count, plural, one {# log selezionato} other {# log selezionati}}. Questa azione non può essere annullata.",- "willDeleteSelectedLogs": "{count, plural, one {# log} other {# log}} verranno eliminati permanentemente"+ "willDeleteSelectedLogs": "{count, plural, one {# log} other {# log}} verranno eliminati permanentemente",+ "createUser": "Crea utente",+ "createUserSubtitle": "Crea un nuovo account, anche con la registrazione disattivata.",+ "mustChangePasswordHint": "L'utente dovrà cambiare questa password al primo accesso.",+ "emailAlreadyExists": "Esiste già un utente con questo indirizzo email"},"appearance": {"title": "Aspetto",@@ -964,7 +971,9 @@"unknownBrowser": "Browser sconosciuto","unknownOs": "Sistema sconosciuto","deleteImpact": "Vengono eliminati anche calendari, turni e condivisioni.",- "deleteNeedsPassword": "Richiede la tua password."+ "deleteNeedsPassword": "Richiede la tua password.",+ "mustChangePasswordTitle": "Cambio password richiesto",+ "mustChangePasswordDescription": "Un amministratore ha creato questo account. Imposta subito una nuova password per continuare."},"adminKit": {"banned": "Bloccato",diff --git a/proxy.ts b/proxy.tsindex dd221d3..fa2b020 100644--- a/proxy.ts+++ b/proxy.ts@@ -374,7 +374,7 @@ export async function proxy(request: NextRequest) {// If no session token, check guest accessif (!sessionToken) {// If guest access is enabled, allow viewing without login- if (allowGuestAccess()) {+ if (await allowGuestAccess()) {return nextWithNonce(request);}