Skip to content

Commit

Permalink
Structure Changes
Browse files Browse the repository at this point in the history
 - Moved providers into runtime folder, you still need to use #auth/providers to access them externally, this is just for structure internally.

- Added hasOwn to utils. In the event that your browser does not support hasOwn it will use Object.prototype.hasOwnProperty.call instead which is functionally the same.

- Some type fixes
  • Loading branch information
Denoder committed Aug 21, 2023
1 parent c17f066 commit 903c56c
Show file tree
Hide file tree
Showing 26 changed files with 77 additions and 76 deletions.
1 change: 0 additions & 1 deletion build.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ export default defineBuildConfig({
{ input: 'src/types/', outDir: 'dist/types', ext: 'd.ts' },
{ input: 'src/runtime/', outDir: 'dist/runtime', ext: 'mjs' },
{ input: 'src/utils/', outDir: 'dist/utils', ext: 'mjs' },
{ input: 'src/providers/', outDir: 'dist/providers', ext: 'mjs' },
],
rollup: {
emitCJS: false,
Expand Down
8 changes: 4 additions & 4 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,14 +69,14 @@ export default defineNuxtModule({
const runtime = resolver.resolve('runtime');
nuxt.options.alias['#auth/runtime'] = runtime;

// Providers
const providers = resolver.resolve('runtime/providers');
nuxt.options.alias['#auth/providers'] = providers;

// Utils
const utils = resolver.resolve('utils');
nuxt.options.alias['#auth/utils'] = utils;

// Providers
const providers = resolver.resolve('providers');
nuxt.options.alias['#auth/providers'] = providers;

// Transpile
nuxt.options.build.transpile.push(runtime, providers, utils)

Expand Down
4 changes: 2 additions & 2 deletions src/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ImportOptions } from './resolve';
import { ModuleOptions, Strategy } from './types';
import type { ImportOptions } from './resolve';
import type { ModuleOptions, Strategy } from './types';

export const getAuthDTS = () => {
return `import type { Plugin } from '#app'
Expand Down
10 changes: 5 additions & 5 deletions src/resolve.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import type { Strategy, ModuleOptions } from './types';
import type { Nuxt } from '@nuxt/schema';
import { ProviderAliases } from './providers';
import * as AUTH_PROVIDERS from './providers';
import { ProviderAliases } from './runtime/providers';
import * as AUTH_PROVIDERS from './runtime/providers';
import { resolvePath } from '@nuxt/kit';
import { existsSync } from 'fs';
import { hash } from 'ohash';

const BuiltinSchemes = {
export const BuiltinSchemes = {
local: 'LocalScheme',
cookie: 'CookieScheme',
oauth2: 'Oauth2Scheme',
Expand All @@ -22,7 +22,7 @@ export interface ImportOptions {
from: string;
}

export async function resolveStrategies(nuxt: Nuxt, options: ModuleOptions): Promise<{ strategies: Strategy[]; strategyScheme: Record<string, ImportOptions>; }> {
export async function resolveStrategies(nuxt: Nuxt, options: ModuleOptions) {
const strategies: Strategy[] = [];
const strategyScheme = {} as Record<string, ImportOptions>;

Expand Down Expand Up @@ -78,7 +78,7 @@ export async function resolveStrategies(nuxt: Nuxt, options: ModuleOptions): Pro
};
}

export async function resolveScheme(scheme: string): Promise<ImportOptions | void> {
export async function resolveScheme(scheme: string) {
if (typeof scheme !== 'string') {
return;
}
Expand Down
4 changes: 2 additions & 2 deletions src/runtime/core/auth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { HTTPRequest, HTTPResponse, Scheme, SchemeCheck, TokenableScheme, RefreshableScheme, ModuleOptions, Route, AuthState } from '../../types';
import type { NuxtApp } from '#app';
import { isSet, getProp, routeMeta, isRelativeURL } from '../../utils';
import { isSet, getProp, routeMeta, isRelativeURL, hasOwn } from '../../utils';
import { navigateTo, useRoute, useRouter } from "#imports";
import { Storage } from './storage';
import { isSamePath, withQuery } from 'ufo';
Expand Down Expand Up @@ -113,7 +113,7 @@ export class Auth {
if (process.client && this.options.watchLoggedIn) {
this.$storage.watchState('loggedIn', (loggedIn: boolean) => {
if (this.$state.loggedIn === loggedIn) return;
if (Object.hasOwn(useRoute().meta, 'auth') && !routeMeta(useRoute(), 'auth', false)) {
if (hasOwn(useRoute().meta, 'auth') && !routeMeta(useRoute(), 'auth', false)) {
this.redirect(loggedIn ? 'home' : 'logout');
}
});
Expand Down
4 changes: 2 additions & 2 deletions src/runtime/core/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { routeMeta, getMatchedComponents, normalizePath } from '../../utils';
import { routeMeta, getMatchedComponents, normalizePath, hasOwn } from '../../utils';
import { useNuxtApp, defineNuxtRouteMiddleware } from '#imports';

export default defineNuxtRouteMiddleware(async (to, from) => {
Expand All @@ -19,7 +19,7 @@ export default defineNuxtRouteMiddleware(async (to, from) => {

const { login, callback } = ctx.$auth.options.redirect;

const pageIsInGuestMode = Object.hasOwn(to.meta, 'auth') && routeMeta(to, 'auth', 'guest');
const pageIsInGuestMode = hasOwn(to.meta, 'auth') && routeMeta(to, 'auth', 'guest');

const insidePage = (page: string) => normalizePath(to.path) === normalizePath(page);

Expand Down
22 changes: 11 additions & 11 deletions src/runtime/core/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export class Storage {
this.setSessionStorage(key, value);

// Local state
this.setState(key as keyof AuthState, value);
this.setState(key, value);

return value;
}
Expand All @@ -55,7 +55,7 @@ export class Storage {

// Local state
if (process.server) {
value = this.getState(key as keyof AuthState);
value = this.getState(key);
}

// Cookies
Expand All @@ -75,7 +75,7 @@ export class Storage {

// Local state
if (isUnset(value)) {
value = this.getState(key as keyof AuthState);
value = this.getState(key);
}

return value;
Expand All @@ -96,7 +96,7 @@ export class Storage {
}

removeUniversal(key: string): void {
this.removeState(key as keyof AuthState);
this.removeState(key);
this.removeCookie(key);
this.removeLocalStorage(key);
this.removeSessionStorage(key);
Expand Down Expand Up @@ -147,8 +147,8 @@ export class Storage {
return this.#initStore;
}

setState(key: keyof AuthState, value: any) {
if (key[0] === '_') {
setState(key: string, value: any) {
if (key.startsWith('_')) {
this.#state[key] = value;
}
else if (this.#piniaEnabled) {
Expand All @@ -159,14 +159,14 @@ export class Storage {
this.state[key] = value;
}

return value;
return this.state[key];
}

getState(key: keyof AuthState) {
if (key[0] !== '_') {
getState(key: string) {
if (!key.startsWith('_')) {
return this.state[key];
} else {
return this.#state[key];
return this.#state[key] as AuthState;
}
}

Expand All @@ -183,7 +183,7 @@ export class Storage {
}
}

removeState(key: keyof AuthState): void {
removeState(key: string): void {
this.setState(key, undefined);
}

Expand Down
7 changes: 3 additions & 4 deletions src/runtime/inc/configuration-document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ export class ConfigurationDocument {
return this.$storage.setState(this.key, value);
}

get(): OpenIDConnectConfigurationDocument {
return this.$storage.getState(this.key);
get() {
return this.$storage.getState(this.key) as OpenIDConnectConfigurationDocument;
}

set(value: OpenIDConnectConfigurationDocument | boolean) {
Expand All @@ -44,8 +44,7 @@ export class ConfigurationDocument {

async request() {
// Get Configuration document from state hydration
// @ts-ignore
const serverDoc: OpenIDConnectConfigurationDocument = this.scheme.$auth.ctx.payload!.data.$auth?.openIDConnect?.configurationDocument;
const serverDoc: OpenIDConnectConfigurationDocument = this.scheme.$auth.ctx.payload.data.$auth?.openIDConnect?.configurationDocument;

if (process.client && serverDoc) {
this.set(serverDoc);
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/inc/request-handler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { TokenableScheme, RefreshableScheme } from '../../types';
import { ExpiredAuthSessionError } from './expired-auth-session-error';
import { FetchInstance, FetchConfig } from '@refactorjs/ofetch'
import { FetchInstance, FetchConfig } from '@refactorjs/ofetch';

export class RequestHandler {
scheme: TokenableScheme | RefreshableScheme;
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export * from "./core";
export * from "./inc";
export * from "./schemes";
export * from "./schemes";
8 changes: 4 additions & 4 deletions src/providers/auth0.ts → src/runtime/providers/auth0.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ProviderOptions, ProviderPartialOptions } from '../types';
import type { Oauth2SchemeOptions } from '../runtime';
import type { Nuxt } from '@nuxt/schema'
import { assignDefaults } from '../utils/provider';
import type { ProviderOptions, ProviderPartialOptions } from '../../types';
import type { Oauth2SchemeOptions } from '..';
import type { Nuxt } from '@nuxt/schema';
import { assignDefaults } from '../../utils/provider';

export interface Auth0ProviderOptions extends ProviderOptions, Oauth2SchemeOptions {
domain: string;
Expand Down
8 changes: 4 additions & 4 deletions src/providers/discord.ts → src/runtime/providers/discord.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ProviderOptions, ProviderPartialOptions } from '../types';
import type { Oauth2SchemeOptions } from '../runtime';
import type { Nuxt } from '@nuxt/schema'
import { assignDefaults, addAuthorize } from '../utils/provider';
import type { ProviderOptions, ProviderPartialOptions } from '../../types';
import type { Oauth2SchemeOptions } from '..';
import type { Nuxt } from '@nuxt/schema';
import { assignDefaults, addAuthorize } from '../../utils/provider';

export interface DiscordProviderOptions extends ProviderOptions, Oauth2SchemeOptions {}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ProviderPartialOptions, ProviderOptions } from '../types';
import type { Oauth2SchemeOptions } from '../runtime';
import type { Nuxt } from '@nuxt/schema'
import { assignDefaults } from '../utils/provider';
import type { ProviderPartialOptions, ProviderOptions } from '../../types';
import type { Oauth2SchemeOptions } from '..';
import type { Nuxt } from '@nuxt/schema';
import { assignDefaults } from '../../utils/provider';

export interface FacebookProviderOptions extends ProviderOptions, Oauth2SchemeOptions {}

Expand Down
8 changes: 4 additions & 4 deletions src/providers/github.ts → src/runtime/providers/github.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ProviderOptions, ProviderPartialOptions } from '../types';
import type { Oauth2SchemeOptions } from '../runtime';
import type { Nuxt } from '@nuxt/schema'
import { assignDefaults, addAuthorize } from '../utils/provider';
import type { ProviderOptions, ProviderPartialOptions } from '../../types';
import type { Oauth2SchemeOptions } from '..';
import type { Nuxt } from '@nuxt/schema';
import { assignDefaults, addAuthorize } from '../../utils/provider';

export interface GithubProviderOptions extends ProviderOptions, Oauth2SchemeOptions {}

Expand Down
8 changes: 4 additions & 4 deletions src/providers/google.ts → src/runtime/providers/google.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ProviderPartialOptions, ProviderOptions } from '../types';
import type { Oauth2SchemeOptions } from '../runtime';
import type { Nuxt } from '@nuxt/schema'
import { assignDefaults } from '../utils/provider';
import type { ProviderPartialOptions, ProviderOptions } from '../../types';
import type { Oauth2SchemeOptions } from '..';
import type { Nuxt } from '@nuxt/schema';
import { assignDefaults } from '../../utils/provider';

export interface GoogleProviderOptions extends ProviderOptions, Oauth2SchemeOptions {}

Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ProviderPartialOptions, ProviderOptions } from '../types';
import type { RefreshSchemeOptions } from '../runtime';
import type { Nuxt } from '@nuxt/schema'
import { assignDefaults, assignAbsoluteEndpoints } from '../utils/provider';
import type { ProviderPartialOptions, ProviderOptions } from '../../types';
import type { RefreshSchemeOptions } from '..';
import type { Nuxt } from '@nuxt/schema';
import { assignDefaults, assignAbsoluteEndpoints } from '../../utils/provider';

export interface LaravelJWTProviderOptions extends ProviderOptions, RefreshSchemeOptions {
url: string;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { RefreshTokenOptions, TokenOptions, UserOptions, RecursivePartial, ProviderPartialOptions, ProviderOptions } from '../types';
import type { Oauth2SchemeOptions, RefreshSchemeOptions } from '../runtime';
import type { Nuxt } from '@nuxt/schema'
import { assignDefaults, addAuthorize, initializePasswordGrantFlow, assignAbsoluteEndpoints } from '../utils/provider';
import type { RefreshTokenOptions, TokenOptions, UserOptions, RecursivePartial, ProviderPartialOptions, ProviderOptions } from '../../types';
import type { Oauth2SchemeOptions, RefreshSchemeOptions } from '..';
import type { Nuxt } from '@nuxt/schema';
import { assignDefaults, addAuthorize, initializePasswordGrantFlow, assignAbsoluteEndpoints } from '../../utils/provider';

export interface LaravelPassportProviderOptions extends ProviderOptions, Oauth2SchemeOptions {
url: string;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ProviderPartialOptions, HTTPRequest, ProviderOptions } from '../types';
import type { CookieSchemeOptions } from '../runtime';
import type { Nuxt } from '@nuxt/schema'
import { assignAbsoluteEndpoints, assignDefaults } from '../utils/provider';
import type { ProviderPartialOptions, HTTPRequest, ProviderOptions } from '../../types';
import type { CookieSchemeOptions } from '..';
import type { Nuxt } from '@nuxt/schema';
import { assignAbsoluteEndpoints, assignDefaults } from '../../utils/provider';

export interface LaravelSanctumProviderOptions extends ProviderOptions, CookieSchemeOptions {}

Expand Down
12 changes: 6 additions & 6 deletions src/runtime/schemes/oauth2.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { RefreshableScheme, SchemePartialOptions, SchemeCheck, RefreshableSchemeOptions, UserOptions, SchemeOptions, HTTPResponse, EndpointsOption, TokenableSchemeOptions } from '../../types';
import type { IncomingMessage } from 'http'
import type { IncomingMessage } from 'node:http';
import type { Auth } from '../core';
import { getProp, normalizePath, randomString, removeTokenPrefix, parseQuery } from '../../utils';
import { RefreshController, RequestHandler, ExpiredAuthSessionError, Token, RefreshToken } from '../inc';
import { joinURL, withQuery } from 'ufo'
import { joinURL, withQuery } from 'ufo';
import { BaseScheme } from './base';
import { useRoute, useRuntimeConfig } from '#imports';
import requrl from 'requrl';
Expand Down Expand Up @@ -197,7 +197,7 @@ export class Oauth2Scheme<OptionsT extends Oauth2SchemeOptions = Oauth2SchemeOpt
this.requestHandler.reset();
}

async login($opts: { state?: string; params?: any; nonce?: string } = {}): Promise<void> {
async login(options: { state?: string; params?: any; nonce?: string } = {}): Promise<void> {
const opts = {
protocol: 'oauth2',
response_type: this.options.responseType,
Expand All @@ -207,12 +207,12 @@ export class Oauth2Scheme<OptionsT extends Oauth2SchemeOptions = Oauth2SchemeOpt
scope: this.scope,
// Note: The primary reason for using the state parameter is to mitigate CSRF attacks.
// https://auth0.com/docs/protocols/oauth2/oauth-state
state: $opts.state || randomString(10),
state: options.state || randomString(10),
code_challenge_method: this.options.codeChallengeMethod,
clientWindow: this.options.clientWindow,
clientWindowWidth: this.options.clientWindowWidth,
clientWindowHeight: this.options.clientWindowHeight,
...$opts.params,
...options.params,
};

if (this.options.organization) {
Expand Down Expand Up @@ -259,7 +259,7 @@ export class Oauth2Scheme<OptionsT extends Oauth2SchemeOptions = Oauth2SchemeOpt
// Keycloak uses nonce for token as well, so support that too
// https://github.com/nuxt-community/auth-module/pull/709
if (opts.response_type.includes('token') || opts.response_type.includes('id_token')) {
opts.nonce = $opts.nonce || randomString(10);
opts.nonce = options.nonce || randomString(10);
}

if (opts.code_challenge_method) {
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/schemes/openIDConnect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { normalizePath, getProp, parseQuery } from '../../utils';
import { IdToken, ConfigurationDocument } from '../inc';
import { IdTokenableSchemeOptions } from '../../types';
import { useRoute } from '#imports';
import { withQuery, QueryObject, QueryValue } from 'ufo'
import { withQuery, QueryObject, QueryValue } from 'ufo';

export interface OpenIDConnectSchemeEndpoints extends Oauth2SchemeEndpoints {
configuration: string;
Expand Down
1 change: 1 addition & 0 deletions src/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export interface UserInfo {
}

export type AuthState = {
[key: string]: unknown;
// user object
user?: UserInfo;
// indicates whether the user is logged in
Expand Down
2 changes: 1 addition & 1 deletion src/types/options.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Strategy } from './strategy';
import type { NuxtPlugin } from '@nuxt/schema'
import type { NuxtPlugin } from '@nuxt/schema';
import type { PersistedStateOptions } from 'pinia-plugin-persistedstate';

export interface ModuleOptions {
Expand Down
2 changes: 1 addition & 1 deletion src/types/request.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { FetchConfig } from '@refactorjs/ofetch'
import { FetchConfig } from '@refactorjs/ofetch';

export type HTTPRequest = FetchConfig & {
body?: Record<string, any>;
Expand Down
4 changes: 3 additions & 1 deletion src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,4 +154,6 @@ export function setH3Cookie(event: H3Event, serializedCookie: string) {
(val) => val.startsWith(value.slice(0, value.indexOf('=')))
) === index
));
}
}

export const hasOwn = <O extends object, K extends PropertyKey>(object: O, key: K) => Object.hasOwn ? Object.hasOwn(object, key) : Object.prototype.hasOwnProperty.call(object, key);
2 changes: 1 addition & 1 deletion src/utils/provider.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Oauth2SchemeOptions, RefreshSchemeOptions, LocalSchemeOptions, CookieSchemeOptions } from '../runtime';
import type { StrategyOptions, HTTPRequest } from '../types';
import type { Nuxt } from '@nuxt/schema'
import type { Nuxt } from '@nuxt/schema';
import { addServerHandler, addTemplate } from '@nuxt/kit';
import { join } from 'pathe';
import { defu } from 'defu';
Expand Down

0 comments on commit 903c56c

Please sign in to comment.