-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathauth.js
70 lines (57 loc) · 1.43 KB
/
auth.js
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
61
62
63
64
65
66
67
68
69
70
import { take, call, put } from 'redux-saga/effects';
import {
fetchLoginState,
failFetchingLoginState,
fetchUser,
failFetchingUser,
login,
clickLogout,
logout
} from '../actions/auth';
import superFetch from '../modules/superFetch';
export function* handleFetchLoginState() {
while (true) {
yield take(`${fetchLoginState}`);
const jwt = localStorage.getItem('jwt');
if (jwt) {
const { payload, err } = yield call(superFetch, {
url: '/api/login/',
type: 'GET',
custom: {
headers: {
authorization: `Bearer ${jwt}`
}
}
});
if (payload && !err) {
yield put(login(Object.assign({}, payload[0], { jwt })));
continue;
}
}
yield put(failFetchingLoginState());
}
}
export function* handleLogin() {
while (true) {
const action = yield take(`${fetchUser}`);
const { payload, err } = yield call(superFetch, {
url: '/api/login/',
type: 'POST',
data: action.payload
});
if (!payload && err) {
yield put(failFetchingUser(String(err).split('Error: ')[1]));
continue;
}
const jwt = payload[0].jsonWebToken;
localStorage.setItem('jwt', jwt);
yield put(login(Object.assign({}, payload[0], { jwt })));
}
}
export function* handleLogout() {
while (true) {
yield take(`${clickLogout}`);
localStorage.removeItem('jwt');
yield put(logout());
}
}