Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import axios from 'axios'
- import router from '@/router'
- /* eslint-disable camelcase */
- export default class ApiClient {
- /**
- * initialize a new client to make request
- */
- static getClient () {
- const client = axios
- .create({
- baseURL: process.env.VUE_APP_URL,
- timeout: process.env.VUE_APP_API_TIMEOUT
- })
- client.interceptors.response.use(response => response, refreshTokenOrFail)
- return client
- }
- /**
- * initialize a new client to make api request
- * @param {object} headers custom headers for api request, default one with 'Authorization' and user token
- */
- static getClientApi (headers = { 'Authorization': 'Bearer ' + localStorage.getItem('access_token') }) {
- const client = axios
- .create({
- baseURL: process.env.VUE_APP_URL + process.env.VUE_APP_API_PATH,
- timeout: process.env.VUE_APP_API_TIMEOUT,
- headers
- })
- client.interceptors.response.use(response => response, refreshTokenOrFail)
- return client
- }
- static isOkReponse (response) {
- return response.hasOwnProperty('status') && response['status'] === 'ok'
- }
- /**
- * @param {string} fileUri URI del fichero que se va a descargar
- * @param {string} fileName Nombre del fichero que se va a descargar
- * @param {string} type MimeType del fichero que se va a descargar
- */
- static downloadFile (fileUri, fileName, type) {
- return axios({
- url: process.env.VUE_APP_URL + process.env.VUE_APP_API_PATH + fileUri,
- method: 'POST',
- responseType: 'blob',
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem('access_token')
- }
- }).then(({data}) => {
- const blob = new Blob([data], { type })
- if (window.navigator.msSaveOrOpenBlob) {
- // BLOB FOR EXPLORER 11
- window.navigator.msSaveOrOpenBlob(blob, fileName)
- } else {
- let link = document.createElement('a')
- link.href = window.URL.createObjectURL(blob)
- link.download = fileName
- document.body.appendChild(link)
- link.click()
- }
- })
- }
- }
- /**
- * If the request return a 401 error this method try to refresh the user token and repeat the request,
- * if the refresh token has expired throws an error
- * @param {Error} error Axios error
- */
- const refreshTokenOrFail = (error) => {
- const {config, response: { status, data }} = error
- if (status === 401 && data.data.message === 'Google auth fail') {
- return ApiClient.getClientApi().get('/api/me')
- .then(response => {
- let refreshToken = response.data.data.refreshToken
- const payload = {
- 'grant_type': 'refresh_token',
- 'client_id': process.env.VUE_APP_DRIVE_CLIENT_ID,
- 'client_secret': process.env.VUE_APP_DRIVE_CLIENT_SECRET,
- 'refresh_token': refreshToken
- }
- console.log(refreshToken)
- return refreshGoogleAccessToken(payload, config)
- })
- }
- if (status === 401 && data.data.message !== 'The refresh token is invalid.') {
- const payload = {
- 'grant_type': 'refresh_token',
- 'client_id': process.env.VUE_APP_CLIENT_ID,
- 'client_secret': process.env.VUE_APP_CLIENT_SECRET,
- 'scope': process.env.VUE_APP_DEFAULT_SCOPE,
- 'refresh_token': localStorage.getItem('refresh_token')
- }
- return refreshAccessToken(payload, config)
- }
- if (status === 401 && data.data.message === 'The refresh token is invalid.') {
- return clearTokensAndReturnToLogin()
- }
- return Promise.reject(error)
- }
- const refreshGoogleAccessToken = (payload, config) => {
- console.log(payload)
- return axios
- .post('https://www.googleapis.com/oauth2/v4/token', { headers: {
- 'Content-Type': 'application/x-www-form-urlencoded'
- },
- data: {...payload}})
- .then(({access_token}) => {
- const originalRequest = config
- originalRequest.headers['Authorization'] = 'Bearer ' + access_token
- console.log('access' + access_token)
- ApiClient.getClientApi().post('/api/me', { accessToken: access_token, _method: 'PATCH' })
- return axios(originalRequest)
- })
- .catch(clearTokensAndReturnToLogin)
- }
- /**
- * @param {object} payload payload with all the data to make a refresh token request
- * @param {*} config last axios request configuration
- */
- const refreshAccessToken = (payload, config) => {
- return ApiClient
- .getClient()
- .post('oauth/token', {...payload})
- .then(({data}) => data)
- .then(({access_token, refresh_token}) => {
- localStorage.setItem('access_token', access_token)
- localStorage.setItem('refresh_token', refresh_token)
- const originalRequest = config
- originalRequest.headers['Authorization'] = 'Bearer ' + access_token
- return axios(originalRequest)
- })
- .catch(clearTokensAndReturnToLogin)
- }
- const clearTokensAndReturnToLogin = () => {
- localStorage.removeItem('access_token')
- localStorage.removeItem('refresh_token')
- router.push({ 'name': 'login', params: { error: 'Sesiรยณn caducada' } })
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement