From 5d870c27b7a68293be188ed4d36b36026914673c Mon Sep 17 00:00:00 2001 From: Herberts Cruz Date: Thu, 9 Nov 2017 12:56:31 -0200 Subject: [PATCH] feat: improvements (#11) * Implementation of the auth property settings in nuxt.config.js with default settings. * Solved (TODO Use set-cookie header for this..res - auth.store.js) * Bug fix resolution. * Creation of the local storage and cookie token name configuration parameter. * Documentation update. * Documentation update. * Documentation update and bug fix. * Documentation update. * Small improvements. * Ajustments. * Added middlewave redirect URL settings. * Bug fixes. * Bug fixes. --- README.md | 22 +++++++++++++++++++++- src/index.js | 8 +++++--- templates/auth.middleware.js | 6 ++++-- templates/auth.store.js | 21 ++++++++++++--------- 4 files changed, 42 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 0345d8235..40f740222 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,9 @@ appendToken: false }, storageTokenName: 'nuxt-auth-token', - tokenType: 'Bearer' + tokenType: 'Bearer', + notLoggedInRedirectTo: '/login', + loggedInRedirectTo: '/' } } ``` @@ -75,6 +77,12 @@ Set the token name in the local storage and in the cookie. #### tokenType Sets the token type of the authorization header. +#### notLoggedInRedirectTo +Sets the redirect URL default of the users not logged in. This is actived when 'auth' middeware is register. + +#### loggedInRedirectTo +Sets the redirect URL default of the users logged in. This is actived when 'no-auth' middeware is register. + ## Example usage ```js @@ -99,6 +107,18 @@ store.state['auth']['user'] // get user data store.getters['auth/loggedIn'] // get login status (true or false) ``` +## Middleware + +```js +// ... in nuxt.config.js ... +router: { + middleware: [ + 'auth', // If user not logged in, redirect to '/login' or to URL defined in notLoggedInRedirectTo property + 'no-auth' // If user is already logged in, redirect to '/' or to URL defined in loggedInRedirectTo property + ] +} +``` + ## License [MIT License](./LICENSE) diff --git a/src/index.js b/src/index.js index b50020ee3..13d28b17b 100644 --- a/src/index.js +++ b/src/index.js @@ -1,7 +1,7 @@ const { resolve } = require('path') const merge = require('lodash/merge') -export default async function module (moduleOptions) { +export default function module (moduleOptions) { // Apply defaults const defaults = { login: { @@ -22,7 +22,9 @@ export default async function module (moduleOptions) { appendToken: false }, storageTokenName: 'nuxt-auth-token', - tokenType: 'Bearer' + tokenType: 'Bearer', + notLoggedInRedirectTo: '/login', + loggedInRedirectTo: '/' } const options = merge(defaults, moduleOptions, this.options.auth) @@ -31,7 +33,7 @@ export default async function module (moduleOptions) { this.addPlugin({ src: resolve(__dirname, '../templates/auth.plugin.js'), fileName: 'auth.plugin.js' }) // Middleware - this.addTemplate({ src: resolve(__dirname, '../templates/auth.middleware.js'), fileName: 'auth.middleware.js' }) + this.addTemplate({ src: resolve(__dirname, '../templates/auth.middleware.js'), fileName: 'auth.middleware.js', options }) // Store this.addTemplate({ src: resolve(__dirname, '../templates/auth.store.js'), fileName: 'auth.store.js', options }) diff --git a/templates/auth.middleware.js b/templates/auth.middleware.js index 27c60ed57..6400277fc 100644 --- a/templates/auth.middleware.js +++ b/templates/auth.middleware.js @@ -1,15 +1,17 @@ import middleware from './middleware' +const options = <%= serialize(options) %> + middleware.auth = function authMiddleware ({ store, redirect }) { // If user not logged in, redirect to /login if (!store.getters['auth/loggedIn']) { - return redirect('/login') + return redirect(options.notLoggedInRedirectTo) } } middleware['no-auth'] = function noAuthMiddleware ({ store, redirect }) { // If user is already logged in, redirect to / if (store.getters['auth/loggedIn']) { - return redirect('/') + return redirect(options.loggedInRedirectTo) } } diff --git a/templates/auth.store.js b/templates/auth.store.js index 497ca32f2..45f2850c1 100644 --- a/templates/auth.store.js +++ b/templates/auth.store.js @@ -106,14 +106,16 @@ export default { // Append token if (appendToken) { - paramTokenName = (paramTokenName) ? ('?' + paramTokenName + '=') : '/'; + paramTokenName = (paramTokenName) ? ('?' + paramTokenName + '=') : '/' endpoint = endpoint + paramTokenName + state.token } // Try to get user profile try { - const headers = {'Authorization': options.tokenType + ' ' + state.token} - const userData = await this.$axios.$get(endpoint, {headers}) + // Set Authorization Token in request + this.$axios.setToken(state.token, options.tokenType) + + const userData = await this.$axios.$get(endpoint) if (propertyName) { commit('SET_USER', userData[propertyName]) @@ -121,7 +123,7 @@ export default { commit('SET_USER', userData) } } catch (e) { - return dispatch('invalidate') + dispatch('invalidate') } }, @@ -137,7 +139,7 @@ export default { dispatch('updateToken', token) // Fetch authenticated user - dispatch('fetch') + await dispatch('fetch') }, // Logout @@ -146,18 +148,19 @@ export default { // Append token if (appendToken) { - paramTokenName = (paramTokenName) ? ('?' + paramTokenName + '=') : '/'; + paramTokenName = (paramTokenName) ? ('?' + paramTokenName + '=') : '/' endpoint = endpoint + paramTokenName + state.token } // Server side logout try { - const headers = {'Authorization': options.tokenType + ' ' + state.token} + // Set Authorization Token in request + this.$axios.setToken(state.token, options.tokenType); if (method.toUpperCase() === 'POST') { - await this.$axios.$post(endpoint, {}, {headers}) + await this.$axios.$post(endpoint) } else { - await this.$axios.$get(endpoint, {headers}) + await this.$axios.$get(endpoint) } } catch (e) { // eslint-disable-next-line no-console