@witchcraft/nuxt-auth 0.5.2 → 0.6.0-beta.1
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 +188 -336
- package/dist/module.d.mts +64 -41
- package/dist/module.json +1 -1
- package/dist/module.mjs +25 -35
- package/dist/runtime/components/ExternalCallback.vue +11 -11
- package/dist/runtime/components/LoginProviderButtons.client.d.vue.ts +10 -15
- package/dist/runtime/components/LoginProviderButtons.client.vue +4 -10
- package/dist/runtime/components/LoginProviderButtons.client.vue.d.ts +10 -15
- package/dist/runtime/components/MockBypassRegistrationFields.d.vue.ts +13 -0
- package/dist/runtime/components/MockBypassRegistrationFields.vue +18 -0
- package/dist/runtime/components/MockBypassRegistrationFields.vue.d.ts +13 -0
- package/dist/runtime/components/Mocker.d.vue.ts +5 -1
- package/dist/runtime/components/Mocker.vue +7 -10
- package/dist/runtime/components/Mocker.vue.d.ts +5 -1
- package/dist/runtime/components/SessionStatus.d.vue.ts +86 -42
- package/dist/runtime/components/SessionStatus.vue +29 -8
- package/dist/runtime/components/SessionStatus.vue.d.ts +86 -42
- package/dist/runtime/components/UserRegistration.d.vue.ts +5 -0
- package/dist/runtime/components/UserRegistration.vue +2 -0
- package/dist/runtime/components/UserRegistration.vue.d.ts +5 -0
- package/dist/runtime/composables/useAuth.d.ts +382 -19
- package/dist/runtime/composables/useAuth.js +191 -28
- package/dist/runtime/composables/useAuthExternalCallback.d.ts +13 -6
- package/dist/runtime/composables/useAuthExternalCallback.js +27 -16
- package/dist/runtime/composables/useAuthExternalCode.d.ts +2 -2
- package/dist/runtime/composables/useAuthExternalCode.js +19 -18
- package/dist/runtime/composables/useAuthMocker.d.ts +11 -1
- package/dist/runtime/composables/useAuthMocker.js +21 -11
- package/dist/runtime/composables/useAuthUserRegistration.d.ts +5 -10
- package/dist/runtime/composables/useAuthUserRegistration.js +12 -25
- package/dist/runtime/core/providerStyles.js +12 -4
- package/dist/runtime/electron/index.d.ts +1 -0
- package/dist/runtime/electron/index.js +1 -0
- package/dist/runtime/electron/main/ElectronAuth.d.ts +123 -0
- package/dist/runtime/electron/main/ElectronAuth.js +200 -0
- package/dist/runtime/electron/main/index.d.ts +2 -0
- package/dist/runtime/electron/main/index.js +2 -0
- package/dist/runtime/electron/main/setupElectronAuthMain.d.ts +665 -0
- package/dist/runtime/electron/main/setupElectronAuthMain.js +137 -0
- package/dist/runtime/electron/preload/createElectronAuthApi.d.ts +7 -0
- package/dist/runtime/electron/preload/createElectronAuthApi.js +15 -0
- package/dist/runtime/electron/preload/index.d.ts +2 -0
- package/dist/runtime/electron/preload/index.js +2 -0
- package/dist/runtime/electron/types.d.ts +54 -0
- package/dist/runtime/electron/types.js +2 -0
- package/dist/runtime/middleware/authGlobal.js +30 -14
- package/dist/runtime/middleware/authProtected.js +2 -2
- package/dist/runtime/plugins/client/electronNuxtAuthPlugin.d.ts +48 -0
- package/dist/runtime/plugins/client/electronNuxtAuthPlugin.js +86 -0
- package/dist/runtime/plugins/client/localOnlyUsers.d.ts +25 -0
- package/dist/runtime/plugins/client/localOnlyUsers.js +110 -0
- package/dist/runtime/plugins/server/devMock.d.ts +51 -0
- package/dist/runtime/plugins/server/devMock.js +162 -0
- package/dist/runtime/server/utils/assertEventWithAuthorizedUser.d.ts +11 -0
- package/dist/runtime/server/utils/assertEventWithAuthorizedUser.js +10 -0
- package/dist/runtime/server/utils/createAuthMiddleware.d.ts +4 -4
- package/dist/runtime/server/utils/createAuthMiddleware.js +16 -23
- package/dist/runtime/server/utils/createAuthSchema.d.ts +391 -94
- package/dist/runtime/server/utils/createAuthSchema.js +43 -13
- package/dist/runtime/server/utils/createBetterAuth.d.ts +34 -0
- package/dist/runtime/server/utils/createBetterAuth.js +160 -0
- package/dist/runtime/server/utils/getBetterAuthInstance.d.ts +3 -0
- package/dist/runtime/server/utils/getBetterAuthInstance.js +10 -0
- package/dist/runtime/types.d.ts +358 -248
- package/dist/runtime/types.js +48 -25
- package/dist/runtime/utils/deserializeAuthLocalUser.d.ts +2 -0
- package/dist/runtime/utils/deserializeAuthLocalUser.js +9 -0
- package/package.json +44 -19
- package/dist/runtime/core/providers/github.d.ts +0 -84
- package/dist/runtime/core/providers/github.js +0 -55
- package/dist/runtime/core/providers/google.d.ts +0 -65
- package/dist/runtime/core/providers/google.js +0 -49
- package/dist/runtime/server/helpers/getSafeSecretsInfo.d.ts +0 -4
- package/dist/runtime/server/helpers/getSafeSecretsInfo.js +0 -10
- package/dist/runtime/server/helpers/logSafeRoute.d.ts +0 -1
- package/dist/runtime/server/helpers/logSafeRoute.js +0 -3
- package/dist/runtime/server/helpers/signJwt.d.ts +0 -3
- package/dist/runtime/server/helpers/signJwt.js +0 -16
- package/dist/runtime/server/helpers/verifyJwt.d.ts +0 -5
- package/dist/runtime/server/helpers/verifyJwt.js +0 -19
- package/dist/runtime/server/utils/Auth.d.ts +0 -85
- package/dist/runtime/server/utils/Auth.js +0 -671
- package/dist/runtime/server/utils/SessionManager.d.ts +0 -26
- package/dist/runtime/server/utils/SessionManager.js +0 -94
- package/dist/runtime/server/utils/createAuthHandler.d.ts +0 -9
- package/dist/runtime/server/utils/createAuthHandler.js +0 -29
- package/dist/runtime/utils/createExternalAuthLoginHandler.d.ts +0 -37
- package/dist/runtime/utils/createExternalAuthLoginHandler.js +0 -23
- package/dist/runtime/utils/getAuthApiRoute.d.ts +0 -6
- package/dist/runtime/utils/getAuthApiRoute.js +0 -14
package/README.md
CHANGED
|
@@ -6,50 +6,26 @@
|
|
|
6
6
|
[![License][license-src]][license-href]
|
|
7
7
|
[![Nuxt][nuxt-src]][nuxt-href]
|
|
8
8
|
|
|
9
|
-
|
|
10
|
-
VERY WIP wrapper module following the guide by [lucia auth](https://lucia-auth.com/) with postgres and drizzle db.
|
|
11
|
-
|
|
12
|
-
I am not an auth expert, **use at your own risk**. The module's auth code is not that long, read
|
|
13
|
-
[src/runtime/server/utils/SessionManager.ts](https://github.com/witchcraftjs/nuxt-auth/blob/master/src/runtime/server/utils/SessionManager.ts) (based on lucia) and
|
|
14
|
-
[`src/runtime/server/utils/Auth.ts`](https://github.com/witchcraftjs/nuxt-auth/blob/master/src/runtime/server/utils/Auth.ts) which contains all the logic.
|
|
9
|
+
Nuxt auth module built on [better-auth](https://www.better-auth.com). Tries to set up nearly everything + some extra goodies.
|
|
15
10
|
|
|
16
11
|
|
|
17
12
|
## Playground
|
|
18
13
|
|
|
19
|
-
There is a playground but it must be run locally as it requires
|
|
20
|
-
|
|
21
|
-
## Features
|
|
22
|
-
|
|
23
|
-
The following providers are included (using the `arctic` library), custom providers can be easily added.
|
|
24
|
-
|
|
25
|
-
- [Google](https://console.cloud.google.com/apis/credentials)
|
|
26
|
-
- [Github](https://github.com/settings/applications/new)
|
|
27
|
-
<!-- - [Facebook](https://developers.facebook.com/apps) -->
|
|
28
|
-
<!-- - [Twitter](https://developer.twitter.com/en/portal/dashboard) -->
|
|
29
|
-
|
|
30
|
-
|
|
14
|
+
There is a playground that runs with in-memory postgres, but it must be run locally as it requires env secrets to be set.
|
|
31
15
|
## Install
|
|
32
16
|
|
|
33
|
-
It is highly recommended you install the nuxt-security module (or something similar) as this module does NOT add middleware to guard against CSRF.
|
|
34
|
-
|
|
35
|
-
```bash
|
|
36
|
-
pnpx nuxi module add nuxt-security
|
|
37
|
-
```
|
|
38
|
-
|
|
39
17
|
The module requires the `@witchcraft/ui` module for ui components but those are optional so it's not needed if you won't be using them.
|
|
40
18
|
|
|
41
19
|
```bash
|
|
42
20
|
pnpx nuxi module add @witchcraft/ui
|
|
43
21
|
```
|
|
44
22
|
|
|
45
|
-
`@witchcraft/nuxt-logger` is also recommended
|
|
46
|
-
All logs are objects with at least an `ns` (namespace) property and can ocassionally contain a `redact` property that **must be redacted in production to be secure**.
|
|
23
|
+
`@witchcraft/nuxt-logger` is also recommended for it's polymorphic-ish loggers (see playground's usage of `use*Logger`s). All logs are objects with at least an `ns` (namespace) property.
|
|
47
24
|
|
|
48
25
|
```bash
|
|
49
26
|
pnpx nuxi module add @witchcraft/nuxt-logger
|
|
50
27
|
|
|
51
28
|
```
|
|
52
|
-
Don't forget to actually pass it's `useServerLogger` when creating the apis.
|
|
53
29
|
|
|
54
30
|
## Usage
|
|
55
31
|
|
|
@@ -57,9 +33,11 @@ Don't forget to actually pass it's `useServerLogger` when creating the apis.
|
|
|
57
33
|
|
|
58
34
|
The following env variables are needed:
|
|
59
35
|
|
|
60
|
-
- `
|
|
61
|
-
- `
|
|
62
|
-
- `
|
|
36
|
+
- `NUXT_AUTH_SECRET` // for nuxt-auth
|
|
37
|
+
- `NUXT_AUTH_{PROVIDER}_CLIENT_ID`
|
|
38
|
+
- `NUXT_AUTH_{PROVIDER}_CLIENT_SECRET`
|
|
39
|
+
|
|
40
|
+
`NUXT_AUTH_SECRET` must be at least 32 bytes (better-auth's minimum). In production the module throws on boot when it is missing or shorter. Generate one with `openssl rand -base64 32`.
|
|
63
41
|
|
|
64
42
|
Set the ones you need in the nuxt config. There is a helper function for doing this:
|
|
65
43
|
|
|
@@ -76,28 +54,25 @@ export default defineNuxtConfig({
|
|
|
76
54
|
// this is set automatically (for production, it's always true, for dev it's true if nuxt.options.devServer.https is defined)
|
|
77
55
|
// this determines whether to use https in the auth callback url
|
|
78
56
|
// isSecure: ...
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
...(process.env.NODE_ENV === "development" ? ["http://localhost:3000"] : []),
|
|
84
|
-
"https://your-app-site.com",
|
|
85
|
-
],
|
|
86
|
-
// see also allowedMiddlewareExclusions for external hosts
|
|
87
|
-
// that should only be allowed access for certain requests
|
|
57
|
+
},
|
|
58
|
+
enabledProviders: ["google", "github"],
|
|
59
|
+
// optional, electron apps only
|
|
60
|
+
// deeplinkSchemes: { electron: "myapp" },
|
|
88
61
|
}
|
|
89
62
|
})
|
|
90
63
|
```
|
|
91
64
|
|
|
65
|
+
`createBetterAuth` trusts `appUrl`. Add extra origins through `betterAuthOptions.trustedOrigins` (list is merged with the defaults):
|
|
66
|
+
|
|
92
67
|
The callback url is `{http/https}://localhost:3000/api/auth/callback/{PROVIDER}`.
|
|
93
|
-
Note that if using `https`, both the
|
|
68
|
+
Note that if using `https`, both the trusted origin and the callback url must have https in the provider's config.
|
|
94
69
|
|
|
95
70
|
### Basic Setup
|
|
96
71
|
|
|
97
72
|
#### DB
|
|
98
73
|
|
|
99
|
-
The module provides a `createAuthSchema` helper and a list of `authUserFields` it needs on the user's table. Unlike some examples, a uuid is used for the id. You can set them up like:
|
|
100
74
|
|
|
75
|
+
The module provides `authUserFields` (the columns it needs on the user's table, including `username`) plus `createAuthSchema` for the session, account, and verification tables. Spread the fields into your own users table. Table shapes follow the [better-auth core schema](https://www.better-auth.com/docs/concepts/database).
|
|
101
76
|
```ts
|
|
102
77
|
// path/to/schema.ts
|
|
103
78
|
// careful not to use nuxt paths, or drizzle won't be able to import them when when generating migrations, etc
|
|
@@ -112,6 +87,7 @@ export const users = pgTable("users", {
|
|
|
112
87
|
export const {
|
|
113
88
|
authAccounts,
|
|
114
89
|
authSessions,
|
|
90
|
+
authVerifications,
|
|
115
91
|
authProvidersRelations,
|
|
116
92
|
authSessionRelations
|
|
117
93
|
} = createAuthSchema(users)
|
|
@@ -120,58 +96,60 @@ export const {
|
|
|
120
96
|
#### SessionManager and Routes
|
|
121
97
|
|
|
122
98
|
|
|
123
|
-
First
|
|
99
|
+
First create your auth instance with your db in some file (it can be anywhere) and export it.
|
|
124
100
|
|
|
125
101
|
Then create two files:
|
|
126
102
|
```
|
|
127
103
|
- server
|
|
104
|
+
// the better auth instance
|
|
105
|
+
auth.ts
|
|
128
106
|
- middleware
|
|
129
107
|
- auth.ts
|
|
130
108
|
- api
|
|
131
109
|
- auth
|
|
132
|
-
|
|
133
|
-
|
|
110
|
+
// this is named like this **literally**, it is a catch-all route
|
|
111
|
+
- [...].ts
|
|
134
112
|
```
|
|
135
113
|
|
|
136
|
-
This creates the
|
|
137
|
-
```ts [server/
|
|
138
|
-
|
|
139
|
-
import { createAuthHandler, useServerLogger } from "#imports"
|
|
140
|
-
import { authAccounts, users } from "~~/db/schema.js"
|
|
141
|
-
import { db } from "[PATH TO YOUR DRIZZLE DB]"
|
|
142
|
-
import { sessionManager } from "[PATH TO YOUR SESSION MANAGER INSTANCE]"
|
|
114
|
+
This creates the auth instance.
|
|
115
|
+
```ts [server/auth.ts]
|
|
116
|
+
import { createBetterAuth } from "@witchcraft/nuxt-auth/server/utils/createBetterAuth"
|
|
143
117
|
|
|
144
|
-
export
|
|
145
|
-
useRuntimeConfig(),
|
|
118
|
+
export const auth = createBetterAuth({
|
|
146
119
|
db,
|
|
147
|
-
users,
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
)
|
|
120
|
+
schema: { users, authAccounts, authSessions, authVerifications },
|
|
121
|
+
// you can gate here or at the nuxt config level, up to you, if you are using electron I suggest at the config level to start (see the playground)
|
|
122
|
+
appUrl: import.meta.dev
|
|
123
|
+
? `${useRuntimeConfig().public.auth.isSecure ? "https" : "http"}://localhost:${useRuntimeConfig().port}`
|
|
124
|
+
: useRuntimeConfig().public.siteUrl as string,
|
|
125
|
+
usernameSchema: z.string().min(3).max(32),
|
|
126
|
+
devBypassAuth: true, // allow the dev only dev-mock bypass
|
|
127
|
+
logger: useServerLogger()
|
|
128
|
+
})
|
|
157
129
|
```
|
|
158
130
|
|
|
159
|
-
This creates the
|
|
131
|
+
This creates the catch-all api handler.
|
|
132
|
+
```ts [server/api/auth/[...].ts]
|
|
133
|
+
import { auth } from "../auth.js"
|
|
160
134
|
|
|
161
|
-
|
|
135
|
+
export default defineEventHandler(event => {
|
|
136
|
+
return auth.handler(toWebRequest(event))
|
|
137
|
+
})
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
The following creates the middleware that sets the user/session on the request context.
|
|
141
|
+
|
|
142
|
+
**IMPORTANT: better-auth validates origins and handles CSRF for its own endpoints. It does not protect your application's own routes. Use nuxt-security or equivalent for those.**
|
|
162
143
|
|
|
163
144
|
```ts
|
|
164
145
|
// server/middleware/auth.ts
|
|
146
|
+
import { auth } from "../auth.js"
|
|
165
147
|
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
import { sessionManager } from "[PATH TO YOUR SESSION MANAGER INSTANCE]"
|
|
169
|
-
export default createAuthMiddleware(
|
|
170
|
-
sessionManager,
|
|
171
|
-
useServerLogger()
|
|
172
|
-
)
|
|
148
|
+
export default createAuthMiddleware(auth, useServerLogger())
|
|
173
149
|
```
|
|
174
150
|
|
|
151
|
+
The middleware fills `event.context.user` plus `event.context.session` (null when logged out). To guard a route, use the `assertEventWithAuthorizedUser` server util. It throws a 401 on a missing user and narrows the event type past the check.
|
|
152
|
+
|
|
175
153
|
### Create the Pages
|
|
176
154
|
|
|
177
155
|
See the playground for a full example, but you will need to create the following pages, components are provided to help create these:
|
|
@@ -186,26 +164,19 @@ By default the module will redirect to corresponding api route when calling `use
|
|
|
186
164
|
|
|
187
165
|
In some cases you may want to customize this behavior, such as when calling this from a desktop app where you need to open a browser instance.
|
|
188
166
|
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
There is also a `createExternalAuthLoginHandler` helper and related utils, see [External Auth Handlers](#external-auth-handlers).
|
|
167
|
+
For handling auth in external apps, see [External Auth Handlers](#external-auth-handlers).
|
|
192
168
|
|
|
193
169
|
### Changing Routes
|
|
194
170
|
|
|
195
|
-
While not recommended, you can change the routes used by the module by setting the `
|
|
196
|
-
|
|
197
|
-
```ts
|
|
198
|
-
getAuthApiRoute(useRuntimeConfig().public, "usersInfo")
|
|
199
|
-
getAuthApiRoute(useRuntimeConfig().public, "usersIdAccounts", id)
|
|
200
|
-
```
|
|
171
|
+
While not recommended, you can change the routes used by the module by setting the `authApiRouteBase` (changing where the server API is) and `authRoutes` options (changing where redirects happen to).
|
|
201
172
|
|
|
202
173
|
#### Middleware
|
|
203
174
|
|
|
204
175
|
### Auth Middleware
|
|
205
176
|
|
|
206
|
-
A global middleware is registered
|
|
177
|
+
A global middleware is registered to determine the user's logged in state (through the better-auth client session), on every navigation. It does not redirect by default.
|
|
207
178
|
|
|
208
|
-
|
|
179
|
+
Reading it is only done on page load or before (because they might redirect) any actions (login/logout/register\*) so that we don't fetch from the server on every page navigation.
|
|
209
180
|
|
|
210
181
|
You can use `useAuth().setFetchUserOnNavigation(...)` to allow fetch on the next navigation. The middleware then disables fetching again to prevent further fetching.
|
|
211
182
|
|
|
@@ -217,12 +188,13 @@ You can also fetch from the api manually if you want and set `auth:user` yoursel
|
|
|
217
188
|
|
|
218
189
|
### Route Protection
|
|
219
190
|
|
|
220
|
-
The module does not
|
|
191
|
+
The module does not redirect by default. You have to add `authProtected` to the page's middleware:
|
|
221
192
|
|
|
222
193
|
```ts
|
|
223
194
|
definePageMeta({ middleware: "authProtected" })
|
|
195
|
+
```
|
|
224
196
|
|
|
225
|
-
This will automatically redirect
|
|
197
|
+
This will automatically redirect a signed out visitor to the `unauthenticated` route (home by default) and an unregistered user to the register page, unless the page sets a `redirectTo`.
|
|
226
198
|
|
|
227
199
|
Additionally you can set the following meta properties to control the middleware:
|
|
228
200
|
|
|
@@ -234,12 +206,14 @@ definePageMeta({
|
|
|
234
206
|
only: "authenticated" /* | "registered" | "authenticated-unregistered" | "unauthenticated" */
|
|
235
207
|
|
|
236
208
|
// change the redirect path
|
|
237
|
-
// or can use the special values "$login", "$register", "$postRegisteredLogin"
|
|
209
|
+
// or can use the special values "$login", "$register", "$postRegisteredLogin", "$externalCode"
|
|
238
210
|
redirectTo: "/some/path",
|
|
239
211
|
}
|
|
240
212
|
})
|
|
241
213
|
```
|
|
242
|
-
You can register additional paths with the `additionalMiddlewarePaths` option.
|
|
214
|
+
You can register additional paths with the `additionalMiddlewarePaths` option. `only` can also be a function that receives the refs like `isAuthenticated` (e.g. `only: ({isAuthenticated}) => !isAuthenticated.value`.
|
|
215
|
+
|
|
216
|
+
A page that only makes sense for a signed in user can still be rendered on the server, but a local user exists only in that window's storage, so the server cannot see them, and `authProtected` would redirect the render instead of painting the page. Set `disableServerRedirect: true` on the page to render it anyway and let the browser decide the redirect or set `ssr: false` for the route.
|
|
243
217
|
|
|
244
218
|
### Clearing User Data on Logout
|
|
245
219
|
|
|
@@ -248,6 +222,7 @@ You can add a `beforeLogout` listener to clear the user data on logout by using
|
|
|
248
222
|
```ts
|
|
249
223
|
useAuth().on("beforeLogout", clearUserData)
|
|
250
224
|
```
|
|
225
|
+
|
|
251
226
|
### Branding
|
|
252
227
|
|
|
253
228
|
The module does not create any pages by default.
|
|
@@ -261,10 +236,12 @@ Only components like `AuthLoginProviderButtons` are provided. It's button styles
|
|
|
261
236
|
`AuthSessionStatus` - Provided for creating a login button / status indificator in the nav bar.
|
|
262
237
|
`AuthLoginProviderButtons` - Provided for creating login the buttons.
|
|
263
238
|
`AuthUserRegistration` - Provided for creating a simple registration form with a username input and check.
|
|
264
|
-
-
|
|
265
|
-
- And it submits
|
|
239
|
+
- It checks against the built-in better-auth endpoint `${authApiRouteBase}/username/valid` (mounted under the app's auth base path).
|
|
240
|
+
- And it submits through the better-auth client (`updateUser` with `body: { username }`).
|
|
266
241
|
- It has a slot for easily adding more fields.
|
|
267
|
-
`
|
|
242
|
+
`AuthExternalCode` - Provided for creating a code page for external auth handlers, see [External Auth Handlers](#external-auth-handlers).
|
|
243
|
+
`AuthMocker` - Provided for building the app's mock auth page at the `mockAuth` route (`/auth/mock` by default, the module strips it from non-dev builds), see [Mocking Auth](#mocking-auth-experimental).
|
|
244
|
+
`AuthMockBypassRegistrationFields` - Provided to easily setup mocking at other points (such as the login for external apps which completely bypass the browser).
|
|
268
245
|
|
|
269
246
|
#### Composables
|
|
270
247
|
|
|
@@ -272,315 +249,190 @@ Only components like `AuthLoginProviderButtons` are provided. It's button styles
|
|
|
272
249
|
|
|
273
250
|
#### Types
|
|
274
251
|
|
|
275
|
-
`
|
|
252
|
+
`defaultZodUsernameSchema` - A zod schema for validating usernames. The module uses it as the default when no `usernameSchema` is passed, it's also nice to have on hand for writing a custom username validation route. We wire the min/max length internally to better-auth's options and it serves as validation on top of theirs and for local users which don't go through the server at all.
|
|
276
253
|
|
|
254
|
+
### Common Account Data Access
|
|
277
255
|
|
|
278
|
-
### Database Schema / Customizing Account Data
|
|
279
256
|
|
|
280
|
-
The
|
|
257
|
+
The user's provider avatar is available as `user.image` (set from the provider profile on login).
|
|
281
258
|
|
|
282
|
-
|
|
259
|
+
Registration state is tracked with `isRegistered` (a better-auth `additionalFields` entry defaulting to false). It flips to true automatically through a `databaseHooks` entry when a username is set.
|
|
283
260
|
|
|
284
|
-
|
|
261
|
+
### Extending the Router
|
|
285
262
|
|
|
286
|
-
You can
|
|
263
|
+
You can extend the router at `/api/auth` with `betterAuthOptions` plugin endpoints (arrays concatenate with the module plugins, see the [better-auth plugin docs](https://www.better-auth.com/docs/concepts/plugins) for the `endpoints` shape):
|
|
287
264
|
|
|
288
265
|
```ts
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
}
|
|
266
|
+
createBetterAuth({
|
|
267
|
+
// ... the rest of your options
|
|
268
|
+
betterAuthOptions: {
|
|
269
|
+
plugins: [myPluginWithEndpoints()]
|
|
294
270
|
}
|
|
295
|
-
}
|
|
271
|
+
})
|
|
296
272
|
```
|
|
297
273
|
|
|
298
|
-
###
|
|
274
|
+
### Local-only users
|
|
299
275
|
|
|
300
|
-
|
|
276
|
+
Unlike better-auth's "anonymouse" plugin. Local-only users have no server account at all. The `local-only-users` client plugin creates them in the shape of real users, entirely in `localStorage`. `useAuth` then wraps better-auth's client to intercept certain calls and wrote them to the plugin's methods instead only when the provider/user is "local". The rest of the methods that would not apply are rejected. See [authClientWrapper.ts](src/runtime/utils/authClientWrapper.ts) for the full table.
|
|
301
277
|
|
|
302
|
-
|
|
303
|
-
```ts
|
|
304
|
-
declare module "@witchcraft/nuxt-auth" {
|
|
305
|
-
interface Register {
|
|
306
|
-
AdditionalProviders: {
|
|
307
|
-
customProvider: {
|
|
308
|
-
id: string
|
|
309
|
-
// ...info as returned by the provider's api
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
}
|
|
313
|
-
}
|
|
314
|
-
}
|
|
315
|
-
```
|
|
278
|
+
Note that a user can also be `local` on an app, it's just the storage backend part usually changes, so their type is still `local`. External apps that support local users should implement an external plugin, if like `@witchcraft/nuxt-electron` they use a session per user. The playground example and the included electron utilities show how to store and manage via electron. If the app does everything with a single session (not reccommended) you can leave local user storage to the single session.
|
|
316
279
|
|
|
317
|
-
|
|
280
|
+
There is no upgrade path at the moment to a normal user (there will be in the future): logging in normally just creates a real session, merging any local data into it is up to the app.
|
|
318
281
|
|
|
319
|
-
|
|
282
|
+
##### How
|
|
320
283
|
|
|
321
|
-
|
|
322
|
-
export default createAuthHandler(useRuntimeConfig(), db, users, authAccounts, sessionManager, useServerLogger(), {
|
|
323
|
-
customProviders: {
|
|
324
|
-
name: class CustomProvider implements ProviderHandler<"oauth2", "customProvider"> {
|
|
325
|
-
//...
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
})
|
|
329
|
-
```
|
|
330
|
-
### Extending the Router
|
|
284
|
+
The default `authGlobal` middleware reads `localStorage` first for the `auth:user` key and uses that user if it carries a `type`. It skips the server. Otherwise it checks the session and falls back to the stored user.
|
|
331
285
|
|
|
332
|
-
|
|
286
|
+
So if we write to that key with a user's shape and type `local`, it will just use it.
|
|
333
287
|
|
|
334
|
-
|
|
288
|
+
A user's `type` may be one of the following:
|
|
289
|
+
1. `type`: undefined: web users. The auth is checked again on each page load. A dead session means no user and the protected routes send them to sign-in.
|
|
290
|
+
2. `type: "external"`: electron/desktop user. The stored user stays across relaunches and the window never waits on the server for it.
|
|
291
|
+
3. `type: "local"`: completely local users. Similar to external users, except they have no server session so server methods just error for them.
|
|
335
292
|
|
|
336
|
-
|
|
293
|
+
This is safe because **you should always check authentication on the server side, if you're not that's inherently unsafe**.
|
|
337
294
|
|
|
338
|
-
|
|
295
|
+
### External Auth Handlers
|
|
296
|
+
|
|
297
|
+
An external auth handler refers to auth flows handled externally in part, such as by a desktop app. These require a more complicated auth flow. Only electron is fully shown and supported with helpers.
|
|
298
|
+
|
|
299
|
+
#### Electron
|
|
300
|
+
|
|
301
|
+
The full example setup can be found in the playground. This is the sign-in flow.
|
|
339
302
|
|
|
340
303
|
```mermaid
|
|
341
304
|
sequenceDiagram
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
User->>Electron App: Pastes short-lived access token (if app doesn't open)
|
|
385
|
-
Electron App->>Nuxt Server: GET /api/auth/external/exchange with short-lived access token
|
|
386
|
-
end
|
|
387
|
-
Nuxt Server->>Electron App: Returns session token
|
|
388
|
-
Electron App->>Electron App: Saves session token, sets it as a cookie on the window session
|
|
389
|
-
end
|
|
305
|
+
autonumber
|
|
306
|
+
participant Main as Main
|
|
307
|
+
participant Preload as Preload
|
|
308
|
+
participant Renderer as Renderer
|
|
309
|
+
participant Browser as Browser
|
|
310
|
+
participant Server as Server
|
|
311
|
+
|
|
312
|
+
Renderer->>Renderer: login click, external plugin login
|
|
313
|
+
alt real
|
|
314
|
+
Renderer->>Preload: requestExternalAuth({ provider, isDevBypass })
|
|
315
|
+
Preload->>Main: ipc (better-auth)
|
|
316
|
+
Main->>Main: requestAuth: make verifier + state, keep the verifier
|
|
317
|
+
Main->>Browser: openExternal(/electron/init-oauth-proxy?code_challenge&state&client_id&provider)
|
|
318
|
+
else mocked
|
|
319
|
+
Renderer->>Preload: auth.mockRequestAuth({ provider, username, devBypassRegistration })
|
|
320
|
+
Preload->>Main: ipc (auth:mockRequestAuth): make verifier + state, stash the identity
|
|
321
|
+
Main->>Main: openExternal intercepted w/ stashed identity to POST to dev/mock
|
|
322
|
+
end
|
|
323
|
+
Renderer->>Renderer: navigate to the callback page with ?provider=, no token yet
|
|
324
|
+
Note over Renderer: waiting room: retry button, paste box
|
|
325
|
+
rect rgba(120, 120, 120, 0.15)
|
|
326
|
+
Note over Browser,Server: When mocked: skipped
|
|
327
|
+
Browser->>Server: GET /electron/init-oauth-proxy
|
|
328
|
+
Server->>Server: sign-in/social, then 302 to the provider
|
|
329
|
+
Browser->>Server: provider callback
|
|
330
|
+
Server->>Server: mints the code, sets the better-auth.electron cookie, redirects to the externalCode page
|
|
331
|
+
Browser->>Browser: externalCode page polls the cookie
|
|
332
|
+
end
|
|
333
|
+
Browser-->>Main: scheme:/callback#token=code reaches the app through the OS
|
|
334
|
+
Main->>Main: handleUrl, only while the app is already running
|
|
335
|
+
Main->>Renderer: loads the callback page with access_token=code, keeping the query
|
|
336
|
+
Renderer->>Preload: authenticate({ token })
|
|
337
|
+
Preload->>Main: ipc
|
|
338
|
+
Main->>Server: POST /electron/token { token, state, code_verifier }
|
|
339
|
+
Server-->>Main: session cookies stored in the client storage
|
|
340
|
+
Renderer->>Preload: electron.api.auth.exchangeSession()
|
|
341
|
+
Preload->>Main: ipc
|
|
342
|
+
Main->>Server: GET /get-session
|
|
343
|
+
Server-->>Main: { user }
|
|
344
|
+
Main->>Main: finishLogin: sets httpOnly cookies on the server origin, localStorage auth:user
|
|
345
|
+
Renderer->>Renderer: navigateTo(postRegisteredLogin), the middleware sees auth:user
|
|
346
|
+
Renderer->>Server: proxied requests carry the cookie
|
|
390
347
|
```
|
|
391
348
|
|
|
392
|
-
### External Auth Handlers
|
|
393
|
-
|
|
394
|
-
An external auth handler refers to auth flows handled externally in part, such as by a desktop app. These require a more complicated auth flow (see above). There are various ways to handle them, this is just one.
|
|
395
349
|
|
|
396
|
-
|
|
350
|
+
Note that unlike better-auth's default implementation, `@witchcraft/nuxt-electron`'s proxy allows us the real cookie on the session, stored against the origin of `publicServerUrl` (your auth server), and it will be sent with proxied requests.
|
|
397
351
|
|
|
398
|
-
|
|
352
|
+
We cannot store it on `app://bundle` for two reasons. Chromium refuses secure cookies for every non-http(s) scheme, so a window served over `app://bundle` or `file://` can never hold one, no matter what privileges the scheme has. Second, server requests get proxied to the real server anyways as is intended with `@witchcraft/nuxt-electron`.
|
|
399
353
|
|
|
400
|
-
|
|
354
|
+
- **Avoid passing nuxt's `useFetch` to better-auth. The better auth client is purposely built on `publicServerUrl` and rewrites every request back to a relative path, so it resolves against the window origin and goes through that proxy. A method that takes its own fetch, such as `auth.client.useSession(useFetch)`, replaces that rewrite and requests the absolute url instead, where no proxy adds the session cookie.
|
|
401
355
|
|
|
402
|
-
|
|
403
|
-
<script setup lang="ts">
|
|
404
|
-
definePageMeta({
|
|
405
|
-
middleware: ["authProtected"],
|
|
406
|
-
auth: {
|
|
407
|
-
only: "authenticated-registered",
|
|
408
|
-
redirectTo: () => isElectron() ? "$login" : undefined,
|
|
409
|
-
}
|
|
410
|
-
})
|
|
411
|
-
</script>
|
|
356
|
+
- `@witchcraft/nuxt-electon`'s `additionalRoutes` option decides which pages exist in the electron bundle. nuxt-electron drops every page except `/`, the electron route and the ones listed, so the callback page and the login page have to be there, because main loads them from the bundled static pages.
|
|
412
357
|
|
|
413
|
-
|
|
358
|
+
- Electron needs to be setup to take a the single instance lock so it can handle the token on the incoming scheme links. It should handle `second-instance` and `open-url`. A url that arrives while the app is closed is ignored, because the verifier only lives in the running process's memory.
|
|
414
359
|
|
|
415
|
-
|
|
360
|
+
- For mocking auth, since you could test a production version of an electron app against a dev server, mocking on the electron side is only enabled with env `TEST`. Without `TEST`, the mock is still reachable through the browser.
|
|
416
361
|
|
|
362
|
+
- The login handler is platform agnostic. The platform supplies `requestExternalAuth`, which starts its own login, and gets `isDevBypass` and context about the type of mocking wanted so it can pick the mock instead of the real sign-in.
|
|
417
363
|
|
|
418
|
-
|
|
419
|
-
<template>
|
|
420
|
-
<AuthLoginProviderButtons :use-auth-options="{handleActions}"/>
|
|
421
|
-
</template>
|
|
422
|
-
<script setup lang="ts">
|
|
423
|
-
import { isElectron } from "#imports"
|
|
424
|
-
import { useRuntimeConfig } from "#app"
|
|
425
|
-
|
|
426
|
-
const rc = useRuntimeConfig()
|
|
427
|
-
|
|
428
|
-
const handleActions: ActionHandler = (action, url) =>
|
|
429
|
-
createExternalAuthLoginHandler(
|
|
430
|
-
"electron", // for the query param
|
|
431
|
-
isElectron, // platform check
|
|
432
|
-
publicServerUrl, // you must define this somehow
|
|
433
|
-
window?.electron?.api.open,
|
|
434
|
-
"auth/code", // the default
|
|
435
|
-
)(action, url)
|
|
436
|
-
|| createExternalAuthLoginHandler(...) // they can be chained
|
|
364
|
+
#### Post-Expiration Session Persistance
|
|
437
365
|
|
|
438
|
-
|
|
439
|
-
```
|
|
366
|
+
In desktop apps we usually want the login session to persist for as long as possible. The module offers an alternative to making the session longer, it just pretends the user is logged in, similarly to local users but with type `external`. See above for details.
|
|
440
367
|
|
|
441
|
-
|
|
368
|
+
The user is considered authenticated on the client side even if they don't have the right cookies to send with requests because they've expired.
|
|
442
369
|
|
|
443
|
-
|
|
370
|
+
This is safe because **you should always check authentication on the server side, if you're not that's inherently unsafe**.
|
|
444
371
|
|
|
445
|
-
|
|
372
|
+
##### Differentiating Between Expired External Users and Not.
|
|
446
373
|
|
|
447
|
-
|
|
448
|
-
<template>
|
|
449
|
-
<AuthExternalCallback
|
|
450
|
-
:save-session="saveSession"
|
|
451
|
-
/>
|
|
452
|
-
</template>
|
|
453
|
-
<script lang="ts" setup>
|
|
454
|
-
|
|
455
|
-
const rc = useRuntimeConfig()
|
|
456
|
-
async function saveSession(token: string) {
|
|
457
|
-
// you would need to define an api similar to this in electron's preload script that exchanges the token and saves the returned session token to a cookie on the session
|
|
458
|
-
// @witchcraft/nuxt-electron provides utilities for helping to create
|
|
459
|
-
// async functions like these which are normally a pain
|
|
460
|
-
await window.electron.api.auth.saveSession(
|
|
461
|
-
rc.public.auth.authRoutes.postRegisteredLogin,
|
|
462
|
-
token
|
|
463
|
-
)
|
|
464
|
-
// alternatively exchange it here, then ask electron to save it to a cookie
|
|
465
|
-
}
|
|
466
|
-
</script>
|
|
467
|
-
```
|
|
374
|
+
The expiry is stored in local storage at the key `externalExpiryStorageKey` (`auth:external:expiresAt` in ms). `logout` removes it. Only external users store this as they are the only ones that can expire and still navigate. The external app should set this when it get's the session.
|
|
468
375
|
|
|
469
|
-
|
|
376
|
+
The included electron utils write it at login from the session it exchanges, and again whenever the server sets or replaces the window's session cookie. The middleware writes it on load, for an external user, from the session it reads.
|
|
470
377
|
|
|
378
|
+
You can use `useAuth().isExpired()` to estimate it on the spot against the clock.
|
|
379
|
+
The middleware also writes `useState("auth:isExpired")` on every client navigation based on the time and stored value to avoid re-calculating it with a timer since it's not something you need to be recalculating all the time.
|
|
471
380
|
|
|
472
|
-
|
|
381
|
+
You can use `useAuth().isExpired()` to estimate it on the spot against the clock.
|
|
382
|
+
The middleware uses it to also write `useState("auth:isExpired")` on every client navigation based on the time and stored value to avoid re-calculating it with a timer since it's not something you need to be recalculating all the time.
|
|
473
383
|
|
|
474
|
-
|
|
384
|
+
And it is not meant to be foolproof anyways. It's meant only to give UI indications for when, for example, you might re-prompt for credentials directly instead of even allowing an action to happen. It is completely possible for it to be wrong!
|
|
475
385
|
|
|
476
|
-
|
|
386
|
+
## Mocking Auth (experimental)
|
|
477
387
|
|
|
478
|
-
|
|
388
|
+
The auth middleware can mock authentication for testing purposes. This is only allowed if `devBypassAuth` is set to true when creating the auth instance (it defaults to false, and the plugin itself only runs in dev). The client sends a `devBypass` query param with their login.
|
|
479
389
|
|
|
480
|
-
|
|
390
|
+
To use the mocked auth, in your login component you can add a checkbox to enable/disable the bypass option which you can pass to the the `AuthLoginProviderButtons` component:
|
|
481
391
|
|
|
482
|
-
```vue
|
|
392
|
+
```vue
|
|
483
393
|
<template>
|
|
484
|
-
<
|
|
394
|
+
<AuthLoginProviderButtons @login="login($event, { devBypass })" />
|
|
485
395
|
</template>
|
|
486
|
-
```
|
|
487
|
-
|
|
488
|
-
If they aren't registered, they are redirected to `auth/register?deeplink=electron` first and once `api/auth/register?deeplink=electron` is called, it will redirect to `auth/code` with the access token and the deeplinkUri.
|
|
489
|
-
|
|
490
|
-
Paths that contain the access token are in the yellow area.
|
|
491
|
-
|
|
492
|
-
Once the access token is transferred to the app (either via the deeplink or manually on the `auth/external/callback` page), the app can exchange it for a proper session token behind the scenes.
|
|
493
|
-
|
|
494
|
-
The module provides a helper class for handling this in electron, but the basic premise is you make a fetch request to `api/auth/external/exchange` with your accessToken to exchange it for the real sessionToken:
|
|
495
396
|
|
|
496
|
-
|
|
497
|
-
const
|
|
498
|
-
|
|
499
|
-
headers: {
|
|
500
|
-
Authorization: `Bearer ${accessToken}`,
|
|
501
|
-
}
|
|
502
|
-
}).then(async res => res.text())
|
|
503
|
-
.catch(err => err)
|
|
504
|
-
if (sessionToken instanceof Error) {
|
|
505
|
-
...
|
|
506
|
-
}
|
|
507
|
-
// valid sessionToken
|
|
397
|
+
<script lang="ts">
|
|
398
|
+
const { login } = useAuth(...)
|
|
399
|
+
</script>
|
|
508
400
|
```
|
|
509
401
|
|
|
510
|
-
|
|
402
|
+
If true, the login request will add the `devBypass` query param so that the server will redirect to the `mockAuth` route (`/auth/mock` with the provider as a query param) instead of the provider's url.
|
|
511
403
|
|
|
512
|
-
|
|
404
|
+
You should place the `AuthMocker` in this route (**the module will remove the route for non-dev builds**). It will allow you to specify a username to login as. When you press the `AuthMocker`'s submit it will redirect to the server's callback with the username and the bypass request in the query params.
|
|
513
405
|
|
|
514
|
-
|
|
406
|
+
The dev-mock plugin hooks `callback/${provider}` paths with `?devBypass=true` plus an optional `username` or `id` queries.
|
|
515
407
|
|
|
516
|
-
|
|
408
|
+
Without `devBypassRegistration` the request must not carry a username and the user is named after their id.
|
|
517
409
|
|
|
518
|
-
|
|
410
|
+
With it the username comes from the query, falling back to the `generateUser`, option, then to `username_<id>`, **trimmed to fit the default username schema (CAREFUL)**. `POST /dev/mock` takes the same fields (`username`, `id`, `provider`, `devBypassRegistration`) as a body.
|
|
519
411
|
|
|
520
|
-
Since the auth check is done against `useState("auth:user")`, if we set it, the user is considered authenticated on the client side even if they don't have the right cookies to send with requests because they've expired.
|
|
521
412
|
|
|
522
|
-
|
|
413
|
+
If the user does not exist, it will be created using this information.
|
|
523
414
|
|
|
524
|
-
The default `authGlobal` middleware will look for a `localStorage` item called `auth:user` and if it's set, set the user to that. It will additionally set `useState("auth:semiAuthed")` to true. This can be used in components and is used in the `SessionStatus` to indicate that while the user is considered logged in, api requests will fail.
|
|
525
415
|
|
|
526
|
-
You can then ask for re-authentication when they trigger an action (e.g. sync) that requires it. By default, clicking on the username in `SessionStatus` will redirect them to the login page instead of `/users/{username}`.
|
|
527
416
|
|
|
528
|
-
If using this feature, you will probably want to set a custom condition on the login page to allow semi-authed users on it:
|
|
529
417
|
```ts
|
|
530
|
-
|
|
531
|
-
|
|
418
|
+
createBetterAuth({
|
|
419
|
+
// ... the rest of your options
|
|
420
|
+
generateUser: () => {
|
|
421
|
+
const id = crypto.randomUUID()
|
|
422
|
+
return {
|
|
423
|
+
|
|
424
|
+
// override the fallback user, e.g. change the email created
|
|
425
|
+
id,
|
|
426
|
+
email: generateEmail(id)
|
|
427
|
+
}
|
|
428
|
+
},
|
|
532
429
|
})
|
|
533
430
|
```
|
|
534
|
-
Note that if the user doesn't have internet access and the request for userInfo fails (even though they might have proper cookies) but the localStorage request suceeds, they will also be considered semi-authenticated. To avoid this, you would have to check from the platform that they still have cookies and set `useState("auth:semiAuthed")` to false.
|
|
535
|
-
|
|
536
|
-
For example:
|
|
537
|
-
```ts [app/app.vue]
|
|
538
|
-
if (isElectron()) {
|
|
539
|
-
// you would have to define this in the preload script
|
|
540
|
-
if (window.electron?.meta.cookiesValid) {
|
|
541
|
-
useAuth().isSemiAuthed.value = false
|
|
542
|
-
}
|
|
543
|
-
}
|
|
544
|
-
```
|
|
545
|
-
|
|
546
|
-
# Mocking Auth (experimental)
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
The auth middleware can mock authentication for testing purposes. This is only allowed if `devBypassAuth` option is true on the route auth handler, and the client sends a `devBypass` query param with their login.
|
|
550
|
-
|
|
551
|
-
`devBypassAuth` should be set to something that makes sure the environment is safe to allow bypassing like `import.meta.dev && process.env.VITEST === "true"` to allow during dev and testing.
|
|
552
|
-
|
|
553
|
-
To use the mocked auth, in your login component you can add a checkbox to enable/disable the bypass option which you can pass to the the `AuthLoginProviderButtons` component:
|
|
554
|
-
|
|
555
|
-
```vue
|
|
556
|
-
<AuthLoginProviderButtons :use-auth-options="{ handleActions }" :login-options="{ devBypass }" />
|
|
557
|
-
```
|
|
558
|
-
|
|
559
|
-
If true, the login request will add the `devBypass` query param so that the server will redirect to the `mockAuth` route (`/auth/mock` with the provider as a query param) instead of the provider's url.
|
|
560
|
-
|
|
561
|
-
You should place the `AuthMocker` in this route (**the module will remove the route for non-dev builds**). It will allow you to specify a username to login as. When you press the `AuthMocker`'s submit it will redirect to the server's callback with the username and the bypass request in the query params.
|
|
562
|
-
|
|
563
|
-
The server by default will mock the getting of the user's info from the provider and return the following:
|
|
564
|
-
```ts
|
|
565
|
-
{
|
|
566
|
-
provider,
|
|
567
|
-
providerId: `dev-${provider}-${username}`,
|
|
568
|
-
email: `dev-${provider}-${username}@dev.com`,
|
|
569
|
-
isVerified: true,
|
|
570
|
-
name: `Dev ${username}`,
|
|
571
|
-
info: null
|
|
572
|
-
}
|
|
573
|
-
```
|
|
574
|
-
If no username is passed either, but an id is passed instead (e.g. for testing unregistered users), the username will be `username-${id}`.
|
|
575
|
-
|
|
576
|
-
You can change this by specifying a custom `createMockUser` function when creating the auth handler.
|
|
577
|
-
|
|
578
|
-
If the user does not exist, it will be created using this information.
|
|
579
|
-
|
|
580
|
-
To simulate existing users with the default function you can use `Auth.defaultCreateMockUser` to get the info when seeding your database.
|
|
581
431
|
|
|
582
432
|
The server will then bypass auth and create a session for the user.
|
|
583
433
|
|
|
434
|
+
We do not use better-auth's mocking utils because they skip the sign-in flow, they just give you a signed-in user, you cannot test any flows.
|
|
435
|
+
|
|
584
436
|
## Testing the Server APIs directly with Mock Users
|
|
585
437
|
|
|
586
438
|
This is a bit more complicated because the ecosystem is not very mature here. The nuxt test utils (really unjs/ofetch) do not expose a $fetch that can use cookies so we have to create it with the help of [`fetch-cookies`](https://www.npmjs.com/package/fetch-cookie). ofetch is stateless by design and will not persist cookies between requests ([unjs/ofetch#382](https://github.com/unjs/ofetch/issues/382), [unjs/ofetch#435](https://github.com/unjs/ofetch/issues/435)):
|
|
@@ -672,12 +524,12 @@ describe("server/db/users", async () => {
|
|
|
672
524
|
credentials: "include",
|
|
673
525
|
})
|
|
674
526
|
console.log(await get$fetchCookies())
|
|
675
|
-
const userInfo = await $fetch("/api/auth/
|
|
527
|
+
const userInfo = await $fetch("/api/auth/get-session", {
|
|
676
528
|
method: "GET",
|
|
677
529
|
credentials: "include",
|
|
678
530
|
})
|
|
679
|
-
expect(userInfo.username).toBe("test")
|
|
680
|
-
expect(userInfo.isRegistered).toBe(true)
|
|
531
|
+
expect(userInfo.user.username).toBe("test")
|
|
532
|
+
expect(userInfo.user.isRegistered).toBe(true)
|
|
681
533
|
console.log({userInfo})
|
|
682
534
|
})
|
|
683
535
|
test("cookies cleared", async () => {
|