All files / modules/10-common/pages/login LoginPage.tsx

85.71% Statements 24/28
25% Branches 1/4
66.67% Functions 2/3
85.71% Lines 24/28

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              1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                     1x 1x 1x 1x 1x 1x   1x 1x                                                                                                 1x       1x   1x                                                                                         1x  
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import React, { useState, useEffect } from 'react'
import { useHistory, Link } from 'react-router-dom'
import { FormInput, Formik, FormikForm, Button, Text, Container, HarnessIcons, Layout } from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { useToaster } from '@common/components'
import AppStorage from 'framework/utils/AppStorage'
import { useStrings } from 'framework/strings'
import routes from '@common/RouteDefinitions'
import { useQueryParams } from '@common/hooks'
import AuthLayout from '@common/components/AuthLayout/AuthLayout'
import AuthFooter, { AuthPage } from '@common/components/AuthLayout/AuthFooter/AuthFooter'
import { getConfig } from 'services/config'
 
interface LoginForm {
  email: string
  password: string
}
 
interface LoginQueryParams {
  returnUrl?: string
  errorCode?: string
}
 
// TODO: add coverage once the correct API is integrated
/* istanbul ignore next */
const createAuthToken = (login: string, password: string): string => {
  const encodedToken = btoa(login + ':' + password)
  return `Basic ${encodedToken}`
}
 
const LoginPage: React.FC = () => {
  const history = useHistory()
  const [isLoading, setLoading] = useState(false)
  const { getString } = useStrings()
  const { showError } = useToaster()
  const { returnUrl, errorCode } = useQueryParams<LoginQueryParams>()
 
  useEffect(() => {
    Iif (localStorage.getItem('samlTestResponse') === 'testing') {
      if (errorCode === 'samltestsuccess') {
        localStorage.setItem('samlTestResponse', 'true')
      } else {
        localStorage.setItem('samlTestResponse', 'false')
      }
    }
  }, [errorCode])
 
  // TODO: add coverage once the correct API is integrated
  /* istanbul ignore next */
  const handleLogin = async (data: LoginForm): Promise<void> => {
    try {
      setLoading(true)
      // hacky/temporary fetch call
      const response = await fetch(getConfig('api/users/login'), {
        method: 'POST',
        headers: {
          accept: 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          authorization: createAuthToken(data.email, data.password)
        })
      })
      setLoading(false)
      if (response.ok) {
        const json = await response.json()
 
        AppStorage.set('token', json.resource.token)
        AppStorage.set('acctId', json.resource.defaultAccountId)
        AppStorage.set('uuid', json.resource.uuid)
        AppStorage.set('lastTokenSetTime', +new Date())
 
        // this is naive redirect for now
        if (returnUrl) {
          window.location.href = returnUrl
        } else {
          history.push(routes.toHome({ accountId: json.resource.defaultAccountId }))
        }
      } else {
        throw response
      }
    } catch (e) {
      setLoading(false)
      showError(e?.statusText)
    }
  }
 
  const handleSubmit = (data: LoginForm): void => {
    handleLogin(data)
  }
 
  const HarnessLogo = HarnessIcons['harness-logo-black']
 
  return (
    <>
      <AuthLayout>
        <Container flex={{ justifyContent: 'space-between', alignItems: 'center' }} margin={{ bottom: 'xxxlarge' }}>
          <HarnessLogo height={25} />
        </Container>
        <Text font={{ size: 'large', weight: 'bold' }} color={Color.BLACK}>
          {getString('signUp.signIn')}
        </Text>
        <Text font={{ size: 'medium' }} color={Color.BLACK} margin={{ top: 'xsmall' }}>
          {getString('signUp.message.secondary')}
        </Text>
 
        <Container margin={{ top: 'xxxlarge' }}>
          <Formik<LoginForm>
            initialValues={{ email: '', password: '' }}
            formName="loginPageForm"
            onSubmit={handleSubmit}
          >
            <FormikForm>
              <FormInput.Text name="email" label={getString('signUp.form.emailLabel')} disabled={isLoading} />
              <FormInput.Text
                name="password"
                label={getString('password')}
                inputGroup={{ type: 'password' }}
                disabled={isLoading}
              />
              <Button type="submit" intent="primary" loading={isLoading} disabled={isLoading} width="100%">
                {getString('signUp.signIn')}
              </Button>
            </FormikForm>
          </Formik>
        </Container>
 
        <AuthFooter page={AuthPage.SignIn} />
 
        <Layout.Horizontal margin={{ top: 'xxxlarge' }} spacing="xsmall">
          <Text>{getString('signUp.noAccount')}</Text>
          <Link to={routes.toSignup()}>{getString('getStarted')}</Link>
        </Layout.Horizontal>
      </AuthLayout>
    </>
  )
}
 
export default LoginPage