8c82ce5bad
- Add trustHost: true to NextAuth configuration - Add console logging for login debugging - Fix authentication issues preventing login redirect
75 lines
1.7 KiB
TypeScript
75 lines
1.7 KiB
TypeScript
import NextAuth from 'next-auth';
|
|
import CredentialsProvider from 'next-auth/providers/credentials';
|
|
import { db } from '@/db';
|
|
import { users } from '@/db/schema';
|
|
import { eq } from 'drizzle-orm';
|
|
import bcrypt from 'bcryptjs';
|
|
|
|
export const { handlers, signIn, signOut, auth } = NextAuth({
|
|
trustHost: true,
|
|
providers: [
|
|
CredentialsProvider({
|
|
name: '邮箱密码',
|
|
credentials: {
|
|
email: { label: '邮箱', type: 'email' },
|
|
password: { label: '密码', type: 'password' },
|
|
},
|
|
async authorize(credentials) {
|
|
if (!credentials?.email || !credentials?.password) {
|
|
return null;
|
|
}
|
|
|
|
const userResult = await db
|
|
.select()
|
|
.from(users)
|
|
.where(eq(users.email, credentials.email as string))
|
|
.limit(1);
|
|
|
|
const user = userResult[0];
|
|
if (!user) {
|
|
return null;
|
|
}
|
|
|
|
const isValid = await bcrypt.compare(
|
|
credentials.password as string,
|
|
user.passwordHash || ''
|
|
);
|
|
|
|
if (!isValid) {
|
|
return null;
|
|
}
|
|
|
|
return {
|
|
id: user.id,
|
|
email: user.email,
|
|
name: user.name,
|
|
isAdmin: user.isAdmin,
|
|
};
|
|
},
|
|
}),
|
|
],
|
|
callbacks: {
|
|
async jwt({ token, user }) {
|
|
if (user) {
|
|
token.id = user.id;
|
|
token.isAdmin = user.isAdmin;
|
|
}
|
|
return token;
|
|
},
|
|
async session({ session, token }) {
|
|
if (session.user) {
|
|
session.user.id = token.id as string;
|
|
session.user.isAdmin = token.isAdmin as boolean;
|
|
}
|
|
return session;
|
|
},
|
|
},
|
|
pages: {
|
|
signIn: '/admin/login',
|
|
error: '/admin/login',
|
|
},
|
|
session: {
|
|
strategy: 'jwt',
|
|
},
|
|
});
|