All files / app/login loginPage.tsx

0% Statements 0/240
100% Branches 1/1
100% Functions 1/1
0% Lines 0/240

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 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
'use client';
 
import {
  useCallback, useContext, useEffect, useState
} from 'react';
import Button from 'react-bootstrap/Button';
import Col from 'react-bootstrap/Col';
import Form from 'react-bootstrap/Form';
import InputGroup from 'react-bootstrap/InputGroup';
import Row from 'react-bootstrap/Row';
import Spinner from 'react-bootstrap/Spinner';
 
import {
  GetLoginCodeApi, SubmitLoginCodeApi
} from '@/types/api/auth';
import { getLogger } from '@/utils/common/logger';
import { formatPhone } from '@/utils/common/strings';
import {
  AddAlertContext, LocationContext, LoggedInUserContext, RefreshLoggedInUserContext
} from '@/utils/frontend/clientContexts';
import { typeFetch } from '@/utils/frontend/typeFetch';
 
const logger = getLogger('loginPage');
 
export default function LoginPage() {
  const user = useContext(LoggedInUserContext);
  const loc = useContext(LocationContext);
  const reCheckUser = useContext(RefreshLoggedInUserContext);
  const addAlert = useContext(AddAlertContext);
 
  const [
    loginState,
    setLoginState,
  ] = useState<{
    phone?: string;
    authCode?: string;
    stage: 'phone' | 'code';
  }>({
    stage: 'phone',
  });
 
  const [
    errorFields,
    setErrorFields,
  ] = useState<string[]>([]);
 
  const handleRedirectAction = useCallback(async () => {
    if (loc === null) {
      return;
    }
 
    // Refresh the user
    await reCheckUser();
 
    // Check for the query string
    const urlParams = new URLSearchParams(loc.search);
    const destination = urlParams.get('redirectTo') || '/';
 
    const validRedirects = [
      '/users/',
      '/status/',
      '/profile/',
      '/texts/',
      '/weather/',
      '/pages/',
    ];
    if (validRedirects.includes(destination)) {
      window.location.assign(destination);
    } else if (validRedirects.includes(`${destination}/`)) {
      window.location.assign(`${destination}/`);
    } else {
      window.location.assign('/');
    }
  }, [
    loc,
    reCheckUser,
  ]);
 
  const [
    isCodeLoading,
    setIsCodeLoading,
  ] = useState(false);
  const getCode = useCallback(async () => {
    // Check for a valid phone number
    if (
      !loginState.phone ||
      !(/^[0-9]{10}$/).test(loginState.phone)
    ) {
      setErrorFields([ 'phone', ]);
      return;
    }
 
    setErrorFields([]);
    setIsCodeLoading(true);
    try {
      const apiParams: GetLoginCodeApi['params'] = {
        id: Number(loginState.phone),
      };
      const [
        code,
        apiResult,
      ] = await typeFetch<GetLoginCodeApi>({
        path: '/api/v2/login/{id}/',
        method: 'GET',
        params: apiParams,
      });
      if (
        code !== 200 ||
        apiResult === null ||
        (
          'message' in apiResult &&
          apiResult.message !== 'Success'
        )
      ) {
        throw {
          code,
          apiResult,
        };
      }
 
      setLoginState(state => ({
        ...state,
        stage: 'code',
      }));
    } catch (e) {
      logger.error(`Failed to get code for ${loginState}`, e);
      addAlert('danger', 'Failed to get a code for this user');
      setErrorFields([ 'phone', ]);
    }
    setIsCodeLoading(false);
  }, [
    loginState,
    addAlert,
  ]);
 
  const [
    isLoginLoading,
    setIsLoginLoading,
  ] = useState(false);
  const submitCode = useCallback(async () => {
    // Validate the phone number and code
    const invalidFields: string[] = [];
    if (!loginState.phone || loginState.phone.length !== 10) {
      invalidFields.push('phone');
    }
    if (!loginState.authCode || loginState.authCode.length !== 6) {
      invalidFields.push('code');
    }
    if (invalidFields.length > 0) {
      setErrorFields(invalidFields);
      return;
    }
 
    setErrorFields([]);
    setIsLoginLoading(true);
    try {
      const apiParams: SubmitLoginCodeApi['params'] = {
        id: Number(loginState.phone),
      };
      const body: SubmitLoginCodeApi['body'] = {
        code: loginState.authCode || '',
      };
      const [
        code,
        apiResult,
      ] = await typeFetch<SubmitLoginCodeApi>({
        path: '/api/v2/login/{id}/',
        method: 'POST',
        params: apiParams,
        body,
      });
      if (
        code !== 200 ||
        apiResult === null ||
        'message' in apiResult
      ) {
        throw {
          code,
          apiResult,
        };
      }
 
      handleRedirectAction();
    } catch (e) {
      logger.error(`Failed to login with ${loginState}`, e);
      addAlert('danger', 'Authentication failed');
      setErrorFields([ 'code', ]);
    }
    setIsLoginLoading(false);
  }, [
    loginState,
    handleRedirectAction,
    addAlert,
  ]);
 
  useEffect(() => {
    if (user && user.isUser) {
      handleRedirectAction();
    }
  }, [
    user,
    handleRedirectAction,
  ]);
 
  return <>
    {user && user.isUser && <h1 className='text-center'>You are already logged in</h1>}
    {user && !user.isUser && loc && <>
      <Row className='justify-content-center my-3'>
        <Col md={6}><InputGroup>
          <InputGroup.Text>Phone Number</InputGroup.Text>
          <Form.Control
            type='text'
            value={formatPhone(loginState.phone || '')}
            onChange={e => setLoginState(state => ({
              ...state,
              phone: e.target.value.replace(/[^0-9]/g, ''),
            }))}
            onKeyUp={e => {
              if (e.key === 'Enter') {
                getCode();
              }
            }}
            isInvalid={errorFields.includes('phone')}
          />
        </InputGroup></Col>
      </Row>
      {loginState.stage === 'code' && <Row className='justify-content-center my-3'>
        <Col md={6}><InputGroup>
          <InputGroup.Text>Authentication Code</InputGroup.Text>
          <Form.Control
            type='text'
            value={loginState.authCode || ''}
            onChange={e => setLoginState(state => ({
              ...state,
              authCode: e.target.value.replace(/[^0-9]/g, ''),
            }))}
            onKeyUp={e => {
              if (e.key === 'Enter') {
                submitCode();
              }
            }}
            isInvalid={errorFields.includes('code')}
          />
        </InputGroup></Col>
      </Row>}
      <Row className='justify-content-center my-3'>
        <Col as={Row} md={6}>
          {loginState.stage === 'phone' && <Col className='d-grid'>
            <Button
              variant='success'
              onClick={getCode}
              disabled={isCodeLoading}
            >{isLoginLoading && <Spinner size='sm' />} Request Code</Button>
          </Col>}
          {loginState.stage === 'code' && <>
            <Col className='d-grid' xs={6}>
              <Button
                variant='success'
                onClick={submitCode}
                disabled={isLoginLoading}
              >{isLoginLoading && <Spinner size='sm' />} Submit Code</Button>
            </Col>
            <Col className='d-grid' xs={6}>
              <Button
                variant='warning'
                onClick={getCode}
                disabled={isCodeLoading}
              >{isCodeLoading && <Spinner size='sm' />} Get New Code</Button>
            </Col>
          </>}
        </Col>
      </Row>
    </>}
  </>;
}