· 8 years ago · Dec 28, 2016, 06:03 PM
1import Vue from 'vue';
2import { echo } from 'services/Echo'
3import { Events, Cookies } from 'quasar-framework'
4
5export default class ApiClient {
6 constructor () {
7 this.api = Vue.http
8
9 /**
10 * @TODO - add this props to a config .env file
11 */
12 this.baseUrl = 'http://tribe.app'
13 this.baseApiUrl = this.baseUrl + '/api/v1'
14 this.clientId = 3
15 this.clientSecret = 'RLWm7cf3hJTowjQVgqhNN1qVIXnfE3gjebADOCE8'
16 }
17
18 url (segment) {
19 return this.baseApiUrl + '/' + segment
20 }
21
22 async init () {
23 if (!Cookies.has('accessToken')) {
24 let response = await this.getAccessToken()
25 Cookies.set('accessToken', response.body.access_token, {
26 path: '/'
27 })
28 }
29
30 this.setAuthorisationHeader(Cookies.get('accessToken'))
31 this.interceptResponses()
32 }
33
34
35 getAccessToken () {
36 const payload = {
37 client_id: this.clientId,
38 client_secret: this.clientSecret,
39 grant_type: 'client_credentials',
40 scope: '*'
41 }
42 return this.api.post(this.baseUrl + '/oauth/token', payload)
43 }
44
45 setAuthorisationHeader (value) {
46 this.setHeader('Authorization', 'Bearer ' + value)
47 }
48
49 setSocketIdHeader (value) {
50 const name = 'X-Socket-ID'
51
52 if (!this.hasHeader(name)) {
53 this.setHeader(name, value)
54 }
55 }
56
57 setHeader (type, value) {
58 Vue.http.headers.common[type] = value
59 }
60
61 hasHeader (type) {
62 return !!Vue.http.headers.common[type]
63 }
64
65 interceptResponses () {
66 Vue.http.interceptors.push((request, next) => {
67 next((response) => {
68 if (response.status === 401) {
69 this.handle401()
70 }
71
72 this.setSocketIdHeader(echo.socketId())
73
74 return response
75 });
76 });
77 }
78
79 handle401 () {
80 Events.$emit('show-login-modal')
81 if (Cookies.has('isAuthenticated')) {
82 Cookies.remove('isAuthenticated')
83 Cookies.remove('accessToken', {
84 path: '/'
85 })
86 }
87
88 }
89}