feat(auth): add role guards and protect admin routes
This commit is contained in:
@@ -1,26 +0,0 @@
|
||||
"use server"
|
||||
|
||||
import { AuthError } from "next-auth"
|
||||
|
||||
import { signIn } from "@/lib/auth"
|
||||
import type { SignInFormType } from "@/lib/schemas/auth.schemas"
|
||||
|
||||
export async function signInAction(values: SignInFormType) {
|
||||
const { username, password } = values
|
||||
|
||||
try {
|
||||
await signIn("credentials", {
|
||||
username,
|
||||
password,
|
||||
redirect: false,
|
||||
})
|
||||
return {
|
||||
success: true,
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof AuthError) {
|
||||
return { error: error.cause?.err?.message }
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
+5
-3
@@ -4,12 +4,11 @@ import { ZodError } from "zod"
|
||||
|
||||
import type { UserRole } from "@/generated/prisma/client"
|
||||
import { SIGN_IN_URL, TOKEN_EXPIRATION_SECONDS } from "@/lib/constants"
|
||||
import { signInSchema } from "@/lib/schemas/auth.schemas"
|
||||
import { verifyPassword } from "@/lib/security"
|
||||
import { signInSchema } from "@/schemas/auth.schema"
|
||||
import { getUserByUsername } from "@/services/user.service"
|
||||
|
||||
declare module "next-auth" {
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
interface Session {
|
||||
user: {
|
||||
id: string
|
||||
@@ -17,7 +16,6 @@ declare module "next-auth" {
|
||||
} & DefaultSession["user"]
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
interface User {
|
||||
role: UserRole
|
||||
}
|
||||
@@ -46,6 +44,10 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
|
||||
throw new Error("Invalid username or password")
|
||||
}
|
||||
|
||||
if (!user.isActive) {
|
||||
throw new Error("Invalid username or password")
|
||||
}
|
||||
|
||||
if (!(await verifyPassword(data.password, user.password)))
|
||||
throw new Error("Invalid username or password")
|
||||
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const signInSchema = z.object({
|
||||
username: z
|
||||
.string()
|
||||
.min(1, {
|
||||
error: "Invalid username"
|
||||
})
|
||||
.nonempty("Username is required"),
|
||||
password: z
|
||||
.string()
|
||||
.min(3, {
|
||||
error: "Password is too short"
|
||||
})
|
||||
.nonempty("Password is required"),
|
||||
})
|
||||
|
||||
export type SignInFormType = z.infer<typeof signInSchema>
|
||||
Reference in New Issue
Block a user