Last active
March 8, 2020 09:21
-
-
Save leeovery/ca70569fc8c90147d305b5e39519291c to your computer and use it in GitHub Desktop.
Laravel Airlock Nuxt Stategy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default class AirlockScheme { | |
constructor(auth, options) { | |
this.$auth = auth; | |
this.name = options._name; | |
this.options = Object.assign({}, DEFAULTS, options); | |
} | |
mounted() { | |
this.$auth.ctx.app.$axios.defaults.withCredentials = true; | |
this.$auth.ctx.app.$axios.setHeader('X-Requested-With', 'XMLHttpRequest'); | |
this.$auth.ctx.app.$axios.setHeader('Content-Type', 'application/json'); | |
return this.$auth.fetchUserOnce(); | |
} | |
async login(endpoint) { | |
if (!this.options.endpoints.login) { | |
return; | |
} | |
await this._logoutLocally(); | |
await this.$auth.request('/airlock/csrf-cookie', this.options.endpoints.csrf); | |
await this.$auth.request(endpoint, this.options.endpoints.login); | |
return this.fetchUser(); | |
} | |
async fetchUser(endpoint) { | |
// User endpoint is disabled. | |
if (!this.options.endpoints.user) { | |
this.$auth.setUser({}); | |
return; | |
} | |
// Try to fetch user and then set | |
const user = await this.$auth.requestWith( | |
this.name, | |
endpoint, | |
this.options.endpoints.user, | |
); | |
this.$auth.setUser(user); | |
} | |
async logout(endpoint) { | |
// Only connect to logout endpoint if it's configured | |
if (this.options.endpoints.logout) { | |
await this.$auth | |
.requestWith(this.name, endpoint, this.options.endpoints.logout) | |
.catch(() => { | |
// | |
}); | |
} | |
return this._logoutLocally(); | |
} | |
async _logoutLocally() { | |
return this.$auth.setUser(false); | |
} | |
} | |
const DEFAULTS = { | |
tokenRequired: false, | |
tokenType: false, | |
globalToken: false, | |
tokenName: false, | |
autoFetchUser: true, | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
auth: { | |
strategies: { | |
airlock: { | |
_scheme: '@/strategies/airlock.js', | |
endpoints: { | |
csrf: { url: 'airlock/csrf-cookie', method: 'get' }, | |
login: { url: 'auth/login', method: 'post' }, | |
user: { url: 'me', method: 'get', propertyName: 'data' }, | |
logout: { url: 'auth/logout', method: 'post' }, | |
}, | |
}, | |
} | |
}, | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment