checkAuthToken.ts 1.98 KB
Newer Older
1
import { checkTokenRequest, loginAppRequest, loginUser } from 'actions/login';
2
import ApiError from 'model/ApiError';
Valeriy Panov's avatar
Valeriy Panov committed
3
4
5
6

function checkAuthTokenRequest(req, dispatch) {
    const token = req.cookies.access_token;
    if (token) {
7
        console.log('Checking cookie token', token);
Valeriy Panov's avatar
Valeriy Panov committed
8
        return dispatch(checkTokenRequest(token))
9
10
11
12
            .then((checkedToken) => {
                console.log(`User token ${token} is valid, response`, checkedToken);
                return dispatch(loginUser(checkedToken));
            })
13
14
            .catch((err) => {
                console.log('Cookie check failed, dispatching loginAppRequest', ApiError.axiosError(err));
Valeriy Panov's avatar
Valeriy Panov committed
15
16
17
                return dispatch(loginAppRequest());
            });
    } else {
18
        console.log('No token in cookie, dispatching loginAppRequest');
Valeriy Panov's avatar
Valeriy Panov committed
19
20
21
22
23
        return dispatch(loginAppRequest());
    }
}

export default function checkAuthToken(req, res, dispatch) {
Valeriy Panov's avatar
Valeriy Panov committed
24
    console.log('Init checkAuthToken method');
Valeriy Panov's avatar
Valeriy Panov committed
25
26
    return checkAuthTokenRequest(req, dispatch)
        .then((data) => {
27
28
            console.log(`Setting cookie to expire in ${(data.exp || data.expires_in) / 60}min from`, data);
            res.cookie('access_token', data.access_token, { path: '/', expires: new Date(data.exp * 1000 || new Date().getTime() + ((data.expires_in * 1000) || (/* 1hr */ 1000 * 60 * 60))) });
29
            if (data.authorities) {
30
                res.cookie('authorities', JSON.stringify(data.authorities), { path: '/', expires: new Date(data.exp * 1000 || new Date().getTime() + ((data.expires_in * 1000) || (/* 1hr */ 1000 * 60 * 60))) });
31
            } else {
32
                res.clearCookie('authorities');
33
34
            }
            return data;
35
36
        }).catch((err) => {
            console.log('Failed checkAuthToken, clearing cookies', ApiError.axiosError(err));
37
38
            res.clearCookie('access_token');
            res.clearCookie('authorities');
39
            return Promise.reject({ message: 'Could not authenticate against the API.' });
40
        });
Valeriy Panov's avatar
Valeriy Panov committed
41
}