1.2.1 • Published 4 years ago

@sport-activities/nuxt-oauth2 v1.2.1

Weekly downloads
4
License
UNLICENSED
Repository
github
Last release
4 years ago

Decathlon OAuth2

Nuxtjs module to use DktConnect OAuth2 authentication.

Installation

npm i -S @sport-activities/nuxt-oauth2

Requirements

Usage

In nuxt.config.js

modules: [
  ...,
  ['@sport-activities/nuxt-oauth2', {
    providers: [
      {
        name: 'decathlon-connect',
        authorizationURL: `${process.env.DKT_CONNECT_HOST}/authorize`,
        tokenURL: `${process.env.DKT_CONNECT_HOST}/token`,
        clientID: process.env.DKT_CLIENT_ID,
        clientSecret: process.env.DKT_CLIENT_SECRET,
        callbackURL: process.env.DKT_REDIRECT_URI,
        scopes: ['openid', 'profile', 'email'],
        redirect: {
          success: '/user/profile',
          failure: '/',
          logout: '/',
        },
      },
      {
        name: 'fedid',
        authorizationURL: `${process.env.FED_HOST}/authorization.oauth2`,
        tokenURL: `${process.env.FED_HOST}/token.oauth2`,
        clientID: process.env.FED_CLIENT_ID,
        clientSecret: process.env.FED_CLIENT_SECRET,
        callbackURL: process.env.FED_REDIRECT_URI,
        scopes: ['openid', 'profile'],
        redirect: {
          success: '/user/profile',
          failure: '/',
          logout: '/',
        },
    ],
    redirect: {
      unauthorized: '/',
    },
    session: {
      secret: process.env.SESSION_SECRET,
      resave: false,
      saveUninitialized: false,
      cookie: {
        maxAge: 1 * 24 * 3600 * 1000 // 1 day
      }
    },
    redis: {
      url: process.env.REDIS_URL,
      logErrors: true
    },
    debug: true,
  }],
  ...
]

You need to dispatch an auth/init event to store the authentication data in the Vuex store.

In store/index.js

const createStore = () => {
  return new Vuex.Store({
    ...,
    actions: {
      async nuxtServerInit ({ dispatch }, { app, req, store }) {
        // init auth store
        dispatch('auth/init', req.user)

        ...
      }
    }
  ...
  }

/!\ As it's session based authentication, you have to send credentials in ajax requests, if you want to get accessToken from req.user object (in express middleware for example)

An example using Axios library :

axios
  .get(`${env.API_URL}api/v1/sports`, {
    withCredentials: true
  })
  .then(res => res.data)

Options

Provider

nametyperequireddefaultdescription
namestringtrueProvider identifier used as param for login()/logout()
authorizationURLstringtrue
tokenURLstringtrue
clientIDstringtrue
clientSecretstringtrue
callbackURLstringtrue
scopesarrayfalse
redirectobjectfalse{ success: '/', failure: '/', logout: '/' }

Redirect

nametyperequireddefaultdescription
unauthorizedstringfalse/The endpoint to redirect in case of access to a protected page without authentication

Session

See express-session documentation

Redis

This parameter is optional.

If fields it instance a RedisStore. Otherwise, fallback to default in-memory store.

Default value :

redis: {
  url: 'redis://localhost:6379'
}

See connect-redis documentation

Debug

You can pass a debug flag in order to obtains debug logs. Default debug state match NODE_ENV value (production value set debug to false).

Vuex store

The module set date in auth store module. You can easily access to the module state through this.$auth.state.

nametypedescription
providerstringOAuth2 provider name
accessTokenstringOAuth2 access token
expiresAtstringOAuth2 access token expiration date
loggedInbooleanLogged in status (based on accessToken)

Generated routes

This module automatically creates the following routes :

routedescription
/login-{providerName}Start login process
/logout-{providerName}Start logout process
/auth/callbackCallback OAuth2 route based on oauth2.callbackURL option

Nuxt usage (and SSR general purposes)

To easily handle credentials during SSR, you can simply use @nuxtjs/axios to perform yout ajax requests. It automaticaly adds credentials in both SSR and classic ajax request and manage headers correctly. It also provide an easy way to manage token through a setToken method.

$auth service

An auth service is automaticaly injected during module initialization, with the following content :

methodsargumentsdescription
loginname, fromstart login process, for given provider
logoutname, fromstart logout process, for given provider
attributesdescription
stateVuex auth module