0.6.3 • Published 7 days ago

@byu-oit-sdk/fastify v0.6.3

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
7 days ago

@byu-oit-sdk/fastify

Requirements:

  • Node.js 18+
    • or Node.js 10+ with fetch and crypto polyfills
  • npm v9+
  • Fastify v4

Installing

In addition to installing this module, you must install and configure a compatible store. Currently only session-dynamo is supported.

npm install @byu-oit-sdk/fastify @byu-oit-sdk/session-dynamo

Introduction

Use this module to configure fastify servers that need to implement the OAuth 2.0 Authorization Code grant type.

This module assumes that the access token returned after the authorization code exchange will be a jwt that it can decode to extract user information. This behavior is configurable by passing in the userInfoCallback function into the plugin configuration.

Options

In addition to the options below, any AuthorizationCodeProvider options may also be passed into the configuration.

OptionTypeDefaultDescription
logInstring/auth/signinThe path which redirects the caller to the authorization url to sign in.
logInRedirectstring/auth/userThe path to redirect the caller to after signing in.
logOutstring/auth/signoutThe path to call to clear a user's session and revoke the access token.
logOutRedirectstring/The path to redirect the caller to after signing out.
errorRedirectstring/auth/errorThe path to redirect the caller to after an error is encountered during the authorization flow.
userInfoCookieNamestringuser_infoThe name of the cookie containing the user information parsed from the token.
clientIdstring-The client identifier issued to the client during the registration process.
clientSecretstring-The client secret of the account being used.
redirectUristring-The redirection endpoint that the authorization server should redirect to after authenticating the resource owner.
discoveryEndpointstring-Used to configure where the user will be sent to sign in.

Signing In

  1. For a user to log in, the browser should direct the user to the logIn route.
  2. After the user logs in, the server will redirect the user to the location provided in the redirect query parameter from the login step, or falls back to the logInRedirect option passed into the configuration.
  3. If the user encounters an error, they will be redirected to errorRedirect and an error message will be displayed in the query parameters of the url.

Signing Out

  1. For a user to log out, the browser should direct the user to thelogOut route.
  2. When the user logs out, their session is cleared but the token is not revoked.
  3. After logging out, they will be redirected to the logOutRedirect route.
  4. If the user encounters an error, they will be redirected to errorRedirect and an error message will be displayed in the query parameters of the url.

Usage

import { ByuLogger } from '@byu-oit/logger'
import { AuthorizationCodeFlow } from '@byu-oit-sdk/fastify'
import fastifyCookie from '@fastify/cookie'
import { SessionPlugin } from '@byu-oit-sdk/session-fastify'
import Fastify from 'fastify'
import dynamoDbStoreFactory from 'connect-dynamodb'
import env from 'env-var'

/**
 * Environment variable setup.
 */
const secret = env.get('BYU_OIT_SIGNING_SECRET').required().asString()
const table = env.get('SESSION_TABLE').required().asString()
const isProduction = env.get('NODE_ENV').default('development').asEnum(['production', 'development']) === 'production'

/**
 * Initialize fastify with BYU Logger.
 */
export const fastify = Fastify({ logger: ByuLogger() })

/**
 * Must register the \@fastify/cookie plugin. The \@fastify/jwt module depends on \@fastify/cookie.
 */
await fastify.register(fastifyCookie)

let store
if (isProduction) {
    const client = new DynamoDBClient({
        region: env.get('AWS_REGION').required().asString(),
        endpoint: 'http://localhost:8000'
    })
    store = new DynamoSessionStore({ client, tableName: 'sessions' })
}

/**
 *  Must register the \@byu-oit-sdk/session-fastify plugin. You must pass in a session storage option for production environments.
 *  Using the default in-memory storage is highly discouraged because it will cause memory leaks.
 */
await fastify.register(SessionPlugin, { store })

/**
 * AuthorizationCodeProvider options may be passed in the second parameter.
 */
await fastify.register(AuthorizationCodeFlow)

/**
 * To require authentication for a route, just specify the authenticate function on the request object in the onRequest hook.
 */
fastify.get('/auth/user', { onRequest: [fastify.authenticate] }, (req, reply) => {
    return `Your CES UUID is ${req.session.user.cesUUID}`
})
import { ByuLogger } from '@byu-oit/logger'
import { AuthorizationCodeFlow } from '@byu-oit-sdk/fastify'
import fastifyCookie from '@fastify/cookie'
import { SessionPlugin } from '@byu-oit-sdk/session-fastify'
import Fastify from 'fastify'
import env from 'env-var'
import { createDecoder } from 'fast-jwt'
import { DynamoSessionStore } from '@byu-oit-sdk/session-dynamo'
import { DynamoDBClient } from '@aws-sdk/client-dynamodb'

