@witchcraft/nuxt-auth 0.0.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 +693 -0
- package/dist/module.d.mts +170 -0
- package/dist/module.json +9 -0
- package/dist/module.mjs +146 -0
- package/dist/runtime/build/genAuthSecretKeys.d.ts +6 -0
- package/dist/runtime/build/genAuthSecretKeys.js +10 -0
- package/dist/runtime/components/ExternalCallback.d.vue.ts +7 -0
- package/dist/runtime/components/ExternalCallback.vue +96 -0
- package/dist/runtime/components/ExternalCallback.vue.d.ts +7 -0
- package/dist/runtime/components/ExternalCode.d.vue.ts +11 -0
- package/dist/runtime/components/ExternalCode.vue +77 -0
- package/dist/runtime/components/ExternalCode.vue.d.ts +11 -0
- package/dist/runtime/components/LoginProviderButtons.client.d.vue.ts +15 -0
- package/dist/runtime/components/LoginProviderButtons.client.vue +66 -0
- package/dist/runtime/components/LoginProviderButtons.client.vue.d.ts +15 -0
- package/dist/runtime/components/Mocker.d.vue.ts +2 -0
- package/dist/runtime/components/Mocker.vue +39 -0
- package/dist/runtime/components/Mocker.vue.d.ts +2 -0
- package/dist/runtime/components/SessionStatus.d.vue.ts +35 -0
- package/dist/runtime/components/SessionStatus.vue +85 -0
- package/dist/runtime/components/SessionStatus.vue.d.ts +35 -0
- package/dist/runtime/components/UserRegistration.d.vue.ts +35 -0
- package/dist/runtime/components/UserRegistration.vue +158 -0
- package/dist/runtime/components/UserRegistration.vue.d.ts +35 -0
- package/dist/runtime/composables/useAuth.d.ts +27 -0
- package/dist/runtime/composables/useAuth.js +73 -0
- package/dist/runtime/core/providerStyles.d.ts +2 -0
- package/dist/runtime/core/providerStyles.js +6 -0
- package/dist/runtime/core/providers/github.d.ts +89 -0
- package/dist/runtime/core/providers/github.js +60 -0
- package/dist/runtime/core/providers/google.d.ts +70 -0
- package/dist/runtime/core/providers/google.js +54 -0
- package/dist/runtime/middleware/authGlobal.d.ts +2 -0
- package/dist/runtime/middleware/authGlobal.js +34 -0
- package/dist/runtime/middleware/authProtected.d.ts +2 -0
- package/dist/runtime/middleware/authProtected.js +38 -0
- package/dist/runtime/server/helpers/getSafeSecretsInfo.d.ts +4 -0
- package/dist/runtime/server/helpers/getSafeSecretsInfo.js +10 -0
- package/dist/runtime/server/helpers/logSafeRoute.d.ts +1 -0
- package/dist/runtime/server/helpers/logSafeRoute.js +3 -0
- package/dist/runtime/server/helpers/signJwt.d.ts +5 -0
- package/dist/runtime/server/helpers/signJwt.js +16 -0
- package/dist/runtime/server/helpers/verifyJwt.d.ts +5 -0
- package/dist/runtime/server/helpers/verifyJwt.js +19 -0
- package/dist/runtime/server/tsconfig.json +3 -0
- package/dist/runtime/server/utils/Auth.d.ts +83 -0
- package/dist/runtime/server/utils/Auth.js +653 -0
- package/dist/runtime/server/utils/SessionManager.d.ts +25 -0
- package/dist/runtime/server/utils/SessionManager.js +93 -0
- package/dist/runtime/server/utils/createAuthHandler.d.ts +8 -0
- package/dist/runtime/server/utils/createAuthHandler.js +29 -0
- package/dist/runtime/server/utils/createAuthMiddleware.d.ts +10 -0
- package/dist/runtime/server/utils/createAuthMiddleware.js +28 -0
- package/dist/runtime/server/utils/createAuthSchema.d.ts +244 -0
- package/dist/runtime/server/utils/createAuthSchema.js +43 -0
- package/dist/runtime/types.d.ts +239 -0
- package/dist/runtime/types.js +15 -0
- package/dist/runtime/utils/createExternalAuthHandler.d.ts +36 -0
- package/dist/runtime/utils/createExternalAuthHandler.js +25 -0
- package/dist/runtime/utils/decodeQueryUri.d.ts +2 -0
- package/dist/runtime/utils/decodeQueryUri.js +4 -0
- package/dist/runtime/utils/getAuthApiRoute.d.ts +3 -0
- package/dist/runtime/utils/getAuthApiRoute.js +14 -0
- package/dist/types.d.mts +13 -0
- package/package.json +101 -0
package/README.md
ADDED
|
@@ -0,0 +1,693 @@
|
|
|
1
|
+
# @witchcraft/nuxt-auth
|
|
2
|
+
|
|
3
|
+
[![npm version][npm-version-src]][npm-version-href]
|
|
4
|
+
[![npm downloads][npm-downloads-src]][npm-downloads-href]
|
|
5
|
+
[![License][license-src]][license-href]
|
|
6
|
+
[![Nuxt][nuxt-src]][nuxt-href]
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
VERY WIP wrapper module following the guide by [lucia auth](https://lucia-auth.com/) with postgres and drizzle db.
|
|
10
|
+
|
|
11
|
+
I am not an auth expert, **use at your own risk**. The module's auth code is not that long, read
|
|
12
|
+
[src/runtime/server/utils/SessionManager.ts](https://github.com/witchcraftjs/nuxt-auth/blob/master/src/runtime/server/utils/SessionManager.ts) (based on lucia) and
|
|
13
|
+
[`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.
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
## Playground
|
|
17
|
+
|
|
18
|
+
There is a playground but it must be run locally as it requires a postgres instance and env secrets to be set.
|
|
19
|
+
|
|
20
|
+
## Features
|
|
21
|
+
|
|
22
|
+
The following providers are included (using the `arctic` library), custom providers can be easily added.
|
|
23
|
+
|
|
24
|
+
- [Google](https://console.cloud.google.com/apis/credentials)
|
|
25
|
+
- [Github](https://github.com/settings/applications/new)
|
|
26
|
+
<!-- - [Facebook](https://developers.facebook.com/apps) -->
|
|
27
|
+
<!-- - [Twitter](https://developer.twitter.com/en/portal/dashboard) -->
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
## Install
|
|
31
|
+
|
|
32
|
+
It is highly recommended you install the nuxt-security module (or something similar) as this module does NOT add middleware to guard against CSRF.
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pnpx nuxi module add nuxt-security
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
The module requires the `@witchcraft/ui` module for ui components but is otherwise optional.
|
|
39
|
+
```bash
|
|
40
|
+
pnpx nuxi module add @witchcraft/ui
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
## Usage
|
|
45
|
+
|
|
46
|
+
### Secrets
|
|
47
|
+
|
|
48
|
+
The following env variables are needed:
|
|
49
|
+
|
|
50
|
+
- `AUTH_SECRET` // for nuxt-auth
|
|
51
|
+
- `AUTH_{PROVIDER}_CLIENT_ID`
|
|
52
|
+
- `AUTH_{PROVIDER}_CLIENT_SECRET`
|
|
53
|
+
|
|
54
|
+
Set the ones you need in the nuxt config. There is a helper function for doing this:
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
import { genAuthSecretKeys } from "@witchcraft/nuxt-auth/build/genAuthSecretKeys"
|
|
58
|
+
// nuxt.config.ts
|
|
59
|
+
export default defineNuxtConfig({
|
|
60
|
+
runtimeConfig: {
|
|
61
|
+
...genAuthSecretKeys(["google", "github"]),
|
|
62
|
+
// or manually
|
|
63
|
+
authGoogleClientSecret: "",
|
|
64
|
+
authGoogleClientId: "",
|
|
65
|
+
public: {
|
|
66
|
+
// this is set automatically (for production, it's always true, for dev it's true if nuxt.options.devServer.https is defined)
|
|
67
|
+
// this determines whether to use https in the auth callback url
|
|
68
|
+
// isSecure: ...
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
auth: {
|
|
72
|
+
allowedOrigins: [
|
|
73
|
+
...(process.env.NODE_ENV === "development" ? ["http://localhost:3000"] : []),
|
|
74
|
+
"https://your-app-site.com",
|
|
75
|
+
],
|
|
76
|
+
// see also allowedMiddlewareExclusions for external hosts
|
|
77
|
+
// that should only be allowed access for certain requests
|
|
78
|
+
}
|
|
79
|
+
})
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
The callback url is `{http/https}://localhost:3000/api/auth/callback/{PROVIDER}`.
|
|
83
|
+
Note that if using `https`, both the allowed origins and the callback url must have https in the provider's config.
|
|
84
|
+
|
|
85
|
+
### Basic Setup
|
|
86
|
+
|
|
87
|
+
#### DB
|
|
88
|
+
|
|
89
|
+
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:
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
// path/to/schema.ts
|
|
93
|
+
// careful not to use nuxt paths, or drizzle won't be able to import them when when generating migrations, etc
|
|
94
|
+
import { authUserFields, createAuthSchema } from "@witchcraft/nuxt-auth/server/utils/createAuthSchema"
|
|
95
|
+
export const users = pgTable("users", {
|
|
96
|
+
id: uuid("id").primaryKey().unique()
|
|
97
|
+
.notNull()
|
|
98
|
+
// ... rest of your table
|
|
99
|
+
...authUserFields
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
export const {
|
|
103
|
+
authAccounts,
|
|
104
|
+
authSessions,
|
|
105
|
+
authProvidersRelations,
|
|
106
|
+
authSessionRelations
|
|
107
|
+
} = createAuthSchema(users)
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
#### SessionManager and Routes
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
First configure your session manager instance with your db in some file (it can be anywhere) and export it.
|
|
114
|
+
|
|
115
|
+
Then create two files:
|
|
116
|
+
```
|
|
117
|
+
- server
|
|
118
|
+
- middleware
|
|
119
|
+
- auth.ts
|
|
120
|
+
- api
|
|
121
|
+
- auth
|
|
122
|
+
// this is named like this literally, it is a catch-all route
|
|
123
|
+
- [...].get.ts
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
This creates the api handler.
|
|
127
|
+
```ts [server/api/auth/[...].ts]
|
|
128
|
+
|
|
129
|
+
import { createAuthHandler } from "#imports"
|
|
130
|
+
import { authAccounts, users } from "~~/db/schema.js"
|
|
131
|
+
import { db } from "[PATH TO YOUR DRIZZLE DB]"
|
|
132
|
+
import { sessionManager } from "[PATH TO YOUR SESSION MANAGER INSTANCE]"
|
|
133
|
+
|
|
134
|
+
export default createAuthHandler(
|
|
135
|
+
useRuntimeConfig(),
|
|
136
|
+
db,
|
|
137
|
+
users,
|
|
138
|
+
authAccounts,
|
|
139
|
+
sessionManager, {
|
|
140
|
+
onRegister: (event, route, deeplink) => {
|
|
141
|
+
// handle user registration, deeplink is for when using external auth handlers (see below)
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
)
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
This creates the middleware that sets the user/session on the request context.
|
|
148
|
+
|
|
149
|
+
**IMPORTANT: The middleware by itself DOES NOT validate the origin and does not have any CSRF protection. The nuxt-security is installed by the module to handle this. DO NOT disable it.**
|
|
150
|
+
|
|
151
|
+
```ts
|
|
152
|
+
// server/middleware/auth.ts
|
|
153
|
+
|
|
154
|
+
import { createAuthMiddleware } from "#imports"
|
|
155
|
+
|
|
156
|
+
import { sessionManager } from "[PATH TO YOUR SESSION MANAGER INSTANCE]"
|
|
157
|
+
export default createAuthMiddleware(sessionManager)
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
### Create the Pages
|
|
161
|
+
|
|
162
|
+
See the playground for a full example, but you will need to create the following pages, components are provided to help create these:
|
|
163
|
+
|
|
164
|
+
- `/login`
|
|
165
|
+
- `/register`
|
|
166
|
+
- `/code` (optional, only if using external auth handlers)
|
|
167
|
+
|
|
168
|
+
### Customizing Login Handling
|
|
169
|
+
|
|
170
|
+
By default the module will redirect to corresponding api route when calling `useAuth().login/logout()`.
|
|
171
|
+
|
|
172
|
+
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.
|
|
173
|
+
|
|
174
|
+
This can be customized with the `handleActions` option on the `useAuth` composable.
|
|
175
|
+
|
|
176
|
+
There is also a `createExternalAuthHandler` helper and related utils, see [External Auth Handlers](#external-auth-handlers).
|
|
177
|
+
|
|
178
|
+
### Changing Routes
|
|
179
|
+
|
|
180
|
+
While not recommended, you can change the routes used by the module by setting the `authApiRoutes` and `authRoutes` options. In the case of the api routes, you will probably want to access them using the getAuthApiRoute helper:
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
getAuthApiRoute(useRuntimeConfig().public, "usersInfo")
|
|
184
|
+
getAuthApiRoute(useRuntimeConfig().public, "usersIdAccounts", id)
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
#### Middleware
|
|
188
|
+
|
|
189
|
+
### Auth Middleware
|
|
190
|
+
|
|
191
|
+
A global middleware is registered by default to determine the user's logged in state (by fetching `/api/auth/users/info`).
|
|
192
|
+
|
|
193
|
+
This 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.
|
|
194
|
+
|
|
195
|
+
You can use `useAuth().setFetchUserOnNavigation(...)` to allow fetch on the next navigation. The middleware then disables fetching again to prevent further fetching.
|
|
196
|
+
|
|
197
|
+
The useState keys used to make this work are `auth:_fetch` and `auth:user` if you want to inspect them in the dev tools.
|
|
198
|
+
|
|
199
|
+
You can also fetch from the api manually if you want and set `auth:user` yourself or do it some other way.
|
|
200
|
+
|
|
201
|
+
\* The AuthUserRegistration component automatically does this, if you don't use it, you'll need to do it after a succesful registration, but before navigating away.
|
|
202
|
+
|
|
203
|
+
### Route Protection
|
|
204
|
+
|
|
205
|
+
The module does not register a global middleware for route protection by default (see `useGlobalMiddleware`). It must be set:
|
|
206
|
+
|
|
207
|
+
```ts
|
|
208
|
+
definePageMeta({ middleware: "authProtected" })
|
|
209
|
+
|
|
210
|
+
This will automatically redirect unauthenticated users to the login page and unregistered users to the register page.
|
|
211
|
+
|
|
212
|
+
Additionally you can set the following meta properties to control the middleware:
|
|
213
|
+
|
|
214
|
+
```ts
|
|
215
|
+
definePageMeta({
|
|
216
|
+
middleware: "authProtected",
|
|
217
|
+
auth: {
|
|
218
|
+
// only allow users on the page that match the given condition.
|
|
219
|
+
only: "authenticated" /* | "registered" | "authenticated-unregistered" | "unauthenticated" */
|
|
220
|
+
|
|
221
|
+
// change the redirect path
|
|
222
|
+
// or can use the special values "$login", "$register", "$postRegisteredLogin"
|
|
223
|
+
redirectTo: "/some/path",
|
|
224
|
+
}
|
|
225
|
+
})
|
|
226
|
+
```
|
|
227
|
+
You can register additional paths with the `additionalMiddlewarePaths` option.
|
|
228
|
+
|
|
229
|
+
### Clearing User Data on Logout
|
|
230
|
+
|
|
231
|
+
You can add a `beforeLogout` listener to clear the user data on logout by using `useAuth().on/off`. All added listeners are awaited before actually logging out.
|
|
232
|
+
|
|
233
|
+
```ts
|
|
234
|
+
useAuth().on("beforeLogout", clearUserData)
|
|
235
|
+
```
|
|
236
|
+
### Branding
|
|
237
|
+
|
|
238
|
+
The module does not create any pages by default.
|
|
239
|
+
|
|
240
|
+
Only components like `AuthLoginProviderButtons` are provided. It's button styles and logos can be customized/extended by setting the `providerStyles` prop on the component.
|
|
241
|
+
|
|
242
|
+
### Other Exports
|
|
243
|
+
|
|
244
|
+
#### Components
|
|
245
|
+
|
|
246
|
+
`AuthSessionStatus` - Provided for creating a login button / status indificator in the nav bar.
|
|
247
|
+
`AuthLoginProviderButtons` - Provided for creating login the buttons.
|
|
248
|
+
`AuthUserRegistration` - Provided for creating a simple registration form with a username input and check.
|
|
249
|
+
- This requires an api route (customizable, see props) that can validate the username (`/api/auth/public/users/:username/valid` by defualt).
|
|
250
|
+
- And it submits (customizable) to an undefined register route (`/api/auth/register` by default) with `body: { username }`.
|
|
251
|
+
- It has a slot for easily adding more fields.
|
|
252
|
+
`AuthExternalCallback` - Provided for creating a callback page for external auth handlers, see [External Auth Handlers](#external-auth-handlers).
|
|
253
|
+
|
|
254
|
+
#### Composables
|
|
255
|
+
|
|
256
|
+
`useAuth` - For getting user info, status, login in and out, and getting routes.
|
|
257
|
+
|
|
258
|
+
#### Types
|
|
259
|
+
|
|
260
|
+
`zodUsernameSchema` - A zod schema for validating usernames. While the module does not make use of it, it's nice have on hand for writing the username validation route.
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
### Database Schema / Customizing Account Data
|
|
264
|
+
|
|
265
|
+
The auth schema creates the session table `authSesssions` table and an `authAccounts` table which describes the user's linked provider accounts and contains any saved information from the provider.
|
|
266
|
+
|
|
267
|
+
What additional information (e.g. `avatarUrl`) is saved when a user logs in with a provider for the first time can be customized when creating the api handler (see `AuthOptions`). It is saved to a single jsonb column `info`.
|
|
268
|
+
|
|
269
|
+
Usually this is only needed pre-registration (e.g. to suggest a username) and can then be deleted. There is also an option, `onlySaveUnregisteredUserAccountInfo` which will only save this additional information if the user is unregistered.
|
|
270
|
+
|
|
271
|
+
You can type this information by extending the `Register` interface:
|
|
272
|
+
|
|
273
|
+
```ts
|
|
274
|
+
declare module "@witchcraft/nuxt-auth" {
|
|
275
|
+
interface Register {
|
|
276
|
+
AdditionalAccountInfo: {
|
|
277
|
+
avatarUrl: string
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
### Custom Providers
|
|
284
|
+
|
|
285
|
+
Custom providers can be added when configuring the handler.
|
|
286
|
+
|
|
287
|
+
You must extend the `Register` interface with the correct types for your provider:
|
|
288
|
+
```ts
|
|
289
|
+
declare module "@witchcraft/nuxt-auth" {
|
|
290
|
+
interface Register {
|
|
291
|
+
AdditionalProviders: {
|
|
292
|
+
customProvider: {
|
|
293
|
+
id: string
|
|
294
|
+
// ...info as returned by the provider's api
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
Then create a class that implements `ProviderHandler<type, PROVIDER_NAME>` which really only needs to tell the module what the url is (and any pcke code verifiers) and how to get the user info.
|
|
303
|
+
|
|
304
|
+
See the included providers for examples. They're quite simple to write with the help of the `arctic` library.
|
|
305
|
+
|
|
306
|
+
```ts
|
|
307
|
+
export default createAuthHandler(useRuntimeConfig(), db, users, authAccounts, sessionManager, {
|
|
308
|
+
customProviders: {
|
|
309
|
+
name: class CustomProvider implements ProviderHandler<"oauth2", "customProvider"> {
|
|
310
|
+
//...
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
})
|
|
314
|
+
```
|
|
315
|
+
### Extending the Router
|
|
316
|
+
|
|
317
|
+
You can extend the router at `/api/auth` with the `extendRouter` option when creating the handler.
|
|
318
|
+
|
|
319
|
+
This is useful for adding custom endpoints like `/api/auth/public/users/:username/valid`.
|
|
320
|
+
|
|
321
|
+
### Auth Flow
|
|
322
|
+
|
|
323
|
+
The full auth flow is as follows:
|
|
324
|
+
|
|
325
|
+
```mermaid
|
|
326
|
+
sequenceDiagram
|
|
327
|
+
participant User
|
|
328
|
+
participant Browser
|
|
329
|
+
participant Nuxt Server
|
|
330
|
+
participant OAuth Provider
|
|
331
|
+
participant Electron App
|
|
332
|
+
|
|
333
|
+
User->>Browser: Clicks login button
|
|
334
|
+
|
|
335
|
+
alt Normal Web Auth
|
|
336
|
+
Browser->>Nuxt Server: GET /api/auth/login/{provider}
|
|
337
|
+
Nuxt Server->>Browser: Redirect to OAuth Provider
|
|
338
|
+
Browser->>OAuth Provider: User authenticates
|
|
339
|
+
OAuth Provider->>Browser: Redirect to /api/auth/callback/{provider}
|
|
340
|
+
Browser->>Nuxt Server: GET /api/auth/callback/{provider}
|
|
341
|
+
Nuxt Server->>Nuxt Server: Creates User & Session
|
|
342
|
+
|
|
343
|
+
alt New User Registration
|
|
344
|
+
Nuxt Server->>Browser: Redirect to /register
|
|
345
|
+
User->>Browser: Fills out username
|
|
346
|
+
Browser->>Nuxt Server: POST /api/auth/register (with username)
|
|
347
|
+
Nuxt Server->>Nuxt Server: Updates user with username
|
|
348
|
+
Nuxt Server->>Browser: Sets session token as cookie
|
|
349
|
+
else Existing User
|
|
350
|
+
Nuxt Server->>Browser: Sets session token as cookie
|
|
351
|
+
end
|
|
352
|
+
|
|
353
|
+
else External Auth (Electron)
|
|
354
|
+
User->>Electron App: Clicks login button in Electron
|
|
355
|
+
rect rgba(255, 0, 0, 0.1)
|
|
356
|
+
Electron App->>Browser: Opens /api/auth/login/{provider}?deeplink=electron
|
|
357
|
+
Browser->>Nuxt Server: GET /api/auth/login/{provider}?deeplink=electron
|
|
358
|
+
Nuxt Server->>Browser: Redirect to OAuth Provider (with deeplink in state)
|
|
359
|
+
Browser->>OAuth Provider: User authenticates
|
|
360
|
+
OAuth Provider->>Browser: Redirect to /api/auth/callback/{provider}
|
|
361
|
+
Browser->>Nuxt Server: GET /api/auth/callback/{provider}
|
|
362
|
+
Nuxt Server->>Nuxt Server: Decodes state, retrieves "deeplink" option
|
|
363
|
+
Nuxt Server->>Nuxt Server: Creates User & Session
|
|
364
|
+
end
|
|
365
|
+
|
|
366
|
+
rect rgba(255, 255, 0, 0.1)
|
|
367
|
+
Nuxt Server->>Browser: Redirect to /auth/code with short-lived access token
|
|
368
|
+
Browser->>User: Displays short-lived access token, attempts to directly open electron app with it.
|
|
369
|
+
User->>Electron App: Pastes short-lived access token (if app doesn't open)
|
|
370
|
+
Electron App->>Nuxt Server: GET /api/auth/external/exchange with short-lived access token
|
|
371
|
+
end
|
|
372
|
+
Nuxt Server->>Electron App: Returns session token
|
|
373
|
+
Electron App->>Electron App: Saves session token, sets it as a cookie on the window session
|
|
374
|
+
end
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
### External Auth Handlers
|
|
378
|
+
|
|
379
|
+
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.
|
|
380
|
+
|
|
381
|
+
For example, using electron:
|
|
382
|
+
|
|
383
|
+
If using nuxt-electron, you will need to tell it to include the `auth/external/callback` route and the `auth/login` route using the `additionalRoutes` option.
|
|
384
|
+
|
|
385
|
+
Then add a custom `redirectTo` function when using the `authProtected` middleware that always redirects any pages that aren't included in the build that only registered users should have access to, to `$login` since they won't exist. This is because we want all that flow to happen on the browser and only redirect back at the end.
|
|
386
|
+
|
|
387
|
+
```vue [pages/auth/(app|register).vue]
|
|
388
|
+
<script setup lang="ts">
|
|
389
|
+
definePageMeta({
|
|
390
|
+
middleware: ["authProtected"],
|
|
391
|
+
auth: {
|
|
392
|
+
only: "authenticated-registered",
|
|
393
|
+
redirectTo: () => isElectron() ? "$login" : undefined,
|
|
394
|
+
}
|
|
395
|
+
})
|
|
396
|
+
</script>
|
|
397
|
+
|
|
398
|
+
```
|
|
399
|
+
|
|
400
|
+
Then in the login page, we can use the `createExternalAuthHandler` to intercept the action of the `LoginProviderButtons` only when the user is on electron.
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
```vue [pages/auth/login.vue]
|
|
404
|
+
<template>
|
|
405
|
+
<AuthLoginProviderButtons :use-auth-options="{handleActions}"/>
|
|
406
|
+
</template>
|
|
407
|
+
<script setup lang="ts">
|
|
408
|
+
import { isElectron } from "#imports"
|
|
409
|
+
import { useRuntimeConfig } from "#app"
|
|
410
|
+
|
|
411
|
+
const rc = useRuntimeConfig()
|
|
412
|
+
|
|
413
|
+
const handleActions: ActionHandler = (action, url) =>
|
|
414
|
+
createExternalAuthHandler(
|
|
415
|
+
"electron", // for the query param
|
|
416
|
+
isElectron, // platform check
|
|
417
|
+
publicServerUrl, // you must define this somehow
|
|
418
|
+
window?.electron?.api.open,
|
|
419
|
+
"auth/code", // the default
|
|
420
|
+
)(action, url)
|
|
421
|
+
|| createExternalAuthHandler(...) // they can be chained
|
|
422
|
+
|
|
423
|
+
</script>
|
|
424
|
+
```
|
|
425
|
+
|
|
426
|
+
This will make a click on a login button on electron redirect to the `auth/external/callback` on electron, and open the browser to the wanted action, appending the query param, `deeplink=electron`.
|
|
427
|
+
|
|
428
|
+
`auth/external/callback` can be dual purpose. If no accessToken is given to it, it can show a link to open the external browser in case it didn't, otherwise it can try to exchange the accessToken for a full sessionToken.
|
|
429
|
+
|
|
430
|
+
You can use the `AuthExternalCallback` component to handle this.
|
|
431
|
+
|
|
432
|
+
```vue
|
|
433
|
+
<template>
|
|
434
|
+
<AuthExternalCallback
|
|
435
|
+
:save-session="saveSession"
|
|
436
|
+
/>
|
|
437
|
+
</template>
|
|
438
|
+
<script lang="ts" setup>
|
|
439
|
+
|
|
440
|
+
const rc = useRuntimeConfig()
|
|
441
|
+
async function saveSession(token: string) {
|
|
442
|
+
// you would need to define an api similar to this in electron's preload script
|
|
443
|
+
// @witchcraft/nuxt-electron provides utilities for helping to create
|
|
444
|
+
// async functions like these which are normally a pain
|
|
445
|
+
await window.electron.api.auth.saveSession(
|
|
446
|
+
rc.public.auth.authRoutes.postRegisteredLogin,
|
|
447
|
+
token
|
|
448
|
+
)
|
|
449
|
+
}
|
|
450
|
+
</script>
|
|
451
|
+
```
|
|
452
|
+
|
|
453
|
+
This query param will be forwarded throughout (see the red area).
|
|
454
|
+
|
|
455
|
+
For the login action, the app will open `/api/auth/login/{provider}?deeplink=electron` which will open the provider page, saving the deeplink query param in the state passed to it.
|
|
456
|
+
|
|
457
|
+
When it redirects to the callback, we decode this state, accesing the `deeplink` query param again.
|
|
458
|
+
|
|
459
|
+
At this point, if the user is registered, we can redirect them to `auth/code` with a short lived access token and the deeplinkUri the page can show in case they click cancel on the prompt. The short lived token should be shown for them to copy if opening the link doesn't work.
|
|
460
|
+
|
|
461
|
+
A component, `AuthExternalCode` is provided for this purpose.
|
|
462
|
+
|
|
463
|
+
```vue [pages/auth/code.vue]
|
|
464
|
+
<template>
|
|
465
|
+
<AuthExternalCode/>
|
|
466
|
+
</template>
|
|
467
|
+
```
|
|
468
|
+
|
|
469
|
+
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.
|
|
470
|
+
|
|
471
|
+
Paths that contain the access token are in the yellow area.
|
|
472
|
+
|
|
473
|
+
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.
|
|
474
|
+
|
|
475
|
+
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:
|
|
476
|
+
|
|
477
|
+
```ts
|
|
478
|
+
const sessionToken = await fetch(`${this.publicServerUrl}${getAuthApiRoute(useRuntimeConfig().public, "externalExchange")}`, {
|
|
479
|
+
method: "GET",
|
|
480
|
+
headers: {
|
|
481
|
+
Authorization: `Bearer ${accessToken}`,
|
|
482
|
+
}
|
|
483
|
+
}).then(async res => res.text())
|
|
484
|
+
.catch(err => err)
|
|
485
|
+
if (sessionToken instanceof Error) {
|
|
486
|
+
...
|
|
487
|
+
}
|
|
488
|
+
// valid sessionToken
|
|
489
|
+
```
|
|
490
|
+
|
|
491
|
+
Then set a cookie (for the server's url) and force the page to reload so the middleware can redirect the user.
|
|
492
|
+
|
|
493
|
+
Why not just pass the token directly? Well we'd have to expose it somewhere (usually this is done via a query param which is not very safe) and while redirecting from the server to the deeplink url is safer (it's not kept in browser history) there is no fallback for if that doesn't work (the tab is immediately closed).
|
|
494
|
+
|
|
495
|
+
This way, only a short lived token is exposed. The app can then safely exchange it for a very long lived one if we want.
|
|
496
|
+
|
|
497
|
+
# Semi-Auth
|
|
498
|
+
|
|
499
|
+
In desktop apps (but this can apply online) 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.
|
|
500
|
+
|
|
501
|
+
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.
|
|
502
|
+
|
|
503
|
+
This is safe because **you should always check authentication on the server side, if you're not that's inherently unsafe**.
|
|
504
|
+
|
|
505
|
+
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.
|
|
506
|
+
|
|
507
|
+
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}`.
|
|
508
|
+
|
|
509
|
+
If using this feature, you will probably want to set a custom condition on the login page to allow semi-authed users on it:
|
|
510
|
+
```ts
|
|
511
|
+
definePageMeta({
|
|
512
|
+
only: ({ isAuthenticated, isSemiAuthed }:ReturnType<typeof useAuth>) => !isAuthenticated.value || isSemiAuthed.value
|
|
513
|
+
})
|
|
514
|
+
```
|
|
515
|
+
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.
|
|
516
|
+
|
|
517
|
+
For example:
|
|
518
|
+
```ts [app/app.vue]
|
|
519
|
+
if (isElectron()) {
|
|
520
|
+
// you would have to define this in the preload script
|
|
521
|
+
if (window.electron?.meta.cookiesValid) {
|
|
522
|
+
useAuth().isSemiAuthed.value = false
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
```
|
|
526
|
+
|
|
527
|
+
# Mocking Auth (experimental)
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
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.
|
|
531
|
+
|
|
532
|
+
`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.
|
|
533
|
+
|
|
534
|
+
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:
|
|
535
|
+
|
|
536
|
+
```vue
|
|
537
|
+
<AuthLoginProviderButtons :use-auth-options="{ handleActions }" :login-options="{ devBypass }" />
|
|
538
|
+
```
|
|
539
|
+
|
|
540
|
+
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.
|
|
541
|
+
|
|
542
|
+
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.
|
|
543
|
+
|
|
544
|
+
The server by default will mock the getting of the user's info from the provider and return the following:
|
|
545
|
+
```ts
|
|
546
|
+
{
|
|
547
|
+
provider,
|
|
548
|
+
providerId: `dev-${provider}-${username}`,
|
|
549
|
+
email: `dev-${provider}-${username}@dev.com`,
|
|
550
|
+
isVerified: true,
|
|
551
|
+
name: `Dev ${username}`,
|
|
552
|
+
info: null
|
|
553
|
+
}
|
|
554
|
+
```
|
|
555
|
+
If no username is passed either, but an id is passed instead (e.g. for testing unregistered users), the username will be `username-${id}`.
|
|
556
|
+
|
|
557
|
+
You can change this by specifying a custom `createMockUser` function when creating the auth handler.
|
|
558
|
+
|
|
559
|
+
If the user does not exist, it will be created using this information.
|
|
560
|
+
|
|
561
|
+
To simulate existing users with the default function you can use `Auth.defaultCreateMockUser` to get the info when seeding your database.
|
|
562
|
+
|
|
563
|
+
The server will then bypass auth and create a session for the user.
|
|
564
|
+
|
|
565
|
+
## Testing the Server APIs directly with Mock Users
|
|
566
|
+
|
|
567
|
+
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):
|
|
568
|
+
|
|
569
|
+
Create a utility function somewhere:
|
|
570
|
+
|
|
571
|
+
```ts [tests/utils/fetch.ts]
|
|
572
|
+
import makeFetchCookie from "fetch-cookie"
|
|
573
|
+
import type { FetchOptions } from "ofetch"
|
|
574
|
+
import { $fetch as $ofetch } from "ofetch"
|
|
575
|
+
import { useTestContext } from "@nuxt/test-utils/e2e"
|
|
576
|
+
import { joinURL } from "ufo"
|
|
577
|
+
import {
|
|
578
|
+
parse,
|
|
579
|
+
serialize
|
|
580
|
+
} from "cookie-es"
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
// copied from nuxt/test-utils
|
|
584
|
+
function getUrl(path: string) {
|
|
585
|
+
const ctx = useTestContext()
|
|
586
|
+
if (!ctx.url) {
|
|
587
|
+
throw new Error("url is not available (is server option enabled?)")
|
|
588
|
+
}
|
|
589
|
+
if (path.startsWith(ctx.url)) {
|
|
590
|
+
return path
|
|
591
|
+
}
|
|
592
|
+
return joinURL(ctx.url, path)
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
const fetchWithCookies = makeFetchCookie($ofetch.native)
|
|
596
|
+
const oFetchWithCookies = $ofetch.create({ }, { fetch: fetchWithCookies })
|
|
597
|
+
export function $fetch(url: string, options?: Omit<FetchOptions, "url">) {
|
|
598
|
+
return oFetchWithCookies(getUrl(url), options)
|
|
599
|
+
}
|
|
600
|
+
export const cookieJar = fetchWithCookies.cookieJar
|
|
601
|
+
|
|
602
|
+
export function get$fetchCookies() {
|
|
603
|
+
return fetchWithCookies.cookieJar.getCookieString(getUrl(""))
|
|
604
|
+
}
|
|
605
|
+
export function set$fetchCookies(cookies: string) {
|
|
606
|
+
return fetchWithCookies.cookieJar.setCookie(cookies, getUrl(""), { ignoreError: false })
|
|
607
|
+
}
|
|
608
|
+
export async function clear$fetchCookies() {
|
|
609
|
+
await set$fetchCookies(serialize("test", "test"))
|
|
610
|
+
const setCookies = await cookieJar.getCookieString(getUrl(""))
|
|
611
|
+
const parsedCookies = parse(setCookies)
|
|
612
|
+
await Promise.all(Object.keys(parsedCookies).map(async (cookie) => {
|
|
613
|
+
await fetchWithCookies.cookieJar.setCookie(serialize(cookie, "", { maxAge: 0 }), getUrl(""), { ignoreError: false })
|
|
614
|
+
}))
|
|
615
|
+
}
|
|
616
|
+
export function use$fetchOriginHeader() {
|
|
617
|
+
return {
|
|
618
|
+
Origin: getUrl("/")
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
```
|
|
622
|
+
|
|
623
|
+
Use in tests like this:
|
|
624
|
+
```ts [tests/sometest.e2e.test.ts]
|
|
625
|
+
import {
|
|
626
|
+
$fetch,
|
|
627
|
+
get$fetchCookies,
|
|
628
|
+
clear$fetchCookies
|
|
629
|
+
} from "~~/tests/utils/fetch.js"
|
|
630
|
+
|
|
631
|
+
describe("server/db/users", async () => {
|
|
632
|
+
beforeAll(async () => {
|
|
633
|
+
await setup({
|
|
634
|
+
...
|
|
635
|
+
// I prefer to run a local instance separate from vitest
|
|
636
|
+
// otherwise nuxt is built with every test which is very slow
|
|
637
|
+
// see https://github.com/nuxt/test-utils/issues/314
|
|
638
|
+
// host: "https://localhost:3000",
|
|
639
|
+
// port: 3000
|
|
640
|
+
})
|
|
641
|
+
})
|
|
642
|
+
beforeEach(async () => {
|
|
643
|
+
await clear$fetchCookies()
|
|
644
|
+
})
|
|
645
|
+
test("bypassed login", async () => {
|
|
646
|
+
await $fetch("/api/auth/callback/google", {
|
|
647
|
+
method: "GET",
|
|
648
|
+
query: {
|
|
649
|
+
username: "test",
|
|
650
|
+
devBypass: true,
|
|
651
|
+
devBypassRegistration: true,
|
|
652
|
+
},
|
|
653
|
+
credentials: "include",
|
|
654
|
+
})
|
|
655
|
+
console.log(await get$fetchCookies())
|
|
656
|
+
const userInfo = await $fetch("/api/auth/users/info", {
|
|
657
|
+
method: "GET",
|
|
658
|
+
credentials: "include",
|
|
659
|
+
})
|
|
660
|
+
expect(userInfo.username).toBe("test")
|
|
661
|
+
expect(userInfo.isRegistered).toBe(true)
|
|
662
|
+
console.log({userInfo})
|
|
663
|
+
})
|
|
664
|
+
test("cookies cleared", async () => {
|
|
665
|
+
expect(await get$fetchCookies()).toBe("")
|
|
666
|
+
})
|
|
667
|
+
})
|
|
668
|
+
```
|
|
669
|
+
|
|
670
|
+
Note that you will need to add the origin header to non-GET requests since nuxt-security guards in part against CRSF by checking the origin header:
|
|
671
|
+
```ts
|
|
672
|
+
test("put works", async () => {
|
|
673
|
+
await $fetch(`/api/some/api`, {
|
|
674
|
+
method: "PUT",
|
|
675
|
+
credentials: "include",
|
|
676
|
+
headers: use$fetchOriginHeader()
|
|
677
|
+
})
|
|
678
|
+
})
|
|
679
|
+
```
|
|
680
|
+
|
|
681
|
+
|
|
682
|
+
<!-- Badges -->
|
|
683
|
+
[npm-version-src]: https://img.shields.io/npm/v/@witchcraft/nuxt-auth/latest.svg?style=flat&colorA=020420&colorB=00DC82
|
|
684
|
+
[npm-version-href]: https://npmjs.com/package/@witchcraft/nuxt-auth
|
|
685
|
+
|
|
686
|
+
[npm-downloads-src]: https://img.shields.io/npm/dm/@witchcraft/nuxt-auth.svg?style=flat&colorA=020420&colorB=00DC82
|
|
687
|
+
[npm-downloads-href]: https://npmjs.com/package/@witchcraft/nuxt-auth
|
|
688
|
+
|
|
689
|
+
[license-src]: https://img.shields.io/npm/l/@witchcraft/nuxt-auth.svg?style=flat&colorA=020420&colorB=00DC82
|
|
690
|
+
[license-href]: https://npmjs.com/package/@witchcraft/nuxt-auth
|
|
691
|
+
|
|
692
|
+
[nuxt-src]: https://img.shields.io/badge/Nuxt-020420?logo=nuxt.js
|
|
693
|
+
[nuxt-href]: https://nuxt.com
|