Skip to content

Commit 63fbd91

Browse files
kzlarBekacru
andauthored
feat: add context to database hooks (#1180)
database hooks now contain endpoint context on their callback --------- Co-authored-by: Bereket Engida <[email protected]>
1 parent 6ff11bd commit 63fbd91

File tree

18 files changed

+180
-70
lines changed

18 files changed

+180
-70
lines changed

packages/better-auth/src/api/routes/callback.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ export const callbackOAuth = createAuthEndpoint(
137137
userId: link.userId,
138138
providerId: provider.id,
139139
accountId: userInfo.id,
140-
});
140+
}, c);
141141
if (!newAccount) {
142142
return redirectOnError("unable_to_link_account");
143143
}

packages/better-auth/src/api/routes/email-verification.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ export const verifyEmail = createAuthEndpoint(
247247
{
248248
email: parsed.updateTo,
249249
emailVerified: false,
250-
},
250+
},ctx
251251
);
252252

253253
const newToken = await createEmailVerificationToken(
@@ -292,7 +292,7 @@ export const verifyEmail = createAuthEndpoint(
292292
}
293293
await ctx.context.internalAdapter.updateUserByEmail(parsed.email, {
294294
emailVerified: true,
295-
});
295+
},ctx);
296296
if (ctx.context.options.emailVerification?.autoSignInAfterVerification) {
297297
const currentSession = await getSessionFromCtx(ctx);
298298
if (!currentSession || currentSession.user.email !== parsed.email) {

packages/better-auth/src/api/routes/forget-password.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -268,12 +268,12 @@ export const resetPassword = createAuthEndpoint(
268268
providerId: "credential",
269269
password: hashedPassword,
270270
accountId: userId,
271-
});
271+
}, ctx);
272272
return ctx.json({
273273
status: true,
274274
});
275275
}
276-
await ctx.context.internalAdapter.updatePassword(userId, hashedPassword);
276+
await ctx.context.internalAdapter.updatePassword(userId, hashedPassword, ctx);
277277
return ctx.json({
278278
status: true,
279279
});

