All files CognitoLogin.tsx

81.4% Statements 105/129
52.24% Branches 35/67
96.55% Functions 28/29
80.53% Lines 91/113
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 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 3402x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x                                               2x         15x 15x                           15x 15x 15x 15x 15x 15x 15x 15x     15x 4x 4x 4x   4x       4x                           4x     4x 4x       4x     15x 1x 1x     1x 1x     15x 1x 1x       1x 1x     15x 1x 1x 1x       1x   1x       1x 1x     15x 1x 1x         1x         1x     15x 1x 1x 1x   1x     15x 1x         1x 1x                             15x 1x               1x   1x         1x   1x     15x 2x 2x 2x   2x           38x     38x                             2x                     1x                                                   1x                     1x                                         1x 1x           1x                           1x 1x                         2x  
import React from 'react';
import { View, Alert, AlertButton } from 'react-native';
import LoginForm from './LoginForm';
import { Colors, CrossButton, CrossLabel } from 'react-native-cross-components';
import { CognitoAuthState, IAuthenticationResult } from '../../types';
import { CognitoUserInputContext } from '../../contexts';
import { OnLogin } from '../../events/OnLogin';
import _ from 'lodash';
import RegisterForm from '../../register/components/RegisterForm';
import { ForgotForm } from '../../forgot/components/ForgotForm';
import { ConfirmForm } from '../../confirm/components/ConfirmForm';
import { OnRegister } from '../../events/OnRegister';
import styles from '../../styles';
import OnConfirmMfaCode from '../../events/OnConfirmMfaCode';
import OnConfirmAccount from '../../events/OnConfirmAccount';
import OnResendSignup from '../../events/OnResendSignup';
import { ICognitoLoginProps } from './ICognitoLoginProps';
import { LoginCurrentForm } from './LoginCurrentForm';
import { ICognitoLoginState } from './ICognitoLoginState';
 
/**
 * A form for logging in to AWS Cognito through Amplify.
 *
 * On successful login the {@link ICognitoLoginProps.onLoggedIn} event is triggered.
 *
 * Remarks:
 * * Requires Amplify to be configured:
 *
 * https://aws-amplify.github.io/docs/js/start?ref=amplify-rn-btn&platform=react-native#step-4-integrate-aws-resources
 *
 * Props are {@link ICognitoLoginProps}
 *
 * @example
 *  <CognitoLogin
 *    onLoggedIn={(user) => console.log(user)}
 *     loginButtonProps={{title: 'Engage'}}>
 *     <Text>Custom layouts here</Text>
 *  </CognitoLogin>
 */
export class CognitoLogin extends React.Component<
  ICognitoLoginProps,
  ICognitoLoginState
