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