feat: custom session response (#579)

This commit is contained in:
Bereket Engida
2024-11-19 21:16:23 +03:00
committed by GitHub
parent a3f0793d68
commit f5f60a23e8
28 changed files with 425 additions and 95 deletions

View File

@@ -8,6 +8,7 @@ import {
oneTapClient,
} from "better-auth/client/plugins";
import { toast } from "sonner";
import { customSessionClient } from "./auth/plugins/session-client";
export const client = createAuthClient({
plugins: [
@@ -22,6 +23,7 @@ export const client = createAuthClient({
oneTapClient({
clientId: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID!,
}),
customSessionClient(),
],
fetchOptions: {
onError(e) {

View File

@@ -8,6 +8,7 @@ import {
twoFactor,
oneTap,
oAuthProxy,
createAuthEndpoint,
} from "better-auth/plugins";
import { reactInvitationEmail } from "./email/invitation";
import { LibsqlDialect } from "@libsql/kysely-libsql";
@@ -16,7 +17,7 @@ import { resend } from "./email/resend";
import { MysqlDialect } from "kysely";
import { createPool } from "mysql2/promise";
import { nextCookies } from "better-auth/next-js";
import * as ac from "./access-control";
import { customSession } from "./auth/plugins/custom-session";
const from = process.env.BETTER_AUTH_EMAIL || "delivered@resend.dev";
const to = process.env.TEST_EMAIL || "";
@@ -112,12 +113,6 @@ export const auth = betterAuth({
},
plugins: [
organization({
ac: ac.ac,
roles: {
admin: ac.admin,
owner: ac.owner,
member: ac.member,
},
async sendInvitationEmail(data) {
const res = await resend.emails.send({
from,
@@ -159,5 +154,6 @@ export const auth = betterAuth({
oneTap(),
oAuthProxy(),
nextCookies(),
customSession(),
],
});

View File

@@ -0,0 +1,32 @@
import { BetterAuthPlugin } from "better-auth";
import { createAuthEndpoint } from "better-auth/plugins";
import { getSessionFromCtx } from "better-auth/api";
export const customSession = () => {
return {
id: "custom-session",
endpoints: {
getSession: createAuthEndpoint(
"/get-session",
{
method: "GET",
},
async (ctx) => {
const session = await getSessionFromCtx(ctx);
if (!session) {
return ctx.json(null);
}
const roles: {
id: number;
name: string;
}[] = [];
return ctx.json({
user: session.user,
session: session.session,
roles,
});
},
),
},
} satisfies BetterAuthPlugin;
};

View File

@@ -0,0 +1,9 @@
import { BetterAuthClientPlugin } from "better-auth";
import { customSession } from "./custom-session";
export const customSessionClient = () => {
return {
id: "session-client",
$InferServerPlugin: {} as ReturnType<typeof customSession>,
} satisfies BetterAuthClientPlugin;
};