login.ts 1.74 KB
Newer Older
Maxym Borodenko's avatar
Maxym Borodenko committed
1
2
3
4
5
6
import { LoginService } from 'service/LoginService';
import * as Constants from 'constants/login';
import * as cookies from 'es-cookie';
import { clearCookies, saveCookies } from 'utilities';
import { ROLE_CLIENT } from 'constants/userRoles';
import {log} from 'utilities/debug';
7
import {loginUser} from 'user/actions/public';
8
import { configureBackendApi } from 'utilities/requestUtils';
Maxym Borodenko's avatar
Maxym Borodenko committed
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

export function checkAccessTokens(dispatch) {
    const cookieToken: string = typeof window !== 'undefined' && cookies.get('access_token');

    const applicationLogin = () =>
        LoginService.loginApp()
            .then((data) => {
                saveCookies({access_token: data.access_token, authorities: [ROLE_CLIENT]});
                dispatch(loginApp(data));
            })
            .catch((error) => {
                log('Something went wrong', error);
            });

    if (cookieToken) {
        return LoginService.checkToken(cookieToken)
            .then((data) => {
                dispatch(loginUser({ access_token: cookieToken, ...data }));
                return true;
            })
            .catch((error) => {
                clearCookies();
                return applicationLogin();
            });
    } else {
        clearCookies();
        return applicationLogin();
    }
}

function loginAppRequest() {
    return (dispatch) => {
        return LoginService.loginApp()
            .then((data) => {
                return dispatch(loginApp(data));
            });
    };
}

function loginApp(d) {
49
50
    // console.log('Login app', d);
    configureBackendApi({ accessToken: d.access_token });
Maxym Borodenko's avatar
Maxym Borodenko committed
51
52
53
54
55
56
57
58
59
    return {
        type: Constants.LOGIN_APP,
        authorities: [ROLE_CLIENT],
        ...d,
    };
}


export {
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
60
    loginAppRequest, loginApp,
Maxym Borodenko's avatar
Maxym Borodenko committed
61
};