102 lines
2.3 KiB
TypeScript
102 lines
2.3 KiB
TypeScript
import NextAuth from "next-auth";
|
|
import Credentials from "next-auth/providers/credentials";
|
|
import argon2 from "argon2";
|
|
import { z } from "zod";
|
|
import { db } from "@/lib/db";
|
|
import { checkRateLimit } from "@/lib/rate-limit";
|
|
|
|
const credentialsSchema = z.object({
|
|
email: z.string().trim().email().toLowerCase(),
|
|
senha: z.string().min(1)
|
|
});
|
|
|
|
export const { handlers, auth, signIn, signOut } = NextAuth({
|
|
session: {
|
|
strategy: "jwt"
|
|
},
|
|
pages: {
|
|
signIn: "/login"
|
|
},
|
|
providers: [
|
|
Credentials({
|
|
credentials: {
|
|
email: { label: "E-mail", type: "email" },
|
|
senha: { label: "Senha", type: "password" }
|
|
},
|
|
async authorize(credentials, request) {
|
|
const parsed = credentialsSchema.safeParse(credentials);
|
|
|
|
if (!parsed.success) {
|
|
return null;
|
|
}
|
|
|
|
const forwardedFor = request.headers.get("x-forwarded-for");
|
|
const ip = forwardedFor?.split(",")[0]?.trim() ?? "local";
|
|
const limit = checkRateLimit(`login:${ip}:${parsed.data.email}`);
|
|
|
|
if (!limit.allowed) {
|
|
return null;
|
|
}
|
|
|
|
const user = await db.user.findUnique({
|
|
where: { email: parsed.data.email },
|
|
select: {
|
|
id: true,
|
|
email: true,
|
|
senhaHash: true,
|
|
papel: true
|
|
}
|
|
});
|
|
|
|
if (!user) {
|
|
return null;
|
|
}
|
|
|
|
const validPassword = await argon2.verify(user.senhaHash, parsed.data.senha);
|
|
|
|
if (!validPassword) {
|
|
return null;
|
|
}
|
|
|
|
return {
|
|
id: user.id,
|
|
email: user.email,
|
|
papel: user.papel
|
|
};
|
|
}
|
|
})
|
|
],
|
|
callbacks: {
|
|
async jwt({ token, user }) {
|
|
if (user) {
|
|
token.userId = user.id;
|
|
token.papel = user.papel;
|
|
}
|
|
|
|
return token;
|
|
},
|
|
async session({ session, token }) {
|
|
if (session.user) {
|
|
session.user.id = token.userId;
|
|
session.user.papel = token.papel;
|
|
}
|
|
|
|
return session;
|
|
}
|
|
},
|
|
cookies: {
|
|
sessionToken: {
|
|
name:
|
|
process.env.NODE_ENV === "production"
|
|
? "__Secure-authjs.session-token"
|
|
: "authjs.session-token",
|
|
options: {
|
|
httpOnly: true,
|
|
sameSite: "lax",
|
|
path: "/",
|
|
secure: process.env.NODE_ENV === "production"
|
|
}
|
|
}
|
|
}
|
|
});
|