mirror of
https://github.com/better-auth/better-auth.git
synced 2026-06-03 21:06:40 -05:00
fix: propagate a secondary storage updates on updated user (#3000)
* update user propagate update on session with secondary storage * lint * descriptive
This commit is contained in:
committed by
GitHub
parent
552ea8a041
commit
e27d77a68f
@@ -264,6 +264,51 @@ describe("updateUser", async () => {
|
||||
// @ts-ignore
|
||||
expect(session?.user.newField).toBe("new");
|
||||
});
|
||||
|
||||
it("should propagate updates across sessions when secondaryStorage is enabled", async () => {
|
||||
const store = new Map<string, string>();
|
||||
const { client: authClient, signInWithTestUser: signIn } =
|
||||
await getTestInstance({
|
||||
secondaryStorage: {
|
||||
set(key, value) {
|
||||
store.set(key, value);
|
||||
},
|
||||
get(key) {
|
||||
return store.get(key) || null;
|
||||
},
|
||||
delete(key) {
|
||||
store.delete(key);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const { headers: headers1 } = await signIn();
|
||||
const { headers: headers2 } = await signIn();
|
||||
|
||||
await authClient.updateUser({
|
||||
name: "updatedName",
|
||||
fetchOptions: {
|
||||
headers: headers1,
|
||||
},
|
||||
});
|
||||
|
||||
const secondSession = await authClient.getSession({
|
||||
fetchOptions: {
|
||||
headers: headers2,
|
||||
throw: true,
|
||||
},
|
||||
});
|
||||
expect(secondSession.user.name).toBe("updatedName");
|
||||
|
||||
const firstSession = await authClient.getSession({
|
||||
fetchOptions: {
|
||||
headers: headers1,
|
||||
throw: true,
|
||||
},
|
||||
});
|
||||
|
||||
expect(firstSession.user.name).toBe("updatedName");
|
||||
});
|
||||
});
|
||||
|
||||
describe("delete user", async () => {
|
||||
|
||||
@@ -672,6 +672,41 @@ export const createInternalAdapter = (
|
||||
undefined,
|
||||
context,
|
||||
);
|
||||
if (secondaryStorage && user) {
|
||||
const listRaw = await secondaryStorage.get(`active-sessions-${userId}`);
|
||||
if (listRaw) {
|
||||
const now = Date.now();
|
||||
const list =
|
||||
safeJSONParse<{ token: string; expiresAt: number }[]>(listRaw) ||
|
||||
[];
|
||||
const validSessions = list.filter((s) => s.expiresAt > now);
|
||||
await Promise.all(
|
||||
validSessions.map(async ({ token }) => {
|
||||
const cached = await secondaryStorage.get(token);
|
||||
if (!cached) return;
|
||||
const parsed = safeJSONParse<{
|
||||
session: Session;
|
||||
user: User;
|
||||
}>(cached);
|
||||
if (!parsed) return;
|
||||
const sessionTTL = Math.max(
|
||||
Math.floor(
|
||||
(new Date(parsed.session.expiresAt).getTime() - now) / 1000,
|
||||
),
|
||||
0,
|
||||
);
|
||||
await secondaryStorage.set(
|
||||
token,
|
||||
JSON.stringify({
|
||||
session: parsed.session,
|
||||
user,
|
||||
}),
|
||||
sessionTTL,
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
return user;
|
||||
},
|
||||
updateUserByEmail: async (
|
||||
|
||||
Reference in New Issue
Block a user