Newer
Older
import { env } from "@/env.mjs"
import { db } from "@/lib/db"
import { PrismaAdapter } from "@auth/prisma-adapter"
import { compare } from "bcrypt"
import { NextAuthOptions } from "next-auth"
import CredentialsProvider from 'next-auth/providers/credentials'
import { normalize } from "normalize-diacritics"
clientId: env.GITHUB_CLIENT_ID,
clientSecret: env.GITHUB_CLIENT_SECRET,
usernameOrEmail: { label: 'Username or Email', type: 'text' },
password: { label: 'Password', type: 'password' }
},
async authorize(credentials) {
if (!credentials?.usernameOrEmail || !credentials?.password) {
OR: [
{ username: credentials.usernameOrEmail.toLowerCase() },
{ email: credentials.usernameOrEmail.toLowerCase() },
],
},
});
throw new Error('user not found')
}
const isPasswordValid = await compare(
credentials.password,
user.password
)
if (!isPasswordValid) {
throw new Error('invalid password')
if(!user.emailVerified){
throw new Error('email not verifyed')
}
session.user.username = token.username
session.user.email = token.email
session.user.image = token.picture
async jwt({ token, user }) {
const dbUser = await db.user.findFirst({
where: {
email: token.email,
},
})
if (!dbUser) {
if (user) {
token.id = user?.id
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
if (!dbUser.username) {
let username = await normalize(dbUser.name?.toLowerCase().replace(/\s/g, ''));
const email = dbUser.email?.toLowerCase();
let isUnique = false;
while (!isUnique) {
const existingUserName = await db.user.findFirst({
where: {
username,
NOT: { email },
},
});
if (existingUserName) {
username = `${username}${Math.floor(Math.random() * 1000)}`;
} else {
isUnique = true;
}
}
dbUser.username = username;
await db.user.update({
where: { email },
data: { username },
});
}