import { handlers } from "@/auth" // Referring to the auth.ts above
export const { GET, POST } = handlers
export { auth as middleware } from "@/auth"
//Add optional Middleware to keep the session alive, this will update the session expiry every time its called.
import NextAuth from "next-auth"
import Credentials from "next-auth/providers/credentials"
// Your own logic for dealing with plaintext password strings; be careful!
import { saltAndHashPassword } from "@/utils/password"
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [
Credentials({
// You can specify which fields should be submitted, by adding keys to the `credentials` object.
// e.g. domain, username, password, 2FA token, etc.
credentials: {
email: {},
password: {},
},
authorize: async (credentials) => {
let user = null
// logic to salt and hash password
const pwHash = saltAndHashPassword(credentials.password)
// logic to verify if the user exists
user = await getUserFromDb(credentials.email, pwHash)
if (!user) {
// No user found, so this is their first attempt to login
// Optionally, this is also the place you could do a user registration
throw new Error("Invalid credentials.")
}
// return user object with their profile data
return user
},
}),
],
// Remove pages and defaults to [basePath]/signin
pages: {
signIn: "/signin",
},
// Obv remove in prod
debug: true,
})
import { signIn, signOut } from "next-auth/react"
signIn() // Redirected to configured sign in page, default /[basePath]/signin
signIn("credentials", formData); // Attempts sign in with that provider
signOut();
"use client"
import { useSession } from "next-auth/react"
export default function Dashboard() {
const { data: session } = useSession()
if (session?.user?.role === "admin") {
return <p>You are an admin, welcome!</p>
}
return <p>You are not authorized to view this page!</p>
}
import { SessionProvider } from "next-auth/react"
import { Dashboard } from "./Dashboard"
export default function Administrator() {
return (
<SessionProvider>
<Dashboard />
</SessionProvider>
)
}