> {
  constructor(props: ICognitoLoginProps) {
    super(props);
    this.state = {
      result: undefined,
      userInput: __DEV__
        ? {
            email: 'cogtest@mailinator.com',
            password: 'Password1#',
            phone: '+46730555252',
          }
        : { email: undefined, password: undefined },
      formState: 'Login',
      code: undefined,
      message: undefined,
    };
 
    this.onEmailChanged = this.onEmailChanged.bind(this);
    this.onPasswordChanged = this.onPasswordChanged.bind(this);
    this.onPhoneChanged = this.onPhoneChanged.bind(this);
    this.onConfirmMFACode = this.onConfirmMFACode.bind(this);
    this.onConfirmAccount = this.onConfirmAccount.bind(this);
    this.onLogin = this.onLogin.bind(this);
    this.onResultChanged = this.onResultChanged.bind(this);
    this.OnResendSignup = this.OnResendSignup.bind(this);
  }
 
  onResultChanged = () => {
    let form: LoginCurrentForm = 'Login';
    const result = this.state.result as IAuthenticationResult;
    const authState: CognitoAuthState = _.get(this.state, ['result', 'state']);
 
    Iif (!authState) {
      return;
    }
 
    switch (authState) {
      case 'Authenticated':
        form = 'Login';
        if (result && result.user && this.props.onLoggedIn) {
          this.props.onLoggedIn(result.user);
        }
        break;
      case 'ConfirmAccountCodeWaiting':
        form = 'ConfirmAccount';
        break;
      case 'ConfirmLoginMFAWaiting':
        form = 'ConfirmMFALogin';
        break;
      default:
        break;
    }
 
    let { message } = this.state;
    Iif (authState === 'Authenticated') {
      message = 'Logged in!';
    }
 
    this.setState({ formState: form, message });
  };
 
  onEmailChanged = (email: string | undefined) => {
    const { userInput } = this.state;
    Iif (_.isNil(email)) {
      return;
    }
    userInput.email = email;
    this.setState({ userInput });
  };
 
  onPasswordChanged = (password: string | undefined) => {
    const { userInput } = this.state;
    Iif (_.isNil(password)) {
      return;
    }
 
    userInput.password = password;
    this.setState({ userInput });
  };
 
  onPhoneChanged = (phone: string | undefined) => {
    const { userInput } = this.state;
    let newPhone = phone;
    Iif (_.isNil(newPhone)) {
      return;
    }
 
    newPhone = newPhone.replace(' ', '').trim();
 
    Iif (!newPhone.startsWith('+')) {
      newPhone = '+' + newPhone;
    }
 
    userInput.phone = newPhone;
    this.setState({ userInput });
  };
 
  OnResendSignup = () => {
    const { email } = this.state.userInput;
    Iif (_.isNil(email)) {
      this.setState({ message: 'Please enter username' });
      return;
    }
 
    const sendButton: AlertButton = {
      text: 'OK',
      onPress: () => OnResendSignup(email),
    };
 
    Alert.alert('Confirm', 'Re-send code?', [sendButton], { cancelable: true });
  };
 
  onRegister = async () => {
    Eif (__DEV__) console.log('***** onRegister ***** ');
    const result = await OnRegister(this.state.userInput);
    Eif (__DEV__) console.log('**** onRegister result: ', result);
 
    this.setState({ result }, this.onResultChanged);
  };
 
  onConfirmAccount = async () => {
    Eif (
      _.isNil(this.state.code) ||
      this.state.code === '' ||
      _.isNil(this.state.userInput.email)
    ) {
      this.setState({ message: 'Need code and user e-mail' });
      return;
    }
 
    if (__DEV__) console.log('***** onConfirmAccount ***** ');
 
    const result = await OnConfirmAccount(
      this.state.code,
      this.state.userInput.email
    );
 
    if (__DEV__) console.log('**** onConfirmAccount result: ', result);
 
    this.setState({ result, formState: 'Login' }, this.onResultChanged);
  };
 
  onConfirmMFACode = async () => {
    Iif (
      _.isNil(this.state.code) ||
      this.state.code === '' ||
      _.isNil(this.state.userInput.email)
    ) {
      return;
    }
 
    Eif (__DEV__) console.log('***** onConfirmMFACode ***** ');
 
    const result = await OnConfirmMfaCode(
      this.state.code,
      this.state.userInput.email
    );
 
    Eif (__DEV__) console.log('**** onConfirmMFACode result: ', result);
 
    this.setState({ result }, this.onResultChanged);
  };
 
  onLogin = async () => {
    Eif (__DEV__) console.log('***** onLogin ***** ');
    const result = await OnLogin(this.state.userInput);
    Eif (__DEV__) console.log('**** onLogin result: ', result);
 
    this.setState({ result }, this.onResultChanged);
  };
 
  render() {
    // Extract error message. Could be an Error or a string
    const error =
      _.get(this.state, ['result', 'error', 'message']) ||
      _.get(this.state, ['result', 'error'] || this.state.message);
 
    return (
      <View style={styles.container}>
        {this.props.children}
        {this.state.formState === 'Login' ? (
          <View style={styles.container}>
            <LoginForm
              initialEmail={this.state.userInput.email}
              initialPassword={this.state.userInput.password}
              onEmailChanged={this.onEmailChanged}
              onPasswordChanged={this.onPasswordChanged}
              {...this.props}
            />
            <CrossButton
              style={styles.marginTop10}
              buttonStyle={styles.buttonStyle}
              onPress={async () => await this.onLogin()}
              mode="contained"
              title="Log in"
              backgroundColor={Colors.NextButton}
              iconName="sign-in"
              {...this.props.loginButtonProps}
            />
            <CrossButton
              style={styles.marginTop10}
              buttonStyle={styles.buttonStyle}
              onPress={() =>
                this.setState({
                  formState: 'Register',
                })
              }
              mode="contained"
              title="Register"
              backgroundColor={Colors.BackButton}
              {...this.props.registerButtonProps}
            />
          </View>
        ) : null}
 
        {this.state.formState === 'Register' ? (
          <View style={styles.container}>
            <RegisterForm
              initialPhone={this.state.userInput.phone}
              onPhoneChanged={this.onPhoneChanged}
              initialEmail={this.state.userInput.email}
              initialPassword={this.state.userInput.password}
              onEmailChanged={this.onEmailChanged}
              onPasswordChanged={this.onPasswordChanged}
              {...this.props}
            />
            <CrossButton
              style={styles.marginTop10}
              buttonStyle={styles.buttonStyle}
              onPress={async () => await this.onRegister()}
              mode="contained"
              title="Save"
              backgroundColor={Colors.NextButton}
              iconName="sign-in"
              {...this.props.saveButtonProps}
            />
            <CrossButton
              style={styles.marginTop10}
              buttonStyle={styles.buttonStyle}
              onPress={() =>
                this.setState({
                  formState: 'Login',
                })
              }
              mode="contained"
              title="Cancel"
              backgroundColor={Colors.CancelButton}
              {...this.props.cancelButtonProps}
            />
          </View>
        ) : null}
        {this.state.formState === 'Forgot' ? (
          <ForgotForm {...this.props} />
        ) : null}
        {this.state.formState === 'ConfirmAccount' ? (
          <View style={styles.container}>
            <ConfirmForm
              testID="ConfirmAccountForm"
              code={this.state.code}
              initialEmail={this.state.userInput.email}
              onEmailChanged={this.onEmailChanged}
              onConfirmPress={async () => await this.onConfirmAccount()}
              onCodeChanged={(code) => this.setState({ code })}
              {...this.props}
            />
            <CrossButton
              style={styles.marginTop10}
              buttonStyle={styles.buttonStyle}
              onPress={() => this.OnResendSignup()}
              mode="contained"
              title="Resend code"
              backgroundColor={Colors.CancelButton}
              {...this.props.cancelButtonProps}
            />
          </View>
        ) : null}
        {this.state.formState === 'ConfirmMFALogin' ? (
          <ConfirmForm
          testID='ConfirmMFAForm'
            code={this.state.code}
            initialEmail={this.state.userInput.email}
            onEmailChanged={this.onEmailChanged}
            onConfirmPress={async () => await this.onConfirmMFACode()}
            onCodeChanged={(code) => this.setState({ code })}
          />
        ) : null}
        <CognitoUserInputContext.Provider value={this.state.userInput} />
 
        <CrossLabel isCaption={true} style={{ color: 'red' }}>
          {(error || '').toString()}
        </CrossLabel>
      </View>
    );
  }
}
 
export default CognitoLogin;