mirror of
https://github.com/Hestia-Homes/assessment-model.git
synced 2026-06-08 11:37:25 +00:00
fixed oauth login bug
This commit is contained in:
parent
ea8dc9f5be
commit
4ae02f5af7
1 changed files with 41 additions and 2 deletions
|
|
@ -11,7 +11,7 @@ import {
|
|||
accounts,
|
||||
verificationTokens,
|
||||
} from "@/app/db/schema/users";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Environment variables
|
||||
|
|
@ -102,7 +102,7 @@ export const AuthOptions: NextAuthOptions = {
|
|||
/**
|
||||
* Sign in callback — ensures user exists and links OAuth provider if needed
|
||||
*/
|
||||
async signIn({ user, account }) {
|
||||
async signIn({ user, account, profile }) {
|
||||
try {
|
||||
if (!user?.email) return false;
|
||||
const normalisedEmail = user.email.toLowerCase();
|
||||
|
|
@ -113,11 +113,50 @@ export const AuthOptions: NextAuthOptions = {
|
|||
.from(users)
|
||||
.where(eq(users.email, normalisedEmail));
|
||||
|
||||
// New user - next auth will handle
|
||||
if (!dbUser) {
|
||||
console.log("New user sign up for email:", normalisedEmail);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Auto-link provider if same verified email but account not linked yet
|
||||
if (account?.provider && account.type === "oauth") {
|
||||
const existingLink = await db
|
||||
.select()
|
||||
.from(accounts)
|
||||
.where(
|
||||
and(
|
||||
eq(accounts.userId, dbUser.id),
|
||||
eq(accounts.provider, account.provider)
|
||||
)
|
||||
);
|
||||
|
||||
const emailVerified =
|
||||
(profile as any)?.email_verified ?? account.provider === "google";
|
||||
|
||||
if (existingLink.length === 0 && emailVerified) {
|
||||
// This handles the case where we had not set up accounts but
|
||||
// signed up users with oauth
|
||||
console.log(
|
||||
`Linking ${account.provider} account for user ${normalisedEmail}`
|
||||
);
|
||||
|
||||
await db
|
||||
.insert(accounts)
|
||||
.values({
|
||||
userId: dbUser.id,
|
||||
type: account.type,
|
||||
provider: account.provider,
|
||||
providerAccountId: account.providerAccountId,
|
||||
access_token: account.access_token,
|
||||
id_token: account.id_token,
|
||||
refresh_token: account.refresh_token,
|
||||
expires_at: account.expires_at,
|
||||
})
|
||||
.onConflictDoNothing();
|
||||
}
|
||||
}
|
||||
|
||||
// Link OAuth ID if missing (helps for older accounts)
|
||||
if (account && !dbUser.oauthId) {
|
||||
console.log("Linking OAuth ID for user:", normalisedEmail);
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue