Skip to content

Commit

Permalink
Merge pull request #263 from auth0/split-config
Browse files Browse the repository at this point in the history
Split configuration into Next and Base config
  • Loading branch information
adamjmcgrath committed Feb 1, 2021
2 parents 022931e + a52b686 commit c50c5f5
Show file tree
Hide file tree
Showing 22 changed files with 332 additions and 354 deletions.
4 changes: 2 additions & 2 deletions README.md
Expand Up @@ -70,7 +70,7 @@ AUTH0_CLIENT_ID='YOUR_AUTH0_CLIENT_ID'
AUTH0_CLIENT_SECRET='YOUR_AUTH0_CLIENT_SECRET'
```

For a [full list of configuration options](https://auth0.github.io/nextjs-auth0/interfaces/config.config-1.html) see the docs.
For a [full list of configuration options](https://auth0.github.io/nextjs-auth0/modules/config.html) see the docs.

Then, create a [Dynamic API Route handler](https://nextjs.org/docs/api-routes/dynamic-api-routes) at `/pages/api/auth/[...auth0].js`.

Expand Down Expand Up @@ -128,7 +128,7 @@ For more extensive examples see [EXAMPLES.md](./EXAMPLES.md).

### API Reference

- [Configuration Options](https://auth0.github.io/nextjs-auth0/interfaces/config.config-1.html)
- [Configuration Options](https://auth0.github.io/nextjs-auth0/modules/config.html)

**Server Side methods**:

Expand Down
4 changes: 2 additions & 2 deletions V1_MIGRATION_GUIDE.md
Expand Up @@ -4,7 +4,7 @@ Guide to migrating from `0.x` to `1.x` (Beta)

### Config changes

> Note: If you only use environment variables to configure the SDK, you don't need to create an instance of the SDK. You can use the named exports (`handleAuth`, `getSession`) directly from `@auth0/nextjs-auth` and they will lazily create an instance of the SDK for you, and configure it using the following [environment variables](https://auth0.github.io/nextjs-auth0/interfaces/config.config-1.html). See the [Basic setup](./EXAMPLES.md#basic-setup) as an example.
> Note: If you only use environment variables to configure the SDK, you don't need to create an instance of the SDK. You can use the named exports (`handleAuth`, `getSession`) directly from `@auth0/nextjs-auth` and they will lazily create an instance of the SDK for you, and configure it using the following [environment variables](https://auth0.github.io/nextjs-auth0/modules/config.html). See the [Basic setup](./EXAMPLES.md#basic-setup) as an example.
If you still want to create the SDK instance yourself, note that the configuration options have changed as follows.

Expand Down Expand Up @@ -78,7 +78,7 @@ export default initAuth0({
});
```

