better-auth-nuxt 0.0.9 → 0.0.10-beta.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -270
- package/dist/module.d.mts +13 -40
- package/dist/module.json +8 -5
- package/dist/module.mjs +625 -358
- package/dist/runtime/adapters/convex.d.ts +111 -0
- package/dist/runtime/adapters/convex.js +213 -0
- package/dist/runtime/app/components/BetterAuthState.d.vue.ts +20 -0
- package/dist/runtime/app/components/BetterAuthState.vue +9 -0
- package/dist/runtime/app/components/BetterAuthState.vue.d.ts +20 -0
- package/dist/runtime/app/composables/useUserSession.d.ts +22 -0
- package/dist/runtime/app/composables/useUserSession.js +159 -0
- package/dist/runtime/app/middleware/auth.global.d.ts +13 -0
- package/dist/runtime/app/middleware/auth.global.js +37 -0
- package/dist/runtime/app/pages/__better-auth-devtools.d.vue.ts +3 -0
- package/dist/runtime/app/pages/__better-auth-devtools.vue +426 -0
- package/dist/runtime/app/pages/__better-auth-devtools.vue.d.ts +3 -0
- package/dist/runtime/app/plugins/session.client.d.ts +2 -0
- package/dist/runtime/app/plugins/session.client.js +15 -0
- package/dist/runtime/app/plugins/session.server.d.ts +2 -0
- package/dist/runtime/app/plugins/session.server.js +24 -0
- package/dist/runtime/config.d.ts +49 -0
- package/dist/runtime/config.js +11 -0
- package/dist/runtime/server/api/_better-auth/_schema.d.ts +16 -0
- package/dist/runtime/server/api/_better-auth/_schema.js +11 -0
- package/dist/runtime/server/api/_better-auth/accounts.get.d.ts +14 -0
- package/dist/runtime/server/api/_better-auth/accounts.get.js +28 -0
- package/dist/runtime/server/api/_better-auth/config.get.d.ts +35 -0
- package/dist/runtime/server/api/_better-auth/config.get.js +47 -0
- package/dist/runtime/server/api/_better-auth/sessions.delete.d.ts +4 -0
- package/dist/runtime/server/api/_better-auth/sessions.delete.js +22 -0
- package/dist/runtime/server/api/_better-auth/sessions.get.d.ts +14 -0
- package/dist/runtime/server/api/_better-auth/sessions.get.js +43 -0
- package/dist/runtime/server/api/_better-auth/users.get.d.ts +14 -0
- package/dist/runtime/server/api/_better-auth/users.get.js +34 -0
- package/dist/runtime/server/api/auth/[...all].d.ts +2 -0
- package/dist/runtime/server/api/auth/[...all].js +6 -0
- package/dist/runtime/server/middleware/route-access.d.ts +2 -0
- package/dist/runtime/server/middleware/route-access.js +29 -0
- package/dist/runtime/server/tsconfig.json +1 -1
- package/dist/runtime/server/utils/auth.d.ts +7 -0
- package/dist/runtime/server/utils/auth.js +81 -0
- package/dist/runtime/server/utils/session.d.ts +9 -0
- package/dist/runtime/server/utils/session.js +23 -0
- package/dist/runtime/types/augment.d.ts +42 -0
- package/dist/runtime/types/augment.js +0 -0
- package/dist/runtime/types.d.ts +23 -0
- package/dist/runtime/types.js +0 -0
- package/dist/runtime/utils/match-user.d.ts +2 -0
- package/dist/runtime/utils/match-user.js +13 -0
- package/dist/types.d.mts +8 -6
- package/package.json +82 -29
- package/LICENSE +0 -21
- package/dist/runtime/middleware/auth.d.ts +0 -2
- package/dist/runtime/middleware/auth.js +0 -31
- package/dist/runtime/plugin.d.ts +0 -2
- package/dist/runtime/plugin.js +0 -3
- package/dist/runtime/server/handler.d.ts +0 -2
- package/dist/runtime/server/handler.js +0 -5
- package/dist/runtime/server.d.ts +0 -6
- package/dist/runtime/server.js +0 -5
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import type { FunctionReference } from 'convex/server';
|
|
2
|
+
interface ConvexCleanedWhere {
|
|
3
|
+
field: string;
|
|
4
|
+
value: string | number | boolean | string[] | number[] | null;
|
|
5
|
+
operator?: 'lt' | 'lte' | 'gt' | 'gte' | 'eq' | 'in' | 'not_in' | 'ne' | 'contains' | 'starts_with' | 'ends_with';
|
|
6
|
+
connector?: 'AND' | 'OR';
|
|
7
|
+
}
|
|
8
|
+
interface PaginationResult<T> {
|
|
9
|
+
page: T[];
|
|
10
|
+
isDone: boolean;
|
|
11
|
+
continueCursor: string | null;
|
|
12
|
+
splitCursor?: string;
|
|
13
|
+
pageStatus?: 'SplitRecommended' | 'SplitRequired' | string;
|
|
14
|
+
count?: number;
|
|
15
|
+
}
|
|
16
|
+
interface ConvexAuthApi {
|
|
17
|
+
create: FunctionReference<'mutation', 'public', {
|
|
18
|
+
input: {
|
|
19
|
+
model: string;
|
|
20
|
+
data: Record<string, unknown>;
|
|
21
|
+
};
|
|
22
|
+
select?: string[];
|
|
23
|
+
}, unknown>;
|
|
24
|
+
findOne: FunctionReference<'query', 'public', {
|
|
25
|
+
model: string;
|
|
26
|
+
where?: ConvexCleanedWhere[];
|
|
27
|
+
select?: string[];
|
|
28
|
+
}, unknown>;
|
|
29
|
+
findMany: FunctionReference<'query', 'public', {
|
|
30
|
+
model: string;
|
|
31
|
+
where?: ConvexCleanedWhere[];
|
|
32
|
+
limit?: number;
|
|
33
|
+
sortBy?: {
|
|
34
|
+
direction: 'asc' | 'desc';
|
|
35
|
+
field: string;
|
|
36
|
+
};
|
|
37
|
+
paginationOpts: {
|
|
38
|
+
numItems: number;
|
|
39
|
+
cursor: string | null;
|
|
40
|
+
};
|
|
41
|
+
}, PaginationResult<unknown>>;
|
|
42
|
+
updateOne: FunctionReference<'mutation', 'public', {
|
|
43
|
+
input: {
|
|
44
|
+
model: string;
|
|
45
|
+
where?: ConvexCleanedWhere[];
|
|
46
|
+
update: Record<string, unknown>;
|
|
47
|
+
};
|
|
48
|
+
}, unknown>;
|
|
49
|
+
updateMany: FunctionReference<'mutation', 'public', {
|
|
50
|
+
input: {
|
|
51
|
+
model: string;
|
|
52
|
+
where?: ConvexCleanedWhere[];
|
|
53
|
+
update: Record<string, unknown>;
|
|
54
|
+
};
|
|
55
|
+
paginationOpts: {
|
|
56
|
+
numItems: number;
|
|
57
|
+
cursor: string | null;
|
|
58
|
+
};
|
|
59
|
+
}, PaginationResult<unknown> & {
|
|
60
|
+
count: number;
|
|
61
|
+
}>;
|
|
62
|
+
deleteOne: FunctionReference<'mutation', 'public', {
|
|
63
|
+
input: {
|
|
64
|
+
model: string;
|
|
65
|
+
where?: ConvexCleanedWhere[];
|
|
66
|
+
};
|
|
67
|
+
}, unknown>;
|
|
68
|
+
deleteMany: FunctionReference<'mutation', 'public', {
|
|
69
|
+
input: {
|
|
70
|
+
model: string;
|
|
71
|
+
where?: ConvexCleanedWhere[];
|
|
72
|
+
};
|
|
73
|
+
paginationOpts: {
|
|
74
|
+
numItems: number;
|
|
75
|
+
cursor: string | null;
|
|
76
|
+
};
|
|
77
|
+
}, PaginationResult<unknown> & {
|
|
78
|
+
count: number;
|
|
79
|
+
}>;
|
|
80
|
+
}
|
|
81
|
+
export interface ConvexHttpAdapterOptions {
|
|
82
|
+
/** Convex deployment URL (e.g., https://your-app.convex.cloud) */
|
|
83
|
+
url: string;
|
|
84
|
+
/** Convex API functions for auth operations - import from your convex/_generated/api */
|
|
85
|
+
api: ConvexAuthApi;
|
|
86
|
+
/** Enable debug logging for adapter operations */
|
|
87
|
+
debugLogs?: boolean;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Creates a Better Auth adapter that communicates with Convex via HTTP.
|
|
91
|
+
* Uses ConvexHttpClient for server-side auth operations.
|
|
92
|
+
*
|
|
93
|
+
* @example
|
|
94
|
+
* ```ts
|
|
95
|
+
* import { api } from '~/convex/_generated/api'
|
|
96
|
+
*
|
|
97
|
+
* export default defineServerAuth(() => ({
|
|
98
|
+
* database: createConvexHttpAdapter({
|
|
99
|
+
* url: process.env.CONVEX_URL!,
|
|
100
|
+
* api: api.auth,
|
|
101
|
+
* }),
|
|
102
|
+
* }))
|
|
103
|
+
* ```
|
|
104
|
+
*
|
|
105
|
+
* @limitations
|
|
106
|
+
* - `update()` only supports AND-connected where clauses (no OR support)
|
|
107
|
+
* - `count()` fetches all documents client-side (Convex limitation)
|
|
108
|
+
* - `offset` pagination not supported in `findMany()`
|
|
109
|
+
*/
|
|
110
|
+
export declare function createConvexHttpAdapter(options: ConvexHttpAdapterOptions): import("better-auth/adapters").AdapterFactory;
|
|
111
|
+
export {};
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { createAdapterFactory } from "better-auth/adapters";
|
|
2
|
+
import { ConvexHttpClient } from "convex/browser";
|
|
3
|
+
function parseWhere(where) {
|
|
4
|
+
if (!where)
|
|
5
|
+
return [];
|
|
6
|
+
const whereArray = Array.isArray(where) ? where : [where];
|
|
7
|
+
return whereArray.map((w) => {
|
|
8
|
+
if (w.value instanceof Date)
|
|
9
|
+
return { ...w, value: w.value.getTime() };
|
|
10
|
+
return w;
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
async function handlePagination(next, { limit } = {}) {
|
|
14
|
+
const state = { isDone: false, cursor: null, docs: [], count: 0 };
|
|
15
|
+
const onResult = (result) => {
|
|
16
|
+
state.cursor = result.pageStatus === "SplitRecommended" || result.pageStatus === "SplitRequired" ? result.splitCursor ?? result.continueCursor : result.continueCursor;
|
|
17
|
+
if (result.page) {
|
|
18
|
+
state.docs.push(...result.page);
|
|
19
|
+
state.isDone = limit && state.docs.length >= limit || result.isDone;
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
if (result.count) {
|
|
23
|
+
state.count += result.count;
|
|
24
|
+
state.isDone = limit && state.count >= limit || result.isDone;
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
state.isDone = result.isDone;
|
|
28
|
+
};
|
|
29
|
+
do {
|
|
30
|
+
const result = await next({
|
|
31
|
+
paginationOpts: {
|
|
32
|
+
numItems: Math.min(200, (limit ?? 200) - state.docs.length, 200),
|
|
33
|
+
cursor: state.cursor
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
onResult(result);
|
|
37
|
+
} while (!state.isDone);
|
|
38
|
+
return state;
|
|
39
|
+
}
|
|
40
|
+
export function createConvexHttpAdapter(options) {
|
|
41
|
+
if (!options.url.startsWith("https://") || !options.url.includes(".convex.")) {
|
|
42
|
+
throw new Error(`Invalid Convex URL: ${options.url}. Expected format: https://your-app.convex.cloud`);
|
|
43
|
+
}
|
|
44
|
+
const client = new ConvexHttpClient(options.url);
|
|
45
|
+
return createAdapterFactory({
|
|
46
|
+
config: {
|
|
47
|
+
adapterId: "convex-http",
|
|
48
|
+
adapterName: "Convex HTTP Adapter",
|
|
49
|
+
debugLogs: options.debugLogs ?? false,
|
|
50
|
+
disableIdGeneration: true,
|
|
51
|
+
transaction: false,
|
|
52
|
+
supportsNumericIds: false,
|
|
53
|
+
supportsJSON: false,
|
|
54
|
+
supportsDates: false,
|
|
55
|
+
supportsArrays: true,
|
|
56
|
+
usePlural: false,
|
|
57
|
+
mapKeysTransformInput: { id: "_id" },
|
|
58
|
+
mapKeysTransformOutput: { _id: "id" },
|
|
59
|
+
customTransformInput: ({ data, fieldAttributes }) => {
|
|
60
|
+
if (data && fieldAttributes.type === "date")
|
|
61
|
+
return new Date(data).getTime();
|
|
62
|
+
return data;
|
|
63
|
+
},
|
|
64
|
+
customTransformOutput: ({ data, fieldAttributes }) => {
|
|
65
|
+
if (data && fieldAttributes.type === "date")
|
|
66
|
+
return new Date(data).getTime();
|
|
67
|
+
return data;
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
adapter: ({ options: authOptions }) => {
|
|
71
|
+
authOptions.telemetry = { enabled: false };
|
|
72
|
+
return {
|
|
73
|
+
id: "convex-http",
|
|
74
|
+
create: async ({ model, data, select }) => {
|
|
75
|
+
return client.mutation(options.api.create, {
|
|
76
|
+
input: { model, data },
|
|
77
|
+
select
|
|
78
|
+
});
|
|
79
|
+
},
|
|
80
|
+
findOne: async (data) => {
|
|
81
|
+
if (data.where?.every((w) => w.connector === "OR")) {
|
|
82
|
+
for (const w of data.where) {
|
|
83
|
+
const result = await client.query(options.api.findOne, {
|
|
84
|
+
...data,
|
|
85
|
+
model: data.model,
|
|
86
|
+
where: parseWhere(w)
|
|
87
|
+
});
|
|
88
|
+
if (result)
|
|
89
|
+
return result;
|
|
90
|
+
}
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
return client.query(options.api.findOne, {
|
|
94
|
+
...data,
|
|
95
|
+
model: data.model,
|
|
96
|
+
where: parseWhere(data.where)
|
|
97
|
+
});
|
|
98
|
+
},
|
|
99
|
+
findMany: async (data) => {
|
|
100
|
+
if (data.offset)
|
|
101
|
+
throw new Error("offset not supported");
|
|
102
|
+
if (data.where?.some((w) => w.connector === "OR")) {
|
|
103
|
+
const results = await Promise.all(
|
|
104
|
+
data.where.map(
|
|
105
|
+
async (w) => handlePagination(async ({ paginationOpts }) => {
|
|
106
|
+
return client.query(options.api.findMany, {
|
|
107
|
+
...data,
|
|
108
|
+
model: data.model,
|
|
109
|
+
where: parseWhere(w),
|
|
110
|
+
paginationOpts
|
|
111
|
+
});
|
|
112
|
+
}, { limit: data.limit })
|
|
113
|
+
)
|
|
114
|
+
);
|
|
115
|
+
const allDocs = results.flatMap((r) => r.docs);
|
|
116
|
+
const uniqueDocs = [...new Map(allDocs.map((d) => [d._id, d])).values()];
|
|
117
|
+
if (data.sortBy) {
|
|
118
|
+
return uniqueDocs.sort((a, b) => {
|
|
119
|
+
const aVal = a[data.sortBy.field];
|
|
120
|
+
const bVal = b[data.sortBy.field];
|
|
121
|
+
const cmp = aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
|
|
122
|
+
return data.sortBy.direction === "asc" ? cmp : -cmp;
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
return uniqueDocs;
|
|
126
|
+
}
|
|
127
|
+
const result = await handlePagination(
|
|
128
|
+
async ({ paginationOpts }) => client.query(options.api.findMany, {
|
|
129
|
+
...data,
|
|
130
|
+
model: data.model,
|
|
131
|
+
where: parseWhere(data.where),
|
|
132
|
+
paginationOpts
|
|
133
|
+
}),
|
|
134
|
+
{ limit: data.limit }
|
|
135
|
+
);
|
|
136
|
+
return result.docs;
|
|
137
|
+
},
|
|
138
|
+
// Note: Convex doesn't have a native count query, so we fetch all docs and count client-side.
|
|
139
|
+
// This is inefficient for large datasets but acceptable for auth tables (typically small).
|
|
140
|
+
count: async (data) => {
|
|
141
|
+
if (data.where?.some((w) => w.connector === "OR")) {
|
|
142
|
+
const results = await Promise.all(
|
|
143
|
+
data.where.map(
|
|
144
|
+
async (w) => handlePagination(async ({ paginationOpts }) => {
|
|
145
|
+
return client.query(options.api.findMany, {
|
|
146
|
+
...data,
|
|
147
|
+
model: data.model,
|
|
148
|
+
where: parseWhere(w),
|
|
149
|
+
paginationOpts
|
|
150
|
+
});
|
|
151
|
+
})
|
|
152
|
+
)
|
|
153
|
+
);
|
|
154
|
+
const allDocs = results.flatMap((r) => r.docs);
|
|
155
|
+
const uniqueDocs = [...new Map(allDocs.map((d) => [d._id, d])).values()];
|
|
156
|
+
return uniqueDocs.length;
|
|
157
|
+
}
|
|
158
|
+
const result = await handlePagination(async ({ paginationOpts }) => client.query(options.api.findMany, {
|
|
159
|
+
...data,
|
|
160
|
+
model: data.model,
|
|
161
|
+
where: parseWhere(data.where),
|
|
162
|
+
paginationOpts
|
|
163
|
+
}));
|
|
164
|
+
return result.docs.length;
|
|
165
|
+
},
|
|
166
|
+
// Supports single eq or multiple AND-connected conditions (Better Auth's common patterns)
|
|
167
|
+
update: async (data) => {
|
|
168
|
+
const hasOrConnector = data.where?.some((w) => w.connector === "OR");
|
|
169
|
+
if (hasOrConnector) {
|
|
170
|
+
throw new Error("update() does not support OR conditions - use updateMany() or split into multiple calls");
|
|
171
|
+
}
|
|
172
|
+
return client.mutation(options.api.updateOne, {
|
|
173
|
+
input: {
|
|
174
|
+
model: data.model,
|
|
175
|
+
where: parseWhere(data.where),
|
|
176
|
+
update: data.update
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
},
|
|
180
|
+
updateMany: async (data) => {
|
|
181
|
+
const result = await handlePagination(async ({ paginationOpts }) => client.mutation(options.api.updateMany, {
|
|
182
|
+
input: {
|
|
183
|
+
...data,
|
|
184
|
+
model: data.model,
|
|
185
|
+
where: parseWhere(data.where)
|
|
186
|
+
},
|
|
187
|
+
paginationOpts
|
|
188
|
+
}));
|
|
189
|
+
return result.count;
|
|
190
|
+
},
|
|
191
|
+
delete: async (data) => {
|
|
192
|
+
await client.mutation(options.api.deleteOne, {
|
|
193
|
+
input: {
|
|
194
|
+
model: data.model,
|
|
195
|
+
where: parseWhere(data.where)
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
},
|
|
199
|
+
deleteMany: async (data) => {
|
|
200
|
+
const result = await handlePagination(async ({ paginationOpts }) => client.mutation(options.api.deleteMany, {
|
|
201
|
+
input: {
|
|
202
|
+
...data,
|
|
203
|
+
model: data.model,
|
|
204
|
+
where: parseWhere(data.where)
|
|
205
|
+
},
|
|
206
|
+
paginationOpts
|
|
207
|
+
}));
|
|
208
|
+
return result.count;
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
});
|
|
213
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
declare var __VLS_1: {
|
|
2
|
+
loggedIn: boolean;
|
|
3
|
+
user: import("../../types.js").AuthUser | null;
|
|
4
|
+
session: import("../../types.js").AuthSession | null;
|
|
5
|
+
signOut: (options?: import("#imports").SignOutOptions) => Promise<void>;
|
|
6
|
+
}, __VLS_3: {};
|
|
7
|
+
type __VLS_Slots = {} & {
|
|
8
|
+
default?: (props: typeof __VLS_1) => any;
|
|
9
|
+
} & {
|
|
10
|
+
placeholder?: (props: typeof __VLS_3) => any;
|
|
11
|
+
};
|
|
12
|
+
declare const __VLS_base: import("vue").DefineComponent<{}, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<{}> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
|
|
13
|
+
declare const __VLS_export: __VLS_WithSlots<typeof __VLS_base, __VLS_Slots>;
|
|
14
|
+
declare const _default: typeof __VLS_export;
|
|
15
|
+
export default _default;
|
|
16
|
+
type __VLS_WithSlots<T, S> = T & {
|
|
17
|
+
new (): {
|
|
18
|
+
$slots: S;
|
|
19
|
+
};
|
|
20
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
<script setup>
|
|
2
|
+
import { useUserSession } from "#imports";
|
|
3
|
+
const { loggedIn, user, session, signOut, ready } = useUserSession();
|
|
4
|
+
</script>
|
|
5
|
+
|
|
6
|
+
<template>
|
|
7
|
+
<slot v-if="ready" v-bind="{ loggedIn, user, session, signOut }" />
|
|
8
|
+
<slot v-else name="placeholder" />
|
|
9
|
+
</template>
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
declare var __VLS_1: {
|
|
2
|
+
loggedIn: boolean;
|
|
3
|
+
user: import("../../types.js").AuthUser | null;
|
|
4
|
+
session: import("../../types.js").AuthSession | null;
|
|
5
|
+
signOut: (options?: import("#imports").SignOutOptions) => Promise<void>;
|
|
6
|
+
}, __VLS_3: {};
|
|
7
|
+
type __VLS_Slots = {} & {
|
|
8
|
+
default?: (props: typeof __VLS_1) => any;
|
|
9
|
+
} & {
|
|
10
|
+
placeholder?: (props: typeof __VLS_3) => any;
|
|
11
|
+
};
|
|
12
|
+
declare const __VLS_base: import("vue").DefineComponent<{}, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<{}> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
|
|
13
|
+
declare const __VLS_export: __VLS_WithSlots<typeof __VLS_base, __VLS_Slots>;
|
|
14
|
+
declare const _default: typeof __VLS_export;
|
|
15
|
+
export default _default;
|
|
16
|
+
type __VLS_WithSlots<T, S> = T & {
|
|
17
|
+
new (): {
|
|
18
|
+
$slots: S;
|
|
19
|
+
};
|
|
20
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { AppAuthClient, AuthSession, AuthUser } from '#nuxt-better-auth';
|
|
2
|
+
import type { ComputedRef, Ref } from 'vue';
|
|
3
|
+
export interface SignOutOptions {
|
|
4
|
+
onSuccess?: () => void | Promise<void>;
|
|
5
|
+
}
|
|
6
|
+
export interface UseUserSessionReturn {
|
|
7
|
+
client: AppAuthClient | null;
|
|
8
|
+
session: Ref<AuthSession | null>;
|
|
9
|
+
user: Ref<AuthUser | null>;
|
|
10
|
+
loggedIn: ComputedRef<boolean>;
|
|
11
|
+
ready: ComputedRef<boolean>;
|
|
12
|
+
signIn: NonNullable<AppAuthClient>['signIn'];
|
|
13
|
+
signUp: NonNullable<AppAuthClient>['signUp'];
|
|
14
|
+
signOut: (options?: SignOutOptions) => Promise<void>;
|
|
15
|
+
waitForSession: () => Promise<void>;
|
|
16
|
+
fetchSession: (options?: {
|
|
17
|
+
headers?: HeadersInit;
|
|
18
|
+
force?: boolean;
|
|
19
|
+
}) => Promise<void>;
|
|
20
|
+
updateUser: (updates: Partial<AuthUser>) => void;
|
|
21
|
+
}
|
|
22
|
+
export declare function useUserSession(): UseUserSessionReturn;
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import createAppAuthClient from "#auth/client";
|
|
2
|
+
import { computed, nextTick, useRequestHeaders, useRequestURL, useRuntimeConfig, useState, watch } from "#imports";
|
|
3
|
+
let _client = null;
|
|
4
|
+
function getClient(baseURL) {
|
|
5
|
+
if (!_client)
|
|
6
|
+
_client = createAppAuthClient(baseURL);
|
|
7
|
+
return _client;
|
|
8
|
+
}
|
|
9
|
+
export function useUserSession() {
|
|
10
|
+
const runtimeConfig = useRuntimeConfig();
|
|
11
|
+
const requestURL = useRequestURL();
|
|
12
|
+
const client = import.meta.client ? getClient(runtimeConfig.public.siteUrl || requestURL.origin) : null;
|
|
13
|
+
const session = useState("auth:session", () => null);
|
|
14
|
+
const user = useState("auth:user", () => null);
|
|
15
|
+
const authReady = useState("auth:ready", () => false);
|
|
16
|
+
const ready = computed(() => authReady.value);
|
|
17
|
+
const loggedIn = computed(() => Boolean(session.value && user.value));
|
|
18
|
+
function clearSession() {
|
|
19
|
+
session.value = null;
|
|
20
|
+
user.value = null;
|
|
21
|
+
}
|
|
22
|
+
function updateUser(updates) {
|
|
23
|
+
if (user.value)
|
|
24
|
+
user.value = { ...user.value, ...updates };
|
|
25
|
+
}
|
|
26
|
+
if (import.meta.client && client) {
|
|
27
|
+
const clientSession = client.useSession();
|
|
28
|
+
watch(
|
|
29
|
+
() => clientSession.value,
|
|
30
|
+
(newSession) => {
|
|
31
|
+
if (newSession?.data?.session && newSession?.data?.user) {
|
|
32
|
+
const { token: _, ...safeSession } = newSession.data.session;
|
|
33
|
+
session.value = safeSession;
|
|
34
|
+
user.value = newSession.data.user;
|
|
35
|
+
} else if (!newSession?.isPending) {
|
|
36
|
+
clearSession();
|
|
37
|
+
}
|
|
38
|
+
if (!authReady.value && !newSession?.isPending)
|
|
39
|
+
authReady.value = true;
|
|
40
|
+
},
|
|
41
|
+
{ immediate: true, deep: true }
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
function waitForSession() {
|
|
45
|
+
return new Promise((resolve) => {
|
|
46
|
+
if (loggedIn.value) {
|
|
47
|
+
resolve();
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
const unwatch = watch(loggedIn, (isLoggedIn) => {
|
|
51
|
+
if (isLoggedIn) {
|
|
52
|
+
unwatch();
|
|
53
|
+
resolve();
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
setTimeout(() => {
|
|
57
|
+
unwatch();
|
|
58
|
+
resolve();
|
|
59
|
+
}, 5e3);
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
function wrapOnSuccess(cb) {
|
|
63
|
+
return async (ctx) => {
|
|
64
|
+
await fetchSession({ force: true });
|
|
65
|
+
if (!loggedIn.value)
|
|
66
|
+
await waitForSession();
|
|
67
|
+
await nextTick();
|
|
68
|
+
await cb(ctx);
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
function wrapAuthMethod(method) {
|
|
72
|
+
return (async (...args) => {
|
|
73
|
+
const [data, options] = args;
|
|
74
|
+
if (data?.fetchOptions?.onSuccess) {
|
|
75
|
+
return method({ ...data, fetchOptions: { ...data.fetchOptions, onSuccess: wrapOnSuccess(data.fetchOptions.onSuccess) } }, options);
|
|
76
|
+
}
|
|
77
|
+
if (options?.onSuccess) {
|
|
78
|
+
return method(data, { ...options, onSuccess: wrapOnSuccess(options.onSuccess) });
|
|
79
|
+
}
|
|
80
|
+
return method(data, options);
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
const signIn = client?.signIn ? new Proxy(client.signIn, {
|
|
84
|
+
get(target, prop) {
|
|
85
|
+
const targetRecord = target;
|
|
86
|
+
const method = targetRecord[prop];
|
|
87
|
+
if (typeof method !== "function")
|
|
88
|
+
return method;
|
|
89
|
+
return wrapAuthMethod((...args) => targetRecord[prop](...args));
|
|
90
|
+
}
|
|
91
|
+
}) : new Proxy({}, {
|
|
92
|
+
get: (_, prop) => {
|
|
93
|
+
throw new Error(`signIn.${String(prop)}() can only be called on client-side`);
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
const signUp = client?.signUp ? new Proxy(client.signUp, {
|
|
97
|
+
get(target, prop) {
|
|
98
|
+
const targetRecord = target;
|
|
99
|
+
const method = targetRecord[prop];
|
|
100
|
+
if (typeof method !== "function")
|
|
101
|
+
return method;
|
|
102
|
+
return wrapAuthMethod((...args) => targetRecord[prop](...args));
|
|
103
|
+
}
|
|
104
|
+
}) : new Proxy({}, {
|
|
105
|
+
get: (_, prop) => {
|
|
106
|
+
throw new Error(`signUp.${String(prop)}() can only be called on client-side`);
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
async function fetchSession(options = {}) {
|
|
110
|
+
if (import.meta.server) {
|
|
111
|
+
if (!authReady.value)
|
|
112
|
+
authReady.value = true;
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (client) {
|
|
116
|
+
try {
|
|
117
|
+
const headers = options.headers || useRequestHeaders(["cookie"]);
|
|
118
|
+
const fetchOptions = headers ? { headers } : void 0;
|
|
119
|
+
const query = options.force ? { disableCookieCache: true } : void 0;
|
|
120
|
+
const result = await client.getSession({ query }, fetchOptions);
|
|
121
|
+
const data = result.data;
|
|
122
|
+
if (data?.session && data?.user) {
|
|
123
|
+
const { token: _, ...safeSession } = data.session;
|
|
124
|
+
session.value = safeSession;
|
|
125
|
+
user.value = data.user;
|
|
126
|
+
} else {
|
|
127
|
+
clearSession();
|
|
128
|
+
}
|
|
129
|
+
} catch (error) {
|
|
130
|
+
clearSession();
|
|
131
|
+
console.error("[nuxt-better-auth] Failed to fetch session:", error);
|
|
132
|
+
} finally {
|
|
133
|
+
if (!authReady.value)
|
|
134
|
+
authReady.value = true;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
async function signOut(options) {
|
|
139
|
+
if (!client)
|
|
140
|
+
throw new Error("signOut can only be called on client-side");
|
|
141
|
+
await client.signOut();
|
|
142
|
+
clearSession();
|
|
143
|
+
if (options?.onSuccess)
|
|
144
|
+
await options.onSuccess();
|
|
145
|
+
}
|
|
146
|
+
return {
|
|
147
|
+
client,
|
|
148
|
+
session,
|
|
149
|
+
user,
|
|
150
|
+
loggedIn,
|
|
151
|
+
ready,
|
|
152
|
+
signIn,
|
|
153
|
+
signUp,
|
|
154
|
+
signOut,
|
|
155
|
+
waitForSession,
|
|
156
|
+
fetchSession,
|
|
157
|
+
updateUser
|
|
158
|
+
};
|
|
159
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { AuthMeta } from '../../types.js';
|
|
2
|
+
declare module '#app' {
|
|
3
|
+
interface PageMeta {
|
|
4
|
+
auth?: AuthMeta;
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
declare module 'vue-router' {
|
|
8
|
+
interface RouteMeta {
|
|
9
|
+
auth?: AuthMeta;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
declare const _default: import("#app").RouteMiddleware;
|
|
13
|
+
export default _default;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { createError, defineNuxtRouteMiddleware, getRouteRules, navigateTo, useNuxtApp, useRequestHeaders, useRuntimeConfig, useUserSession } from "#imports";
|
|
2
|
+
import { matchesUser } from "../../utils/match-user.js";
|
|
3
|
+
export default defineNuxtRouteMiddleware(async (to) => {
|
|
4
|
+
const nuxtApp = useNuxtApp();
|
|
5
|
+
if (import.meta.client) {
|
|
6
|
+
const isPrerendered = nuxtApp.payload.prerenderedAt || nuxtApp.payload.isCached;
|
|
7
|
+
if (isPrerendered && nuxtApp.isHydrating)
|
|
8
|
+
return;
|
|
9
|
+
}
|
|
10
|
+
if (to.meta.auth === void 0) {
|
|
11
|
+
const rules = await getRouteRules({ path: to.path });
|
|
12
|
+
if (rules.auth !== void 0)
|
|
13
|
+
to.meta.auth = rules.auth;
|
|
14
|
+
}
|
|
15
|
+
const auth = to.meta.auth;
|
|
16
|
+
if (auth === void 0 || auth === false)
|
|
17
|
+
return;
|
|
18
|
+
const config = useRuntimeConfig().public.auth;
|
|
19
|
+
const { fetchSession, user, loggedIn } = useUserSession();
|
|
20
|
+
if (!loggedIn.value) {
|
|
21
|
+
const headers = import.meta.server ? useRequestHeaders(["cookie"]) : void 0;
|
|
22
|
+
await fetchSession({ headers });
|
|
23
|
+
}
|
|
24
|
+
const mode = typeof auth === "string" ? auth : auth?.only ?? "user";
|
|
25
|
+
const redirectTo = typeof auth === "object" ? auth.redirectTo : void 0;
|
|
26
|
+
if (mode === "guest") {
|
|
27
|
+
if (loggedIn.value)
|
|
28
|
+
return navigateTo(redirectTo ?? config?.redirects?.guest ?? "/");
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
if (!loggedIn.value)
|
|
32
|
+
return navigateTo(redirectTo ?? config?.redirects?.login ?? "/login");
|
|
33
|
+
if (typeof auth === "object" && auth.user) {
|
|
34
|
+
if (!user.value || !matchesUser(user.value, auth.user))
|
|
35
|
+
throw createError({ statusCode: 403, statusMessage: "Access denied" });
|
|
36
|
+
}
|
|
37
|
+
});
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
declare const __VLS_export: import("vue").DefineComponent<{}, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<{}> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
|
|
2
|
+
declare const _default: typeof __VLS_export;
|
|
3
|
+
export default _default;
|