@witchcraft/nuxt-auth 0.1.9 → 0.2.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 CHANGED
@@ -187,7 +187,7 @@ In some cases you may want to customize this behavior, such as when calling this
187
187
 
188
188
  This can be customized with the `handleActions` option on the `useAuth` composable.
189
189
 
190
- There is also a `createExternalAuthHandler` helper and related utils, see [External Auth Handlers](#external-auth-handlers).
190
+ There is also a `createExternalAuthLoginHandler` helper and related utils, see [External Auth Handlers](#external-auth-handlers).
191
191
 
192
192
  ### Changing Routes
193
193
 
@@ -411,7 +411,7 @@ definePageMeta({
411
411
 
412
412
  ```
413
413
 
414
- Then in the login page, we can use the `createExternalAuthHandler` to intercept the action of the `LoginProviderButtons` only when the user is on electron.
414
+ Then in the login page, we can use the `createExternalAuthLoginHandler` to intercept the action of the `LoginProviderButtons` only when the user is on electron.
415
415
 
416
416
 
417
417
  ```vue [pages/auth/login.vue]
@@ -425,14 +425,14 @@ import { useRuntimeConfig } from "#app"
425
425
  const rc = useRuntimeConfig()
426
426
 
427
427
  const handleActions: ActionHandler = (action, url) =>
428
- createExternalAuthHandler(
428
+ createExternalAuthLoginHandler(
429
429
  "electron", // for the query param
430
430
  isElectron, // platform check
431
431
  publicServerUrl, // you must define this somehow
432
432
  window?.electron?.api.open,
433
433
  "auth/code", // the default
434
434
  )(action, url)
435
- || createExternalAuthHandler(...) // they can be chained
435
+ || createExternalAuthLoginHandler(...) // they can be chained
436
436
 
437
437
  </script>
438
438
  ```
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "auth",
3
3
  "configKey": "auth",
4
- "version": "0.1.9",
4
+ "version": "0.2.1",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.2",
7
7
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -109,7 +109,7 @@ const module = defineNuxtModule({
109
109
  "runtime/utils/getAuthApiRoute",
110
110
  "runtime/core/providers/google",
111
111
  "runtime/core/providers/github",
112
- "runtime/utils/createExternalAuthHandler"
112
+ "runtime/utils/createExternalAuthLoginHandler"
113
113
  ]) {
114
114
  nuxt.options.build.transpile.push(resolve(file));
115
115
  }
@@ -1,10 +1,10 @@
1
- import type { ProviderNames, UseAuthComposableOptions } from "../types.js";
1
+ import type { AuthUser, ProviderNames, UseAuthComposableOptions } from "../types.js";
2
2
  type AuthListenerHook = () => void;
3
3
  type AuthListenerHooks = "beforeLogout";
4
4
  export declare const useAuth: ({ handleActions }?: UseAuthComposableOptions) => {
5
5
  on: (hook: AuthListenerHooks, listener: AuthListenerHook) => Promise<void>;
6
6
  off: (hook: AuthListenerHooks, listener: AuthListenerHook) => Promise<void>;
7
- user: import("vue").Ref<import("../types.js").AuthUserFields | null, import("../types.js").AuthUserFields | null>;
7
+ user: import("vue").Ref<AuthUser | null, AuthUser | null>;
8
8
  setFetchUserOnNavigation: (value?: boolean) => void;
9
9
  login: (provider: ProviderNames, { devBypass }?: {
10
10
  /** Send the request with the devBypass query param (This will only actually bypass auth if the server permits it). */
@@ -28,8 +28,7 @@ export const useAuth = ({ handleActions } = {}) => {
28
28
  setFetchUserOnNavigation();
29
29
  const loginRoute = getAuthApiRoute(useRuntimeConfig().public, "login", { provider: provider.toLowerCase() }, { devBypass });
30
30
  const external = provider ? true : void 0;
31
- let handled = handleActions?.("login", loginRoute, provider);
32
- if (handled instanceof Promise) handled = await handled;
31
+ const handled = handleActions?.("login", loginRoute, provider);
33
32
  if (!handled) {
34
33
  await navigateTo(loginRoute, { external });
35
34
  }
@@ -2,6 +2,7 @@ import type { BaseLogger } from "@witchcraft/nuxt-logger/shared/createUseLogger"
2
2
  import { type OAuth2RequestError, type OAuth2Tokens } from "arctic";
3
3
  import type { CookieSerializeOptions } from "cookie-es";
4
4
  import type { PgDatabase } from "drizzle-orm/pg-core";
5
+ import type { PgliteDatabase } from "drizzle-orm/pglite";
5
6
  import type { EventHandler, H3Event, Router } from "h3";
6
7
  import type { JwtPayload } from "jsonwebtoken";
7
8
  import type { RuntimeConfig } from "nuxt/schema";
@@ -37,7 +38,7 @@ export declare class Auth {
37
38
  createMockUser: AuthOptions["createMockUser"];
38
39
  generateUser: AuthOptions["generateUser"];
39
40
  static defaultCreateMockUser(_username: string | undefined, id: string | undefined, provider: string): Omit<BaseProviderAccountInfo, "userId">;
40
- db: PgDatabase<any, any, any>;
41
+ db: PgDatabase<any, any, any> | PgliteDatabase<any>;
41
42
  usersTable: UserTable;
42
43
  authAccountsTable: AuthAccountsTable;
43
44
  sessionManager: SessionManager;
@@ -1,5 +1,6 @@
1
1
  import type { DeepPartial } from "@alanscodelog/utils";
2
2
  import type { PgDatabase } from "drizzle-orm/pg-core";
3
+ import type { PgliteDatabase } from "drizzle-orm/pglite";
3
4
  import type { RuntimeConfig } from "nuxt/schema";
4
5
  import type { AuthSessionsTable, AuthUsersTable } from "./createAuthSchema.js";
5
6
  import type { AuthSession, SessionCookie, SessionCookieOptions, SessionValidationResult } from "../../types.js";
@@ -12,7 +13,7 @@ export declare class SessionManager {
12
13
  attributes: Omit<SessionCookieOptions, "maxAge">;
13
14
  };
14
15
  };
15
- db: PgDatabase<any, any, any>;
16
+ db: PgDatabase<any, any, any> | PgliteDatabase<any>;
16
17
  sessionTable: AuthSessionsTable;
17
18
  userTable: AuthUsersTable;
18
19
  constructor(rc: RuntimeConfig, db: SessionManager["db"], sessionTable: SessionManager["sessionTable"], userTable: SessionManager["userTable"], options?: DeepPartial<SessionManager["options"]>);
@@ -1,8 +1,9 @@
1
1
  import type { BaseLogger } from "@witchcraft/nuxt-logger/shared/createUseLogger";
2
2
  import type { PgDatabase } from "drizzle-orm/pg-core";
3
+ import type { PgliteDatabase } from "drizzle-orm/pglite";
3
4
  import type { EventHandler } from "h3";
4
5
  import type { RuntimeConfig } from "nuxt/schema";
5
6
  import type { AuthAccountsTable, UserTable } from "./createAuthSchema.js";
6
7
  import type { SessionManager } from "./SessionManager.js";
7
8
  import type { AuthHandlerOptions } from "../../types.js";
8
- export declare function createAuthHandler(rc: RuntimeConfig, db: PgDatabase<any, any, any>, usersTable: UserTable, authAccountsTable: AuthAccountsTable, sessionManager: SessionManager, logger: BaseLogger, opts?: Partial<AuthHandlerOptions>): EventHandler;
9
+ export declare function createAuthHandler(rc: RuntimeConfig, db: PgDatabase<any, any, any> | PgliteDatabase<any>, usersTable: UserTable, authAccountsTable: AuthAccountsTable, sessionManager: SessionManager, logger: BaseLogger, opts?: Partial<AuthHandlerOptions>): EventHandler;
@@ -92,10 +92,10 @@ export type AdditionalAccountInfo = Register extends {
92
92
  } ? T : never;
93
93
  export type AdditionalApiRoutes = (Register extends {
94
94
  ApiRoutes: infer T;
95
- } ? T extends Record<string, any> ? T : {} : {});
95
+ } ? T extends Record<string, any> ? T : object : object);
96
96
  export type ApiRoutesParams = (Register extends {
97
97
  ApiRoutesParams: infer T;
98
- } ? T extends Record<string, any> ? T : {} : {}) & {
98
+ } ? T extends Record<string, any> ? T : object : object) & {
99
99
  userIdAccounts: Record<"id", string>;
100
100
  login: Record<"provider", string>;
101
101
  callback: Record<"provider", string>;
@@ -103,10 +103,10 @@ export type ApiRoutesParams = (Register extends {
103
103
  };
104
104
  export type AuthSession = (Register extends {
105
105
  AuthSession: infer T;
106
- } ? T extends Record<string, any> ? T : {} : {}) & DbAuthSession;
106
+ } ? T extends Record<string, any> ? T : object : object) & DbAuthSession;
107
107
  export type AuthUser = (Register extends {
108
108
  AuthUser: infer T;
109
- } ? T extends Record<string, any> ? T : {} : {}) & DbAuthUser;
109
+ } ? T extends Record<string, any> ? T : object : object) & DbAuthUser;
110
110
  export type SessionValidationResult = {
111
111
  session: AuthSession;
112
112
  user: AuthUser;
@@ -240,13 +240,25 @@ export type UseAuthComposableOptions = {
240
240
  * Handle login and logout actions yourself.
241
241
  *
242
242
  * Return `true` to let prevent the handler from handling the action.
243
+ *
244
+ * To run an async function while returning true you can do:
245
+ *
246
+ * ```
247
+ * setTimeout(() => {
248
+ * void (async function() {})()
249
+ * })
250
+ * return true
251
+ * ```
252
+ *
253
+ * The reason handlers cna't return a promise is to allow handler chaining (see the docs).
243
254
  */
244
255
  handleActions?: ActionHandler;
245
256
  };
257
+ export type ActionReturnType = undefined | false | true;
246
258
  /**
247
259
  * See {@link UseAuthComposableOptions.handleActions}
248
260
  */
249
- export type ActionHandler = ((action: "login", url: string, provider: ProviderNames) => any | false) & ((action: "logout", url: string) => any | false);
261
+ export type ActionHandler = ((action: "login", url: string, provider: ProviderNames) => ActionReturnType) & ((action: "logout", url: string) => ActionReturnType);
250
262
  export declare const AUTH_ERROR: {
251
263
  USER_ALREADY_REGISTERED: "AUTH.USER_ALREADY_REGISTERED";
252
264
  UNKNOWN_PROVIDER: "AUTH.UNKNOWN_PROVIDER";
@@ -1,7 +1,8 @@
1
+ import type { ActionHandler } from "../types.js";
1
2
  /**
2
- * Creates an external (e.g. desktop) auth handler.
3
+ * Creates an external (e.g. desktop) auth login handler. A logout one doesn't exist as that is very platform dependant.
3
4
  */
4
- export declare function createExternalAuthHandler(
5
+ export declare function createExternalAuthLoginHandler(
5
6
  /**
6
7
  * The name of the platform.
7
8
  *
@@ -21,7 +22,7 @@ isExternal: () => boolean,
21
22
  *
22
23
  * This is allowed to be undefined because it might only be available in some environments, BUT, it cannot be undefined when isExternal returns true.
23
24
  */
24
- serverUrl: string | (() => string) | (() => Promise<string>) | undefined,
25
+ serverUrl: string | (() => string) | undefined,
25
26
  /**
26
27
  * The function on the external **platform** to open the url on a browser.
27
28
  *
@@ -33,4 +34,4 @@ open: ((url: string) => void | Promise<void>) | undefined,
33
34
  *
34
35
  * @default runctimeConfig().public.auth.authRoutes.deeplink
35
36
  */
36
- deeplinkCallbackPath?: string): (_action: "login" | "logout", url: string) => Promise<boolean>;
37
+ deeplinkCallbackPath?: string): ActionHandler;
@@ -0,0 +1,23 @@
1
+ import { navigateTo, useRuntimeConfig } from "#imports";
2
+ export function createExternalAuthLoginHandler(name, isExternal, serverUrl, open, deeplinkCallbackPath = useRuntimeConfig().public.auth.authRoutes.deeplink) {
3
+ return (action, url) => {
4
+ if (action !== "login") return false;
5
+ if (!isExternal()) return false;
6
+ if (deeplinkCallbackPath === void 0) {
7
+ throw new Error("createExternalAuthLoginHandler: deeplinkCallbackPath cannot be undefined. See docs for more info.");
8
+ }
9
+ if (!serverUrl) throw new Error("createExternalAuthLoginHandler: serverUrl cannot be undefined when isExternal returns true. See docs for more info.");
10
+ if (!open) throw new Error("createExternalAuthLoginHandler: open cannot be undefined when isExternal returns true. See docs for more info.");
11
+ const origin = typeof serverUrl === "function" ? serverUrl() : serverUrl;
12
+ const serverAuth = new URL(url, origin);
13
+ serverAuth.searchParams.set("deeplink", name);
14
+ const serverAuthUri = encodeURIComponent(serverAuth.toString());
15
+ const callbackUrl = new URL(deeplinkCallbackPath, window.location.origin);
16
+ callbackUrl.searchParams.set("authUri", serverAuthUri);
17
+ void open(serverAuth.toString());
18
+ setTimeout(() => {
19
+ void navigateTo(callbackUrl.toString(), { external: true });
20
+ }, 0);
21
+ return true;
22
+ };
23
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@witchcraft/nuxt-auth",
3
- "version": "0.1.9",
3
+ "version": "0.2.1",
4
4
  "description": "Nuxt module for logging.",
5
5
  "repository": "witchcraftjs/nuxt-auth",
6
6
  "license": "MIT",
@@ -1,25 +0,0 @@
1
- import { navigateTo, useRuntimeConfig } from "#imports";
2
- export function createExternalAuthHandler(name, isExternal, serverUrl, open, deeplinkCallbackPath = useRuntimeConfig().public.auth.authRoutes.deeplink) {
3
- return async (_action, url) => {
4
- if (!isExternal()) return false;
5
- if (deeplinkCallbackPath === void 0) {
6
- throw new Error("createExternalAuthHandler: deeplinkCallbackPath cannot be undefined. See docs for more info.");
7
- }
8
- if (!serverUrl) throw new Error("createExternalAuthHandler: serverUrl cannot be undefined when isExternal returns true. See docs for more info.");
9
- if (!open) throw new Error("createExternalAuthHandler: open cannot be undefined when isExternal returns true. See docs for more info.");
10
- let origin = typeof serverUrl === "function" ? serverUrl() : serverUrl;
11
- if (origin instanceof Promise) {
12
- origin = await origin;
13
- }
14
- const serverAuth = new URL(url, origin);
15
- serverAuth.searchParams.set("deeplink", name);
16
- const serverAuthUri = encodeURIComponent(serverAuth.toString());
17
- const callbackUrl = new URL(deeplinkCallbackPath, window.location.origin);
18
- callbackUrl.searchParams.set("authUri", serverAuthUri);
19
- void open(serverAuth.toString());
20
- setTimeout(() => {
21
- void navigateTo(callbackUrl.toString(), { external: true });
22
- }, 0);
23
- return true;
24
- };
25
- }