orderiom-api-package 0.4.87 → 0.4.89

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.ts CHANGED
@@ -8,7 +8,6 @@ export const formatDate: (date: Date) => string;
8
8
  export const formatTime: (date: Date) => string;
9
9
 
10
10
  export interface AuthState<SignedIn extends boolean> {
11
- publicToken: string | null,
12
11
  privateToken: string | null,
13
12
  expires_at: string | null,
14
13
  user: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "orderiom-api-package",
3
- "version": "0.4.87",
3
+ "version": "0.4.89",
4
4
  "description": "This package will install all necessary API calls for every orderiom restaurant",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
package/src/common.js CHANGED
@@ -113,33 +113,93 @@ export function formatTime(date){
113
113
  }
114
114
 
115
115
  export function isTokenExpired(token) {
116
- const base64Url = token.split(".")[1];
117
- const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
118
- const jsonPayload = decodeURIComponent(
119
- atob(base64)
120
- .split("")
121
- .map(function (c) {
122
- return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
123
- })
124
- .join("")
125
- );
126
-
127
- const { exp } = JSON.parse(jsonPayload);
128
- return Date.now() >= exp * 1000;
116
+ try{
117
+ const base64Url = token.split(".")[1];
118
+ const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
119
+
120
+ const jsonPayload = decodeURIComponent(
121
+ atob(base64)
122
+ .split("")
123
+ .map(function (c) {
124
+ return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
125
+ })
126
+ .join("")
127
+ );
128
+
129
+ const { exp } = JSON.parse(jsonPayload);
130
+ return Date.now() >= exp * 1000;
131
+ } catch (err){
132
+ return true;
133
+ }
134
+ }
135
+
136
+ let isFetchingToken = false;
137
+ const reqBuffer = []; // List of axios requests waiting for the fetch of public token (Each item is a function)
138
+ const getTokenAPI = "api/oauth/token"; // API to get public token needs
139
+
140
+ const getAuthToken = () => {
141
+ isFetchingToken = true;
142
+ return axios
143
+ .post(getTokenAPI, {
144
+ grant_type: process.env.VUE_APP_GRANT_TYPE || window.dynamicData.VUE_APP_GRANT_TYPE,
145
+ client_id: process.env.VUE_APP_CLIENT_ID || window.dynamicData.VUE_APP_CLIENT_ID,
146
+ client_secret: process.env.VUE_APP_CLIENT_SECRET || window.dynamicData.VUE_APP_CLIENT_SECRET
147
+ })
148
+ .then(res => {
149
+ window.localStorage.setItem("publicToken", res.data.data.access_token);
150
+ })
151
+ .catch(
152
+ commonErrorCallback()
153
+ )
154
+ .finally(() => {
155
+ while (reqBuffer.length) {
156
+ reqBuffer.shift()(); // First in First out
157
+ }
158
+ isFetchingToken = false;
159
+ });
129
160
  }
130
161
 
131
162
  axios.defaults.baseURL = process.env.VUE_APP_BASE_API_URL || window.dynamicData.VUE_APP_BASE_API_URL;
132
163
  axios.interceptors.request.use(config => {
133
- const token = localStorage.getItem("privateToken") || localStorage.getItem("publicToken");
134
- if (token) config.headers["Authorization"] = `Bearer ${token}`;
164
+ // exception API that does not need any pre-process
165
+ if(config.url === getTokenAPI) return config;
135
166
 
167
+ // attach restaurant ID to all other requests
136
168
  const key = config.method === 'get' ? 'params' : 'data';
137
169
  const data = config[key] || {};
138
170
  const idFromEnv = restaurantIdEnv();
139
171
  if(idFromEnv && !data.restaurantId) data.restaurantId = idFromEnv;
140
172
  config[key] = data;
141
173
 
142
- return config;
174
+ // use the valid token if possible
175
+ let token = localStorage.getItem("privateToken") || localStorage.getItem("publicToken");
176
+ if(token && !isTokenExpired(token)){
177
+ config.headers["Authorization"] = `Bearer ${token}`
178
+ return config;
179
+ }
180
+
181
+ // if the token is expired or does not exist, wait for public token to be fetched
182
+ return new Promise((resolve, reject) => {
183
+ // remove invalid or expired tokens
184
+ token = null;
185
+ localStorage.removeItem("privateToken");
186
+ localStorage.removeItem("publicToken");
187
+
188
+ // Push the request to waitlist and wait for new token to be fetched
189
+ reqBuffer.push(() => {
190
+ const newToken = localStorage.getItem("publicToken");
191
+ if(newToken){
192
+ config.headers["Authorization"] = `Bearer ${newToken}`
193
+ resolve(config);
194
+ } else {
195
+ config.headers["Authorization"] = undefined;
196
+ reject(`Not authorized! token required for ${config.url}.`);
197
+ }
198
+ });
199
+
200
+ // Start to fetch token if it is not already fetching
201
+ if(!isFetchingToken) getAuthToken();
202
+ })
143
203
  }, error => {
144
204
  return Promise.reject(error);
145
205
  });
@@ -177,6 +237,7 @@ axios.interceptors.response.use(
177
237
 
178
238
  if (
179
239
  error.response &&
240
+ error.response.status === 422 &&
180
241
  error.response.data &&
181
242
  error.response.data.message &&
182
243
  error.response.data.message.body === "unauthenticated"
@@ -1,7 +1,6 @@
1
- import {commonErrorCallback, $http, isTokenExpired, restaurantIdEnv } from '../common';
1
+ import {commonErrorCallback, $http, restaurantIdEnv } from '../common';
2
2
 
3
3
  const state = {
4
- publicToken: null,
5
4
  privateToken: null,
6
5
  expires_at: null,
7
6
  user: {},
@@ -12,9 +11,6 @@ const state = {
12
11
  userAddress: []
13
12
  };
14
13
  const mutations = {
15
- setPublicToken(state, token) {
16
- state.publicToken = token
17
- },
18
14
  authUser(state, userData) {
19
15
  state.privateToken = userData.privateToken;
20
16
  state.expires_at = userData.expires_at;
@@ -52,23 +48,8 @@ const mutations = {
52
48
  }
53
49
  };
54
50
  const actions = {
55
- auth({ commit }) {
56
- const publicToken = localStorage.getItem('publicToken');
57
- if(publicToken && !isTokenExpired(publicToken)) return;
58
-
59
- return $http
60
- .post("api/oauth/token", {
61
- grant_type: process.env.VUE_APP_GRANT_TYPE || window.dynamicData.VUE_APP_GRANT_TYPE,
62
- client_id: process.env.VUE_APP_CLIENT_ID || window.dynamicData.VUE_APP_CLIENT_ID,
63
- client_secret: process.env.VUE_APP_CLIENT_SECRET || window.dynamicData.VUE_APP_CLIENT_SECRET
64
- })
65
- .then(res => {
66
- commit('setPublicToken', res.data.data.access_token)
67
- window.localStorage.setItem("publicToken", res.data.data.access_token);
68
- })
69
- .catch(
70
- commonErrorCallback()
71
- );
51
+ auth({ }) {
52
+ console.warn('auth/auth action is deprecated. No need to call');
72
53
  },
73
54
  login({ commit, dispatch }, authData) {
74
55
  var data = { ...authData };