declare module '@byu-oit-sdk/fastify' {
    interface UserInfo {
        /**
         * Declare your user info properties here
         */
    }
}

const secret = env.get('BYU_OIT_SIGNING_SECRET').required().asString()
const isProduction = env.get('NODE_ENV').default('development').asEnum(['production', 'development']) === 'production'

export const fastify = Fastify({ logger: ByuLogger() })

/**
 * Must register the \@fastify/cookie plugin. The \@fastify/jwt module depends on \@fastify/cookie.
 */
await fastify.register(fastifyCookie)

let store
if (isProduction) {
  const client = new DynamoDBClient({})
  store = new DynamoSessionStore({ client, tableName: 'sessions' })
}

/**
 *  Must register the \@byu-oit-sdk/session-fastify plugin. You must pass in a session storage option for production environments.
 *  Using the default in-memory storage is highly discouraged because it will cause memory leaks.
 */
await fastify.register(SessionPlugin, { store })

/* Initialize jwt decoder for user info callback */
const decode = createDecoder()

await fastify.register(AuthorizationCodeFlow, {
    /**
     * A user info callback function can be supplied to implement a custom way to return the user info data.
     * the default behavior is to decode the access token returned from the oauth provider token endpoint.
     * The context of the `userInfoCallback` function is bound to the FastifyAuthorizationCodeProvider instance.
     */
    userInfoCallback (token) {
        if (typeof token.additional.id_token !== 'string') {
            /** The id token property must exist in the token response body */
            throw Error('Missing or mal-formatted ID token in response from token endpoint. Did you set the right scopes?')
        }
        /** Decode the `id_token` property, which should return the user info object. */
        return decode(token.additional.id_token)
    }
})

/**
 * To require authentication for a route, just specify the authenticate function on the request object in the onRequest hook.
 */
fastify.get('/auth/user', { onRequest: [fastify.authenticate] }, (req, reply) => {
    return req.session.user
})

Logging in and out

This package sets up two ways for users to log in and out. The main way is to have a link that sends the user to the value passed in as logIn or logOut in the options for the AuthorizationCodeFlow() function (the default is /auth/signin and /auth/signout, respectively). The user could even manually navigate to those routes in their browser.

<a href="/auth/signout">Sign Out</a>
<a href="/auth/signin">Sign In</a>

If you want to have the user be redirected to log in or log out while running server-side code, a set of functions will be added to the fastify reply object in route handlers and such, so you can simply call reply.login(<optional redirect url>) or reply.logout(<optional redirect url>). The parameter for each function is optional and if not provided, the logInRedirect and logOutRedirect values from the options passed into the AuthorizationCodeFlow() function will be used.

fastify.get((request, reply) => {
  if (req.session.data.token == null ) {
    reply.login('/return_to_me_after_login')
  }
})

This package also exposes two functions on your fastify instance: authenticate and autoAuthenticate. To require authentication for a route, just specify the authenticate function on the request object in the onRequest hook. If you use the autoAuthenticate instead, the user will automatically be redirected to the signin route if they attempt to access a protected route without being logged in.

0.6.3

7 days ago

0.6.2-beta.0

2 months ago

0.6.2

2 months ago

0.6.1-beta.0

2 months ago

0.6.1

2 months ago

0.6.0-beta.5

2 months ago

0.6.0-beta.4

3 months ago

0.6.0

3 months ago

0.6.0-beta.3

4 months ago

0.6.0-beta.2

4 months ago

0.6.0-beta.1

4 months ago

0.5.0-beta.11

9 months ago

0.5.0-beta.12

8 months ago

0.5.0-beta.10

9 months ago

0.5.0-beta.13

8 months ago

0.5.0-beta.1

9 months ago

0.5.0-beta.0

9 months ago

0.5.0-beta.9

9 months ago

0.5.0-beta.8

9 months ago

0.5.0-beta.7

9 months ago

0.5.0-beta.6

9 months ago

0.5.0-beta.5

9 months ago

0.5.0-beta.4

9 months ago

0.5.0-beta.3

9 months ago

0.5.0-beta.2

9 months ago

0.6.0-beta.0

8 months ago

0.5.0

8 months ago

0.4.1

11 months ago

0.4.0

11 months ago

0.4.2

10 months ago

0.3.0

11 months ago

0.2.3

11 months ago

0.2.4

11 months ago

0.2.2

11 months ago

0.2.1

11 months ago

0.2.0

11 months ago

1.0.0-beta.0

11 months ago

0.1.6

11 months ago

0.1.5

11 months ago

0.1.4

11 months ago

0.1.3

11 months ago

0.1.2

11 months ago

0.1.1

11 months ago

0.1.0

11 months ago