Permalink
Browse files

feat: watchState and watchLoggedIn

  • Loading branch information...
pi0 committed Feb 3, 2018
1 parent d9756e5 commit b628455eba8fa6f1d66b8fef1f668367ccd99e7a
Showing with 27 additions and 12 deletions.
  1. +9 −0 README.md
  2. +1 −0 lib/defaults.js
  3. +17 −7 lib/templates/auth.class.js
  4. +0 −5 lib/templates/auth.plugin.js
@@ -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`
@@ -2,6 +2,7 @@ module.exports = {
fetchUserOnLogin: true,
resetOnError: true,
rewriteRedirects: true,
watchLoggedIn: true,
namespace: 'auth',
scopeKey: 'scope',
endpoints: {
@@ -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) {
@@ -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()

0 comments on commit b628455

Please sign in to comment.