feat(auth): implement guest login api route and UI integration
This commit is contained in:
parent
580afe8978
commit
1d56f9ef1f
4 changed files with 136 additions and 11 deletions
|
|
@ -23,6 +23,7 @@ A modern, high-performance real-time chat application, designed for seamless com
|
||||||
The project uses Next.js Route Groups without a `src/` directory to maintain a clean root layout:
|
The project uses Next.js Route Groups without a `src/` directory to maintain a clean root layout:
|
||||||
|
|
||||||
- `app/(app)/` — Application routes (Layout, Home, Components)
|
- `app/(app)/` — Application routes (Layout, Home, Components)
|
||||||
|
- `app/(auth)/` — Public authentication routes (Login, Register)
|
||||||
- `app/api/` — Backend API endpoints & Auth handlers (`[...nextauth]`)
|
- `app/api/` — Backend API endpoints & Auth handlers (`[...nextauth]`)
|
||||||
- `components/` — Modular UI components (Chat, Navigation, Sidebars)
|
- `components/` — Modular UI components (Chat, Navigation, Sidebars)
|
||||||
- `db/` — Database schema definitions, migrations, and Drizzle configuration (`drizzle.config.ts`)
|
- `db/` — Database schema definitions, migrations, and Drizzle configuration (`drizzle.config.ts`)
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ import { useState } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import { loginUser } from "@/lib/services/auth.service";
|
import { loginAsGuest, loginUser } from "@/lib/services/auth.service";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Renders the user login interface and manages authentication form state.
|
* Renders the user login interface and manages authentication form state.
|
||||||
|
|
@ -19,7 +19,9 @@ import { loginUser } from "@/lib/services/auth.service";
|
||||||
export default function LoginPage() {
|
export default function LoginPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loadingType, setLoadingType] = useState<
|
||||||
|
"credentials" | "guest" | null
|
||||||
|
>(null);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Form submit handler extracting credentials from FormData and delegating to handleSignIn.
|
* Form submit handler extracting credentials from FormData and delegating to handleSignIn.
|
||||||
|
|
@ -31,29 +33,51 @@ export default function LoginPage() {
|
||||||
const formData = new FormData(e.currentTarget);
|
const formData = new FormData(e.currentTarget);
|
||||||
const email = formData.get("email") as string;
|
const email = formData.get("email") as string;
|
||||||
const password = formData.get("password") as string;
|
const password = formData.get("password") as string;
|
||||||
await handleSignIn(email, password);
|
await handleSignIn(email, password, "credentials");
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Authenticates the user with provided credentials and redirects upon success.
|
* Authenticates the user with provided credentials and redirects upon success.
|
||||||
*
|
*
|
||||||
* @param {string} email - The user's email address.
|
|
||||||
* @param {string} password - The user's password.
|
|
||||||
*/
|
*/
|
||||||
const handleSignIn = async (email: string, password: string) => {
|
const handleSignIn = async (
|
||||||
|
email: string,
|
||||||
|
password: string,
|
||||||
|
type: "credentials" | "guest",
|
||||||
|
) => {
|
||||||
setError(null);
|
setError(null);
|
||||||
setLoading(true);
|
setLoadingType(type);
|
||||||
|
|
||||||
const result = await loginUser(email, password);
|
const result = await loginUser(email, password);
|
||||||
|
|
||||||
if (result.error) {
|
if (result.error) {
|
||||||
setError(result.error);
|
setError(result.error);
|
||||||
setLoading(false);
|
setLoadingType(null);
|
||||||
} else {
|
} else {
|
||||||
router.push("/");
|
router.push("/");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Triggers secure guest authentication via the backend service.
|
||||||
|
*
|
||||||
|
* @async
|
||||||
|
*/
|
||||||
|
const handleGuestLogin = async () => {
|
||||||
|
setError(null);
|
||||||
|
setLoadingType("guest");
|
||||||
|
|
||||||
|
const result = await loginAsGuest();
|
||||||
|
|
||||||
|
if (result.error) {
|
||||||
|
setError(result.error);
|
||||||
|
setLoadingType(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
router.push("/");
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen w-full flex items-center justify-center bg-background p-4">
|
<div className="min-h-screen w-full flex items-center justify-center bg-background p-4">
|
||||||
<div className="w-full max-w-md bg-[hsl(200_6%_8%)] border border-neutral-800 rounded-xl p-8 shadow-2xl">
|
<div className="w-full max-w-md bg-[hsl(200_6%_8%)] border border-neutral-800 rounded-xl p-8 shadow-2xl">
|
||||||
|
|
@ -121,13 +145,30 @@ export default function LoginPage() {
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={loading}
|
disabled={loadingType !== null}
|
||||||
className="w-full bg-accent hover:opacity-90 transition-opacity text-white font-medium py-2.5 rounded-lg text-sm disabled:opacity-50 mt-2 cursor-pointer"
|
className="w-full bg-accent hover:opacity-90 transition-opacity text-white font-medium py-2.5 rounded-lg text-sm disabled:opacity-50 mt-2 cursor-pointer"
|
||||||
>
|
>
|
||||||
{loading ? "Sign In..." : "Sign In"}
|
{loadingType === "credentials" ? "Signing in..." : "Sign In"}{" "}
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
|
<div className="relative flex items-center pt-4 pb-2">
|
||||||
|
<div className="grow border-t border-neutral-800"></div>
|
||||||
|
<span className="shrink mx-4 text-xs text-muted uppercase">or</span>
|
||||||
|
<div className="grow border-t border-neutral-800"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={loadingType !== null}
|
||||||
|
onClick={handleGuestLogin}
|
||||||
|
className="w-full bg-transparent hover:bg-accent/10 text-accent border border-accent/40 hover:border-accent transition-all font-medium py-2.5 rounded-lg text-sm disabled:opacity-50 mt-2 cursor-pointer"
|
||||||
|
>
|
||||||
|
{loadingType === "guest"
|
||||||
|
? "Signing in as Guest..."
|
||||||
|
: "Sign in as Guest"}
|
||||||
|
</button>
|
||||||
|
|
||||||
{/* Footer Link */}
|
{/* Footer Link */}
|
||||||
<p className="text-xs text-neutral-400 text-center mt-6">
|
<p className="text-xs text-neutral-400 text-center mt-6">
|
||||||
Don't have an account yet?{" "}
|
Don't have an account yet?{" "}
|
||||||
|
|
|
||||||
58
app/api/auth/guest/route.ts
Normal file
58
app/api/auth/guest/route.ts
Normal file
|
|
@ -0,0 +1,58 @@
|
||||||
|
/**
|
||||||
|
* @file app/api/auth/guest/route.ts
|
||||||
|
* @description API route handler for guest authentication utilizing server-side environment variables and auto sign-in.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { signIn } from "@/auth";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles POST requests to authenticate as a guest user using environment credentials.
|
||||||
|
*
|
||||||
|
* @async
|
||||||
|
* @returns {Promise<NextResponse>} A JSON response confirming successful guest sign-in or an error message.
|
||||||
|
*/
|
||||||
|
export async function POST() {
|
||||||
|
const email = process.env.GUEST_EMAIL;
|
||||||
|
const password = process.env.GUEST_PASSWORD;
|
||||||
|
|
||||||
|
if (!email || !password) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Guest login is not configured on the server." },
|
||||||
|
{ status: 500 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await signIn("credentials", {
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
redirect: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ success: true }, { status: 200 });
|
||||||
|
} catch (error: any) {
|
||||||
|
if (
|
||||||
|
error?.message?.includes("NEXT_REDIRECT") ||
|
||||||
|
error?.type === "NavigationFailure"
|
||||||
|
) {
|
||||||
|
return NextResponse.json({ success: true }, { status: 200 });
|
||||||
|
}
|
||||||
|
|
||||||
|
console.error("Guest login error:", error);
|
||||||
|
if (
|
||||||
|
error?.message?.includes("CredentialsSignin") ||
|
||||||
|
error?.type === "CredentialsSignin"
|
||||||
|
) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Incorrect guest credentials." },
|
||||||
|
{ status: 401 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Internal Server Error" },
|
||||||
|
{ status: 500 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,11 +1,36 @@
|
||||||
/**
|
/**
|
||||||
* @file app/lib/services/auth.service.ts
|
* @file app/lib/services/auth.service.ts
|
||||||
* @description Authentication service providing helper functions for sign-in, and registration.
|
* @description Authentication service providing helper functions for guest credentials, sign-in, and registration.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { loginSchema, registerSchema } from "@/lib/schemas/auth.schema";
|
import { loginSchema, registerSchema } from "@/lib/schemas/auth.schema";
|
||||||
import { signIn } from "next-auth/react";
|
import { signIn } from "next-auth/react";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Triggers guest authentication securely via the backend API route.
|
||||||
|
*
|
||||||
|
* @async
|
||||||
|
* @returns {Promise<{ success?: boolean; error?: string }>} An object indicating success or describing the error.
|
||||||
|
*/
|
||||||
|
export async function loginAsGuest() {
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/auth/guest", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
return { error: data.error || "Guest login failed." };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true };
|
||||||
|
} catch (err: any) {
|
||||||
|
return { error: "Server error: API endpoint not available" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Authenticates a user using email and password credentials, performing client-side validation first.
|
* Authenticates a user using email and password credentials, performing client-side validation first.
|
||||||
*
|
*
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue