Next-auth首次登录后无法检测关联账户(OAuthAccountNotLinked)
问题:NextAuth + Drizzle + libSQL 重复登录时触发 OAuthAccountNotLinked 错误
我基于 Next.js 14、next-auth 4、libSQL 和 Drizzle ORM 开发项目,首次登录(账户及用户数据未存入数据库时)流程正常,但后续使用 GoogleProvider 登录时,会返回 OAuthAccountNotLinked 错误。
相关代码
app/api/auth/[...nextauth]/options.ts
import type { NextAuthOptions } from "next-auth"; import GoogleProvider from "next-auth/providers/google"; import { DrizzleAdapter } from "@auth/drizzle-adapter"; import { db } from "@/lib/db"; export const options: NextAuthOptions = { adapter: DrizzleAdapter(db), secret: process.env.NEXTAUTH_SECRET, providers: [ GoogleProvider({ clientId: process.env.GOOGLE_CLIENT_ID as string, clientSecret: process.env.GOOGLE_CLIENT_SECRET as string, authorization: { params: { prompt: "consent", access_type: "offline", response_type: "code", }, }, }), ], session: { strategy: "jwt", maxAge: 30 * 24 * 60 * 60, // 30 days }, pages: { signIn: "/signin", error: "/signin", }, };
schema.ts
import { integer, sqliteTable, text, primaryKey, } from "drizzle-orm/sqlite-core"; import type { AdapterAccount } from "@auth/core/adapters"; export const users = sqliteTable("user", { id: text("id").notNull().primaryKey(), name: text("name"), email: text("email").notNull(), emailVerified: integer("emailVerified", { mode: "timestamp_ms" }), image: text("image"), }); export const accounts = sqliteTable( "account", { userId: text("userId") .notNull() .references(() => users.id, { onDelete: "cascade" }), type: text("type").$type<AdapterAccount["type"]>().notNull(), provider: text("provider").notNull(), providerAccountId: text("providerAccountId").notNull(), refresh_token: text("refresh_token"), access_token: text("access_token"), expires_at: integer("expires_at"), token_type: text("token_type"), scope: text("scope"), id_token: text("id_token"), session_state: text("session_state"), }, (account) => ({ compoundKey: primaryKey({ columns: [account.provider, account.providerAccountId], }), }) ); export const verificationTokens = sqliteTable( "verificationToken", { identifier: text("identifier").notNull(), token: text("token").notNull(), expires: integer("expires", { mode: "timestamp_ms" }).notNull(), }, (vt) => ({ compoundKey: primaryKey({ columns: [vt.identifier, vt.token] }), }) );
尝试的临时方案及问题
我尝试在 GoogleProvider 配置中添加 allowDangerousLinking: true,虽然能完成登录,但控制台会抛出以下错误:
LibsqlError: SQLITE_CONSTRAINT: SQLite error: UNIQUE constraint failed: account.provider, account.providerAccountId
这说明系统未识别到已关联的账户记录,每次登录都尝试重复插入相同的账户数据。
内容的提问来源于stack exchange,提问作者Kyle
相关产品推荐
相关产品推荐

