-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathauth.ts
More file actions
201 lines (185 loc) · 6.73 KB
/
Copy pathauth.ts
File metadata and controls
201 lines (185 loc) · 6.73 KB
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
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
/**
* NextAuth v5 Configuration
*
* Authentication configuration using NextAuth v5 (Auth.js)
* Supports Google OAuth provider and Credentials (email/password) for database-backed authentication
*
* Following DEVELOPMENT_RULES.md: Centralized auth, TypeScript, proper types
*/
import NextAuth from "next-auth";
import Google from "next-auth/providers/google";
import Credentials from "next-auth/providers/credentials";
import { prisma } from "./lib/prisma";
import bcrypt from "bcryptjs";
import { createLocalUser } from "./lib/user-registration";
/**
* NextAuth configuration
* Uses Google OAuth provider and Credentials provider for authentication
*/
export const { handlers, auth, signIn, signOut } = NextAuth({
providers: [
/**
* Credentials Provider - Email/Password authentication
* Only authenticates users that exist in the database with matching credentials
*/
Credentials({
name: "Credentials",
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) {
return null;
}
// Type assertion for credentials
const email = credentials.email as string;
const password = credentials.password as string;
// Check database for user with password
try {
const dbUser = await prisma.user.findUnique({
where: { email: email.trim().toLowerCase() },
});
if (!dbUser || !dbUser.password) {
// User doesn't exist or has no password set
return null;
}
// User exists in database - verify password
const isValidPassword = await bcrypt.compare(password, dbUser.password);
if (isValidPassword) {
return {
id: dbUser.id,
email: dbUser.email,
name: dbUser.name || undefined,
image: dbUser.picture || undefined,
};
}
// Password doesn't match
return null;
} catch (error) {
console.error("Database authentication error:", error);
// Return null on database errors - don't allow authentication
return null;
}
},
}),
/**
* Google OAuth Provider
*/
Google({
clientId: process.env.GOOGLE_ID || process.env.GOOGLE_CLIENT_ID || "",
clientSecret: process.env.GOOGLE_SECRET || process.env.GOOGLE_CLIENT_SECRET || "",
authorization: {
params: {
prompt: "consent",
access_type: "offline",
response_type: "code",
},
},
}),
],
callbacks: {
/**
* SignIn callback - runs on every sign in
* Used to create database records for OAuth users (Google, etc.)
*/
async signIn({ user, account, profile }) {
// Only handle OAuth providers (not Credentials - those are handled by signup API)
if (account?.provider === "google" && user.email) {
try {
// Check if user already exists in database
const existingUser = await prisma.user.findUnique({
where: { email: user.email.trim().toLowerCase() },
});
if (!existingUser) {
const created = await createLocalUser({
email: user.email,
name: user.name || profile?.name || null,
picture:
user.image ||
(profile as { picture?: string })?.picture ||
null,
provider: "google",
});
user.id = created.id;
} else {
// User exists - update their info and use existing ID
await prisma.user.update({
where: { email: user.email.trim().toLowerCase() },
data: {
name: user.name || profile?.name || existingUser.name,
picture: user.image || (profile as { picture?: string })?.picture || existingUser.picture,
updatedAt: new Date(),
},
});
console.log(`✅ Google OAuth user updated: ${user.email} (ID: ${existingUser.id})`);
// Use existing user ID for JWT
user.id = existingUser.id;
}
} catch (error) {
console.error("Error creating/updating OAuth user:", error);
// Still allow sign-in even if database operation fails
// The user will just not have a database record until next sign-in
}
}
// Return true to allow sign-in
return true;
},
/**
* JWT callback - runs whenever a JWT is accessed
* Used to add custom claims to the token
*/
async jwt({ token, user, account, profile }) {
// Initial sign in - add user info to token
if (user) {
// Use user.id if provided (from Credentials provider), otherwise generate one
token.id = user.id || user.email?.split("@")[0] + "_" + Date.now() || `user_${Date.now()}`;
token.email = user.email;
token.name = user.name;
// Set picture from user.image (OAuth providers set this from profile)
if (user.image) {
token.picture = user.image;
}
}
// For Google OAuth, also check the profile for picture (backup)
if (profile && account?.provider === "google") {
const googleProfile = profile as { picture?: string };
if (googleProfile.picture) {
token.picture = googleProfile.picture;
}
}
// Add access token from OAuth provider (only for OAuth providers, not Credentials)
if (account && account.provider !== "credentials") {
token.accessToken = account.access_token;
token.refreshToken = account.refresh_token;
token.expiresAt = account.expires_at;
}
return token;
},
/**
* Session callback - runs whenever a session is checked
* Used to customize the session object returned to client
*/
async session({ session, token }) {
// Add user ID, image, and access token to session
if (session.user) {
session.user.id = token.id;
session.user.accessToken = token.accessToken;
// Pass the picture from token to session (for Google OAuth profile image)
if (token.picture) {
session.user.image = token.picture as string;
}
}
return session;
},
},
pages: {
signIn: "/", // Custom sign-in page (we'll use our own dialog)
},
session: {
strategy: "jwt", // Use JWT strategy for better Next.js App Router compatibility
maxAge: 30 * 24 * 60 * 60, // 30 days
},
// Enable debug mode in development
debug: process.env.NODE_ENV === "development",
});