Last active
February 28, 2018 21:18
-
-
Save schefferdev/9811e5ca3d6a4e8e2cb0c7dc5b7dde83 to your computer and use it in GitHub Desktop.
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
| import http from '@/plugins/axios' | |
| import vuex from '@/plugins/store' | |
| class Auth { | |
| constructor (jwt = false) { | |
| this.jwt = jwt | |
| this.loginUrl = jwt ? 'api-token-auth/' : 'rest-auth/login/' | |
| } | |
| _tokenType () { | |
| let type = this.jwt ? 'JWT ' : 'Token ' | |
| let token = vuex.state.token | |
| return type + token | |
| } | |
| login (form) { | |
| return new Promise((resolve, reject) => { | |
| http.post(this.loginUrl, form) | |
| .then(response => { | |
| vuex.commit('AUTH', this.jwt ? response.data.token : response.data.key) | |
| this.check().then(res => resolve(res), err => reject(err)) | |
| }).catch(err => { | |
| this.logout() | |
| reject(err.response.data) | |
| }) | |
| }) | |
| } | |
| logout () { | |
| vuex.commit('LOGOUT') | |
| } | |
| check () { | |
| return new Promise((resolve, reject) => { | |
| vuex.commit('CHECK') | |
| let token = vuex.state.token | |
| if (token !== null) { | |
| $.ajaxSetup({ | |
| headers: { | |
| 'Authorization': this._tokenType() | |
| }, | |
| beforeSend (xhr, options) { | |
| options.url = 'http://localhost:8000/' + options.url | |
| } | |
| }) | |
| http.defaults.headers.common['Authorization'] = this._tokenType() | |
| http.get('api/core/user/') | |
| .then( | |
| res => { | |
| vuex.commit('LOGIN', res.data) | |
| resolve() | |
| }, | |
| err => { | |
| this.logout() | |
| reject(err.response.data) | |
| } | |
| ) | |
| } else { | |
| this.logout() | |
| reject(new Error('Não foi encontrado o token')) | |
| } | |
| }) | |
| } | |
| refresh () { | |
| return new Promise((resolve, reject) => { | |
| let post = { | |
| token: vuex.state.token | |
| } | |
| http.post('api-token-refresh', post).then( | |
| res => { | |
| vuex.commit('AUTH', res.data.token) | |
| resolve(res) | |
| }, | |
| err => { | |
| vuex.commit('LOGOUT') | |
| reject(err) | |
| } | |
| ) | |
| }) | |
| } | |
| } | |
| export default new Auth(true) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment