forked from aws-amplify/amplify-js
/
Authenticator.js
226 lines (203 loc) · 6 KB
/
Authenticator.js
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
/*
* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
import React from 'react';
import { Auth, Analytics, Logger, Hub, JS } from 'aws-amplify';
import AmplifyTheme from '../AmplifyTheme';
import AmplifyMessageMap from '../AmplifyMessageMap';
import { Container } from '../AmplifyUI';
import Loading from './Loading';
import SignIn from './SignIn';
import ConfirmSignIn from './ConfirmSignIn';
import VerifyContact from './VerifyContact';
import SignUp from './SignUp';
import ConfirmSignUp from './ConfirmSignUp';
import ForgotPassword from './ForgotPassword';
import RequireNewPassword from './RequireNewPassword';
import Greetings from './Greetings';
const logger = new Logger('Authenticator');
const EmptyContainer = ({ children }) => (
<React.Fragment>{children}</React.Fragment>
);
class AuthDecorator {
constructor(onStateChange) {
this.onStateChange = onStateChange;
}
signIn(username, password) {
const that = this;
return Auth.signIn(username, password).then(data => {
that.onStateChange('signedIn');
return data;
});
}
signOut() {
const that = this;
return Auth.signOut().then(() => {
that.onStateChange('signedOut');
});
}
}
export default class Authenticator extends React.Component {
constructor(props) {
super(props);
this._initialAuthState = this.props.authState || 'signIn';
this.state = {
authState: props.authState || 'loading',
authData: props.authData,
};
this.handleStateChange = this.handleStateChange.bind(this);
this.checkUser = this.checkUser.bind(this);
this.onHubCapsule = this.onHubCapsule.bind(this);
this.checkContact = this.checkContact.bind(this);
Hub.listen('auth', this.onHubCapsule);
}
componentDidMount() {
this._isMounted = true;
this.checkUser();
}
componentWillUnmount() {
this._isMounted = false;
}
onHubCapsule(capsule) {
const {
payload: { event },
data,
} = capsule;
switch (event) {
case 'cognitoHostedUI':
return this.handleStateChange('signedIn', data);
case 'cognitoHostedUI_failure':
case 'parsingUrl_failure':
case 'signOut':
case 'customGreetingSignOut':
return this.handleStateChange('signIn', null);
}
}
handleStateChange(state, data) {
if (state === undefined) return logger.info('state cannot be undefined');
logger.info(
'Inside handleStateChange Method current authState:',
this.state.authState
);
let nextAuthState;
if (state === 'signedOut') {
nextAuthState = this._initialAuthState;
} else {
nextAuthState = state;
}
let nextAuthData = this.state.authData;
if (data !== undefined) {
nextAuthData = data;
}
if (this._isMounted) {
this.setState({
authState: nextAuthState,
authData: nextAuthData,
error: null,
});
logger.log('Auth Data was set:', nextAuthData);
logger.info(`authState has been updated to ${nextAuthState}`);
}
if (this.props.onStateChange) {
this.props.onStateChange(state, data);
}
switch (state) {
case 'signedIn':
Analytics.record('_userauth.sign_in');
break;
case 'signedUp':
Analytics.record('_userauth.sign_up');
break;
}
}
async checkContact(user) {
try {
const data = await Auth.verifiedContact(user);
logger.debug('verified user attributes', data);
if (!JS.isEmpty(data.verified)) {
this.handleStateChange('signedIn', user);
} else {
user = Object.assign(user, data);
this.handleStateChange('verifyContact', user);
}
} catch (e) {
logger.warn('Failed to verify contact', e);
this.handleStateChange('signedIn', user);
}
}
checkUser() {
const { authState } = this.state;
const statesJumpToSignIn = ['signedIn', 'signedOut', 'loading'];
Auth.currentAuthenticatedUser()
.then(user => {
if (!this._isMounted) return;
if (user) {
this.checkContact(user);
} else {
if (statesJumpToSignIn.includes(authState)) {
this.handleStateChange(this._initialAuthState, null);
}
}
})
.catch(err => {
if (!this._isMounted) return;
logger.debug(err);
if (statesJumpToSignIn.includes(authState)) {
Auth.signOut()
.then(() => {
this.handleStateChange(this._initialAuthState, null);
})
.catch(err => this.error(err));
}
});
}
render() {
const { authState, authData } = this.state;
const theme = this.props.theme || AmplifyTheme;
const messageMap = this.props.errorMessage || AmplifyMessageMap;
// If container prop is undefined, default to AWS Amplify UI Container (SafeAreaView)
// otherwise if truthy, use the supplied render prop
// otherwise if falsey, use EmptyContainer
const ContainerWrapper =
this.props.container === undefined
? Container
: this.props.container || EmptyContainer;
const { hideDefault, signUpConfig, usernameAttributes } = this.props;
const props_children = this.props.children || [];
const default_children = [
<Loading />,
<SignIn />,
<ConfirmSignIn />,
<VerifyContact />,
<SignUp signUpConfig={signUpConfig} />,
<ConfirmSignUp />,
<ForgotPassword />,
<RequireNewPassword />,
<Greetings />,
];
const children = (hideDefault ? [] : default_children)
.concat(props_children)
.map((child, index) => {
return React.cloneElement(child, {
key: 'auth_piece_' + index,
theme: theme,
messageMap: messageMap,
authState: authState,
authData: authData,
onStateChange: this.handleStateChange,
Auth: new AuthDecorator(this.handleStateChange),
usernameAttributes,
});
});
return <ContainerWrapper theme={theme}>{children}</ContainerWrapper>;
}
}