forked from aws-amplify/amplify-js
/
amplify-sign-in.tsx
301 lines (280 loc) · 10.4 KB
/
amplify-sign-in.tsx
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
import { Auth } from '@aws-amplify/auth';
import { I18n, Logger, isEmpty } from '@aws-amplify/core';
import { Component, Prop, State, Host, h } from '@stencil/core';
import {
FormFieldTypes,
PhoneNumberInterface,
} from '../../components/amplify-auth-fields/amplify-auth-fields-interface';
import {
AuthState,
ChallengeName,
FederatedConfig,
AuthStateHandler,
UsernameAliasStrings,
} from '../../common/types/auth-types';
import { Translations } from '../../common/Translations';
import {
NO_AUTH_MODULE_FOUND,
COUNTRY_DIAL_CODE_DEFAULT,
COUNTRY_DIAL_CODE_SUFFIX,
PHONE_SUFFIX,
} from '../../common/constants';
import {
dispatchToastHubEvent,
dispatchAuthStateChangeEvent,
composePhoneNumberInput,
checkUsernameAlias,
} from '../../common/helpers';
import { SignInAttributes } from './amplify-sign-in-interface';
const logger = new Logger('SignIn');
/**
* @slot footer - Content is place in the footer of the component
* @slot primary-footer-content - Content placed on the right side of the footer
* @slot secondary-footer-content - Content placed on the left side of the footer
*/
@Component({
tag: 'amplify-sign-in',
styleUrl: 'amplify-sign-in.scss',
shadow: true,
})
export class AmplifySignIn {
/** Fires when sign in form is submitted */
@Prop() handleSubmit: (event: Event) => void = event => this.signIn(event);
/** Used for header text in sign in component */
@Prop() headerText: string = I18n.get(Translations.SIGN_IN_HEADER_TEXT);
/** Used for the submit button text in sign in component */
@Prop() submitButtonText: string = I18n.get(Translations.SIGN_IN_ACTION);
/** Federated credentials & configuration. */
@Prop() federated: FederatedConfig;
/** Auth state change handler for this component */
@Prop() handleAuthStateChange: AuthStateHandler = dispatchAuthStateChangeEvent;
/** Username Alias is used to setup authentication with `username`, `email` or `phone_number` */
@Prop() usernameAlias: UsernameAliasStrings = 'username';
/**
* Form fields allows you to utilize our pre-built components such as username field, code field, password field, email field, etc.
* by passing an array of strings that you would like the order of the form to be in. If you need more customization, such as changing
* text for a label or adjust a placeholder, you can follow the structure below in order to do just that.
* ```
* [
* {
* type: string,
* label: string,
* placeholder: string,
* hint: string | Functional Component | null,
* required: boolean
* }
* ]
* ```
*/
@Prop() formFields: FormFieldTypes | string[] = [];
/* Whether or not the sign-in component is loading */
@State() loading: boolean = false;
private phoneNumber: PhoneNumberInterface = {
countryDialCodeValue: COUNTRY_DIAL_CODE_DEFAULT,
phoneNumberValue: null,
};
private newFormFields: FormFieldTypes | string[] = [];
@State() signInAttributes: SignInAttributes = {
userInput: '',
password: '',
};
private handleFormFieldInput(fieldType) {
switch (fieldType) {
case 'username':
case 'email':
return event => (this.signInAttributes.userInput = event.target.value);
case 'phone_number':
return event => this.handlePhoneNumberChange(event);
case 'password':
return event => (this.signInAttributes.password = event.target.value);
}
}
private handleFormFieldInputWithCallback(event, field) {
const fnToCall = field['handleInputChange']
? field['handleInputChange']
: (event, cb) => {
cb(event);
};
const callback =
field.type === 'phone_number'
? event => (this.signInAttributes.userInput = event.target.value)
: this.handleFormFieldInput(field.type);
fnToCall(event, callback.bind(this));
}
private handlePhoneNumberChange(event) {
const name = event.target.name;
const value = event.target.value;
/** Cognito expects to have a string be passed when signing up. Since the Select input is separate
* input from the phone number input, we need to first capture both components values and combined
* them together.
*/
if (name === COUNTRY_DIAL_CODE_SUFFIX) {
this.phoneNumber.countryDialCodeValue = value;
}
if (name === PHONE_SUFFIX) {
this.phoneNumber.phoneNumberValue = value;
}
}
private checkContact(user) {
if (!Auth || typeof Auth.verifiedContact !== 'function') {
throw new Error(NO_AUTH_MODULE_FOUND);
}
Auth.verifiedContact(user).then(data => {
if (!isEmpty(data.verified)) {
this.handleAuthStateChange(AuthState.SignedIn, user);
} else {
user = Object.assign(user, data);
this.handleAuthStateChange(AuthState.VerifyContact, user);
}
});
}
private async signIn(event: Event) {
// avoid submitting the form
if (event) {
event.preventDefault();
}
if (!Auth || typeof Auth.signIn !== 'function') {
throw new Error(NO_AUTH_MODULE_FOUND);
}
this.loading = true;
switch (this.usernameAlias) {
case 'phone_number':
this.signInAttributes.userInput = composePhoneNumberInput(this.phoneNumber);
default:
break;
}
try {
const user = await Auth.signIn(this.signInAttributes.userInput, this.signInAttributes.password);
logger.debug(user);
if (user.challengeName === ChallengeName.SMSMFA || user.challengeName === ChallengeName.SoftwareTokenMFA) {
logger.debug('confirm user with ' + user.challengeName);
this.handleAuthStateChange(AuthState.ConfirmSignIn, user);
} else if (user.challengeName === ChallengeName.NewPasswordRequired) {
logger.debug('require new password', user.challengeParam);
this.handleAuthStateChange(AuthState.ResetPassword, user);
} else if (user.challengeName === ChallengeName.MFASetup) {
logger.debug('TOTP setup', user.challengeParam);
this.handleAuthStateChange(AuthState.TOTPSetup, user);
} else if (
user.challengeName === ChallengeName.CustomChallenge &&
user.challengeParam &&
user.challengeParam.trigger === 'true'
) {
logger.debug('custom challenge', user.challengeParam);
this.handleAuthStateChange(AuthState.CustomConfirmSignIn, user);
} else {
this.checkContact(user);
}
} catch (error) {
dispatchToastHubEvent(error);
if (error.code === 'UserNotConfirmedException') {
logger.debug('the user is not confirmed');
this.handleAuthStateChange(AuthState.ConfirmSignUp, { username: this.signInAttributes.userInput });
} else if (error.code === 'PasswordResetRequiredException') {
logger.debug('the user requires a new password');
this.handleAuthStateChange(AuthState.ForgotPassword, { username: this.signInAttributes.userInput });
}
} finally {
this.loading = false;
}
}
async componentWillLoad() {
checkUsernameAlias(this.usernameAlias);
if (this.formFields.length === 0) {
const formFieldInputs = [];
switch (this.usernameAlias) {
case 'email':
formFieldInputs.push({
type: 'email',
required: true,
handleInputChange: this.handleFormFieldInput('email'),
inputProps: {
'data-test': 'sign-in-email-input',
},
});
break;
case 'phone_number':
formFieldInputs.push({
type: 'phone_number',
required: true,
handleInputChange: this.handleFormFieldInput('phone_number'),
inputProps: {
'data-test': 'sign-in-phone-number-input',
},
});
break;
case 'username':
default:
formFieldInputs.push({
type: 'username',
required: true,
handleInputChange: this.handleFormFieldInput('username'),
inputProps: {
'data-test': 'sign-in-username-input',
},
});
break;
}
formFieldInputs.push({
type: 'password',
hint: (
<div>
{I18n.get(Translations.FORGOT_PASSWORD_TEXT)}{' '}
<amplify-button
variant="anchor"
onClick={() => this.handleAuthStateChange(AuthState.ForgotPassword)}
data-test="sign-in-forgot-password-link"
>
{I18n.get(Translations.RESET_PASSWORD_TEXT)}
</amplify-button>
</div>
),
required: true,
handleInputChange: this.handleFormFieldInput('password'),
inputProps: {
'data-test': 'sign-in-password-input',
},
});
this.newFormFields = [...formFieldInputs];
} else {
this.formFields.forEach(field => {
const newField = { ...field };
newField['handleInputChange'] = event => this.handleFormFieldInputWithCallback(event, field);
this.newFormFields.push(newField);
});
}
}
render() {
return (
<Host>
<amplify-form-section headerText={this.headerText} handleSubmit={this.handleSubmit} testDataPrefix={'sign-in'}>
<amplify-federated-buttons handleAuthStateChange={this.handleAuthStateChange} federated={this.federated} />
{!isEmpty(this.federated) && <amplify-strike>or</amplify-strike>}
<amplify-auth-fields formFields={this.newFormFields} />
<div slot="amplify-form-section-footer" class="sign-in-form-footer">
<slot name="footer">
<slot name="secondary-footer-content">
<span>
{I18n.get(Translations.NO_ACCOUNT_TEXT)}{' '}
<amplify-button
variant="anchor"
onClick={() => this.handleAuthStateChange(AuthState.SignUp)}
data-test="sign-in-create-account-link"
>
{I18n.get(Translations.CREATE_ACCOUNT_TEXT)}
</amplify-button>
</span>
</slot>
<slot name="primary-footer-content">
<amplify-button type="submit" disabled={this.loading} data-test="sign-in-sign-in-button">
<amplify-loading-spinner style={{ display: this.loading ? 'initial' : 'none' }} />
<span style={{ display: this.loading ? 'none' : 'initial' }}>{this.submitButtonText}</span>
</amplify-button>
</slot>
</slot>
</div>
</amplify-form-section>
</Host>
);
}
}