feat: custom password reset flow with 8-char token + Appwrite Messaging
This commit is contained in:
@@ -9,11 +9,11 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
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";
|
||||
|
||||
export function ForgotPasswordForm1({ className, ...props }: React.ComponentProps<"div">) {
|
||||
const [state, formAction, isPending] = useActionState(forgotPasswordAction, initialAuthState);
|
||||
const [state, formAction, isPending] = useActionState(requestPasswordResetAction, initialAuthState);
|
||||
|
||||
return (
|
||||
<div className={cn("flex flex-col gap-6", className)} {...props}>
|
||||
@@ -31,7 +31,7 @@ export function ForgotPasswordForm1({ className, ...props }: React.ComponentProp
|
||||
<MailCheck className="size-6" />
|
||||
</div>
|
||||
<p className="text-sm">
|
||||
Bağlantı emailinize gönderildi. Gelen kutusunu kontrol edin.
|
||||
Sıfırlama kodunuz e-posta adresinize gönderildi. Kodu girerek şifrenizi yenileyebilirsiniz.
|
||||
</p>
|
||||
<Link
|
||||
href="/sign-in"
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useActionState } from "react";
|
||||
import { ArrowLeft, Loader2, ShieldCheck } from "lucide-react";
|
||||
|
||||
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 ? (
|
||||
<>
|
||||
<Loader2 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 "lucide-react";
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -6,15 +6,20 @@ import { getCurrentUser } from "@/lib/appwrite/server";
|
||||
export default async function Page({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ invite?: string }>;
|
||||
searchParams: Promise<{ invite?: string; reset?: string }>;
|
||||
}) {
|
||||
const { invite } = await searchParams;
|
||||
const { invite, reset } = await searchParams;
|
||||
const user = await getCurrentUser();
|
||||
if (user) redirect(invite ? `/d/${invite}` : "/dashboard");
|
||||
|
||||
return (
|
||||
<div className="bg-muted flex min-h-svh flex-col items-center justify-center p-6 md:p-10">
|
||||
<div className="w-full max-w-sm md:max-w-4xl">
|
||||
{reset === "success" && (
|
||||
<p className="mb-4 rounded-lg bg-green-50 px-4 py-3 text-center text-sm text-green-700">
|
||||
Şifreniz güncellendi. Giriş yapabilirsiniz.
|
||||
</p>
|
||||
)}
|
||||
<LoginForm1 inviteCode={invite} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
"use server";
|
||||
|
||||
import { createHash, randomBytes } from "crypto";
|
||||
import { ID, Query } from "node-appwrite";
|
||||
import { cookies } from "next/headers";
|
||||
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;
|
||||
const RESET_SESSION_COOKIE = "pw_reset";
|
||||
|
||||
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 { $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(),
|
||||
});
|
||||
|
||||
(await cookies()).delete(RESET_SESSION_COOKIE);
|
||||
} catch {
|
||||
return { ok: false, error: "Şifre güncellenemedi. Tekrar deneyin." };
|
||||
}
|
||||
|
||||
redirect("/sign-in?reset=success");
|
||||
}
|
||||
@@ -26,6 +26,7 @@ export const TABLES = {
|
||||
savedCards: "saved_cards",
|
||||
leads: "leads",
|
||||
leadActivities: "lead_activities",
|
||||
passwordResets: "password_resets",
|
||||
} as const;
|
||||
|
||||
export type TableId = (typeof TABLES)[keyof typeof TABLES];
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
Account,
|
||||
Client,
|
||||
Databases,
|
||||
Messaging,
|
||||
Storage,
|
||||
TablesDB,
|
||||
Teams,
|
||||
@@ -40,6 +41,7 @@ export function createAdminClient() {
|
||||
databases: new Databases(client),
|
||||
tablesDB: new TablesDB(client),
|
||||
storage: new Storage(client),
|
||||
messaging: new Messaging(client),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user