-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth.ts
99 lines (93 loc) · 3.19 KB
/
auth.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import NextAuth from 'next-auth';
import GoogleProvider from "next-auth/providers/google";
import GithubProvider from "next-auth/providers/github";
import CredentialsProvider from "next-auth/providers/credentials";
import { authConfig } from './auth.config';
import { z } from 'zod';
import type { Account } from '@/app/lib/definitions/definitions';
import bcrypt from 'bcrypt';
import { eq } from 'drizzle-orm';
import { db } from './app/lib/db/db';
import { accounts } from './app/lib//db/schema';
async function getUser(email: string): Promise<Account | undefined> {
try {
const users = await db.select().from(accounts).where(eq(accounts.email, email)).limit(1);
const user = users[0];
if (!user) return undefined;
// Map the database result to your Account type
return {
id: user.id,
name: user.name,
email: user.email,
password: user.password ?? undefined,
provider: user.provider ?? undefined,
providerAccountId: user.providerAccountId ?? undefined,
lastLogin: user.lastLogin ?? undefined
};
} catch (error) {
console.error('Failed to fetch user:', error);
throw new Error('Failed to fetch user.');
}
}
export const { auth, signIn, signOut, handlers } = NextAuth({
...authConfig,
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
}),
GithubProvider({
clientId: process.env.GITHUB_ID!,
clientSecret: process.env.GITHUB_SECRET!,
}),
CredentialsProvider({
async authorize(credentials) {
const parsedCredentials = z
.object({ email: z.string().email(), password: z.string().min(6) })
.safeParse(credentials);
if (parsedCredentials.success) {
const { email, password } = parsedCredentials.data;
const user = await getUser(email);
if (!user) return null;
const passwordsMatch = await bcrypt.compare(password, user.password || '');
if (passwordsMatch) return user;
}
console.log('Invalid credentials');
return null;
},
}),
],
callbacks: {
async signIn({ user, account }) {
if (account?.provider === 'google' || account?.provider === 'github') {
const email = user.email;
if (!email) {
console.error('User email is missing');
return false;
}
const existingUser = await getUser(email);
if (existingUser) {
// User exists, update last login
await db.update(accounts)
.set({
lastLogin: new Date(),
provider: account.provider,
providerAccountId: account.providerAccountId
})
.where(eq(accounts.email, email));
} else {
// New user, create account
await db.insert(accounts).values({
id: user.id ?? crypto.randomUUID(), // Use provided id or generate a new one
name: user.name ?? 'Unknown',
email: email,
provider: account.provider,
providerAccountId: account.providerAccountId,
lastLogin: new Date()
});
}
}
return true;
},
},
});