From b628455eba8fa6f1d66b8fef1f668367ccd99e7a Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Sat, 3 Feb 2018 23:49:27 +0330 Subject: [PATCH] feat: watchState and watchLoggedIn #52 --- README.md | 9 +++++++++ lib/defaults.js | 1 + lib/templates/auth.class.js | 24 +++++++++++++++++------- lib/templates/auth.plugin.js | 5 ----- 4 files changed, 27 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 505cac417..64ca0b4ca 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,9 @@ Working with low level state: (Not recommended) this.$auth.setState(key, val) this.$auth.getState(key) +// Watch state changes +this.$auth.watchState('loggedIn', newValue => { }) + // Cookie this.$auth.setCookie(key, val, options) this.$auth.getCookie(key) @@ -257,6 +260,12 @@ If enabled, user will be automatically logged out if any error happens. (For exa If enabled, user will redirect back to the original guarded route instead of `redirects.home`. +### `watchLoggedIn` + +* Default: `true` + +If enabled, user will automatically redirected to `redirects.home` after login/logout. + ### `namespace` * Default: `auth` diff --git a/lib/defaults.js b/lib/defaults.js index 94c842c73..b02924b5e 100644 --- a/lib/defaults.js +++ b/lib/defaults.js @@ -2,6 +2,7 @@ module.exports = { fetchUserOnLogin: true, resetOnError: true, rewriteRedirects: true, + watchLoggedIn: true, namespace: 'auth', scopeKey: 'scope', endpoints: { diff --git a/lib/templates/auth.class.js b/lib/templates/auth.class.js index 84a6ec1d1..8056a749f 100644 --- a/lib/templates/auth.class.js +++ b/lib/templates/auth.class.js @@ -22,6 +22,11 @@ export default class Auth { this._resetOnError() } + // Watch for loggedIn changes only in client side + if (this.options.watchLoggedIn && process.browser) { + this._watchLoggedIn() + } + this._registerVuexStore() } @@ -50,15 +55,13 @@ export default class Auth { }) } - watchLoggedIn () { + _watchLoggedIn () { this._loggedInWatcher = this._loggedInWatcher || - this.$store.watch( - state => state[this.options.namespace]['loggedIn'], - () => { - this.redirect('home') - } - ) + this.watchState('loggedIn', () => { + $auth.redirect('home') + }) + return this._loggedInWatcher } @@ -138,6 +141,13 @@ export default class Auth { return this.state[key] } + watchState (key, fn) { + return this.$store.watch( + state => getProp(state[this.options.namespace], key), + fn + ) + } + setLocalStorage (name, value) { if (typeof localStorage !== 'undefined') { if (value) { diff --git a/lib/templates/auth.plugin.js b/lib/templates/auth.plugin.js index 01d20eb95..480fb6e6f 100644 --- a/lib/templates/auth.plugin.js +++ b/lib/templates/auth.plugin.js @@ -17,11 +17,6 @@ export default function (ctx, inject) { // Sync token $auth.syncToken() - // Watch for loggedIn changes only in client side - if (process.browser) { - $auth.watchLoggedIn() - } - // Fetch user if is not available if (!$auth.state.user) { return $auth.fetchUser()