# Code coverage report for atlas-mobile-ts/src/hooks/useAuth.ts

# All files / atlas-mobile-ts/src/hooks useAuth.ts

0% Statements 0/59
0% Branches 0/5
0% Functions 0/5
0% Lines 0/58

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
    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
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136

     ﻿/* Copyright (C) Click & Push Accessibility, Inc - All Rights Reserved
     * Unauthorized copying of this file, via any medium is strictly prohibited
     * Proprietary and confidential
     * Written and maintained by the Click & Push Development team
     * <dev@clicknpush.ca>, January 2022
     */

    import axios, { AxiosRequestConfig, AxiosError } from "axios";
    import { API_URL, reportAxiosError } from "../utils/RequestUtils";
    import { authStore, IdToken } from "../libs/auth/AuthStore";
    import jwtDecode from "jwt-decode";
    import * as SecureStore from 'expo-secure-store'
    import { SECURESTORE_ACCESSTOKEN } from "../utils/GlobalUtils";

    /**
     * Hook that exposes common authentication logic.
     * @category Hooks
     * @namespace useAuth
     */
    export const useAuth = () => {
        /**
         * Logs out the user
         * @memberOf useAuth
         */
        const logout = async () => {
            try {
                const tokenParams = new URLSearchParams();
                tokenParams.append('client_id', 'atlas.mobile');
                tokenParams.append('token', authStore.accessToken as string);

                const response = await axios.post(API_URL + `/o/revoke-token/`, tokenParams, {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                });

                await authStore.setAccessTokenAsync(null);
                await authStore.setRefreshTokenAsync(null);
                await authStore.setNotificationTokenAsync(null);
                await authStore.setIdAsync(null);
            } catch (error) {
                reportAxiosError("Something went wrong when retrieving access token", error);
            }
        }

        const getNotificationTokenFromServer = async () => {
            const config: AxiosRequestConfig = {
                method: 'GET',
                url: API_URL + `/api/notif-token/${authStore.userId}/`,
                headers: { "Authorization": "Bearer " + authStore.accessToken, }
            }

            try {
                const response = await axios(config);
                return response.data;
            } catch (error) {
                Iif (error.response.status == 401) {
                    try {
                        await refreshAccessToken()
                        const response = await axios({...config, headers: { "Authorization": "Bearer " + authStore.accessToken }});

                        return response.data;
                    } catch (error) {
                        // refreshAccessToken will report errors
                    }
                }

                reportAxiosError('Something went wrong when retrieving landmarks', error)
                throw new Error;
            }
        }

        const ensureNotificationTokenExistsOnServer = async (notificationToken: string, retries: number) => {
            if (retries > 0) {
                const config: AxiosRequestConfig = {
                    method: 'POST',
                    data: {token: notificationToken},
                    url: API_URL + `/api/notif-token/${authStore.userId}/`,
                    headers: { "Authorization": "Bearer " + authStore.accessToken, }
                }
                try {
                    const response = await axios(config);
                    return response.data;
                } catch (error) {
                    Iif (error.response.status == 401) {
                        try {
                            await refreshAccessToken()
                            const response = await axios({...config, headers: { "Authorization": "Bearer " + authStore.accessToken }});

                            return response.data;
                        } catch (error) {
                            // refreshAccessToken will report errors
                        }
                    }
                    reportAxiosError('Something went wrong when retrieving landmarks', error)
                }

                ensureNotificationTokenExistsOnServer(notificationToken, retries - 1)
            }
            else {
                throw new Error;
            }
        }

        /**
         * 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 () => {
            Iif (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');
                    console.log('[Authentication]: Attempting to refresh token...')
                    const { data: refreshResponseData } = await axios.post(API_URL + "/o/token/", tokenData, {
                        headers: { 'Content-Type': "application/x-www-form-urlencoded" }
                    });

                    const idToken = jwtDecode(refreshResponseData.id_token) as IdToken;
                    await authStore.setIdAsync(idToken.sub);
                    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("[Authentication]: Error when trying to refresh access token", error);
                }
            }
        }

        return { refreshAccessToken, logout, getNotificationTokenFromServer, ensureNotificationTokenExistsOnServer }
    }