next-auth integrated

This commit is contained in:
Proxyy587 2024-06-27 01:17:18 +05:30
parent 8580e24b68
commit c42ef7c52c
10 changed files with 146 additions and 71 deletions

View file

@ -4,4 +4,6 @@ UPLOADTHING_SECRET=
UPLOADTHING_APP_ID= UPLOADTHING_APP_ID=
ADMIN_USERNAME= ADMIN_USERNAME=
ADMIN_PASSWORD= ADMIN_PASSWORD=
NEXTAUTH_SECRET=

View file

@ -20,6 +20,12 @@ import { logsSchema } from "@/lib/validations/validation";
const AdminPage = () => { const AdminPage = () => {
const form = useForm<z.infer<typeof logsSchema>>({ const form = useForm<z.infer<typeof logsSchema>>({
resolver: zodResolver(logsSchema), resolver: zodResolver(logsSchema),
defaultValues: {
fileName: "",
version: "",
downloadLink: "",
fileSize: "",
},
}); });
const onSubmit: SubmitHandler<z.infer<typeof logsSchema>> = async (data) => { const onSubmit: SubmitHandler<z.infer<typeof logsSchema>> = async (data) => {
@ -42,8 +48,8 @@ const AdminPage = () => {
}; };
return ( return (
<section id="admin-page" className="wrapper container"> <section id="logs-page" className="wrapper container">
<h1 className="text-3xl font-bold py-6">Admin Upload Section</h1> <h1 className="text-3xl font-bold py-6">Server Logs Form</h1>
<Form {...form}> <Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4"> <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField <FormField

View file

@ -20,6 +20,12 @@ import { downloadSchema } from "@/lib/validations/validation";
const AdminPage = () => { const AdminPage = () => {
const form = useForm<z.infer<typeof downloadSchema>>({ const form = useForm<z.infer<typeof downloadSchema>>({
resolver: zodResolver(downloadSchema), resolver: zodResolver(downloadSchema),
defaultValues: {
fileName: "",
version: "",
downloadLink: "",
fileSize: "",
},
}); });
const onSubmit: SubmitHandler<z.infer<typeof downloadSchema>> = async ( const onSubmit: SubmitHandler<z.infer<typeof downloadSchema>> = async (
@ -44,8 +50,8 @@ const AdminPage = () => {
}; };
return ( return (
<section id="admin-page" className="wrapper container"> <section id="downloads-page" className="wrapper container">
<h1 className="text-3xl font-bold py-6">Admin Upload Section</h1> <h1 className="text-3xl font-bold py-6">Mods Form</h1>
<Form {...form}> <Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4"> <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField <FormField

View file

@ -20,6 +20,12 @@ import { modsSchema } from "@/lib/validations/validation";
const AdminPage = () => { const AdminPage = () => {
const form = useForm<z.infer<typeof modsSchema>>({ const form = useForm<z.infer<typeof modsSchema>>({
resolver: zodResolver(modsSchema), resolver: zodResolver(modsSchema),
defaultValues: {
fileName: "",
version: "",
downloadLink: "",
fileSize: "",
},
}); });
const onSubmit: SubmitHandler<z.infer<typeof modsSchema>> = async (data) => { const onSubmit: SubmitHandler<z.infer<typeof modsSchema>> = async (data) => {
@ -42,8 +48,8 @@ const AdminPage = () => {
}; };
return ( return (
<section id="admin-page" className="wrapper container"> <section id="mods-page" className="wrapper container">
<h1 className="text-3xl font-bold py-6">Admin Upload Section</h1> <h1 className="text-3xl font-bold py-6">Download Form</h1>
<Form {...form}> <Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4"> <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField <FormField

View file

@ -0,0 +1,53 @@
import { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
export const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
id: "credentials",
name: "Credentials",
credentials: {
username: { label: "Username", type: "text" },
password: { label: "Password", type: "password" },
},
async authorize(credentials: any): Promise<any> {
const adminUsername = process.env.ADMIN_USERNAME;
const adminPassword = process.env.ADMIN_PASSWORD;
if (
credentials.username === adminUsername &&
credentials.password === adminPassword
) {
// Any object returned will be saved in `user` property of the JWT
return { id: 1, name: "svrjsAdmin" };
} else {
// If you return null then an error will be displayed advising the user to check their details.
return null;
}
},
}),
],
callbacks: {
async jwt({ token, user }) {
// Add user info to token
if (user) {
token.id = user.id;
token.name = user.name;
}
return token;
},
async session({ session, token }) {
// Add token info to session
// session.user.id = token.id;
// session.user.name = token.name;
return session;
},
},
pages: {
signIn: "/login",
},
session: {
strategy: "jwt",
},
secret: process.env.NEXTAUTH_SECRET,
};

View file

@ -0,0 +1,6 @@
import NextAuth from "next-auth/next";
import { authOptions } from "./options";
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };

View file

@ -1,64 +1,61 @@
"use client"; "use client";
import React, { useState } from "react"; import React, { useState } from "react";
import { signIn } from "next-auth/react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
const LoginPage = () => { const LoginPage = () => {
const [username, setUsername] = useState(""); const [username, setUsername] = useState("");
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
const [error, setError] = useState(""); const [error, setError] = useState("");
const router = useRouter(); const router = useRouter();
const handleLogin = async (e: React.FormEvent) => { const handleLogin = async (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
const res = await signIn("credentials", {
redirect: false,
username,
password,
});
const response = await fetch("/api/login", { if (res?.ok) {
method: "POST", router.push("/admin");
headers: { } else {
"Content-Type": "application/json", setError("Invalid credentials");
}, }
body: JSON.stringify({ username, password }), };
});
if (response.ok) { return (
router.push("/admin"); <div className="max-w-xl h-screen flex justify-center bg-gray-900 flex-col container">
} else { <h1 className="text-3xl font-bold mb-4">SVRJS ADMIN PANEL</h1>
const data = await response.json(); {error && <p className="text-red-500 mb-4">{error}</p>}
setError(data.message); <form onSubmit={handleLogin}>
} <div className="mb-4">
}; <input
type="text"
return ( id="username"
<div className="max-w-xl h-screen flex justify-center bg-gray-900 flex-col container"> placeholder="Username"
<h1 className="text-3xl font-bold mb-4">SVRJS ADMIN PANEL</h1> value={username}
{error && <p className="text-red-500 mb-4">{error}</p>} onChange={(e) => setUsername(e.target.value)}
<form onSubmit={handleLogin}> className="mt-1 block w-full bg-gray-800 rounded-full px-5 py-2 shadow-sm p-2"
<div className="mb-4"> />
<input </div>
type="text" <div className="mb-4">
id="username" <input
placeholder="Username" type="password"
value={username} placeholder="Password"
onChange={(e) => setUsername(e.target.value)} id="password"
className="mt-1 block w-full bg-gray-800 rounded-full px-5 py-2 shadow-sm p-2" value={password}
/> onChange={(e) => setPassword(e.target.value)}
</div> className="mt-1 block w-full bg-gray-800 rounded-full px-5 py-2 shadow-sm"
<div className="mb-4"> />
<input </div>
type="password" <Button type="submit" className="w-full rounded-full" size={"lg"}>
placeholder="Password" Login
id="password" </Button>
value={password} </form>
onChange={(e) => setPassword(e.target.value)} </div>
className="mt-1 block w-full bg-gray-800 rounded-full px-5 py-2 shadow-sm" );
/>
</div>
<Button type="submit" className="w-full rounded-full" size={"lg"}>
Login
</Button>
</form>
</div>
);
}; };
export default LoginPage; export default LoginPage;

BIN
bun.lockb Normal file

Binary file not shown.

View file

@ -1,21 +1,19 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import type { NextRequest } from "next/server"; import type { NextRequest } from "next/server";
import { getToken } from "next-auth/jwt";
export function middleware(req: NextRequest) { export async function middleware(req: NextRequest) {
const url = req.nextUrl.clone(); const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });
if (url.pathname.startsWith("/admin")) { if (req.nextUrl.pathname.startsWith("/admin") && !token) {
const authCookie = req.cookies.get("auth"); const url = req.nextUrl.clone();
url.pathname = "/login";
return NextResponse.redirect(url);
}
if (!authCookie) { return NextResponse.next();
url.pathname = "/login";
return NextResponse.redirect(url);
}
}
return NextResponse.next();
} }
export const config = { export const config = {
matcher: ["/admin/:path*"], matcher: ["/admin/:path*"],
}; };

View file

@ -27,6 +27,7 @@
"lucide-react": "^0.394.0", "lucide-react": "^0.394.0",
"mini-svg-data-uri": "^1.4.4", "mini-svg-data-uri": "^1.4.4",
"mongoose": "^8.4.3", "mongoose": "^8.4.3",
"next-auth": "^4.24.7",
"next-themes": "^0.3.0", "next-themes": "^0.3.0",
"nextra": "^2.13.4", "nextra": "^2.13.4",
"nextra-theme-docs": "^2.13.4", "nextra-theme-docs": "^2.13.4",