Skip to content

Commit

Permalink
feat: watchState and watchLoggedIn
Browse files Browse the repository at this point in the history
  • Loading branch information
Pooya Parsa committed Feb 3, 2018
1 parent d9756e5 commit b628455
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 12 deletions.
9 changes: 9 additions & 0 deletions README.md
Expand Up @@ -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)
Expand Down Expand Up @@ -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`
Expand Down
1 change: 1 addition & 0 deletions lib/defaults.js
Expand Up @@ -2,6 +2,7 @@ module.exports = {
fetchUserOnLogin: true,
resetOnError: true,
rewriteRedirects: true,
watchLoggedIn: true,
namespace: 'auth',
scopeKey: 'scope',
endpoints: {
Expand Down
24 changes: 17 additions & 7 deletions lib/templates/auth.class.js
Expand Up @@ -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()
}

Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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) {
Expand Down
5 changes: 0 additions & 5 deletions lib/templates/auth.plugin.js
Expand Up @@ -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()
Expand Down

0 comments on commit b628455

Please sign in to comment.