diff --git a/docs/api/auth.md b/docs/api/auth.md index eee3762f3..e59629a52 100644 --- a/docs/api/auth.md +++ b/docs/api/auth.md @@ -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` diff --git a/lib/core/auth.js b/lib/core/auth.js index dba4ce241..3fc9a3160 100644 --- a/lib/core/auth.js +++ b/lib/core/auth.js @@ -44,7 +44,7 @@ export default class Auth { return Promise.resolve() } } - + try { // Call mounted for active strategy on initial load await this.mounted() @@ -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) diff --git a/lib/schemes/local.js b/lib/schemes/local.js index ed87f1b52..c05b39410 100644 --- a/lib/schemes/local.js +++ b/lib/schemes/local.js @@ -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) {