auth: login pill toggle for clinic/lab + server-side kind validation
Sign-in form now has a Klinik / Laboratuvar pill toggle (defaults to clinic). The selected kind is posted alongside email+password; the server action resolves the user's memberships, picks a tenant_settings row matching the chosen kind, and sets it as active. If no matching tenant exists the session is rolled back with a clear error. Invite-flow logins skip the kind check — invite code drives team assignment.
This commit is contained in:
@@ -1,8 +1,8 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useActionState } from "react";
|
import { useActionState, useState } from "react";
|
||||||
import { Loader2 } from "lucide-react";
|
import { FlaskConical, Loader2, Stethoscope } from "lucide-react";
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Card, CardContent } from "@/components/ui/card";
|
import { Card, CardContent } from "@/components/ui/card";
|
||||||
@@ -13,11 +13,14 @@ import { cn } from "@/lib/utils";
|
|||||||
import { signInAction } from "@/lib/appwrite/auth-actions";
|
import { signInAction } from "@/lib/appwrite/auth-actions";
|
||||||
import { initialAuthState } from "@/lib/appwrite/auth-types";
|
import { initialAuthState } from "@/lib/appwrite/auth-types";
|
||||||
|
|
||||||
|
type Kind = "clinic" | "lab";
|
||||||
|
|
||||||
export function LoginForm1({
|
export function LoginForm1({
|
||||||
className,
|
className,
|
||||||
inviteCode,
|
inviteCode,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<"div"> & { inviteCode?: string }) {
|
}: React.ComponentProps<"div"> & { inviteCode?: string }) {
|
||||||
|
const [kind, setKind] = useState<Kind>("clinic");
|
||||||
const [state, formAction, isPending] = useActionState(signInAction, initialAuthState);
|
const [state, formAction, isPending] = useActionState(signInAction, initialAuthState);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -26,6 +29,7 @@ export function LoginForm1({
|
|||||||
<CardContent className="grid p-0 md:grid-cols-2">
|
<CardContent className="grid p-0 md:grid-cols-2">
|
||||||
<form action={formAction} className="p-6 md:p-10">
|
<form action={formAction} className="p-6 md:p-10">
|
||||||
{inviteCode && <input type="hidden" name="inviteCode" value={inviteCode} />}
|
{inviteCode && <input type="hidden" name="inviteCode" value={inviteCode} />}
|
||||||
|
<input type="hidden" name="kind" value={kind} />
|
||||||
<div className="flex flex-col gap-6">
|
<div className="flex flex-col gap-6">
|
||||||
<div className="flex justify-center">
|
<div className="flex justify-center">
|
||||||
<Link href="/" className="flex items-center gap-2 font-medium">
|
<Link href="/" className="flex items-center gap-2 font-medium">
|
||||||
@@ -45,10 +49,14 @@ export function LoginForm1({
|
|||||||
<div className="flex flex-col items-center text-center">
|
<div className="flex flex-col items-center text-center">
|
||||||
<h1 className="text-2xl font-bold tracking-tight">Tekrar hoş geldiniz</h1>
|
<h1 className="text-2xl font-bold tracking-tight">Tekrar hoş geldiniz</h1>
|
||||||
<p className="text-muted-foreground text-sm text-balance mt-1">
|
<p className="text-muted-foreground text-sm text-balance mt-1">
|
||||||
Hesabınıza giriş yaparak işletmenizi yönetmeye devam edin
|
Hesabınıza giriş yapın
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{!inviteCode && (
|
||||||
|
<KindPill value={kind} onChange={setKind} disabled={isPending} />
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="grid gap-3">
|
<div className="grid gap-3">
|
||||||
<Label htmlFor="email">Email</Label>
|
<Label htmlFor="email">Email</Label>
|
||||||
<Input
|
<Input
|
||||||
@@ -128,6 +136,72 @@ export function LoginForm1({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function KindPill({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
disabled,
|
||||||
|
}: {
|
||||||
|
value: Kind;
|
||||||
|
onChange: (next: Kind) => void;
|
||||||
|
disabled?: boolean;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="radiogroup"
|
||||||
|
aria-label="Hesap türü"
|
||||||
|
className="bg-muted text-muted-foreground inline-flex w-full items-center gap-1 rounded-full border p-1"
|
||||||
|
>
|
||||||
|
<PillButton
|
||||||
|
active={value === "clinic"}
|
||||||
|
onClick={() => onChange("clinic")}
|
||||||
|
disabled={disabled}
|
||||||
|
>
|
||||||
|
<Stethoscope className="size-4" />
|
||||||
|
Klinik
|
||||||
|
</PillButton>
|
||||||
|
<PillButton
|
||||||
|
active={value === "lab"}
|
||||||
|
onClick={() => onChange("lab")}
|
||||||
|
disabled={disabled}
|
||||||
|
>
|
||||||
|
<FlaskConical className="size-4" />
|
||||||
|
Laboratuvar
|
||||||
|
</PillButton>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function PillButton({
|
||||||
|
active,
|
||||||
|
onClick,
|
||||||
|
disabled,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
active: boolean;
|
||||||
|
onClick: () => void;
|
||||||
|
disabled?: boolean;
|
||||||
|
children: React.ReactNode;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="radio"
|
||||||
|
aria-checked={active}
|
||||||
|
onClick={onClick}
|
||||||
|
disabled={disabled}
|
||||||
|
className={cn(
|
||||||
|
"flex flex-1 items-center justify-center gap-1.5 rounded-full px-3 py-1.5 text-sm font-medium transition-colors",
|
||||||
|
active
|
||||||
|
? "bg-background text-foreground shadow-sm"
|
||||||
|
: "hover:text-foreground",
|
||||||
|
disabled && "cursor-not-allowed opacity-60",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function BrandPanel() {
|
function BrandPanel() {
|
||||||
return (
|
return (
|
||||||
<div className="bg-primary text-primary-foreground relative hidden md:flex md:flex-col md:justify-between overflow-hidden p-10">
|
<div className="bg-primary text-primary-foreground relative hidden md:flex md:flex-col md:justify-between overflow-hidden p-10">
|
||||||
@@ -157,10 +231,10 @@ function BrandPanel() {
|
|||||||
|
|
||||||
<div className="relative z-10 flex flex-col gap-3">
|
<div className="relative z-10 flex flex-col gap-3">
|
||||||
<h2 className="text-3xl font-semibold leading-tight">
|
<h2 className="text-3xl font-semibold leading-tight">
|
||||||
Müşteriden faturaya, tek panelden işletmenizi yönetin.
|
Klinik ve laboratuvar tek panelde.
|
||||||
</h2>
|
</h2>
|
||||||
<p className="text-primary-foreground/80 text-sm">
|
<p className="text-primary-foreground/80 text-sm">
|
||||||
Müşteriler, hizmetler, takvim, görevler ve finans — hepsi tek yerde, multi-tenant ve ekibinize özel.
|
İş yayınla, taranan dosyaları paylaş, protez aşamalarını adım adım takip et — finansal akışla birlikte.
|
||||||
</p>
|
</p>
|
||||||
<div className="text-primary-foreground/70 mt-4 text-xs">Kovak Yazılım tarafından</div>
|
<div className="text-primary-foreground/70 mt-4 text-xs">Kovak Yazılım tarafından</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -2,9 +2,11 @@
|
|||||||
|
|
||||||
import { cookies } from "next/headers";
|
import { cookies } from "next/headers";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { AppwriteException, ID } from "node-appwrite";
|
import { AppwriteException, ID, Query } from "node-appwrite";
|
||||||
|
|
||||||
import { APPWRITE_SESSION_COOKIE, createAdminClient, createSessionClient } from "./server";
|
import { APPWRITE_SESSION_COOKIE, createAdminClient, createSessionClient } from "./server";
|
||||||
|
import { DATABASE_ID, TABLES, type TenantKind, type TenantSettings } from "./schema";
|
||||||
|
import { ACTIVE_TENANT_COOKIE } from "./tenant-types";
|
||||||
import type { AuthState } from "./auth-types";
|
import type { AuthState } from "./auth-types";
|
||||||
|
|
||||||
function appwriteError(e: unknown): string {
|
function appwriteError(e: unknown): string {
|
||||||
@@ -38,23 +40,90 @@ async function setSessionCookie(secret: string, expire: string) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function setActiveTenantCookie(tenantId: string) {
|
||||||
|
(await cookies()).set(ACTIVE_TENANT_COOKIE, tenantId, {
|
||||||
|
path: "/",
|
||||||
|
httpOnly: true,
|
||||||
|
sameSite: "strict",
|
||||||
|
secure: process.env.NODE_ENV === "production",
|
||||||
|
maxAge: 60 * 60 * 24 * 365,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pickTenantIdByKind(userId: string, kind: TenantKind): Promise<string | null> {
|
||||||
|
const { users, tablesDB } = createAdminClient();
|
||||||
|
const memberships = await users.listMemberships(userId);
|
||||||
|
const teamIds = memberships.memberships.map((m) => m.teamId);
|
||||||
|
if (teamIds.length === 0) return null;
|
||||||
|
|
||||||
|
const result = await tablesDB.listRows({
|
||||||
|
databaseId: DATABASE_ID,
|
||||||
|
tableId: TABLES.tenantSettings,
|
||||||
|
queries: [
|
||||||
|
Query.equal("tenantId", teamIds),
|
||||||
|
Query.equal("kind", kind),
|
||||||
|
Query.limit(1),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const row = result.rows[0] as unknown as TenantSettings | undefined;
|
||||||
|
return row?.tenantId ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
export async function signInAction(_prev: AuthState, formData: FormData): Promise<AuthState> {
|
export async function signInAction(_prev: AuthState, formData: FormData): Promise<AuthState> {
|
||||||
const email = String(formData.get("email") ?? "").trim();
|
const email = String(formData.get("email") ?? "").trim();
|
||||||
const password = String(formData.get("password") ?? "");
|
const password = String(formData.get("password") ?? "");
|
||||||
const inviteCode = String(formData.get("inviteCode") ?? "").trim();
|
const inviteCode = String(formData.get("inviteCode") ?? "").trim();
|
||||||
|
const rawKind = String(formData.get("kind") ?? "").trim();
|
||||||
|
const kind: TenantKind | null =
|
||||||
|
rawKind === "lab" || rawKind === "clinic" ? rawKind : null;
|
||||||
|
|
||||||
if (!email || !password) {
|
if (!email || !password) {
|
||||||
return { ok: false, error: "Email ve şifre zorunlu." };
|
return { ok: false, error: "Email ve şifre zorunlu." };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let sessionUserId: string | null = null;
|
||||||
|
let sessionId: string | null = null;
|
||||||
try {
|
try {
|
||||||
const { account } = createAdminClient();
|
const { account } = createAdminClient();
|
||||||
const session = await account.createEmailPasswordSession(email, password);
|
const session = await account.createEmailPasswordSession(email, password);
|
||||||
|
sessionUserId = session.userId;
|
||||||
|
sessionId = session.$id;
|
||||||
await setSessionCookie(session.secret, session.expire);
|
await setSessionCookie(session.secret, session.expire);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return { ok: false, error: appwriteError(e) };
|
return { ok: false, error: appwriteError(e) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Invite flow short-circuits the kind check — invite code drives team membership
|
||||||
|
if (!inviteCode && kind && sessionUserId) {
|
||||||
|
const matchedTenantId = await pickTenantIdByKind(sessionUserId, kind);
|
||||||
|
if (!matchedTenantId) {
|
||||||
|
// Roll back session: user has no tenant of the requested kind
|
||||||
|
try {
|
||||||
|
const { users } = createAdminClient();
|
||||||
|
if (sessionId) await users.deleteSession(sessionUserId, sessionId);
|
||||||
|
} catch {
|
||||||
|
/* best-effort */
|
||||||
|
}
|
||||||
|
(await cookies()).delete(APPWRITE_SESSION_COOKIE);
|
||||||
|
const label = kind === "lab" ? "laboratuvar" : "klinik";
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
error: `Bu hesap için ${label} kaydı bulunamadı. Diğer hesap türünü seçin veya yeni çalışma alanı oluşturun.`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
await setActiveTenantCookie(matchedTenantId);
|
||||||
|
try {
|
||||||
|
const { users } = createAdminClient();
|
||||||
|
const user = await users.get(sessionUserId);
|
||||||
|
await users.updatePrefs(sessionUserId, {
|
||||||
|
...(user.prefs ?? {}),
|
||||||
|
activeTenant: matchedTenantId,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
/* best-effort */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
redirect(inviteCode ? `/d/${inviteCode}` : "/dashboard");
|
redirect(inviteCode ? `/d/${inviteCode}` : "/dashboard");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user