Files
DeepTutor/web/components/sidebar/SidebarShell.tsx
xor_xe 6688408800 feat: add optional auth with login, registration, and admin dashboard
Closes #227. Auth is disabled by default (AUTH_ENABLED=false) so
localhost usage is unaffected. Set AUTH_ENABLED=true +
NEXT_PUBLIC_AUTH_ENABLED=true to require login when hosting publicly.

Backend
- New deeptutor/services/auth.py: bcrypt password hashing, JWT
  create/decode, multi-user JSON store with role + created_at schema,
  auto-migration of old flat-hash format, first-user → admin bootstrap
- New deeptutor/api/routers/auth.py: require_auth / require_admin
  FastAPI dependencies; public endpoints /login /logout /status
  /register /is_first_user; admin-only /users /users/{u}/role
- deeptutor/api/main.py: Depends(require_auth) applied to all 14
  protected routers
- deeptutor/api/routers/unified_ws.py: cookie-based JWT check before
  ws.accept() when AUTH_ENABLED
- Added bcrypt>=4.0.0 and python-jose[cryptography]>=3.3.0 to
  requirements/server.txt and pyproject.toml extras

Frontend
- web/middleware.ts: route protection; /login and /register are public
- web/lib/api.ts: apiFetch wrapper — credentials:include + 401→login
- web/lib/auth.ts: login/logout/fetchAuthStatus + register() +
  checkIsFirstUser()
- web/lib/admin-api.ts: listUsers / deleteUser / setUserRole
- web/lib/session-api.ts: credentials:include on all fetches;
  expectJson redirects to /login on 401 instead of throwing
- web/app/(auth)/login/page.tsx: auto-redirects to /register when no
  users exist; shows success banner after registration
- web/app/(auth)/register/page.tsx: new registration page with
  first-user admin notice and password confirmation
- web/app/(admin)/admin/users/page.tsx: admin dashboard — user table
  with role toggle and delete; guards against self-demotion/deletion
- AdminLink and LogoutButton hidden when AUTH_ENABLED=false
- .env.example and README.md updated with auth vars and setup guide

Made-with: Cursor
2026-04-17 21:40:28 +04:00

258 lines
8.8 KiB
TypeScript

