feat: custom password reset flow (token-based, Appwrite Messaging)
- db: new password_resets table (email, userId, tokenHash, expiresAt, usedAt) - lib: password-reset-actions.ts — requestPasswordResetAction, verifyResetToken, resetPasswordAction - lib: Messaging added to createAdminClient - page: /reset-password — validates token server-side, shows form or error card - page: /forgot-password — now uses requestPasswordResetAction (custom flow) - page: /sign-in — shows success banner after ?reset=success redirect
This commit is contained in:
@@ -9,11 +9,11 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
|
|||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { forgotPasswordAction } from "@/lib/appwrite/auth-actions";
|
import { requestPasswordResetAction } from "@/lib/appwrite/password-reset-actions";
|
||||||
import { initialAuthState } from "@/lib/appwrite/auth-types";
|
import { initialAuthState } from "@/lib/appwrite/auth-types";
|
||||||
|
|
||||||
export function ForgotPasswordForm1({ className, ...props }: React.ComponentProps<"div">) {
|
export function ForgotPasswordForm1({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
const [state, formAction, isPending] = useActionState(forgotPasswordAction, initialAuthState);
|
const [state, formAction, isPending] = useActionState(requestPasswordResetAction, initialAuthState);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={cn("flex flex-col gap-6", className)} {...props}>
|
<div className={cn("flex flex-col gap-6", className)} {...props}>
|
||||||
|
|||||||
@@ -0,0 +1,93 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useActionState } from "react";
|
||||||
|
import { ArrowLeft, CircleNotch, ShieldCheck } from "@/lib/icons";
|
||||||
|
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { resetPasswordAction } from "@/lib/appwrite/password-reset-actions";
|
||||||
|
import { initialAuthState } from "@/lib/appwrite/auth-types";
|
||||||
|
|
||||||
|
interface Props extends React.ComponentProps<"div"> {
|
||||||
|
token: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ResetPasswordForm({ token, className, ...props }: Props) {
|
||||||
|
const [state, formAction, isPending] = useActionState(resetPasswordAction, initialAuthState);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={cn("flex flex-col gap-6", className)} {...props}>
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="text-center">
|
||||||
|
<div className="bg-primary/10 text-primary mx-auto mb-2 flex size-12 items-center justify-center rounded-full">
|
||||||
|
<ShieldCheck className="size-6" />
|
||||||
|
</div>
|
||||||
|
<CardTitle className="text-xl">Yeni şifre belirle</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Kod doğrulandı. Yeni şifrenizi girin.
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<form action={formAction} className="flex flex-col gap-4">
|
||||||
|
<input type="hidden" name="token" value={token} />
|
||||||
|
|
||||||
|
<div className="grid gap-3">
|
||||||
|
<Label htmlFor="password">Yeni şifre</Label>
|
||||||
|
<Input
|
||||||
|
id="password"
|
||||||
|
name="password"
|
||||||
|
type="password"
|
||||||
|
placeholder="En az 8 karakter"
|
||||||
|
autoComplete="new-password"
|
||||||
|
required
|
||||||
|
minLength={8}
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-3">
|
||||||
|
<Label htmlFor="confirmPassword">Şifre tekrar</Label>
|
||||||
|
<Input
|
||||||
|
id="confirmPassword"
|
||||||
|
name="confirmPassword"
|
||||||
|
type="password"
|
||||||
|
placeholder="Şifreyi tekrar girin"
|
||||||
|
autoComplete="new-password"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{state.error && (
|
||||||
|
<p className="text-destructive text-center text-sm" role="alert">
|
||||||
|
{state.error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Button type="submit" className="w-full" disabled={isPending}>
|
||||||
|
{isPending ? (
|
||||||
|
<>
|
||||||
|
<CircleNotch className="size-4 animate-spin" />
|
||||||
|
Güncelleniyor...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
"Şifreyi güncelle"
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Link
|
||||||
|
href="/sign-in"
|
||||||
|
className="text-muted-foreground hover:text-foreground flex items-center justify-center gap-1 text-sm underline-offset-4 hover:underline"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="size-3.5" />
|
||||||
|
Giriş sayfasına dön
|
||||||
|
</Link>
|
||||||
|
</form>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import { XCircle } from "@/lib/icons";
|
||||||
|
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { verifyResetToken } from "@/lib/appwrite/password-reset-actions";
|
||||||
|
import { ResetPasswordForm } from "./components/reset-password-form";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
searchParams: Promise<{ token?: string }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function ResetPasswordPage({ searchParams }: Props) {
|
||||||
|
const { token } = await searchParams;
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
return <InvalidToken message="Geçersiz bağlantı. Yeni bir sıfırlama kodu talep edin." />;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { valid } = await verifyResetToken(token);
|
||||||
|
|
||||||
|
if (!valid) {
|
||||||
|
return <InvalidToken message="Bu kod geçersiz veya süresi dolmuş. Yeni bir sıfırlama kodu talep edin." />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-svh items-center justify-center p-6">
|
||||||
|
<div className="w-full max-w-sm">
|
||||||
|
<ResetPasswordForm token={token} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function InvalidToken({ message }: { message: string }) {
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-svh items-center justify-center p-6">
|
||||||
|
<div className="w-full max-w-sm">
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="text-center">
|
||||||
|
<div className="text-destructive mx-auto mb-2 flex size-12 items-center justify-center rounded-full bg-red-50">
|
||||||
|
<XCircle className="size-6" />
|
||||||
|
</div>
|
||||||
|
<CardTitle className="text-xl">Geçersiz kod</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="flex flex-col items-center gap-4 text-center">
|
||||||
|
<p className="text-muted-foreground text-sm">{message}</p>
|
||||||
|
<Link
|
||||||
|
href="/forgot-password"
|
||||||
|
className="text-primary text-sm underline underline-offset-4"
|
||||||
|
>
|
||||||
|
Yeni kod talep et
|
||||||
|
</Link>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -14,8 +14,9 @@ import { initialAuthState } from "@/lib/appwrite/auth-types";
|
|||||||
export function LoginForm1({
|
export function LoginForm1({
|
||||||
className,
|
className,
|
||||||
inviteCode,
|
inviteCode,
|
||||||
|
passwordReset,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<"div"> & { inviteCode?: string }) {
|
}: React.ComponentProps<"div"> & { inviteCode?: string; passwordReset?: boolean }) {
|
||||||
const [state, formAction, isPending] = useActionState(signInAction, initialAuthState);
|
const [state, formAction, isPending] = useActionState(signInAction, initialAuthState);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -123,6 +124,12 @@ export function LoginForm1({
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{passwordReset && (
|
||||||
|
<p className="rounded-md border bg-green-50 px-3 py-2 text-center text-xs text-green-700 dark:bg-green-950 dark:text-green-300">
|
||||||
|
Şifreniz güncellendi. Yeni şifrenizle giriş yapabilirsiniz.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
{inviteCode && (
|
{inviteCode && (
|
||||||
<p className="rounded-md border bg-blue-50 px-3 py-2 text-center text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300">
|
<p className="rounded-md border bg-blue-50 px-3 py-2 text-center text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300">
|
||||||
Davete katılmak için giriş yapın.
|
Davete katılmak için giriş yapın.
|
||||||
|
|||||||
@@ -6,11 +6,11 @@ import { getCurrentUser } from "@/lib/appwrite/server";
|
|||||||
export default async function Page({
|
export default async function Page({
|
||||||
searchParams,
|
searchParams,
|
||||||
}: {
|
}: {
|
||||||
searchParams: Promise<{ invite?: string }>;
|
searchParams: Promise<{ invite?: string; reset?: string }>;
|
||||||
}) {
|
}) {
|
||||||
const { invite } = await searchParams;
|
const { invite, reset } = await searchParams;
|
||||||
const user = await getCurrentUser();
|
const user = await getCurrentUser();
|
||||||
if (user) redirect(invite ? `/d/${invite}` : "/dashboard");
|
if (user) redirect(invite ? `/d/${invite}` : "/dashboard");
|
||||||
|
|
||||||
return <LoginForm1 inviteCode={invite} />;
|
return <LoginForm1 inviteCode={invite} passwordReset={reset === "success"} />;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,131 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { createHash, randomBytes } from "crypto";
|
||||||
|
import { ID, Query } from "node-appwrite";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
|
import { createAdminClient } from "./server";
|
||||||
|
import { DATABASE_ID, TABLES } from "./schema";
|
||||||
|
import type { AuthState } from "./auth-types";
|
||||||
|
|
||||||
|
const TOKEN_EXPIRY_MS = 15 * 60 * 1000;
|
||||||
|
|
||||||
|
function generateToken(): { plain: string; hash: string } {
|
||||||
|
const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
||||||
|
const bytes = randomBytes(8);
|
||||||
|
const plain = Array.from(bytes)
|
||||||
|
.map((b) => chars[b % chars.length])
|
||||||
|
.join("");
|
||||||
|
const hash = createHash("sha256").update(plain).digest("hex");
|
||||||
|
return { plain, hash };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function requestPasswordResetAction(
|
||||||
|
_prev: AuthState,
|
||||||
|
formData: FormData,
|
||||||
|
): Promise<AuthState> {
|
||||||
|
const email = String(formData.get("email") ?? "").trim().toLowerCase();
|
||||||
|
if (!email) return { ok: false, error: "Email zorunlu." };
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { tablesDB, users, messaging } = createAdminClient();
|
||||||
|
|
||||||
|
const found = await users.list([Query.equal("email", email), Query.limit(1)]);
|
||||||
|
// Kullanıcı yoksa hata vermiyoruz — timing attack önlemi
|
||||||
|
if (found.total === 0) return { ok: true };
|
||||||
|
|
||||||
|
const user = found.users[0];
|
||||||
|
const { plain, hash } = generateToken();
|
||||||
|
const expiresAt = new Date(Date.now() + TOKEN_EXPIRY_MS).toISOString();
|
||||||
|
|
||||||
|
await tablesDB.createRow(DATABASE_ID, TABLES.passwordResets, ID.unique(), {
|
||||||
|
email,
|
||||||
|
userId: user.$id,
|
||||||
|
tokenHash: hash,
|
||||||
|
expiresAt,
|
||||||
|
});
|
||||||
|
|
||||||
|
const appUrl = process.env.APP_URL?.replace(/\/$/, "") ?? "http://localhost:3000";
|
||||||
|
const resetLink = `${appUrl}/reset-password?token=${plain}`;
|
||||||
|
|
||||||
|
await messaging.createEmail(
|
||||||
|
ID.unique(),
|
||||||
|
"Şifre Sıfırlama Kodunuz",
|
||||||
|
`<p>Merhaba,</p>
|
||||||
|
<p>Şifre sıfırlama talebiniz alındı. Aşağıdaki kodu kullanın:</p>
|
||||||
|
<h2 style="letter-spacing:6px;font-size:32px;">${plain}</h2>
|
||||||
|
<p>Veya doğrudan linke tıklayın:</p>
|
||||||
|
<p><a href="${resetLink}">${resetLink}</a></p>
|
||||||
|
<p style="color:#888;font-size:12px;">Bu kod 15 dakika geçerlidir. Bu talebi siz yapmadıysanız bu e-postayı dikkate almayın.</p>`,
|
||||||
|
[],
|
||||||
|
[user.$id],
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
return { ok: true };
|
||||||
|
} catch {
|
||||||
|
return { ok: false, error: "Bir hata oluştu. Tekrar deneyin." };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function verifyResetToken(
|
||||||
|
token: string,
|
||||||
|
): Promise<{ valid: boolean; tokenId?: string; userId?: string }> {
|
||||||
|
if (!token) return { valid: false };
|
||||||
|
|
||||||
|
try {
|
||||||
|
const hash = createHash("sha256").update(token.toUpperCase().trim()).digest("hex");
|
||||||
|
const { tablesDB } = createAdminClient();
|
||||||
|
|
||||||
|
const result = await tablesDB.listRows({
|
||||||
|
databaseId: DATABASE_ID,
|
||||||
|
tableId: TABLES.passwordResets,
|
||||||
|
queries: [
|
||||||
|
Query.equal("tokenHash", hash),
|
||||||
|
Query.greaterThan("expiresAt", new Date().toISOString()),
|
||||||
|
Query.limit(1),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.total === 0) return { valid: false };
|
||||||
|
|
||||||
|
const row = result.rows[0] as unknown as { $id: string; userId: string; usedAt?: string };
|
||||||
|
if (row.usedAt) return { valid: false };
|
||||||
|
|
||||||
|
return { valid: true, tokenId: row.$id, userId: row.userId };
|
||||||
|
} catch {
|
||||||
|
return { valid: false };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function resetPasswordAction(
|
||||||
|
_prev: AuthState,
|
||||||
|
formData: FormData,
|
||||||
|
): Promise<AuthState> {
|
||||||
|
const token = String(formData.get("token") ?? "").trim();
|
||||||
|
const password = String(formData.get("password") ?? "");
|
||||||
|
const confirmPassword = String(formData.get("confirmPassword") ?? "");
|
||||||
|
|
||||||
|
if (!token || !password) return { ok: false, error: "Tüm alanlar zorunlu." };
|
||||||
|
if (password.length < 8) return { ok: false, error: "Şifre en az 8 karakter olmalı." };
|
||||||
|
if (password !== confirmPassword) return { ok: false, error: "Şifreler eşleşmiyor." };
|
||||||
|
|
||||||
|
const { valid, tokenId, userId } = await verifyResetToken(token);
|
||||||
|
if (!valid || !tokenId || !userId) {
|
||||||
|
return { ok: false, error: "Kod geçersiz veya süresi dolmuş." };
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { tablesDB, users } = createAdminClient();
|
||||||
|
|
||||||
|
await users.updatePassword(userId, password);
|
||||||
|
|
||||||
|
await tablesDB.updateRow(DATABASE_ID, TABLES.passwordResets, tokenId, {
|
||||||
|
usedAt: new Date().toISOString(),
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
return { ok: false, error: "Şifre güncellenemedi. Tekrar deneyin." };
|
||||||
|
}
|
||||||
|
|
||||||
|
redirect("/sign-in?reset=success");
|
||||||
|
}
|
||||||
@@ -16,6 +16,7 @@ export const TABLES = {
|
|||||||
tenantSettings: "tenant_settings",
|
tenantSettings: "tenant_settings",
|
||||||
inviteLinks: "invite_links",
|
inviteLinks: "invite_links",
|
||||||
deals: "deals",
|
deals: "deals",
|
||||||
|
passwordResets: "password_resets",
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
export type TableId = (typeof TABLES)[keyof typeof TABLES];
|
export type TableId = (typeof TABLES)[keyof typeof TABLES];
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
Account,
|
Account,
|
||||||
Client,
|
Client,
|
||||||
Databases,
|
Databases,
|
||||||
|
Messaging,
|
||||||
Storage,
|
Storage,
|
||||||
TablesDB,
|
TablesDB,
|
||||||
Teams,
|
Teams,
|
||||||
@@ -38,6 +39,7 @@ export function createAdminClient() {
|
|||||||
databases: new Databases(client),
|
databases: new Databases(client),
|
||||||
tablesDB: new TablesDB(client),
|
tablesDB: new TablesDB(client),
|
||||||
storage: new Storage(client),
|
storage: new Storage(client),
|
||||||
|
messaging: new Messaging(client),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user