Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor: make LobeNextAuthDBAdapter Edge Compatible (#9088)

Rylan Cai411f88eca184
diff --git a/packages/database/src/server/models/__tests__/nextauth.test.ts b/packages/database/src/server/models/__tests__/nextauth.test.ts
deleted file mode 100644
index caff53501f2..00000000000
--- a/packages/database/src/server/models/__tests__/nextauth.test.ts
+++ /dev/null
@@ -1,556 +0,0 @@
-import type {
- AdapterAccount,
- AdapterAuthenticator,
- AdapterSession,
- AdapterUser,
- VerificationToken,
-} from '@auth/core/adapters';
-import { eq } from 'drizzle-orm';
-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { LobeNextAuthDbAdapter } from '@/libs/next-auth/adapter';
-
-import { getTestDBInstance } from '../../../core/dbForTest';
-import {
- nextauthAccounts,
- nextauthAuthenticators,
- nextauthSessions,
- nextauthVerificationTokens,
- users,
-} from '../../../schemas';
-
-let serverDB = await getTestDBInstance();
-
-let nextAuthAdapter = LobeNextAuthDbAdapter(serverDB);
-
-const userId = 'user-db';
-const user: AdapterUser = {
- id: userId,
- name: 'John Doe',
- email: '[email protected]',
- emailVerified: new Date(),
- image: 'https://example.com/avatar.jpg',
-};
-
-const sessionToken = 'session-token';
-
-beforeAll(async () => {
- await serverDB.delete(users);
- await serverDB.delete(nextauthAccounts);
- await serverDB.delete(nextauthAuthenticators);
- await serverDB.delete(nextauthSessions);
- await serverDB.delete(nextauthVerificationTokens);
-});
-
-beforeEach(async () => {
- process.env.KEY_VAULTS_SECRET = 'ofQiJCXLF8mYemwfMWLOHoHimlPu91YmLfU7YZ4lreQ=';
- // insert a user
- // @ts-expect-error: createUser is defined
- await nextAuthAdapter.createUser(user);
-});
-
-afterEach(async () => {
- await serverDB.delete(users);
-});
-
-afterAll(async () => {
- await serverDB.delete(users);
- await serverDB.delete(nextauthAccounts);
- await serverDB.delete(nextauthAuthenticators);
- await serverDB.delete(nextauthSessions);
- await serverDB.delete(nextauthVerificationTokens);
- process.env.KEY_VAULTS_SECRET = undefined;
-});
-
-/**
- * The tests below only test the database operation functionality,
- * the mock values might not represent the actual value
- */
-describe('LobeNextAuthDbAdapter', () => {
- describe('users', () => {
- describe('createUser', () => {
- it('should create a new user', async () => {
- expect(nextAuthAdapter).toBeDefined();
- expect(nextAuthAdapter.createUser).toBeDefined();
- const anotherUserId = 'user-db-2';
- const anotherUserName = 'John Doe 2';
- const anotherEmail = '[email protected]';
- // @ts-expect-error: createUser is defined
- const createdUser = await nextAuthAdapter.createUser({
- ...user,
- id: anotherUserId,
- name: anotherUserName,
- email: anotherEmail,
- });
- expect(createdUser).toBeDefined();
- expect(createdUser.id).toBe(anotherUserId);
- expect(createdUser.name).toBe(anotherUserName);
- expect(createdUser.email).toBe(anotherEmail);
- expect(createdUser.emailVerified).toBe(user.emailVerified);
- expect(createdUser.image).toBe(user.image);
- });
-
- it('should not create a user if it already exists', async () => {
- expect(nextAuthAdapter).toBeDefined();
- expect(nextAuthAdapter.createUser).toBeDefined();
- // @ts-expect-error: createUser is defined
- await nextAuthAdapter.createUser(user);
- // Should not create a new user if it already exists
- expect(
- await serverDB.query.users.findMany({ where: eq(users.email, user.email) }),
- ).toHaveLength(1);
- });
-
- it('should not create a user if email exist', async () => {
- expect(nextAuthAdapter).toBeDefined();
- expect(nextAuthAdapter.createUser).toBeDefined();
- const anotherUserId = 'user-db-2';
- const anotherUserName = 'John Doe 2';
- // @ts-expect-error: createUser is defined
- await nextAuthAdapter.createUser({
- ...user,
- id: anotherUserId,
- name: anotherUserName,
- });
- // Should not create a new user if email already exists
- expect(
- await serverDB.query.users.findMany({ where: eq(users.email, user.email) }),
- ).toHaveLength(1);
- });
-
- it('should create a user if id not exist and email is null', async () => {
- // In previous version, it will link the account to the existing user if the email is null
- // issue: https://github.com/lobehub/lobe-chat/issues/4918
- expect(nextAuthAdapter).toBeDefined();
- expect(nextAuthAdapter.createUser).toBeDefined();
-
- const existUserId = 'user-db-1';
- const existUserName = 'John Doe 1';
- // @ts-expect-error: createUser is defined
- await nextAuthAdapter.createUser({
- ...user,
- id: existUserId,
- name: existUserName,
- email: '',
- });
-
- const anotherUserId = 'user-db-2';
- const anotherUserName = 'John Doe 2';
- // @ts-expect-error: createUser is defined
- await nextAuthAdapter.createUser({
- ...user,
- id: anotherUserId,
- name: anotherUserName,
- email: '',
- });
- // Should create a new user if id not exists and email is null
- expect(
- await serverDB.query.users.findMany({ where: eq(users.id, anotherUserId) }),
- ).toHaveLength(1);
- });
-
- it('should create a user if id not exist even email is invalid type', async () => {
- // In previous version, it will link the account to the existing user if the email is null
- // issue: https://github.com/lobehub/lobe-chat/issues/4918
- expect(nextAuthAdapter).toBeDefined();
- expect(nextAuthAdapter.createUser).toBeDefined();
-
- const existUserId = 'user-db-1';
- const existUserName = 'John Doe 1';
- // @ts-expect-error: createUser is defined
- await nextAuthAdapter.createUser({
- ...user,
- id: existUserId,
- name: existUserName,
- email: Object({}), // assign a non-string value
- });
-
- const anotherUserId = 'user-db-2';
- const anotherUserName = 'John Doe 2';
- // @ts-expect-error: createUser is defined
- await nextAuthAdapter.createUser({
- ...user,
- id: anotherUserId,
- name: anotherUserName,
- // @ts-expect-error: try to assign undefined value
- email: undefined,
- });
-
- // Should create a new user if id not exists and email is null
- expect(
- await serverDB.query.users.findMany({ where: eq(users.id, anotherUserId) }),
- ).toHaveLength(1);
- });
- });
-
- describe('deleteUser', () => {
- it('should delete a user', async () => {
- expect(nextAuthAdapter).toBeDefined();
- expect(nextAuthAdapter.deleteUser).toBeDefined();
- // @ts-expect-error: deleteUser is defined
- await nextAuthAdapter.deleteUser(userId);
- const deletedUser = await serverDB.query.users.findFirst({ where: eq(users.id, userId) });
- expect(deletedUser).toBeUndefined();
- });
- });
-
- describe('getUser', () => {
- it('should get a user', async () => {
- expect(nextAuthAdapter).toBeDefined();
- expect(nextAuthAdapter.getUser).toBeDefined();
- // @ts-expect-error: getUser is defined
- const fetchedUser = await nextAuthAdapter.getUser(userId);
- expect(fetchedUser).toBeDefined();
- expect(fetchedUser?.id).toBe(user.id);
- expect(fetchedUser?.name).toBe(user.name);
- expect(fetchedUser?.email).toBe(user.email);
- expect(fetchedUser?.emailVerified).toEqual(user.emailVerified);
- expect(fetchedUser?.image).toBe(user.image);
- });
- });
-
- describe('getUserByEmail', () => {
- it('should get a user by email', async () => {
- expect(nextAuthAdapter).toBeDefined();
- expect(nextAuthAdapter.getUserByEmail).toBeDefined();
- // @ts-expect-error: getUserByEmail is defined
- const fetchedUser = await nextAuthAdapter.getUserByEmail(user.email);
- expect(fetchedUser).toBeDefined();
- expect(fetchedUser?.id).toBe(user.id);
- expect(fetchedUser?.name).toBe(user.name);
- expect(fetchedUser?.email).toBe(user.email);
- expect(fetchedUser?.emailVerified).toEqual(user.emailVerified);
- expect(fetchedUser?.image).toBe(user.image);
- });
- });
-
- describe('getUserByAccount', () => {
- it('should get a user by account', async () => {
- const account: AdapterAccount = {
- providerAccountId: 'provider-account-id',
- userId: userId,
- provider: 'auth0',
- type: 'email',
- };
- // @ts-expect-error: linkAccount is defined
- await nextAuthAdapter.linkAccount(account);
- expect(nextAuthAdapter).toBeDefined();
- expect(nextAuthAdapter.getUserByAccount).toBeDefined();
- // @ts-expect-error: getUserByAccount is defined
- const fetchedUser = await nextAuthAdapter.getUserByAccount(account);
- expect(fetchedUser).toBeDefined();
- expect(fetchedUser?.id).toBe(user.id);
- expect(fetchedUser?.name).toBe(user.name);
- expect(fetchedUser?.email).toBe(user.email);
- expect(fetchedUser?.emailVerified).toEqual(user.emailVerified);
- expect(fetchedUser?.image).toBe(user.image);
- });
- });
-
- describe('updateUser', () => {
- it('should update a user', async () => {
- expect(nextAuthAdapter).toBeDefined();
- expect(nextAuthAdapter.updateUser).toBeDefined();
- const updatedName = 'updated' + user.name;
- const updatedEmail = 'updated' + user.email;
- // @ts-expect-error: updateUser is defined
- const updatedUser = await nextAuthAdapter.updateUser({
- id: userId,
- name: updatedName,
- email: updatedEmail,
- });
- expect(updatedUser).toBeDefined();
- expect(updatedUser.id).toBe(userId);
- expect(updatedUser.name).toBe(updatedName);
- expect(updatedUser.email).toBe(updatedEmail);
- });
- });
- });
-
- describe('authenticators', () => {
- describe('createAuthenticator', () => {
- it('should create a new authenticator', async () => {
- // Create an authenticator and link to the exists user
- const params: AdapterAuthenticator = {
- credentialBackedUp: false,
- credentialDeviceType: 'type',
- credentialID: 'some-id',
- credentialPublicKey: 'some-key',
- userId: userId,
- providerAccountId: 'provider-account-id',
- counter: 1,
- };
- expect(nextAuthAdapter).toBeDefined();
- expect(nextAuthAdapter.createAuthenticator).toBeDefined();
- // @ts-expect-error: createAuthenticator is defined
- const authenticator = await nextAuthAdapter.createAuthenticator(params);
-
- expect(authenticator).toBeDefined();
- expect(authenticator.userId).toBe(params.userId);
- expect(authenticator.providerAccountId).toBe(params.providerAccountId);
- });
- });
-
- describe('getAuthenticator', () => {
- it('should get an authenticator', async () => {
- // Create an authenticator and link to the exists user
- const params: AdapterAuthenticator = {
- credentialBackedUp: false,
- credentialDeviceType: 'type',
- credentialID: 'some-id',
- credentialPublicKey: 'some-key',
- userId: userId,
- providerAccountId: 'provider-account-id',
- counter: 1,
- };
- // @ts-expect-error: createAuthenticator is defined
- await nextAuthAdapter.createAuthenticator(params);
- expect(nextAuthAdapter).toBeDefined();
- expect(nextAuthAdapter.getAuthenticator).toBeDefined();
- // @ts-expect-error: getAuthenticator is defined
- const fetchedAuthenticator = await nextAuthAdapter.getAuthenticator(params.credentialID);
- expect(fetchedAuthenticator).toBeDefined();
- expect(fetchedAuthenticator?.userId).toBe(params.userId);
- expect(fetchedAuthenticator?.providerAccountId).toBe(params.providerAccountId);
- });
- });
-
- describe('updateAuthenticatorCounter', () => {
- it('should update an authenticator counter', async () => {
- // Create an authenticator and link to the exists user
- const params: AdapterAuthenticator = {
- credentialBackedUp: false,
- credentialDeviceType: 'type',
- credentialID: 'some-id',
- credentialPublicKey: 'some-key',
- userId: userId,
- providerAccountId: 'provider-account-id',
- counter: 1,
- };
- // @ts-expect-error: createAuthenticator is defined
- await nextAuthAdapter.createAuthenticator(params);
- expect(nextAuthAdapter).toBeDefined();
- expect(nextAuthAdapter.updateAuthenticatorCounter).toBeDefined();
- // @ts-expect-error: updateAuthenticatorCounter is defined
- const updatedAuthenticator = await nextAuthAdapter.updateAuthenticatorCounter(
- params.credentialID,
- 2,
- );
- expect(updatedAuthenticator).toBeDefined();
- expect(updatedAuthenticator.counter).toBe(2);
- });
- });
-
- describe('listAuthenticatorsByUserId', () => {
- it('should list authenticators by user id', async () => {
- // Create an authenticator and link to the exists user
- const params: AdapterAuthenticator = {
- credentialBackedUp: false,
- credentialDeviceType: 'type',
- credentialID: 'some-id',
- credentialPublicKey: 'some-key',
- userId: userId,
- providerAccountId: 'provider-account-id',
- counter: 1,
- };
- // @ts-expect-error: createAuthenticator is defined
- await nextAuthAdapter.createAuthenticator(params);
- expect(nextAuthAdapter).toBeDefined();
- expect(nextAuthAdapter.listAuthenticatorsByUserId).toBeDefined();
- // @ts-expect-error: listAuthenticatorsByUserId is defined
- const authenticators = await nextAuthAdapter.listAuthenticatorsByUserId(userId);
- expect(authenticators).toBeDefined();
- expect(authenticators.length).toBeGreaterThan(0);
- expect(authenticators[0].userId).toBe(params.userId);
- expect(authenticators[0].providerAccountId).toBe(params.providerAccountId);
- });
- });
- });
-
- describe('session', () => {
- describe('createSession', () => {
- it('should create a new session', async () => {
- const data: AdapterSession = {
- sessionToken,
- userId: userId,
- expires: new Date(),
- };
- expect(nextAuthAdapter).toBeDefined();
- expect(nextAuthAdapter.createSession).toBeDefined();
-
- // @ts-expect-error: createSession is defined
- const session = await nextAuthAdapter.createSession(data);
-
- expect(session).toBeDefined();
- expect(session.sessionToken).toBe(data.sessionToken);
- expect(session.userId).toBe(data.userId);
- expect(session.expires).toEqual(data.expires);
- });
- });
-
- describe('updateSession', () => {
- it('should update a session', async () => {
- const data: AdapterSession = {
- sessionToken,
- userId: userId,
- expires: new Date(),
- };
- // @ts-expect-error: createSession is defined
- await nextAuthAdapter.createSession(data);
- const updatedExpires = new Date();
- expect(nextAuthAdapter).toBeDefined();
- expect(nextAuthAdapter.updateSession).toBeDefined();
- // @ts-expect-error: updateSession is defined
- const updatedSession = await nextAuthAdapter.updateSession({
- sessionToken,
- expires: updatedExpires,
- });
- expect(updatedSession).toBeDefined();
- expect(updatedSession?.sessionToken).toBe(data.sessionToken);
- expect(updatedSession?.expires).toEqual(updatedExpires);
- });
- });
-
- describe('getSessionAndUser', () => {
- it('should get a session and user', async () => {
- // create session
- const data = {
- sessionToken,
- userId: userId,
- expires: new Date(),
- };
- // @ts-expect-error: createSession is defined
- await nextAuthAdapter.createSession(data);
-
- // @ts-expect-error: getSessionAndUser is defined
- const sessionAndUser = await nextAuthAdapter.getSessionAndUser(sessionToken);
- expect(sessionAndUser?.session.sessionToken).toBe(sessionToken);
- expect(sessionAndUser?.user.id).toBe(user.id);
- });
- });
-
- describe('deleteSession', () => {
- it('should delete a session', async () => {
- const data = {
- sessionToken,
- userId: userId,
- expires: new Date(),
- };
- // @ts-expect-error: createSession is defined
- await nextAuthAdapter.createSession(data);
-
- // @ts-expect-error: deleteSession is defined
- await nextAuthAdapter.deleteSession(sessionToken);
- const session = await serverDB.query.nextauthSessions.findFirst({
- where: eq(nextauthSessions.sessionToken, sessionToken),
- });
- expect(session).toBeUndefined();
- });
- });
- });
-
- describe('verificationToken', () => {
- describe('createVerificationToken', () => {
- it('should create a new verification token', async () => {
- const token: VerificationToken = {
- identifier: 'identifier',
- expires: new Date(),
- token: 'token',
- };
- // @ts-expect-error: createVerificationToken is defined
- const createdToken = await nextAuthAdapter.createVerificationToken(token);
- expect(createdToken).toBeDefined();
- expect(createdToken?.identifier).toBe(token.identifier);
- expect(createdToken?.expires).toEqual(token.expires);
- expect(createdToken?.token).toBe(token.token);
- });
- });
-
- describe('useVerificationToken', () => {
- it('should use a verification token if exist', async () => {
- const token: VerificationToken = {
- identifier: 'identifier',
- expires: new Date(),
- token: 'token2',
- };
- // @ts-expect-error: createVerificationToken is defined
- await nextAuthAdapter.createVerificationToken(token);
- // @ts-expect-error: useVerificationToken is defined
- await nextAuthAdapter.useVerificationToken(token.token);
- });
-
- it('should return null if the token does not exist', async () => {
- const token: VerificationToken = {
- identifier: 'identifier',
- expires: new Date(),
- token: 'token-not-exist',
- };
- // @ts-expect-error: useVerificationToken is defined
- const result = await nextAuthAdapter.useVerificationToken(token.token);
- expect(result).toBeNull();
- });
- });
- });
-
- describe('accounts', () => {
- describe('linkAccount', () => {
- it('should link an account', async () => {
- const account: AdapterAccount = {
- providerAccountId: 'provider-account-id',
- userId: userId,
- provider: 'auth0',
- type: 'email',
- };
- // @ts-expect-error: linkAccount is defined
- const insertedAccount = await nextAuthAdapter.linkAccount(account);
- expect(insertedAccount).toBeDefined();
- expect(insertedAccount?.providerAccountId).toBe(account.providerAccountId);
- expect(insertedAccount?.userId).toBe(userId);
- expect(insertedAccount?.provider).toBe(account.provider);
- expect(insertedAccount?.type).toBe(account.type);
- });
- });
-
- describe('getAccount', () => {
- it('should get an account', async () => {
- const account: AdapterAccount = {
- providerAccountId: 'provider-account-id',
- userId: userId,
- provider: 'auth0',
- type: 'email',
- };
- // @ts-expect-error: linkAccount is defined
- await nextAuthAdapter.linkAccount(account);
- // @ts-expect-error: getAccount is defined
- const fetchedAccount = await nextAuthAdapter.getAccount(
- account.providerAccountId,
- account.provider,
- );
- expect(fetchedAccount).toBeDefined();
- expect(fetchedAccount?.providerAccountId).toBe(account.providerAccountId);
- expect(fetchedAccount?.userId).toBe(userId);
- expect(fetchedAccount?.provider).toBe(account.provider);
- expect(fetchedAccount?.type).toBe(account.type);
- });
- });
-
- describe('unlinkAccount', () => {
- it('should unlink an account', async () => {
- const account: AdapterAccount = {
- providerAccountId: 'provider-account-id',
- userId: userId,
- provider: 'auth0',
- type: 'email',
- };
- // @ts-expect-error: linkAccount is defined
- await nextAuthAdapter.linkAccount(account);
- // @ts-expect-error: unlinkAccount is defined
- await nextAuthAdapter.unlinkAccount(account);
- const fetchedAccount = await serverDB.query.nextauthAccounts.findFirst({
- where: eq(nextauthAccounts.providerAccountId, account.providerAccountId),
- });
- expect(fetchedAccount).toBeUndefined();
- });
- });
- });
-});
diff --git a/packages/utils/src/server/__tests__/auth.test.ts b/packages/utils/src/server/__tests__/auth.test.ts
index 80241f9fda0..b819f91a716 100644
--- a/packages/utils/src/server/__tests__/auth.test.ts
+++ b/packages/utils/src/server/__tests__/auth.test.ts
@@ -28,7 +28,7 @@ vi.mock('@/libs/clerk-auth', () => ({
},
}));
-vi.mock('@/libs/next-auth/edge', () => ({
+vi.mock('@/libs/next-auth', () => ({
default: {
auth: vi.fn().mockResolvedValue({
user: {
diff --git a/packages/utils/src/server/auth.ts b/packages/utils/src/server/auth.ts
index 6b629b9170a..1f8981df8fa 100644
--- a/packages/utils/src/server/auth.ts
+++ b/packages/utils/src/server/auth.ts
@@ -12,9 +12,9 @@ export const getUserAuth = async () => {
}
if (enableNextAuth) {
- const { default: NextAuthEdge } = await import('@/libs/next-auth/edge');
+ const { default: NextAuth } = await import('@/libs/next-auth');
- const session = await NextAuthEdge.auth();
+ const session = await NextAuth.auth();
const userId = session?.user.id;
diff --git a/src/app/(backend)/api/auth/adapter/route.ts b/src/app/(backend)/api/auth/adapter/route.ts
new file mode 100644
index 00000000000..15a5e09bdbf
--- /dev/null
+++ b/src/app/(backend)/api/auth/adapter/route.ts
@@ -0,0 +1,137 @@
+import debug from 'debug';
+import { NextRequest, NextResponse } from 'next/server';
+
+import { serverDBEnv } from '@/config/db';
+import { serverDB } from '@/database/server';
+import { dateKeys } from '@/libs/next-auth/adapter';
+import { NextAuthUserService } from '@/server/services/nextAuthUser';
+
+const log = debug('lobe-next-auth:api:auth:adapter');
+
+/**
+ * @description Process the db query for the NextAuth adapter.
+ * Returns the db query result directly and let NextAuth handle the raw results.
+ * @returns {
+ * success: boolean; // Only return false if the database query fails or the action is invalid.
+ * data?: any;
+ * error?: string;
+ * }
+ */
+export async function POST(req: NextRequest) {
+ try {
+ // try validate the request
+ if (
+ !req.headers.get('Authorization') ||
+ req.headers.get('Authorization')?.trim() !== `Bearer ${serverDBEnv.KEY_VAULTS_SECRET}`
+ ) {
+ log('Unauthorized request, missing or invalid Authorization header');
+ return NextResponse.json({ error: 'Unauthorized', success: false }, { status: 401 });
+ }
+
+ // Parse the request body
+ const data = await req.json();
+ log('Received request data:', data);
+ // Preprocess
+ if (data?.data) {
+ for (const key of dateKeys) {
+ if (data?.data && data.data[key]) {
+ data.data[key] = new Date(data.data[key]);
+ continue;
+ }
+ }
+ }
+ const service = new NextAuthUserService(serverDB);
+ let result;
+ switch (data.action) {
+ case 'createAuthenticator': {
+ result = await service.createAuthenticator(data.data);
+ break;
+ }
+ case 'createSession': {
+ result = await service.createSession(data.data);
+ break;
+ }
+ case 'createUser': {
+ result = await service.createUser(data.data);
+ break;
+ }
+ case 'createVerificationToken': {
+ result = await service.createVerificationToken(data.data);
+ break;
+ }
+ case 'deleteSession': {
+ result = await service.deleteSession(data.data);
+ break;
+ }
+ case 'deleteUser': {
+ result = await service.deleteUser(data.data);
+ break;
+ }
+ case 'getAccount': {
+ result = await service.getAccount(data.data.providerAccountId, data.data.provider);
+ break;
+ }
+ case 'getAuthenticator': {
+ result = await service.getAuthenticator(data.data);
+ break;
+ }
+ case 'getSessionAndUser': {
+ result = await service.getSessionAndUser(data.data);
+ break;
+ }
+ case 'getUser': {
+ result = await service.getUser(data.data);
+ break;
+ }
+ case 'getUserByAccount': {
+ result = await service.getUserByAccount(data.data);
+ break;
+ }
+ case 'getUserByEmail': {
+ result = await service.getUserByEmail(data.data);
+ break;
+ }
+ case 'linkAccount': {
+ result = await service.linkAccount(data.data);
+ break;
+ }
+ case 'listAuthenticatorsByUserId': {
+ result = await service.listAuthenticatorsByUserId(data.data);
+ break;
+ }
+ case 'unlinkAccount': {
+ result = await service.unlinkAccount(data.data);
+ break;
+ }
+ case 'updateAuthenticatorCounter': {
+ result = await service.updateAuthenticatorCounter(
+ data.data.credentialID,
+ data.data.counter,
+ );
+ break;
+ }
+ case 'updateSession': {
+ result = await service.updateSession(data.data);
+ break;
+ }
+ case 'updateUser': {
+ result = await service.updateUser(data.data);
+ break;
+ }
+ case 'useVerificationToken': {
+ result = await service.useVerificationToken(data.data);
+ break;
+ }
+ default: {
+ return NextResponse.json({ error: 'Invalid action', success: false }, { status: 400 });
+ }
+ }
+ return NextResponse.json({ data: result, success: true });
+ } catch (error) {
+ log('Error processing request:');
+ log(error);
+ return NextResponse.json({ error, success: false }, { status: 400 });
+ }
+}
+
+export const runtime = 'nodejs';
diff --git a/src/app/(backend)/api/webhooks/logto/route.ts b/src/app/(backend)/api/webhooks/logto/route.ts
index 39bddd15ed1..e5cd6feb237 100644
--- a/src/app/(backend)/api/webhooks/logto/route.ts
+++ b/src/app/(backend)/api/webhooks/logto/route.ts
@@ -36,6 +36,15 @@ export const POST = async (req: Request): Promise<NextResponse> => {
},
);
}
+ case 'User.SuspensionStatus.Updated': {
+ if (data.isSuspended) {
+ return nextAuthUserService.safeSignOutUser({
+ provider: 'logto',
+ providerAccountId: data.id,
+ });
+ }
+ return NextResponse.json({ message: 'user reactivated', success: true }, { status: 200 });
+ }
default: {
pino.warn(
diff --git a/src/config/auth.ts b/src/config/auth.ts
index adee4abfb04..d3529013ffe 100644
--- a/src/config/auth.ts
+++ b/src/config/auth.ts
@@ -18,6 +18,8 @@ declare global {
NEXT_AUTH_DEBUG?: string;
+ NEXT_AUTH_SSO_SESSION_STRATEGY?: string;
+
AUTH0_CLIENT_ID?: string;
AUTH0_CLIENT_SECRET?: string;
AUTH0_ISSUER?: string;
@@ -159,6 +161,7 @@ export const getAuthConfig = () => {
NEXT_AUTH_SECRET: z.string().optional(),
NEXT_AUTH_SSO_PROVIDERS: z.string().optional().default('auth0'),
NEXT_AUTH_DEBUG: z.boolean().optional().default(false),
+ NEXT_AUTH_SSO_SESSION_STRATEGY: z.enum(['jwt', 'database']).optional().default('jwt'),
// Auth0
AUTH0_CLIENT_ID: z.string().optional(),
@@ -221,6 +224,7 @@ export const getAuthConfig = () => {
NEXT_AUTH_SSO_PROVIDERS: process.env.NEXT_AUTH_SSO_PROVIDERS,
NEXT_AUTH_SECRET: process.env.NEXT_AUTH_SECRET,
NEXT_AUTH_DEBUG: !!process.env.NEXT_AUTH_DEBUG,
+ NEXT_AUTH_SSO_SESSION_STRATEGY: process.env.NEXT_AUTH_SSO_SESSION_STRATEGY || 'jwt',
// Auth0
AUTH0_CLIENT_ID: process.env.AUTH0_CLIENT_ID,
diff --git a/src/libs/next-auth/adapter/index.ts b/src/libs/next-auth/adapter/index.ts
index 0c5dd6bab20..df91c3a4739 100644
--- a/src/libs/next-auth/adapter/index.ts
+++ b/src/libs/next-auth/adapter/index.ts
@@ -4,273 +4,175 @@ import type {
AdapterUser,
VerificationToken,
} from '@auth/core/adapters';
-import { and, eq } from 'drizzle-orm';
-import type { NeonDatabase } from 'drizzle-orm/neon-serverless';
+import debug from 'debug';
import { Adapter, AdapterAccount } from 'next-auth/adapters';
+import urlJoin from 'url-join';
-import { UserModel } from '@/database/models/user';
-import * as schema from '@/database/schemas';
-import { AgentService } from '@/server/services/agent';
-import { merge } from '@/utils/merge';
+import { serverDBEnv } from '@/config/db';
+import { appEnv } from '@/envs/app';
-import {
- mapAdapterUserToLobeUser,
- mapAuthenticatorQueryResutlToAdapterAuthenticator,
- mapLobeUserToAdapterUser,
- partialMapAdapterUserToLobeUser,
-} from './utils';
+const log = debug('lobe-next-auth:adapter');
-const {
- nextauthAccounts,
- nextauthAuthenticators,
- nextauthSessions,
- nextauthVerificationTokens,
- users,
-} = schema;
+interface BackendAdapterResponse {
+ data?: any;
+ error?: string;
+ success: boolean;
+}
+
+// Due to use direct HTTP Post, the date string cannot parse automatically
+export const dateKeys = ['expires', 'emailVerified'];
/**
* @description LobeNextAuthDbAdapter is implemented to handle the database operations
* for NextAuth, this function do the same things as `src/app/api/webhooks/clerk/route.ts`
* @returns {Adapter}
*/
-export function LobeNextAuthDbAdapter(serverDB: NeonDatabase<typeof schema>): Adapter {
+export function LobeNextAuthDbAdapter(): Adapter {
+ const baseUrl = appEnv.APP_URL;
+
+ // Ensure the baseUrl is set, otherwise throw an error
+ if (!baseUrl) {
+ throw new Error('LobeNextAuthDbAdapter: APP_URL is not set in environment variables');
+ }
+ const interactionUrl = urlJoin(baseUrl, '/api/auth/adapter');
+ log(`LobeNextAuthDbAdapter initialized with url: ${interactionUrl}`);
+
+ // Ensure serverDBEnv.KEY_VAULTS_SECRET is set, otherwise throw an error
+ if (!serverDBEnv.KEY_VAULTS_SECRET) {
+ throw new Error('LobeNextAuthDbAdapter: KEY_VAULTS_SECRET is not set in environment variables');
+ }
+
+ const fetcher = (action: string, data: any) =>
+ fetch(interactionUrl, {
+ body: JSON.stringify({ action, data }),
+ headers: {
+ 'Authorization': `Bearer ${serverDBEnv.KEY_VAULTS_SECRET}`,
+ 'Content-Type': 'application/json',
+ },
+ method: 'POST',
+ });
+ const postProcessor = async (res: Response) => {
+ const data = (await res.json()) as BackendAdapterResponse;
+ log('LobeNextAuthDbAdapter: postProcessor called with data:', data);
+ if (!data.success) {
+ log('LobeNextAuthDbAdapter: Error in postProcessor:');
+ log(data);
+ throw new Error(`LobeNextAuthDbAdapter: ${data.error}`);
+ }
+ if (data?.data) {
+ for (const key of dateKeys) {
+ if (data.data[key]) {
+ data.data[key] = new Date(data.data[key]);
+ continue;
+ }
+ }
+ }
+ return data.data;
+ };
+
return {
async createAuthenticator(authenticator): Promise<AdapterAuthenticator> {
- const result = await serverDB
- .insert(nextauthAuthenticators)
- .values(authenticator)
- .returning()
- .then((res) => res[0] ?? undefined);
- if (!result) throw new Error('LobeNextAuthDbAdapter: Failed to create authenticator');
- return mapAuthenticatorQueryResutlToAdapterAuthenticator(result);
+ const data = await fetcher('createAuthenticator', authenticator);
+ return await postProcessor(data);
},
- async createSession(data): Promise<AdapterSession> {
- return serverDB
- .insert(nextauthSessions)
- .values(data)
- .returning()
- .then((res) => res[0]);
+ async createSession(session): Promise<AdapterSession> {
+ const data = await fetcher('createSession', session);
+ return await postProcessor(data);
},
async createUser(user): Promise<AdapterUser> {
- const { id, name, email, emailVerified, image, providerAccountId } = user;
- // return the user if it already exists
- let existingUser =
- email && typeof email === 'string' && email.trim()
- ? await UserModel.findByEmail(serverDB, email)
- : undefined;
- // If the user is not found by email, try to find by providerAccountId
- if (!existingUser && providerAccountId) {
- existingUser = await UserModel.findById(serverDB, providerAccountId);
- }
- if (existingUser) {
- const adapterUser = mapLobeUserToAdapterUser(existingUser);
- return adapterUser;
- }
-
- // create a new user if it does not exist
- // Use id from provider if it exists, otherwise use id assigned by next-auth
- // ref: https://github.com/lobehub/lobe-chat/pull/2935
- const uid = providerAccountId ?? id;
- await UserModel.createUser(
- serverDB,
- mapAdapterUserToLobeUser({
- email,
- emailVerified,
- // Use providerAccountId as userid to identify if the user exists in a SSO provider
- id: uid,
- image,
- name,
- }),
- );
-
- // 3. Create an inbox session for the user
- const agentService = new AgentService(serverDB, uid);
- await agentService.createInbox();
-
- return { ...user, id: uid };
+ const data = await fetcher('createUser', user);
+ return await postProcessor(data);
},
async createVerificationToken(data): Promise<VerificationToken | null | undefined> {
- return serverDB
- .insert(nextauthVerificationTokens)
- .values(data)
- .returning()
- .then((res) => res[0]);
+ const result = await fetcher('createVerificationToken', data);
+ return await postProcessor(result);
},
async deleteSession(sessionToken): Promise<AdapterSession | null | undefined> {
- await serverDB
- .delete(nextauthSessions)
- .where(eq(nextauthSessions.sessionToken, sessionToken));
+ const result = await fetcher('deleteSession', sessionToken);
+ await postProcessor(result);
return;
},
async deleteUser(id): Promise<AdapterUser | null | undefined> {
- const user = await UserModel.findById(serverDB, id);
- if (!user) throw new Error('NextAuth: Delete User not found');
-
- await UserModel.deleteUser(serverDB, id);
+ const result = await fetcher('deleteUser', id);
+ await postProcessor(result);
return;
},
async getAccount(providerAccountId, provider): Promise<AdapterAccount | null> {
- return serverDB
- .select()
- .from(nextauthAccounts)
- .where(
- and(
- eq(nextauthAccounts.provider, provider),
- eq(nextauthAccounts.providerAccountId, providerAccountId),
- ),
- )
- .then((res) => res[0] ?? null) as Promise<AdapterAccount | null>;
+ const data = await fetcher('getAccount', {
+ provider,
+ providerAccountId,
+ });
+ return await postProcessor(data);
},
async getAuthenticator(credentialID): Promise<AdapterAuthenticator | null> {
- const result = await serverDB
- .select()
- .from(nextauthAuthenticators)
- .where(eq(nextauthAuthenticators.credentialID, credentialID))
- .then((res) => res[0] ?? null);
- if (!result) throw new Error('LobeNextAuthDbAdapter: Failed to get authenticator');
- return mapAuthenticatorQueryResutlToAdapterAuthenticator(result);
+ const result = await fetcher('getAuthenticator', credentialID);
+ return await postProcessor(result);
},
async getSessionAndUser(sessionToken): Promise<{
session: AdapterSession;
user: AdapterUser;
} | null> {
- const result = await serverDB
- .select({
- session: nextauthSessions,
- user: users,
- })
- .from(nextauthSessions)
- .where(eq(nextauthSessions.sessionToken, sessionToken))
- .innerJoin(users, eq(users.id, nextauthSessions.userId))
- .then((res) => (res.length > 0 ? res[0] : null));
-
- if (!result) return null;
- const adapterUser = mapLobeUserToAdapterUser(result.user);
- if (!adapterUser) return null;
- return {
- session: result.session,
- user: adapterUser,
- };
+ const result = await fetcher('getSessionAndUser', sessionToken);
+ return await postProcessor(result);
},
async getUser(id): Promise<AdapterUser | null> {
- const lobeUser = await UserModel.findById(serverDB, id);
- if (!lobeUser) return null;
- return mapLobeUserToAdapterUser(lobeUser);
+ log('getUser called with id:', id);
+ const result = await fetcher('getUser', id);
+ return await postProcessor(result);
},
async getUserByAccount(account): Promise<AdapterUser | null> {
- const result = await serverDB
- .select({
- account: nextauthAccounts,
- users,
- })
- .from(nextauthAccounts)
- .innerJoin(users, eq(nextauthAccounts.userId, users.id))
- .where(
- and(
- eq(nextauthAccounts.provider, account.provider),
- eq(nextauthAccounts.providerAccountId, account.providerAccountId),
- ),
- )
- .then((res) => res[0]);
-
- return result?.users ? mapLobeUserToAdapterUser(result.users) : null;
+ const data = await fetcher('getUserByAccount', account);
+ return await postProcessor(data);
},
async getUserByEmail(email): Promise<AdapterUser | null> {
- const lobeUser =
- email && typeof email === 'string' && email.trim()
- ? await UserModel.findByEmail(serverDB, email)
- : undefined;
- return lobeUser ? mapLobeUserToAdapterUser(lobeUser) : null;
+ const data = await fetcher('getUserByEmail', email);
+ return await postProcessor(data);
},
async linkAccount(data): Promise<AdapterAccount | null | undefined> {
- const [account] = await serverDB
- .insert(nextauthAccounts)
- .values(data as any)
- .returning();
- if (!account) throw new Error('NextAuthAccountModel: Failed to create account');
- // TODO Update type annotation
- return account as any;
+ const result = await fetcher('linkAccount', data);
+ return await postProcessor(result);
},
async listAuthenticatorsByUserId(userId): Promise<AdapterAuthenticator[]> {
- const result = await serverDB
- .select()
- .from(nextauthAuthenticators)
- .where(eq(nextauthAuthenticators.userId, userId))
- .then((res) => res);
- if (result.length === 0)
- throw new Error('LobeNextAuthDbAdapter: Failed to get authenticator list');
- return result.map((r) => mapAuthenticatorQueryResutlToAdapterAuthenticator(r));
+ const result = await fetcher('listAuthenticatorsByUserId', userId);
+ return await postProcessor(result);
},
// @ts-ignore: The return type is {Promise<void> | Awaitable<AdapterAccount | undefined>}
async unlinkAccount(account): Promise<void | AdapterAccount | undefined> {
- await serverDB
- .delete(nextauthAccounts)
- .where(
- and(
- eq(nextauthAccounts.provider, account.provider),
- eq(nextauthAccounts.providerAccountId, account.providerAccountId),
- ),
- );
+ const result = await fetcher('unlinkAccount', account);
+ await postProcessor(result);
+ return;
},
async updateAuthenticatorCounter(credentialID, counter): Promise<AdapterAuthenticator> {
- const result = await serverDB
- .update(nextauthAuthenticators)
- .set({ counter })
- .where(eq(nextauthAuthenticators.credentialID, credentialID))
- .returning()
- .then((res) => res[0]);
- if (!result) throw new Error('LobeNextAuthDbAdapter: Failed to update authenticator counter');
- return mapAuthenticatorQueryResutlToAdapterAuthenticator(result);
+ const result = await fetcher('updateAuthenticatorCounter', {
+ counter,
+ credentialID,
+ });
+ return await postProcessor(result);
},
async updateSession(data): Promise<AdapterSession | null | undefined> {
- const res = await serverDB
- .update(nextauthSessions)
- .set(data)
- .where(eq(nextauthSessions.sessionToken, data.sessionToken))
- .returning();
- return res[0];
+ const result = await fetcher('updateSession', data);
+ return await postProcessor(result);
},
async updateUser(user): Promise<AdapterUser> {
- const lobeUser = await UserModel.findById(serverDB, user?.id);
- if (!lobeUser) throw new Error('NextAuth: User not found');
- const userModel = new UserModel(serverDB, user.id);
-
- const updatedUser = await userModel.updateUser({
- ...partialMapAdapterUserToLobeUser(user),
- });
- if (!updatedUser) throw new Error('NextAuth: Failed to update user');
-
- // merge new user data with old user data
- const newAdapterUser = mapLobeUserToAdapterUser(lobeUser);
- if (!newAdapterUser) {
- throw new Error('NextAuth: Failed to map user data to adapter user');
- }
- return merge(newAdapterUser, user);
+ const result = await fetcher('updateUser', user);
+ return await postProcessor(result);
},
async useVerificationToken(identifier_token): Promise<VerificationToken | null> {
- return serverDB
- .delete(nextauthVerificationTokens)
- .where(
- and(
- eq(nextauthVerificationTokens.identifier, identifier_token.identifier),
- eq(nextauthVerificationTokens.token, identifier_token.token),
- ),
- )
- .returning()
- .then((res) => (res.length > 0 ? res[0] : null));
+ const result = await fetcher('useVerificationToken', identifier_token);
+ return await postProcessor(result);
},
};
}
diff --git a/src/libs/next-auth/auth.config.ts b/src/libs/next-auth/auth.config.ts
index 6ba7bacf7a3..a9401bdfb40 100644
--- a/src/libs/next-auth/auth.config.ts
+++ b/src/libs/next-auth/auth.config.ts
@@ -1,12 +1,24 @@
import type { NextAuthConfig } from 'next-auth';
-import { authEnv } from '@/config/auth';
+import { getAuthConfig } from '@/config/auth';
+import { getServerDBConfig } from '@/config/db';
+import { LobeNextAuthDbAdapter } from './adapter';
import { ssoProviders } from './sso-providers';
+const {
+ NEXT_AUTH_DEBUG,
+ NEXT_AUTH_SECRET,
+ NEXT_AUTH_SSO_SESSION_STRATEGY,
+ NEXT_AUTH_SSO_PROVIDERS,
+ NEXT_PUBLIC_ENABLE_NEXT_AUTH,
+} = getAuthConfig();
+
+const { NEXT_PUBLIC_ENABLED_SERVER_SERVICE } = getServerDBConfig();
+
export const initSSOProviders = () => {
- return authEnv.NEXT_PUBLIC_ENABLE_NEXT_AUTH
- ? authEnv.NEXT_AUTH_SSO_PROVIDERS.split(/[,,]/).map((provider) => {
+ return NEXT_PUBLIC_ENABLE_NEXT_AUTH
+ ? NEXT_AUTH_SSO_PROVIDERS.split(/[,,]/).map((provider) => {
const validProvider = ssoProviders.find((item) => item.id === provider.trim());
if (validProvider) return validProvider.provider;
@@ -18,6 +30,7 @@ export const initSSOProviders = () => {
// Notice this is only an object, not a full Auth.js instance
export default {
+ adapter: NEXT_PUBLIC_ENABLED_SERVER_SERVICE ? LobeNextAuthDbAdapter() : undefined,
callbacks: {
// Note: Data processing order of callback: authorize --> jwt --> session
async jwt({ token, user }) {
@@ -39,12 +52,16 @@ export default {
return session;
},
},
- debug: authEnv.NEXT_AUTH_DEBUG,
+ debug: NEXT_AUTH_DEBUG,
pages: {
error: '/next-auth/error',
signIn: '/next-auth/signin',
},
providers: initSSOProviders(),
- secret: authEnv.NEXT_AUTH_SECRET,
+ secret: NEXT_AUTH_SECRET,
+ session: {
+ // Force use JWT if server service is disabled
+ strategy: NEXT_PUBLIC_ENABLED_SERVER_SERVICE ? NEXT_AUTH_SSO_SESSION_STRATEGY : 'jwt',
+ },
trustHost: process.env?.AUTH_TRUST_HOST ? process.env.AUTH_TRUST_HOST === 'true' : true,
} satisfies NextAuthConfig;
diff --git a/src/libs/next-auth/edge.ts b/src/libs/next-auth/edge.ts
deleted file mode 100644
index 4f20532d974..00000000000
--- a/src/libs/next-auth/edge.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import NextAuth from 'next-auth';
-
-import authConfig from './auth.config';
-
-/**
- * NextAuth initialization without Database adapter
- *
- * @example
- * ```ts
- * import NextAuthEdge from '@/libs/next-auth/edge';
- * const { auth } = NextAuthEdge;
- * ```
- *
- * @note
- * We currently use `jwt` strategy for session management.
- * So you don't need to import `signIn` or `signOut` from
- * this module, just import from `next-auth` directly.
- *
- * Inside react component
- * @example
- * ```ts
- * import { signOut } from 'next-auth/react';
- * signOut();
- * ```
- */
-export default NextAuth(authConfig);
diff --git a/src/libs/next-auth/index.ts b/src/libs/next-auth/index.ts
index 807eb61af22..70c2490c1fb 100644
--- a/src/libs/next-auth/index.ts
+++ b/src/libs/next-auth/index.ts
@@ -1,33 +1,20 @@
import NextAuth from 'next-auth';
-import { getServerDBConfig } from '@/config/db';
-import { serverDB } from '@/database/server';
-
-import { LobeNextAuthDbAdapter } from './adapter';
-import config from './auth.config';
-
-const { NEXT_PUBLIC_ENABLED_SERVER_SERVICE } = getServerDBConfig();
+import authConfig from './auth.config';
/**
- * NextAuth initialization with Database adapter
+ * NextAuth initialization without Database adapter
+ *
+ * @note
+ * We currently use `jwt` strategy for session management.
+ * So you don't need to import `signIn` or `signOut` from
+ * this module, just import from `next-auth` directly.
*
+ * Inside react component
* @example
* ```ts
- * import NextAuthNode from '@/libs/next-auth';
- * const { handlers } = NextAuthNode;
+ * import { signOut } from 'next-auth/react';
+ * signOut();
* ```
- *
- * @note
- * If you meet the edge runtime compatible problem,
- * you can import from `@/libs/next-auth/edge` which is not initial with the database adapter.
- *
- * The difference and usage of the two different NextAuth modules is can be
- * ref to: https://github.com/lobehub/lobe-chat/pull/2935
*/
-export default NextAuth({
- ...config,
- adapter: NEXT_PUBLIC_ENABLED_SERVER_SERVICE ? LobeNextAuthDbAdapter(serverDB) : undefined,
- session: {
- strategy: 'jwt',
- },
-});
+export default NextAuth(authConfig);
diff --git a/src/libs/trpc/edge/context.ts b/src/libs/trpc/edge/context.ts
index 8de438e6d5a..af7570d39b7 100644
--- a/src/libs/trpc/edge/context.ts
+++ b/src/libs/trpc/edge/context.ts
@@ -54,9 +54,9 @@ export const createEdgeContext = async (request: NextRequest): Promise<EdgeConte
if (enableNextAuth) {
try {
- const { default: NextAuthEdge } = await import('@/libs/next-auth/edge');
+ const { default: NextAuth } = await import('@/libs/next-auth');
- const session = await NextAuthEdge.auth();
+ const session = await NextAuth.auth();
if (session && session?.user?.id) {
auth = session.user;
userId = session.user.id;
diff --git a/src/libs/trpc/lambda/context.ts b/src/libs/trpc/lambda/context.ts
index 77c7e3ce871..4b17d7b215f 100644
--- a/src/libs/trpc/lambda/context.ts
+++ b/src/libs/trpc/lambda/context.ts
@@ -161,9 +161,9 @@ export const createLambdaContext = async (request: NextRequest): Promise<LambdaC
if (enableNextAuth) {
log('Attempting NextAuth authentication');
try {
- const { default: NextAuthEdge } = await import('@/libs/next-auth/edge');
+ const { default: NextAuth } = await import('@/libs/next-auth');
- const session = await NextAuthEdge.auth();
+ const session = await NextAuth.auth();
if (session && session?.user?.id) {
auth = session.user;
userId = session.user.id;
diff --git a/src/middleware.ts b/src/middleware.ts
index 854f058da99..aafd4a5c396 100644
--- a/src/middleware.ts
+++ b/src/middleware.ts
@@ -10,7 +10,7 @@ import { OAUTH_AUTHORIZED } from '@/const/auth';
import { LOBE_LOCALE_COOKIE } from '@/const/locale';
import { LOBE_THEME_APPEARANCE } from '@/const/theme';
import { appEnv } from '@/envs/app';
-import NextAuthEdge from '@/libs/next-auth/edge';
+import NextAuth from '@/libs/next-auth';
import { Locales } from '@/locales/resources';
import { oidcEnv } from './envs/oidc';
@@ -170,7 +170,7 @@ const isProtectedRoute = createRouteMatcher([
]);
// Initialize an Edge compatible NextAuth middleware
-const nextAuthMiddleware = NextAuthEdge.auth(async (req) => {
+const nextAuthMiddleware = NextAuth.auth((req) => {
logNextAuth('NextAuth middleware processing request: %s %s', req.method, req.url);
const response = defaultMiddleware(req);
diff --git a/src/server/routers/lambda/user.test.ts b/src/server/routers/lambda/user.test.ts
index 1466dd5304e..360bcc5d080 100644
--- a/src/server/routers/lambda/user.test.ts
+++ b/src/server/routers/lambda/user.test.ts
@@ -6,8 +6,8 @@ import { MessageModel } from '@/database/models/message';
import { SessionModel } from '@/database/models/session';
import { UserModel, UserNotFoundError } from '@/database/models/user';
import { serverDB } from '@/database/server';
-import { LobeNextAuthDbAdapter } from '@/libs/next-auth/adapter';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+import { NextAuthUserService } from '@/server/services/nextAuthUser';
import { UserService } from '@/server/services/user';
import { userRouter } from './user';
@@ -24,10 +24,10 @@ vi.mock('@/database/server', () => ({
vi.mock('@/database/models/message');
vi.mock('@/database/models/session');
vi.mock('@/database/models/user');
-vi.mock('@/libs/next-auth/adapter');
vi.mock('@/server/modules/KeyVaultsEncrypt');
vi.mock('@/server/modules/S3');
vi.mock('@/server/services/user');
+vi.mock('@/server/services/nextAuthUser');
vi.mock('@/const/auth', () => ({
enableClerk: true,
}));
@@ -221,7 +221,7 @@ describe('userRouter', () => {
type: 'oauth',
};
- vi.mocked(LobeNextAuthDbAdapter).mockReturnValue({
+ vi.mocked(NextAuthUserService).mockReturnValue({
getAccount: vi.fn().mockResolvedValue(mockAccount),
unlinkAccount: vi.fn().mockResolvedValue(undefined),
} as any);
@@ -237,7 +237,7 @@ describe('userRouter', () => {
providerAccountId: '123',
};
- vi.mocked(LobeNextAuthDbAdapter).mockReturnValue({
+ vi.mocked(NextAuthUserService).mockReturnValue({
getAccount: vi.fn().mockResolvedValue(null),
unlinkAccount: vi.fn(),
} as any);
@@ -246,19 +246,6 @@ describe('userRouter', () => {
userRouter.createCaller({ ...mockCtx }).unlinkSSOProvider(mockInput),
).rejects.toThrow('The account does not exist');
});
-
- it('should throw error if adapter methods are not implemented', async () => {
- const mockInput = {
- provider: 'google',
- providerAccountId: '123',
- };
-
- vi.mocked(LobeNextAuthDbAdapter).mockReturnValue({} as any);
-
- await expect(
- userRouter.createCaller({ ...mockCtx }).unlinkSSOProvider(mockInput),
- ).rejects.toThrow('The method in LobeNextAuthDbAdapter `unlinkAccount` is not implemented');
- });
});
describe('updateSettings', () => {
diff --git a/src/server/routers/lambda/user.ts b/src/server/routers/lambda/user.ts
index 86aff358cf8..be7217677a9 100644
--- a/src/server/routers/lambda/user.ts
+++ b/src/server/routers/lambda/user.ts
@@ -9,12 +9,12 @@ import { SessionModel } from '@/database/models/session';
import { UserModel, UserNotFoundError } from '@/database/models/user';
import { ClerkAuth } from '@/libs/clerk-auth';
import { pino } from '@/libs/logger';
-import { LobeNextAuthDbAdapter } from '@/libs/next-auth/adapter';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import { S3 } from '@/server/modules/S3';
import { FileService } from '@/server/services/file';
+import { NextAuthUserService } from '@/server/services/nextAuthUser';
import { UserService } from '@/server/services/user';
import {
NextAuthAccountSchame,
@@ -29,7 +29,7 @@ const userProcedure = authedProcedure.use(serverDatabase).use(async ({ ctx, next
ctx: {
clerkAuth: new ClerkAuth(),
fileService: new FileService(ctx.serverDB, ctx.userId),
- nextAuthDbAdapter: LobeNextAuthDbAdapter(ctx.serverDB),
+ nextAuthUserService: new NextAuthUserService(ctx.serverDB),
userModel: new UserModel(ctx.serverDB, ctx.userId),
},
});
@@ -134,19 +134,10 @@ export const userRouter = router({
unlinkSSOProvider: userProcedure.input(NextAuthAccountSchame).mutation(async ({ ctx, input }) => {
const { provider, providerAccountId } = input;
- if (
- ctx.nextAuthDbAdapter?.unlinkAccount &&
- typeof ctx.nextAuthDbAdapter.unlinkAccount === 'function' &&
- ctx.nextAuthDbAdapter?.getAccount &&
- typeof ctx.nextAuthDbAdapter.getAccount === 'function'
- ) {
- const account = await ctx.nextAuthDbAdapter.getAccount(providerAccountId, provider);
- // The userId can either get from ctx.nextAuth?.id or ctx.userId
- if (!account || account.userId !== ctx.userId) throw new Error('The account does not exist');
- await ctx.nextAuthDbAdapter.unlinkAccount({ provider, providerAccountId });
- } else {
- throw new Error('The method in LobeNextAuthDbAdapter `unlinkAccount` is not implemented');
- }
+ const account = await ctx.nextAuthUserService.getAccount(providerAccountId, provider);
+ // The userId can either get from ctx.nextAuth?.id or ctx.userId
+ if (!account || account.userId !== ctx.userId) throw new Error('The account does not exist');
+ await ctx.nextAuthUserService.unlinkAccount({ provider, providerAccountId });
}),
// 服务端上传头像
diff --git a/src/server/services/nextAuthUser/index.test.ts b/src/server/services/nextAuthUser/index.test.ts
deleted file mode 100644
index cab84d527bb..00000000000
--- a/src/server/services/nextAuthUser/index.test.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-// @vitest-environment node
-import { NextResponse } from 'next/server';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { UserModel } from '@/database/models/user';
-import { UserItem } from '@/database/schemas';
-import { serverDB } from '@/database/server';
-import { pino } from '@/libs/logger';
-
-import { NextAuthUserService } from './index';
-
-vi.mock('@/libs/logger', () => ({
- pino: {
- info: vi.fn(),
- warn: vi.fn(),
- },
-}));
-
-vi.mock('@/database/models/user');
-vi.mock('@/database/server');
-
-describe('NextAuthUserService', () => {
- let service: NextAuthUserService;
-
- beforeEach(async () => {
- vi.clearAllMocks();
- service = new NextAuthUserService(serverDB);
- });
-
- describe('safeUpdateUser', () => {
- const mockUser = {
- id: 'user-123',
- email: '[email protected]',
- };
-
- const mockAccount = {
- provider: 'github',
- providerAccountId: '12345',
- };
-
- const mockUpdateData: Partial<UserItem> = {
- avatar: 'https://example.com/avatar.jpg',
- email: '[email protected]',
- fullName: 'Test User',
- };
-
- it('should update user when user is found', async () => {
- const mockUserModel = {
- updateUser: vi.fn().mockResolvedValue({}),
- };
-
- vi.mocked(UserModel).mockImplementation(() => mockUserModel as any);
-
- // Mock the adapter directly on the service instance
- service.adapter = {
- getUserByAccount: vi.fn().mockResolvedValue(mockUser),
- };
-
- const response = await service.safeUpdateUser(mockAccount, mockUpdateData);
-
- expect(pino.info).toHaveBeenCalledWith(
- `updating user "${JSON.stringify(mockAccount)}" due to webhook`,
- );
-
- expect(service.adapter.getUserByAccount).toHaveBeenCalledWith(mockAccount);
- expect(UserModel).toHaveBeenCalledWith(serverDB, mockUser.id);
- expect(mockUserModel.updateUser).toHaveBeenCalledWith(mockUpdateData);
-
- expect(response).toBeInstanceOf(NextResponse);
- expect(response.status).toBe(200);
- const data = await response.json();
- expect(data).toEqual({ message: 'user updated', success: true });
- });
-
- it('should handle case when user is not found', async () => {
- // Mock the adapter directly on the service instance
- service.adapter = {
- getUserByAccount: vi.fn().mockResolvedValue(null),
- };
-
- const response = await service.safeUpdateUser(mockAccount, mockUpdateData);
-
- expect(pino.warn).toHaveBeenCalledWith(
- `[${mockAccount.provider}]: Webhooks handler user "${JSON.stringify(mockAccount)}" update for "${JSON.stringify(mockUpdateData)}", but no user was found by the providerAccountId.`,
- );
-
- expect(UserModel).not.toHaveBeenCalled();
-
- expect(response).toBeInstanceOf(NextResponse);
- expect(response.status).toBe(200);
- const data = await response.json();
- expect(data).toEqual({ message: 'user updated', success: true });
- });
-
- it('should handle errors during user update', async () => {
- const mockError = new Error('Database error');
-
- // Mock the adapter directly on the service instance
- service.adapter = {
- getUserByAccount: vi.fn().mockRejectedValue(mockError),
- };
-
- await expect(service.safeUpdateUser(mockAccount, mockUpdateData)).rejects.toThrow(mockError);
-
- expect(UserModel).not.toHaveBeenCalled();
- });
- });
-});
diff --git a/src/server/services/nextAuthUser/index.ts b/src/server/services/nextAuthUser/index.ts
index 8f09bff19f1..bdf45d4f8e7 100644
--- a/src/server/services/nextAuthUser/index.ts
+++ b/src/server/services/nextAuthUser/index.ts
@@ -1,18 +1,33 @@
+import { and, eq } from 'drizzle-orm';
+import { Adapter, AdapterAccount } from 'next-auth/adapters';
import { NextResponse } from 'next/server';
import { UserModel } from '@/database/models/user';
-import { UserItem } from '@/database/schemas';
+import {
+ UserItem,
+ nextauthAccounts,
+ nextauthAuthenticators,
+ nextauthSessions,
+ nextauthVerificationTokens,
+ users,
+} from '@/database/schemas';
import { LobeChatDatabase } from '@/database/type';
import { pino } from '@/libs/logger';
-import { LobeNextAuthDbAdapter } from '@/libs/next-auth/adapter';
+import { merge } from '@/utils/merge';
+
+import { AgentService } from '../agent';
+import {
+ mapAdapterUserToLobeUser,
+ mapAuthenticatorQueryResutlToAdapterAuthenticator,
+ mapLobeUserToAdapterUser,
+ partialMapAdapterUserToLobeUser,
+} from './utils';
export class NextAuthUserService {
- adapter;
private db: LobeChatDatabase;
constructor(db: LobeChatDatabase) {
this.db = db;
- this.adapter = LobeNextAuthDbAdapter(db);
}
safeUpdateUser = async (
@@ -21,8 +36,7 @@ export class NextAuthUserService {
) => {
pino.info(`updating user "${JSON.stringify({ provider, providerAccountId })}" due to webhook`);
// 1. Find User by account
- // @ts-expect-error: Already impl in `LobeNextauthDbAdapter`
- const user = await this.adapter.getUserByAccount({
+ const user = await this.getUserByAccount({
provider,
providerAccountId,
});
@@ -44,4 +58,266 @@ export class NextAuthUserService {
}
return NextResponse.json({ message: 'user updated', success: true }, { status: 200 });
};
+
+ safeSignOutUser = async ({
+ providerAccountId,
+ provider,
+ }: {
+ provider: string;
+ providerAccountId: string;
+ }) => {
+ pino.info(`Signing out user "${JSON.stringify({ provider, providerAccountId })}"`);
+ const user = await this.getUserByAccount({
+ provider,
+ providerAccountId,
+ });
+
+ // 2. If found, Update user data from provider
+ if (user?.id) {
+ // Perform update
+ await this.db.delete(nextauthSessions).where(eq(nextauthSessions.userId, user.id));
+ } else {
+ pino.warn(
+ `[${provider}]: Webhooks handler user "${JSON.stringify({ provider, providerAccountId })}" to signout", but no user was found by the providerAccountId.`,
+ );
+ }
+ return NextResponse.json({ message: 'user signed out', success: true }, { status: 200 });
+ };
+
+ createAuthenticator: NonNullable<Adapter['createAuthenticator']> = async (authenticator) => {
+ return await this.db
+ .insert(nextauthAuthenticators)
+ .values(authenticator)
+ .returning()
+ .then((res: any) => res[0] ?? undefined);
+ };
+
+ createSession: NonNullable<Adapter['createSession']> = async (data) => {
+ return await this.db
+ .insert(nextauthSessions)
+ .values(data)
+ .returning()
+ .then((res: any) => res[0]);
+ };
+
+ createUser: NonNullable<Adapter['createUser']> = async (user) => {
+ const { id, name, email, emailVerified, image, providerAccountId } = user;
+ // return the user if it already exists
+ let existingUser =
+ email && typeof email === 'string' && email.trim()
+ ? await UserModel.findByEmail(this.db, email)
+ : undefined;
+ // If the user is not found by email, try to find by providerAccountId
+ if (!existingUser && providerAccountId) {
+ existingUser = await UserModel.findById(this.db, providerAccountId);
+ }
+ if (existingUser) {
+ const adapterUser = mapLobeUserToAdapterUser(existingUser);
+ return adapterUser;
+ }
+
+ // create a new user if it does not exist
+ // Use id from provider if it exists, otherwise use id assigned by next-auth
+ // ref: https://github.com/lobehub/lobe-chat/pull/2935
+ const uid = providerAccountId ?? id;
+ await UserModel.createUser(
+ this.db,
+ mapAdapterUserToLobeUser({
+ email,
+ emailVerified,
+ // Use providerAccountId as userid to identify if the user exists in a SSO provider
+ id: uid,
+ image,
+ name,
+ }),
+ );
+
+ // 3. Create an inbox session for the user
+ const agentService = new AgentService(this.db, uid);
+ await agentService.createInbox();
+
+ return { ...user, id: uid };
+ };
+
+ createVerificationToken: NonNullable<Adapter['createVerificationToken']> = async (data) => {
+ return await this.db
+ .insert(nextauthVerificationTokens)
+ .values(data)
+ .returning()
+ .then((res: any) => res[0]);
+ };
+
+ deleteSession: NonNullable<Adapter['deleteSession']> = async (sessionToken) => {
+ await this.db.delete(nextauthSessions).where(eq(nextauthSessions.sessionToken, sessionToken));
+ };
+
+ deleteUser: NonNullable<Adapter['deleteUser']> = async (id) => {
+ const user = await UserModel.findById(this.db, id);
+ if (!user) throw new Error('NextAuth: Delete User not found');
+ await UserModel.deleteUser(this.db, id);
+ };
+
+ getAccount: NonNullable<Adapter['getAccount']> = async (providerAccountId, provider) => {
+ return (await this.db
+ .select()
+ .from(nextauthAccounts)
+ .where(
+ and(
+ eq(nextauthAccounts.provider, provider),
+ eq(nextauthAccounts.providerAccountId, providerAccountId),
+ ),
+ )
+ .then((res: any) => res[0] ?? null)) as Promise<AdapterAccount | null>;
+ };
+
+ getAuthenticator: NonNullable<Adapter['getAuthenticator']> = async (credentialID) => {
+ const result = await this.db
+ .select()
+ .from(nextauthAuthenticators)
+ .where(eq(nextauthAuthenticators.credentialID, credentialID))
+ .then((res) => res[0] ?? null);
+ if (!result) throw new Error('NextAuthUserService: Failed to get authenticator');
+ return mapAuthenticatorQueryResutlToAdapterAuthenticator(result);
+ };
+
+ getSessionAndUser: NonNullable<Adapter['getSessionAndUser']> = async (sessionToken) => {
+ const result = await this.db
+ .select({
+ session: nextauthSessions,
+ user: users,
+ })
+ .from(nextauthSessions)
+ .where(eq(nextauthSessions.sessionToken, sessionToken))
+ .innerJoin(users, eq(users.id, nextauthSessions.userId))
+ .then((res: any) => (res.length > 0 ? res[0] : null));
+
+ if (!result) return null;
+ const adapterUser = mapLobeUserToAdapterUser(result.user);
+ if (!adapterUser) return null;
+ return {
+ session: result.session,
+ user: adapterUser,
+ };
+ };
+
+ getUser: NonNullable<Adapter['getUser']> = async (id) => {
+ const lobeUser = await UserModel.findById(this.db, id);
+ if (!lobeUser) return null;
+ return mapLobeUserToAdapterUser(lobeUser);
+ };
+
+ getUserByAccount: NonNullable<Adapter['getUserByAccount']> = async (account) => {
+ const result = await this.db
+ .select({
+ account: nextauthAccounts,
+ users,
+ })
+ .from(nextauthAccounts)
+ .innerJoin(users, eq(nextauthAccounts.userId, users.id))
+ .where(
+ and(
+ eq(nextauthAccounts.provider, account.provider),
+ eq(nextauthAccounts.providerAccountId, account.providerAccountId),
+ ),
+ )
+ .then((res: any) => res[0]);
+
+ return result?.users ? mapLobeUserToAdapterUser(result.users) : null;
+ };
+
+ getUserByEmail: NonNullable<Adapter['getUserByEmail']> = async (email) => {
+ const lobeUser =
+ email && typeof email === 'string' && email.trim()
+ ? await UserModel.findByEmail(this.db, email)
+ : undefined;
+ return lobeUser ? mapLobeUserToAdapterUser(lobeUser) : null;
+ };
+
+ linkAccount: NonNullable<Adapter['linkAccount']> = async (data) => {
+ const [account] = await this.db
+ .insert(nextauthAccounts)
+ .values(data as any)
+ .returning();
+ if (!account) throw new Error('NextAuthAccountModel: Failed to create account');
+ // TODO Update type annotation
+ return account as any;
+ };
+
+ listAuthenticatorsByUserId: NonNullable<Adapter['listAuthenticatorsByUserId']> = async (
+ userId,
+ ) => {
+ const result = await this.db
+ .select()
+ .from(nextauthAuthenticators)
+ .where(eq(nextauthAuthenticators.userId, userId))
+ .then((res: any) => res);
+ if (result.length === 0)
+ throw new Error('NextAuthUserService: Failed to get authenticator list');
+ return result.map((r: any) => mapAuthenticatorQueryResutlToAdapterAuthenticator(r));
+ };
+
+ unlinkAccount: NonNullable<Adapter['unlinkAccount']> = async (account) => {
+ await this.db
+ .delete(nextauthAccounts)
+ .where(
+ and(
+ eq(nextauthAccounts.provider, account.provider),
+ eq(nextauthAccounts.providerAccountId, account.providerAccountId),
+ ),
+ );
+ };
+
+ updateAuthenticatorCounter: NonNullable<Adapter['updateAuthenticatorCounter']> = async (
+ credentialID,
+ counter,
+ ) => {
+ const result = await this.db
+ .update(nextauthAuthenticators)
+ .set({ counter })
+ .where(eq(nextauthAuthenticators.credentialID, credentialID))
+ .returning()
+ .then((res: any) => res[0]);
+ if (!result) throw new Error('NextAuthUserService: Failed to update authenticator counter');
+ return mapAuthenticatorQueryResutlToAdapterAuthenticator(result);
+ };
+
+ updateSession: NonNullable<Adapter['updateSession']> = async (data) => {
+ const res = await this.db
+ .update(nextauthSessions)
+ .set(data)
+ .where(eq(nextauthSessions.sessionToken, data.sessionToken))
+ .returning();
+ return res[0];
+ };
+
+ updateUser: NonNullable<Adapter['updateUser']> = async (user) => {
+ const lobeUser = await UserModel.findById(this.db, user?.id);
+ if (!lobeUser) throw new Error('NextAuth: User not found');
+ const userModel = new UserModel(this.db, user.id);
+
+ const updatedUser = await userModel.updateUser({
+ ...partialMapAdapterUserToLobeUser(user),
+ });
+ if (!updatedUser) throw new Error('NextAuth: Failed to update user');
+
+ // merge new user data with old user data
+ const newAdapterUser = mapLobeUserToAdapterUser(lobeUser);
+ if (!newAdapterUser) {
+ throw new Error('NextAuth: Failed to map user data to adapter user');
+ }
+ return merge(newAdapterUser, user);
+ };
+
+ useVerificationToken: NonNullable<Adapter['useVerificationToken']> = async (identifier_token) => {
+ return await this.db
+ .delete(nextauthVerificationTokens)
+ .where(
+ and(
+ eq(nextauthVerificationTokens.identifier, identifier_token.identifier),
+ eq(nextauthVerificationTokens.token, identifier_token.token),
+ ),
+ )
+ .returning()
+ .then((res: any) => (res.length > 0 ? res[0] : null));
+ };
}
diff --git a/src/libs/next-auth/adapter/utils.ts b/src/server/services/nextAuthUser/utils.ts
similarity index 100%
rename from src/libs/next-auth/adapter/utils.ts
rename to src/server/services/nextAuthUser/utils.ts