Advertisement
claukiller

Untitled

Jun 28th, 2018
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.03 KB | None | 0 0
  1. import axios from 'axios'
  2. import router from '@/router'
  3.  
  4. /* eslint-disable camelcase */
  5. export default class ApiClient {
  6. /**
  7. * initialize a new client to make request
  8. */
  9. static getClient () {
  10. const client = axios
  11. .create({
  12. baseURL: process.env.VUE_APP_URL,
  13. timeout: process.env.VUE_APP_API_TIMEOUT
  14. })
  15.  
  16. client.interceptors.response.use(response => response, refreshTokenOrFail)
  17. return client
  18. }
  19.  
  20. /**
  21. * initialize a new client to make api request
  22. * @param {object} headers custom headers for api request, default one with 'Authorization' and user token
  23. */
  24. static getClientApi (headers = { 'Authorization': 'Bearer ' + localStorage.getItem('access_token') }) {
  25. const client = axios
  26. .create({
  27. baseURL: process.env.VUE_APP_URL + process.env.VUE_APP_API_PATH,
  28. timeout: process.env.VUE_APP_API_TIMEOUT,
  29. headers
  30. })
  31.  
  32. client.interceptors.response.use(response => response, refreshTokenOrFail)
  33. return client
  34. }
  35.  
  36. static isOkReponse (response) {
  37. return response.hasOwnProperty('status') && response['status'] === 'ok'
  38. }
  39.  
  40. /**
  41. * @param {string} fileUri URI del fichero que se va a descargar
  42. * @param {string} fileName Nombre del fichero que se va a descargar
  43. * @param {string} type MimeType del fichero que se va a descargar
  44. */
  45. static downloadFile (fileUri, fileName, type) {
  46. return axios({
  47. url: process.env.VUE_APP_URL + process.env.VUE_APP_API_PATH + fileUri,
  48. method: 'POST',
  49. responseType: 'blob',
  50. headers: {
  51. 'Authorization': 'Bearer ' + localStorage.getItem('access_token')
  52. }
  53. }).then(({data}) => {
  54. const blob = new Blob([data], { type })
  55. if (window.navigator.msSaveOrOpenBlob) {
  56. // BLOB FOR EXPLORER 11
  57. window.navigator.msSaveOrOpenBlob(blob, fileName)
  58. } else {
  59. let link = document.createElement('a')
  60. link.href = window.URL.createObjectURL(blob)
  61. link.download = fileName
  62. document.body.appendChild(link)
  63. link.click()
  64. }
  65. })
  66. }
  67. }
  68.  
  69. /**
  70. * If the request return a 401 error this method try to refresh the user token and repeat the request,
  71. * if the refresh token has expired throws an error
  72. * @param {Error} error Axios error
  73. */
  74. const refreshTokenOrFail = (error) => {
  75. const {config, response: { status, data }} = error
  76. if (status === 401 && data.data.message === 'Google auth fail') {
  77. return ApiClient.getClientApi().get('/api/me')
  78. .then(response => {
  79. let refreshToken = response.data.data.refreshToken
  80. const payload = {
  81. 'grant_type': 'refresh_token',
  82. 'client_id': process.env.VUE_APP_DRIVE_CLIENT_ID,
  83. 'client_secret': process.env.VUE_APP_DRIVE_CLIENT_SECRET,
  84. 'refresh_token': refreshToken
  85. }
  86. console.log(refreshToken)
  87. return refreshGoogleAccessToken(payload, config)
  88. })
  89. }
  90.  
  91. if (status === 401 && data.data.message !== 'The refresh token is invalid.') {
  92. const payload = {
  93. 'grant_type': 'refresh_token',
  94. 'client_id': process.env.VUE_APP_CLIENT_ID,
  95. 'client_secret': process.env.VUE_APP_CLIENT_SECRET,
  96. 'scope': process.env.VUE_APP_DEFAULT_SCOPE,
  97. 'refresh_token': localStorage.getItem('refresh_token')
  98. }
  99.  
  100. return refreshAccessToken(payload, config)
  101. }
  102.  
  103. if (status === 401 && data.data.message === 'The refresh token is invalid.') {
  104. return clearTokensAndReturnToLogin()
  105. }
  106.  
  107. return Promise.reject(error)
  108. }
  109.  
  110. const refreshGoogleAccessToken = (payload, config) => {
  111. console.log(payload)
  112. return axios
  113. .post('https://www.googleapis.com/oauth2/v4/token', { headers: {
  114. 'Content-Type': 'application/x-www-form-urlencoded'
  115. },
  116. data: {...payload}})
  117. .then(({access_token}) => {
  118. const originalRequest = config
  119. originalRequest.headers['Authorization'] = 'Bearer ' + access_token
  120. console.log('access' + access_token)
  121. ApiClient.getClientApi().post('/api/me', { accessToken: access_token, _method: 'PATCH' })
  122.  
  123. return axios(originalRequest)
  124. })
  125. .catch(clearTokensAndReturnToLogin)
  126. }
  127.  
  128. /**
  129. * @param {object} payload payload with all the data to make a refresh token request
  130. * @param {*} config last axios request configuration
  131. */
  132. const refreshAccessToken = (payload, config) => {
  133. return ApiClient
  134. .getClient()
  135. .post('oauth/token', {...payload})
  136. .then(({data}) => data)
  137. .then(({access_token, refresh_token}) => {
  138. localStorage.setItem('access_token', access_token)
  139. localStorage.setItem('refresh_token', refresh_token)
  140.  
  141. const originalRequest = config
  142. originalRequest.headers['Authorization'] = 'Bearer ' + access_token
  143.  
  144. return axios(originalRequest)
  145. })
  146. .catch(clearTokensAndReturnToLogin)
  147. }
  148.  
  149. const clearTokensAndReturnToLogin = () => {
  150. localStorage.removeItem('access_token')
  151. localStorage.removeItem('refresh_token')
  152. router.push({ 'name': 'login', params: { error: 'Sesiรƒยณn caducada' } })
  153. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement