/
LoginView.js
251 lines (224 loc) · 9.09 KB
/
LoginView.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
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
import React from "react";
import { Dimensions } from "react-native";
import { WebView } from 'react-native-webview';
import log from "./logger";
import B2CAuthentication from "./ReactNativeADB2C";
export default class LoginView extends React.Component {
needRedirect = true;
onTokenGranted = () => { };
lock = false;
accessToken = {};
constructor(props) {
super(props);
if (!this.props.context instanceof B2CAuthentication)
throw new Error("property `context` of LoginView should be an instance of B2CAuthentication, but got", this.props.context);
const context = this.props.context;
this.needRedirect = this.props.needLogout || false;
this.state = {
page: this.getLoginUrl(context.getConfig().authority_host),
visible: true
};
this._lock = false;
}
componentWillUpdate(nextProps, nextState) {
if (this.state.visible === nextState.visible && this.state.page === nextState.page)
return false;
return true;
}
componentWillReceiveProps(nextProps) {
if (!this.props.needLogout && nextProps.needLogout) {
const context = this.props.context;
this.needRedirect = nextProps.needLogout || false;
this.setState({
page: this.getLoginUrl(context.getConfig().authority_host),
visible: true
});
}
}
render() {
// Fix visibility problem on Android webview
let js = `document.getElementsByTagName('body')[0].style.height = '${
Dimensions.get("window").height
}px';`;
return this.state.visible ? (
<WebView
ref="ADLoginView"
automaticallyAdjustContentInsets={false}
style={[
this.props.style,
{
flex: 1,
alignSelf: "stretch",
width: Dimensions.get("window").width,
height: Dimensions.get("window").height
}
]}
source={{ uri: this.state.page }}
javaScriptEnabled={true}
domStorageEnabled={true}
onLoadEnd={() => {
if (this._needRedirect) {
this._needRedirect = false;
this.setState({ page: this.getLoginUrl(this.props.context.getConfig().authority_host) });
}
}}
decelerationRate="normal"
javaScriptEnabledAndroid={true}
onNavigationStateChange={this._handleADToken.bind(this)}
onShouldStartLoadWithRequest={e => {
return true;
}}
startInLoadingState={false}
injectedJavaScript={js}
scalesPageToFit={true}
/>
) : null;
};
/**
* Get authority host URI,
* @param {string} tenant Custom tenant ID, this filed is optional, default
* values is `common`.
* @return {string} The Authority host URI.
*/
getLoginUrl = (url) => {
const authUrl = url;
const context = this.props.context || null;
const redirect = context.getConfig().redirect_uri;
const prompt = context.getConfig().prompt || "login";
const userFlowPolicy = context.getConfig().user_flow_policy;
const clientId = context.getConfig().client_id;
const scope = context.getConfig().scope;
if (context !== null) {
const result =
`${authUrl}?p=${userFlowPolicy}&response_type=code` +
`&client_id=${clientId}` +
(redirect ? `&redirect_uri=${redirect}&nonce=rnad-${Date.now()}` : "") +
(prompt ? `&prompt=${prompt}` : "") +
(scope ? `&scope=${scope.join(" ")}` : "");
;
console.log(result);
return result;
} else {
throw new Error("context should not be null/undefined.");
}
}
getPasswordResetUrl = () => {
const context = this.props.context || null;
const authUrl = context.getConfig().authority_host;
const redirect = context.getConfig().redirect_uri;
const prompt = context.getConfig().prompt || 'login';
const passwordResetPolicy = context.getConfig().reset_password_policy;
const tenant = context.getConfig().tenant;
const clientId = context.getConfig().client_id;
const scope = context.getConfig().scope;
if (context !== null) {
const result =
`${authUrl}?p=${passwordResetPolicy}` +
'&response_type=code' +
`&client_id=${clientId}` +
(redirect ? `&redirect_uri=${redirect}&nonce=rnad-${Date.now()}` : '') +
(prompt ? `&prompt=${prompt}` : '') +
'&response_mode=fragment' +
(scope ? `&scope=${scope.join('%20')}` : '');
console.log(result);
return result;
} else {
throw new Error("context should not be null/undefined.");
}
}
/**
* An interceptor for handling webview url change, when it detects possible
* authorization code in url, it will triggers authentication flow.
* @param {object} e Navigation state change event object.
*/
_handleADToken(e) {
const context = this.props.context;
log.verbose("ADLoginView navigate to", e.url);
if (this._lock) return true;
let errorDescription = /((\?|\&)error_description\=)[^\%]+/.exec(e.url);
// let code = /((\?|\&)code\=)[^\&]+/.exec(e.url);
//when using facebook integration, code comes after ? is not valid for getting access token
//look for the code comes after #
let code = /((\&|\#)code\=)[^\&]+/.exec(e.url);
if (this._needRedirect) {
// this._needRedirect = false
return true;
}
if (this.props.onURLChange) this.props.onURLChange(e);
if (errorDescription !== null) {
let errorCode = String(errorDescription[0]).replace(/(\?|\&)?error_description\=/, "")
switch (errorCode) {
case "AADB2C90118":
this.setState({
page: this.getPasswordResetUrl(),
visible: true
});
return true;
break;
case 'AADB2C90091': //when user cancel to go back from the login page.
this.setState({
page: this.getLoginUrl(context.getConfig().authority_host),
visible: true,
policy: context.getConfig().user_flow_policy,
});
return false;
break;
default:
break;
}
}
if (code !== null) {
this._lock = true;
log.verbose("LoginView._handleADToken code=", code[0]);
code = String(code[0]).replace(/(\&|\#)?code\=/, '');
this.setState({ visible: !this.props.hideAfterLogin });
this.props.onVisibilityChange && this.props.onVisibilityChange(false);
this._getResourceAccessToken(code).catch(err => {
log.error("LoginView._getResourceAccessToken", err);
});
return true;
}
return true;
}
/**
* Get access token for each resoureces
* @param {string} code The authorization code from `onNavigationStateChange`
* callback.
* @return {Promise<void>}
*/
_getResourceAccessToken(code) {
const context = this.props.context;
if (!context)
throw new Error(
"property `context` of LoginView should not be null/undefined"
);
const adConfig = this.props.context.getConfig();
log.verbose("LoginView get access token for resources");
let promises = [];
const config = {
client_id: adConfig.client_id,
redirect_uri: adConfig.redirect_uri,
code,
client_secret: adConfig.client_secret,
// set resource to common by default
resource: "common"
};
promises.push(context.grantAccessToken("authorization_code", config));
return Promise.all(promises)
.then((resps) => {
log.verbose("LoginView response access info ", resps);
if (!this.props.context)
throw new Error("value of property `context` is invalid=", this.props.context);
const context = this.props.context;
const onSuccess = this.props.onSuccess || function () { };
// trigger loggined finished event
if (context !== null && typeof this.props.onSuccess === "function")
onSuccess(context.getCredentials());
this._lock = false;
})
.catch(err => {
log.error(err);
throw new Error("Failed to acquire token for resources", err.stack);
});
}
}