Skip to content

Commit

Permalink
feat(setUserToken): Add functionality to manually set auth token
Browse files Browse the repository at this point in the history
  • Loading branch information
farnabaz committed Feb 7, 2019
2 parents 750881e + c4691ab commit 9f53a4f
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
13 changes: 13 additions & 0 deletions docs/api/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,19 @@ this.$auth.login(/* .... */)
.then(() => this.$toast.success('Logged In!'))
```

### `setUserToken(token)`

- Returns: `Promise`

Set the auth token and fetch the user using the new token and current strategy.

> **TIP:** This function can properly set the user after registration
```js
this.$auth.setUserToken(token)
.then(() => this.$toast.success('User set!'))
```

## `logout()`

- Returns: `Promise`
Expand Down
14 changes: 13 additions & 1 deletion lib/core/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export default class Auth {
return Promise.resolve()
}
}

try {
// Call mounted for active strategy on initial load
await this.mounted()
Expand Down Expand Up @@ -156,6 +156,18 @@ export default class Auth {
})
}

setUserToken (token) {
if (!this.strategy.setUserToken) {
this.setToken(this.strategy.name, token)
return Promise.resolve()
}

return Promise.resolve(this.strategy.setUserToken(token)).catch(error => {
this.callOnError(error, { method: 'setUserToken' })
return Promise.reject(error)
})
}

reset () {
if (!this.strategy.reset) {
this.setUser(false)
Expand Down
16 changes: 16 additions & 0 deletions lib/schemes/local.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,22 @@ export default class LocalScheme {
return this.fetchUser()
}

async setUserToken (tokenValue) {
// Ditch any leftover local tokens before attempting to log in
await this._logoutLocally()

if (this.options.tokenRequired) {
const token = this.options.tokenType
? this.options.tokenType + ' ' + tokenValue
: tokenValue

this.$auth.setToken(this.name, token)
this._setToken(token)
}

return this.fetchUser()
}

async fetchUser (endpoint) {
// User endpoint is disabled.
if (!this.options.endpoints.user) {
Expand Down

0 comments on commit 9f53a4f

Please sign in to comment.