"use client";
import Image from "next/image";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useState, type ReactNode } from "react";
import {
BookOpen,
Bot,
Brain,
GraduationCap,
MessageSquare,
PanelLeftClose,
PanelLeftOpen,
PenLine,
Plus,
Settings,
type LucideIcon,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import SessionList from "@/components/SessionList";
import { TutorBotRecent } from "@/components/sidebar/TutorBotRecent";
import type { SessionSummary } from "@/lib/session-api";
interface NavEntry {
href: string;
label: string;
icon: LucideIcon;
}
const PRIMARY_NAV: NavEntry[] = [
{ href: "/chat", label: "Chat", icon: MessageSquare },
{ href: "/agents", label: "TutorBot", icon: Bot },
{ href: "/co-writer", label: "Co-Writer", icon: PenLine },
{ href: "/guide", label: "Guided Learning", icon: GraduationCap },
{ href: "/knowledge", label: "Knowledge", icon: BookOpen },
{ href: "/memory", label: "Memory", icon: Brain },
];
const SECONDARY_NAV: NavEntry[] = [
{ href: "/settings", label: "Settings", icon: Settings },
];
const DEFAULT_SESSION_VIEWPORT_CLASS_NAME = "max-h-[112px]";
interface SidebarShellProps {
sessions?: SessionSummary[];
activeSessionId?: string | null;
loadingSessions?: boolean;
showSessions?: boolean;
sessionViewportClassName?: string;
onNewChat?: () => void;
onSelectSession?: (sessionId: string) => void | Promise<void>;
onRenameSession?: (sessionId: string, title: string) => void | Promise<void>;
onDeleteSession?: (sessionId: string) => void | Promise<void>;
footerSlot?: ReactNode;
}
export function SidebarShell({
sessions = [],
activeSessionId = null,
loadingSessions = false,
showSessions = false,
sessionViewportClassName = DEFAULT_SESSION_VIEWPORT_CLASS_NAME,
onNewChat,
onSelectSession,
onRenameSession,
onDeleteSession,
footerSlot,
}: SidebarShellProps) {
const pathname = usePathname();
const router = useRouter();
const { t } = useTranslation();
const [collapsed, setCollapsed] = useState(false);
const handleNewChat = () => {
if (onNewChat) {
onNewChat();
return;
}
router.push("/chat");
};
/* ---- Collapsed state ---- */
if (collapsed) {
return (
<aside className="flex w-[56px] h-screen shrink-0 flex-col items-center bg-[var(--secondary)] py-3 transition-all duration-200">
<button
onClick={() => setCollapsed(false)}
className="mb-4 rounded-md p-1.5 text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"
aria-label={t("Expand sidebar")}
>
<PanelLeftOpen size={15} />
</button>
<button
onClick={handleNewChat}
className="mb-3 rounded-lg p-2 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--background)]/60 hover:text-[var(--foreground)]"
aria-label={t("New Chat")}
>
<Plus size={16} strokeWidth={2} />
</button>
<nav className="flex flex-col items-center gap-px pt-1">
{PRIMARY_NAV.map((item) => {
const active =
item.href === "/"
? pathname === "/"
: pathname.startsWith(item.href);
return (
<div key={item.href} className="flex flex-col items-center">
<Link
href={item.href}
className={`rounded-lg p-2 transition-colors ${
active
? "bg-[var(--background)]/70 text-[var(--foreground)]"
: "text-[var(--muted-foreground)] hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"
}`}
>
<item.icon size={16} strokeWidth={active ? 1.9 : 1.5} />
</Link>
{item.href === "/agents" && <TutorBotRecent collapsed />}
</div>
);
})}
</nav>
<div className="flex-1" />
<div className="flex flex-col items-center gap-px pb-1">
{SECONDARY_NAV.map((item) => {
const active = pathname.startsWith(item.href);
return (
<Link
key={item.href}
href={item.href}
className={`rounded-lg p-2 transition-colors ${
active
? "bg-[var(--background)]/70 text-[var(--foreground)]"
: "text-[var(--muted-foreground)] hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"
}`}
>
<item.icon size={16} strokeWidth={active ? 1.9 : 1.5} />
</Link>
);
})}
{footerSlot && <div className="mt-1">{footerSlot}</div>}
</div>
</aside>
);
}
/* ---- Expanded state ---- */
return (
<aside className="flex w-[220px] h-screen shrink-0 flex-col bg-[var(--secondary)] transition-all duration-200">
{/* Header: logo + collapse toggle */}
<div className="flex h-12 items-center justify-between px-4">
<Link href="/" className="flex items-center gap-2">
<Image src="/logo-ver2.png" alt="DeepTutor" width={20} height={20} />
<span className="text-[15px] font-semibold tracking-tight text-[var(--foreground)]">
DeepTutor
</span>
</Link>
<button
onClick={() => setCollapsed(true)}
className="rounded-md p-1 text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"
aria-label={t("Collapse sidebar")}
>
<PanelLeftClose size={15} />
</button>
</div>
{/* Primary nav */}
<nav className="px-2 pt-1">
<div className="space-y-px">
{/* New chat */}
<button
onClick={handleNewChat}
className="flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-[13.5px] text-[var(--muted-foreground)] transition-colors hover:bg-[var(--background)]/60 hover:text-[var(--foreground)]"
>
<Plus size={16} strokeWidth={2} />
<span>{t("New Chat")}</span>
</button>
{PRIMARY_NAV.map((item) => {
const active =
item.href === "/"
? pathname === "/"
: pathname.startsWith(item.href);
const hasSessionsBelow =
item.href === "/" &&
showSessions &&
onSelectSession &&
onRenameSession &&
onDeleteSession;
const hasBots = item.href === "/agents";
return (
<div key={item.href}>
<Link
href={item.href}
className={`flex items-center gap-2.5 rounded-lg px-3 py-2 text-[13.5px] transition-colors ${
active
? "bg-[var(--background)]/70 font-medium text-[var(--foreground)]"
: "text-[var(--muted-foreground)] hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"
}`}
>
<item.icon size={16} strokeWidth={active ? 1.9 : 1.5} />
<span>{t(item.label)}</span>
</Link>
{hasSessionsBelow && (
<div
className={`${sessionViewportClassName} overflow-y-auto`}
>
<SessionList
sessions={sessions}
activeSessionId={activeSessionId}
loading={loadingSessions}
onSelect={onSelectSession}
onRename={onRenameSession}
onDelete={onDeleteSession}
compact
/>
</div>
)}
{hasBots && <TutorBotRecent />}
</div>
);
})}
</div>
</nav>
{/* Spacer */}
<div className="flex-1" />
{/* Secondary nav + footer */}
<div className="border-t border-[var(--border)]/40 px-2 py-2">
{SECONDARY_NAV.map((item) => {
const active = pathname.startsWith(item.href);
return (
<Link
key={item.href}
href={item.href}
className={`flex items-center gap-2.5 rounded-lg px-3 py-2 text-[13.5px] transition-colors ${
active
? "bg-[var(--background)]/70 font-medium text-[var(--foreground)]"
: "text-[var(--muted-foreground)] hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"
}`}
>
<item.icon size={16} strokeWidth={active ? 1.9 : 1.5} />
<span>{t(item.label)}</span>
</Link>
);
})}
{footerSlot}
</div>
</aside>
);
}