packages/better-auth/src/api/routes/sign-up.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ export const signUpEmail = <O extends BetterAuthOptions>() =>
151151
image,
152152
...additionalData,
153153
emailVerified: false,
154-
});
154+
}, ctx);
155155
if (!createdUser) {
156156
throw new APIError("BAD_REQUEST", {
157157
message: BASE_ERROR_CODES.FAILED_TO_CREATE_USER,
@@ -180,7 +180,7 @@ export const signUpEmail = <O extends BetterAuthOptions>() =>
180180
providerId: "credential",
181181
accountId: createdUser.id,
182182
password: hash,
183-
});
183+
}, ctx);
184184
if (
185185
ctx.context.options.emailVerification?.sendOnSignUp ||
186186
ctx.context.options.emailAndPassword.requireEmailVerification

packages/better-auth/src/api/routes/update-user.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ export const updateUser = <O extends BetterAuthOptions>() =>
100100
name,
101101
image,
102102
...additionalFields,
103-
},
103+
},ctx
104104
);
105105
/**
106106
* Update the session cookie with the new user data
@@ -294,7 +294,7 @@ export const setPassword = createAuthEndpoint(
294294
providerId: "credential",
295295
accountId: session.user.id,
296296
password: passwordHash,
297-
});
297+
}, ctx);
298298
return ctx.json({
299299
status: true,
300300
});
@@ -582,7 +582,7 @@ export const changeEmail = createAuthEndpoint(
582582
ctx.context.session.user.email,
583583
{
584584
email: ctx.body.newEmail,
585-
},
585+
},ctx
586586
);
587587
return ctx.json({
588588
status: true,

packages/better-auth/src/db/internal-adapter.test.ts

+12-11
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { beforeAll, expect, it, describe, vi, afterEach } from "vitest";
22
import type { BetterAuthOptions, BetterAuthPlugin } from "../types";
33
import Database from "better-sqlite3";
4+
import { createInternalAdapter } from "./internal-adapter";
5+
import { getAdapter } from "./utils";
46
import { init } from "../init";
57
import { getMigrations } from "./get-migration";
68
import { SqliteDialect } from "kysely";
@@ -12,10 +14,10 @@ describe("adapter test", async () => {
1214
});
1315
const map = new Map();
1416
let id = 1;
15-
const pluginHookUserCreateBefore = vi.fn();
16-
const pluginHookUserCreateAfter = vi.fn();
1717
const hookUserCreateBefore = vi.fn();
1818
const hookUserCreateAfter = vi.fn();
19+
const pluginHookUserCreateBefore = vi.fn();
20+
const pluginHookUserCreateAfter = vi.fn();
1921
const opts = {
2022
database: {
2123
dialect: sqliteDialect,
@@ -46,12 +48,12 @@ describe("adapter test", async () => {
4648
databaseHooks: {
4749
user: {
4850
create: {
49-
async before(user) {
50-
hookUserCreateBefore(user);
51+
async before(user, context) {
52+
hookUserCreateBefore(user, context);
5153
return { data: user };
5254
},
53-
async after(user) {
54-
hookUserCreateAfter(user);
55+
async after(user, context) {
56+
hookUserCreateAfter(user, context);
5557
return;
5658
},
5759
},
@@ -66,13 +68,12 @@ describe("adapter test", async () => {
6668
databaseHooks: {
6769
user: {
6870
create: {
69-
async before(user) {
70-
pluginHookUserCreateBefore(user);
71+
async before(user, context) {
72+
pluginHookUserCreateBefore(user, context);
7173
return { data: user };
7274
},
73-
async after(user) {
74-
pluginHookUserCreateAfter(user);
75-
return;
75+
async after(user, context) {
76+
pluginHookUserCreateAfter(user, context);
7677
},
7778
},
7879
},

packages/better-auth/src/db/internal-adapter.ts

+47-3
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,13 @@ import { getWithHooks } from "./with-hooks";
1010
import { getIp } from "../utils/get-request-ip";
1111
import { safeJSONParse } from "../utils/json";
1212
import { generateId } from "../utils";
13-
import type { Adapter, AuthContext, BetterAuthOptions, Where } from "../types";
13+
import type {
14+
Adapter,
15+
AuthContext,
16+
BetterAuthOptions,
17+
GenericEndpointContext,
18+
Where,
19+
} from "../types";
1420

1521
export const createInternalAdapter = (
1622
adapter: Adapter,
@@ -31,6 +37,7 @@ export const createInternalAdapter = (
3137
user: Omit<User, "id" | "createdAt" | "updatedAt"> & Partial<User>,
3238
account: Omit<Account, "userId" | "id" | "createdAt" | "updatedAt"> &
3339
Partial<Account>,
40+
context?: GenericEndpointContext,
3441
) => {
3542
const createdUser = await createWithHooks(
3643
{
@@ -39,6 +46,8 @@ export const createInternalAdapter = (
3946
...user,
4047
},
4148
"user",
49+
undefined,
50+
context,
4251
);
4352
const createdAccount = await createWithHooks(
4453
{
@@ -48,6 +57,8 @@ export const createInternalAdapter = (
4857
updatedAt: new Date(),
4958
},
5059
"account",
60+
undefined,
61+
context,
5162
);
5263
return {
5364
user: createdUser,
@@ -58,6 +69,7 @@ export const createInternalAdapter = (
5869
user: Omit<User, "id" | "createdAt" | "updatedAt" | "emailVerified"> &
5970
Partial<User> &
6071
Record<string, any>,
72+
context?: GenericEndpointContext,
6173
) => {
6274
const createdUser = await createWithHooks(
6375
{
@@ -68,13 +80,16 @@ export const createInternalAdapter = (
6880
email: user.email.toLowerCase(),
6981
},
7082
"user",
83+
undefined,
84+
context,
7185
);
7286
return createdUser as T & User;
7387
},
7488
createAccount: async <T>(
7589
account: Omit<Account, "id" | "createdAt" | "updatedAt"> &
7690
Partial<Account> &
7791
Record<string, any>,
92+
context?: GenericEndpointContext,
7893
) => {
7994
const createdAccount = await createWithHooks(
8095
{
@@ -83,6 +98,8 @@ export const createInternalAdapter = (
8398
...account,
8499
},
85100
"account",
101+
undefined,
102+
context,
86103
);
87104
return createdAccount as T & Account;
88105
},
@@ -190,6 +207,7 @@ export const createInternalAdapter = (
190207
request: Request | Headers | undefined,
191208
dontRememberMe?: boolean,
192209
override?: Partial<Session> & Record<string, any>,
210+
context?: GenericEndpointContext,
193211
) => {
194212
const headers = request instanceof Request ? request.headers : request;
195213
const { id: _, ...rest } = override || {};
@@ -248,6 +266,7 @@ export const createInternalAdapter = (
248266
executeMainFn: options.session?.storeSessionInDatabase,
249267
}
250268
: undefined,
269+
context,
251270
);
252271
return res as Session;
253272
},
@@ -384,6 +403,7 @@ export const createInternalAdapter = (
384403
updateSession: async (
385404
sessionToken: string,
386405
session: Partial<Session> & Record<string, any>,
406+
context?: GenericEndpointContext,
387407
) => {
388408
const updatedSession = await updateWithHooks<Session>(
389409
session,
@@ -411,6 +431,7 @@ export const createInternalAdapter = (
411431
executeMainFn: options.session?.storeSessionInDatabase,
412432
}
413433
: undefined,
434+
context,
414435
);
415436
return updatedSession;
416437
},
@@ -615,6 +636,7 @@ export const createInternalAdapter = (
615636
linkAccount: async (
616637
account: Omit<Account, "id" | "createdAt" | "updatedAt"> &
617638
Partial<Account>,
639+
context?: GenericEndpointContext,
618640
) => {
619641
const _account = await createWithHooks(
620642
{
@@ -623,12 +645,15 @@ export const createInternalAdapter = (
623645
updatedAt: new Date(),
624646
},
625647
"account",
648+
undefined,
649+
context,
626650
);
627651
return _account;
628652
},
629653
updateUser: async (
630654
userId: string,
631655
data: Partial<User> & Record<string, any>,
656+
context?: GenericEndpointContext,
632657
) => {
633658
const user = await updateWithHooks<User>(
634659
data,
@@ -639,12 +664,15 @@ export const createInternalAdapter = (
639664
},
640665
],
641666
"user",
667+
undefined,
668+
context,
642669
);
643670
return user;
644671
},
645672
updateUserByEmail: async (
646673
email: string,
647674
data: Partial<User & Record<string, any>>,
675+
context?: GenericEndpointContext,
648676
) => {
649677
const user = await updateWithHooks<User>(
650678
data,
@@ -655,10 +683,12 @@ export const createInternalAdapter = (
655683
},
656684
],
657685
"user",
686+
undefined,
687+
context,
658688
);
659689
return user;
660690
},
661-
updatePassword: async (userId: string, password: string) => {
691+
updatePassword: async (userId: string, password: string, context?: GenericEndpointContext,) => {
662692
await updateManyWithHooks(
663693
{
664694
password,
@@ -674,6 +704,8 @@ export const createInternalAdapter = (
674704
},
675705
],
676706
"account",
707+
undefined,
708+
context
677709
);
678710
},
679711
findAccounts: async (userId: string) => {
@@ -712,17 +744,24 @@ export const createInternalAdapter = (
712744
});
713745
return account;
714746
},
715-
updateAccount: async (accountId: string, data: Partial<Account>) => {
747+
updateAccount: async (
748+
accountId: string,
749+
data: Partial<Account>,
750+
context?: GenericEndpointContext,
751+
) => {
716752
const account = await updateWithHooks<Account>(
717753
data,
718754
[{ field: "id", value: accountId }],
719755
"account",
756+
undefined,
757+
context,
720758
);
721759
return account;
722760
},
723761
createVerificationValue: async (
724762
data: Omit<Verification, "createdAt" | "id" | "updatedAt"> &
725763
Partial<Verification>,
764+
context?: GenericEndpointContext,
726765
) => {
727766
const verification = await createWithHooks(
728767
{
@@ -731,6 +770,8 @@ export const createInternalAdapter = (
731770
...data,
732771
},
733772
"verification",
773+
undefined,
774+
context,
734775
);
735776
return verification as Verification;
736777
},
@@ -789,11 +830,14 @@ export const createInternalAdapter = (
789830
updateVerificationValue: async (
790831
id: string,
791832
data: Partial<Verification>,
833+
context?: GenericEndpointContext,
792834
) => {
793835
const verification = await updateWithHooks<Verification>(
794836
data,
795837
[{ field: "id", value: id }],
796838
"verification",
839+
undefined,
840+
context,
797841
);
798842
return verification;
799843
},

0 commit comments

Comments
 (0)