|
| 1 | +export const httpClient = () => { |
| 2 | + const { token } = JSON.parse(localStorage.getItem('auth')) || {}; |
| 3 | + return { Authorization: `Bearer ${token}` }; |
| 4 | +}; |
| 5 | + |
| 6 | +export const authProvider = { |
| 7 | + // authentication |
| 8 | + login: ({ username, password }) => { |
| 9 | + const request = new Request( |
| 10 | + process.env.REACT_APP_API_URL + '/users/login', |
| 11 | + { |
| 12 | + method: 'POST', |
| 13 | + body: JSON.stringify({ email: username, password }), |
| 14 | + headers: new Headers({ 'Content-Type': 'application/json' }), |
| 15 | + } |
| 16 | + ); |
| 17 | + return fetch(request) |
| 18 | + .then((response) => { |
| 19 | + if (response.status < 200 || response.status >= 300) { |
| 20 | + throw new Error(response.statusText); |
| 21 | + } |
| 22 | + return response.json(); |
| 23 | + }) |
| 24 | + .then((auth) => { |
| 25 | + localStorage.setItem( |
| 26 | + 'auth', |
| 27 | + JSON.stringify({ ...auth, fullName: username }) |
| 28 | + ); |
| 29 | + }) |
| 30 | + .catch(() => { |
| 31 | + throw new Error('Network error'); |
| 32 | + }); |
| 33 | + }, |
| 34 | + checkError: (error) => { |
| 35 | + const status = error.status; |
| 36 | + if (status === 401 || status === 403) { |
| 37 | + localStorage.removeItem('auth'); |
| 38 | + return Promise.reject(); |
| 39 | + } |
| 40 | + // other error code (404, 500, etc): no need to log out |
| 41 | + return Promise.resolve(); |
| 42 | + }, |
| 43 | + checkAuth: () => |
| 44 | + localStorage.getItem('auth') |
| 45 | + ? Promise.resolve() |
| 46 | + : Promise.reject({ message: 'login required' }), |
| 47 | + logout: () => { |
| 48 | + localStorage.removeItem('auth'); |
| 49 | + return Promise.resolve(); |
| 50 | + }, |
| 51 | + getIdentity: () => { |
| 52 | + try { |
| 53 | + const { id, fullName, avatar } = JSON.parse(localStorage.getItem('auth')); |
| 54 | + return Promise.resolve({ id, fullName, avatar }); |
| 55 | + } catch (error) { |
| 56 | + return Promise.reject(error); |
| 57 | + } |
| 58 | + }, |
| 59 | + getPermissions: (params) => Promise.resolve(), |
| 60 | +}; |
0 commit comments