See the API docs for a [full list of configuration options](https://auth0.github.io/nextjs-auth0/interfaces/config.config-1.html).
See the API docs for a [full list of configuration options](https://auth0.github.io/nextjs-auth0/modules/config.html).

### getSession

Expand Down
50 changes: 2 additions & 48 deletions src/auth0-session/config.ts
Expand Up @@ -3,20 +3,12 @@ import { AuthorizationParameters as OidcAuthorizationParameters } from 'openid-c

/**
* Configuration properties.
*
* ```.env
* ISSUER_BASE_URL=https://YOUR_DOMAIN
* CLIENT_ID=YOUR_CLIENT_ID
* BASE_URL=https://YOUR_APPLICATION_ROOT_URL
* SECRET=LONG_RANDOM_VALUE
* ```
*/
export interface Config {
/**
* The secret(s) used to derive an encryption key for the user identity in a session cookie and
* to sign the transient cookies used by the login callback.
* Use a single string key or array of keys for an encrypted session cookie.
* Can use env key SECRET instead.
*/
secret: string | Array<string>;

Expand Down Expand Up @@ -79,20 +71,17 @@ export interface Config {

/**
* The root URL for the application router, eg https://localhost
* Can use env key BASE_URL instead.
*/
baseURL: string;

/**
* The Client ID for your application.
* Can be read from CLIENT_ID instead.
*/
clientID: string;

/**
* The Client Secret for your application.
* Required when requesting access tokens.
* Can be read from CLIENT_SECRET instead.
*/
clientSecret?: string;

Expand All @@ -115,23 +104,7 @@ export interface Config {
enableTelemetry: boolean;

/**
* Throw a 401 error instead of triggering the login process for routes that require authentication.
* Default is `false`
*/
errorOnRequiredAuth: boolean;

/**
* Attempt silent login (`prompt: 'none'`) on the first unauthenticated route the user visits.
* For protected routes this can be useful if your Identity Provider does not default to
* `prompt: 'none'` and you'd like to attempt this before requiring the user to interact with a login prompt.
* For unprotected routes this can be useful if you want to check the user's logged in state on their IDP, to
* show them a login/logout button for example.
* Default is `false`
*/
attemptSilentLogin: boolean;

/**
* Function that returns an object with URL-safe state values for `res.oidc.login()`.
* Function that returns an object with URL-safe state values for login.
* Used for passing custom state parameters to your authorization server.
*
* ```js
Expand Down Expand Up @@ -166,7 +139,6 @@ export interface Config {

/**
* REQUIRED. The root URL for the token issuer with no trailing slash.
* Can use env key ISSUER_BASE_URL instead.
*/
issuerBaseURL: string;

Expand All @@ -176,25 +148,7 @@ export interface Config {
*/
legacySameSiteCookie: boolean;

/**
* Require authentication for all routes.
*/
authRequired: boolean;

/**
* Boolean value to automatically install the login and logout routes.
*/
routes: {
/**
* Relative path to application login.
*/
login: string | false;

/**
* Relative path to application logout.
*/
logout: string | false;

/**
* Either a relative path to the application or a valid URI to an external domain.
* This value must be registered on the authorization server.
Expand Down Expand Up @@ -285,7 +239,7 @@ export interface CookieConfig {
* Passed to the [Response cookie](https://expressjs.com/en/api.html#res.cookie) as `samesite`.
* Defaults to "Lax" but will be adjusted based on {@link AuthorizationParameters.response_type}.
*/
sameSite: boolean | 'lax' | 'strict' | 'none';
sameSite: 'lax' | 'strict' | 'none';
}

export interface AuthorizationParameters extends OidcAuthorizationParameters {
Expand Down
15 changes: 2 additions & 13 deletions src/auth0-session/get-config.ts
Expand Up @@ -133,9 +133,7 @@ const paramsSchema = Joi.object({
issuerBaseURL: Joi.string().uri().required(),
legacySameSiteCookie: Joi.boolean().optional().default(true),
routes: Joi.object({
login: Joi.alternatives([Joi.string().uri({ relativeOnly: true }), Joi.boolean().valid(false)]).default('/login'),
logout: Joi.alternatives([Joi.string().uri({ relativeOnly: true }), Joi.boolean().valid(false)]).default('/logout'),
callback: Joi.string().uri({ relativeOnly: true }).default('/callback'),
callback: Joi.string().uri({ relativeOnly: true }).required(),
postLogoutRedirect: Joi.string().uri({ allowRelative: true }).default('')
})
.default()
Expand All @@ -155,16 +153,7 @@ export type DeepPartial<T> = {
export type ConfigParameters = DeepPartial<Config>;

export const get = (params: ConfigParameters = {}): Config => {
const config = {
secret: process.env.SECRET,
issuerBaseURL: process.env.ISSUER_BASE_URL,
baseURL: process.env.BASE_URL,
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
...params
};

const { value, error, warning } = paramsSchema.validate(config);
const { value, error, warning } = paramsSchema.validate(params);
if (error) {
throw new TypeError(error.details[0].message);
}
Expand Down
8 changes: 5 additions & 3 deletions src/auth0-session/handlers/callback.ts
Expand Up @@ -17,13 +17,15 @@ export type CallbackOptions = {
afterCallback?: AfterCallback;
};

export default function callbackHandler(
export type HandleCallback = (req: IncomingMessage, res: ServerResponse, options?: CallbackOptions) => Promise<void>;

export default function callbackHandlerFactory(
config: Config,
getClient: ClientFactory,
sessionCache: SessionCache,
transientCookieHandler: TransientStore
) {
return async (req: IncomingMessage, res: ServerResponse, options?: CallbackOptions): Promise<void> => {
): HandleCallback {
return async (req, res, options) => {
const client = await getClient();

const redirectUri = getRedirectUri(config);
Expand Down
10 changes: 8 additions & 2 deletions src/auth0-session/handlers/login.ts
Expand Up @@ -13,8 +13,14 @@ function getRedirectUri(config: Config): string {
return urlJoin(config.baseURL, config.routes.callback);
}

export default function loginHandler(config: Config, getClient: ClientFactory, transientHandler: TransientStore) {
return async (req: IncomingMessage, res: ServerResponse, options: LoginOptions = {}): Promise<void> => {
export type HandleLogin = (req: IncomingMessage, res: ServerResponse, options?: LoginOptions) => Promise<void>;

export default function loginHandlerFactory(
config: Config,
getClient: ClientFactory,
transientHandler: TransientStore
): HandleLogin {
return async (req, res, options = {}) => {
const client = await getClient();

const returnTo = options.returnTo || config.baseURL;
Expand Down
14 changes: 8 additions & 6 deletions src/auth0-session/handlers/logout.ts
Expand Up @@ -2,18 +2,20 @@ import { IncomingMessage, ServerResponse } from 'http';
import url from 'url';
import urlJoin from 'url-join';
import createDebug from '../utils/debug';
import { Config } from '../config';
import { Config, LogoutOptions } from '../config';
import { ClientFactory } from '../client';
import { SessionCache } from '../session-cache';

const debug = createDebug('logout');

export interface LogoutOptions {
returnTo?: string;
}
export type HandleLogout = (req: IncomingMessage, res: ServerResponse, options?: LogoutOptions) => Promise<void>;

export default function logoutHandler(config: Config, getClient: ClientFactory, sessionCache: SessionCache) {
return async (req: IncomingMessage, res: ServerResponse, options: LogoutOptions = {}): Promise<void> => {
export default function logoutHandlerFactory(
config: Config,
getClient: ClientFactory,
sessionCache: SessionCache
): HandleLogout {
return async (req, res, options = {}) => {
let returnURL = options.returnTo || config.routes.postLogoutRedirect;
debug('logout() with return url: %s', returnURL);

Expand Down
6 changes: 3 additions & 3 deletions src/auth0-session/index.ts
Expand Up @@ -2,8 +2,8 @@ export { default as CookieStore } from './cookie-store';
export { default as TransientStore } from './transient-store';
export { Config, SessionConfig, CookieConfig, LoginOptions, LogoutOptions, AuthorizationParameters } from './config';
export { get as getConfig, ConfigParameters, DeepPartial } from './get-config';
export { default as loginHandler } from './handlers/login';
export { default as logoutHandler } from './handlers/logout';
export { default as callbackHandler, CallbackOptions, AfterCallback } from './handlers/callback';
export { default as loginHandler, HandleLogin } from './handlers/login';
export { default as logoutHandler, HandleLogout } from './handlers/logout';
export { default as callbackHandler, CallbackOptions, AfterCallback, HandleCallback } from './handlers/callback';
export { default as clientFactory, ClientFactory } from './client';
export { SessionCache } from './session-cache';

0 comments on commit c50c5f5

Please sign in to comment.