# All files / atlas-mobile-ts/src/components/Auth Intro.tsx

0% Statements 0/37
0% Branches 0/5
0% Functions 0/6
0% Lines 0/36

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
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164

     ﻿/* 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 from "axios";
    import { loadAsync, makeRedirectUri, ResponseType } from "expo-auth-session";
    import * as WebBrowser from 'expo-web-browser';
    import { maybeCompleteAuthSession } from "expo-web-browser";
    import jwt_decode from 'jwt-decode';
    import React, { useState } from "react";
    import { ActivityIndicator, Image, StyleSheet, Text, TouchableOpacity, View } from "react-native";
    import { UnAuthStackNavigationProp } from "../../navigation/UnauthorizedNavigator";
    import { authStore, IdToken } from "../../libs/auth/AuthStore";
    import {authenticate} from '../../libs/auth/core'
    import { API_URL } from "../../utils/RequestUtils";
    import { PrimaryButton, SecondaryButton } from "../Buttons";
    import UnauthorizedLayout from "./AuthLayout";
    import { testTag } from "../../utils/GlobalUtils";

    /**
     * Props used by the {@link Intro} screen.
     */
    export interface IntroProps {
        /**The {@link AuthStackNavigationProp} navigation object used to interact with the {@link Auth} navigator.*/
        navigation: UnAuthStackNavigationProp;
    }

    /**
     * A base url for the api's authorization endpoints
     */
    const issuer = API_URL + "/o";

    /**
     * An object containing the discovery endpoints for the api, necessary for OIDC authentication {@link https://swagger.io/docs/specification/authentication/openid-connect-discovery/}
     */
    const discovery = {
        authorizationEndpoint: issuer + "/authorize/",
        tokenEndpoint: issuer + "/token/",
        revocationEndpoint: issuer + "/revoke/",
    };

    /**
     * Creates a browser session through which the user will login
     */
    maybeCompleteAuthSession();

    /**
     * The Intro screen displayed to unauthenticated users. Contains necessary methods to facilitate login and navigation to the [Registration]{@link RegisterMain} screens.
     * @component
     * @category Unauthorized
     */
    const Intro : React.FC<IntroProps> = ({navigation}) => {
        /**
         * @type {string}
         * React state holding the login result message to display to the user.
         * */
        const loginMessageState = "";
        const [loginMessage, setLoginMessage] = useState<string>(loginMessageState);
        /**
         * @type {boolean}
         * React state holding the error state of the component.
         * */
         const errorState = false;
        const [error, setError] = useState<boolean>(errorState);

        const redirectUri = makeRedirectUri({
            path: 'callback'
        });

        /**
         * Function that initiates the login flow. It opens up with the in app browser and sends an authorization request to the API, which redirects the user to the backend login page.
         * If the credentials entered are valid, the OAuth Authorization Code flow will occur, which results in the user recieving an access token and refresh token which are then stored in {@link AuthStore}.
         * */
        const login = async () => {
            setLoginMessage("Logging you in...");

            const result = await authenticate({
                clientId: "atlas.mobile",
                responseType: ResponseType.Code,
                redirectUri,
                usePKCE: true,
                scopes: ['openid'],

            }, discovery)

            Iif (result.errorMessage) {
                setError(true)
                setLoginMessage(result.errorMessage)
            }
        }

        /**
         * Navigates to {@link RegisterMain}.
         */
        const goToRegistration = (): void => {
            console.log('[Navigation]: Navigating to registration page.')
            navigation.navigate("Register");
        }

        /**
         * Opens up the [privacy policy page]{@link https://app.clicknpush.ca/privacy}.
         */
        const openPrivacyPolicy = async () => {
            console.log('[Navigation]: Opening privacy policy.')
            await WebBrowser.openBrowserAsync(API_URL + "/privacy")
        }

        return (
            <UnauthorizedLayout>
                {!loginMessage ?
                <View style={styles.introContainer}>
                    <View style={styles.brandContainer}>
                        <Image style={{flex: 1}} resizeMode="contain" source={require('../../../assets/logo-white.png')}></Image>
                        <Text style={styles.title} >Click & Push</Text>
                    </View>
                    <View style={styles.btnContainer}>
                        <PrimaryButton accessibilityLabel="introLoginBtn" text="Login" onPress={login}/>
                        <SecondaryButton accessibilityLabel="introRegisterBtn" text="Create account" onPress={goToRegistration} />
                    </View>
                </View> :
                <View style={{height: '100%', justifyContent: "center", alignItems: "center"}}>
                    <Text style={{color: 'white', fontSize: 20, marginBottom: 30}}>{loginMessage}</Text>
                    {!error ? <ActivityIndicator { ...testTag("introSpinner")} color='white' size="large"/> : <PrimaryButton { ...testTag("introOkayBtn")} text="Okay" onPress={() => {setError(false); setLoginMessage('')}}/> }
                </View> }
                <TouchableOpacity { ...testTag("introPrivacyBtn")} onPress={async () => await openPrivacyPolicy()}>
                    <Text style={{fontSize: 12, textDecorationLine: "underline", alignSelf: "flex-end", color: 'white'}}>Privacy policy</Text>
                </TouchableOpacity>
            </UnauthorizedLayout>
        )
    }

    const styles = StyleSheet.create({
        introContainer: {
            flex: 1,
            marginVertical: 50,
            alignItems: "center",
            justifyContent: 'space-between'
        },
        brandContainer: {
            flex: 2,
            marginVertical: 50,
            alignItems: "center",
        },
        title: {
            marginTop: 30,
            color: 'white',
            fontSize: 30
        },
        btnContainer: {
            flex: 1,
            alignItems: 'center',
            width: '100%',
        },
        registerBtn: {
            borderColor: 'white',
            borderWidth: 2,
            backgroundColor: 'transparent',
        }
    })

    export default Intro;