All files / atlas/src/hooks useAuth.ts

21.43% Statements 3/14
0% Branches 0/2
50% Functions 1/2
21.43% Lines 3/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                  6x           8x                                           8x  
import axios from "axios";
import { API_URL, reportAxiosError } from "../globals";
import { authStore } from "../stores/AuthStore";
 
/**
 * Hook that exposes common authentication logic.
 * @category Hooks
 * @namespace useAuth
 */
export const useAuth = () => {
    /**
     * If there is a refresh token available, attempts to use it to obtain a new, valid access token.
     * Used in {@link Atlas}
     * @memberOf useAuth
     */
    const refreshAccessToken = async () => {
        if (authStore.refreshToken) {
            try {
                const tokenData = new URLSearchParams();
                tokenData.append('grant_type', 'refresh_token');
                tokenData.append('refresh_token', authStore.refreshToken);
                tokenData.append('client_id', 'atlas.mobile');
                const { data: refreshResponseData } = await axios.post(API_URL + "/o/token/", tokenData, {
                    headers: { 'Content-Type': "application/x-www-form-urlencoded" }
                });   
 
                await authStore.setRefreshTokenAsync(refreshResponseData.refresh_token);
                await authStore.setAccessTokenAsync(refreshResponseData.access_token);
 
                console.info('Successfully refreshed access token, re-attempting initial request...')
            }
            catch (error) {
                reportAxiosError("Error when trying to refresh access token", error);            
            }
        }
    }
 
    return { refreshAccessToken }
}