-
Notifications
You must be signed in to change notification settings - Fork 11
/
MainPage.xaml.cs
480 lines (384 loc) · 15.4 KB
/
MainPage.xaml.cs
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
using System;
using System.Collections.Generic;
using Xamarin.Forms;
using Xamarin.Auth;
using System.Linq;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
using ComicBookPCL;
using System.Text;
using Xamarin.Auth.XamarinForms;
namespace ComicBook
{
public partial class MainPage : ContentPage
{
const string ServiceId = "ComicBook";
const string Scope = "profile";
Account account;
AccountStore store = null;
public MainPage()
{
InitializeComponent();
implicitButton.Clicked += ImplicitButtonClicked;
authorizationCodeButton.Clicked += AuthorizationCodeButtonClicked;
getProfileButton.Clicked += GetProfileButtonClicked;
refreshButton.Clicked += RefreshButtonClicked;
/*
store = AccountStore.Create();
account = store.FindAccountsForService(ServiceId).FirstOrDefault();
if (account != null)
{
statusText.Text = "Restored previous session";
getProfileButton.IsEnabled = true;
refreshButton.IsEnabled = true;
}
*/
this.BindingContext = this;
this.pickerUIFrameworks.SelectedIndexChanged += pickerUIFrameworks_SelectedIndexChanged;
this.pickerFormsImplementations.SelectedIndexChanged += pickerFormsImplementations_SelectedIndexChanged;
this.pickerNavigationType.SelectedIndexChanged += pickerNavigationType_SelectedIndexChanged;
this.pickerViews.SelectedIndexChanged += pickerViews_SelectedIndexChanged;
this.pickerUIFrameworks.SelectedIndex = 0;
this.pickerFormsImplementations.SelectedIndex = 0;
this.pickerNavigationType.SelectedIndex = 0;
switch (Xamarin.Forms.Device.RuntimePlatform)
{
case "iOS":
this.pickerViews.SelectedIndex = 0;
break;
}
buttonGoogle.Clicked += ButtonGoogle_Clicked;
buttonFacebook.Clicked += ButtonFacebook_Clicked;
buttonLinkedIn.Clicked += ButtonLinkedIn_Clicked;
buttonMeetUp.Clicked += ButtonMeetUp_Clicked;
return;
}
void ImplicitButtonClicked(object sender, EventArgs e)
{
OAuth2Authenticator authenticator = new OAuth2Authenticator
(
ServerInfo.ClientId,
Scope,
ServerInfo.AuthorizationEndpoint,
ServerInfo.RedirectionEndpoint,
null,
isUsingNativeUI: native_ui
);
authenticator.Completed += OnAuthCompleted;
authenticator.Error += OnAuthError;
AuthenticationState.Authenticator = authenticator;
if (forms_implementation_renderers)
{
// Renderers Implementaion
if (navigation_push_modal == true)
{
Navigation.PushModalAsync(new Xamarin.Auth.XamarinForms.AuthenticatorPage());
}
else
{
Navigation.PushAsync(new Xamarin.Auth.XamarinForms.AuthenticatorPage());
}
}
else
{
// Presenters Implementation
Xamarin.Auth.Presenters.OAuthLoginPresenter presenter = null;
presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
presenter.Login(authenticator);
}
return;
}
void AuthorizationCodeButtonClicked(object sender, EventArgs e)
{
OAuth2Authenticator authenticator = new OAuth2Authenticator
(
ServerInfo.ClientId,
ServerInfo.ClientSecret,
Scope,
ServerInfo.AuthorizationEndpoint,
ServerInfo.RedirectionEndpoint,
ServerInfo.TokenEndpoint,
null,
isUsingNativeUI: true
);
authenticator.Completed += OnAuthCompleted;
authenticator.Error += OnAuthError;
AuthenticationState.Authenticator = authenticator;
PresentUILoginScreen(authenticator);
return;
}
async void GetProfileButtonClicked(object sender, EventArgs e)
{
try
{
var request = new OAuth2Request("GET", ServerInfo.ApiEndpoint, null, account);
var response = await request.GetResponseAsync();
var text = response.GetResponseText();
var json = JObject.Parse(text);
var name = (string)json["Name"];
var email = (string)json["Email"];
var imageUrl = (string)json["ImageUrl"];
nameText.Text = name;
emailText.Text = email;
var imageRequest = new OAuth2Request("GET", new Uri(imageUrl), null, account);
var stream = await (await imageRequest.GetResponseAsync()).GetResponseStreamAsync();
profileImage.Source = ImageSource.FromStream(() => stream);
statusText.Text = "Get data succeeded";
}
catch (Exception x)
{
getProfileButton.IsEnabled = false;
statusText.Text = "Get data failure: " + x.Message + "\r\nHas the access token expired?";
}
}
async void RefreshButtonClicked(object sender, EventArgs e)
{
var refreshToken = account.Properties["refresh_token"];
if (string.IsNullOrWhiteSpace(refreshToken))
return;
var queryValues = new Dictionary<string, string>
{
{"refresh_token", refreshToken},
{"client_id", ServerInfo.ClientId},
{"grant_type", "refresh_token"},
{"client_secret", ServerInfo.ClientSecret},
};
var authenticator = new OAuth2Authenticator
(
ServerInfo.ClientId,
ServerInfo.ClientSecret,
"profile",
ServerInfo.AuthorizationEndpoint,
ServerInfo.RedirectionEndpoint,
ServerInfo.TokenEndpoint,
null,
isUsingNativeUI: true
);
try
{
var result = await authenticator.RequestAccessTokenAsync(queryValues);
if (result.ContainsKey("access_token"))
account.Properties["access_token"] = result["access_token"];
if (result.ContainsKey("refresh_token"))
account.Properties["refresh_token"] = result["refresh_token"];
store.Save(account, ServiceId);
statusText.Text = "Refresh succeeded";
}
catch (Exception ex)
{
statusText.Text = "Refresh failed " + ex.Message;
}
}
void OnAuthCompleted(object sender, AuthenticatorCompletedEventArgs e)
{
var authenticator = sender as OAuth2Authenticator;
if (authenticator != null)
{
authenticator.Completed -= OnAuthCompleted;
authenticator.Error -= OnAuthError;
}
if (e.IsAuthenticated)
{
getProfileButton.IsEnabled = true;
if (this.account != null)
store.Delete(this.account, ServiceId);
store.Save(account = e.Account, ServiceId);
getProfileButton.IsEnabled = true;
if (account.Properties.ContainsKey("expires_in"))
{
var expires = int.Parse(account.Properties["expires_in"]);
statusText.Text = "Token lifetime is: " + expires + "s";
}
else
{
statusText.Text = "Authentication succeeded";
}
if (account.Properties.ContainsKey("refresh_token"))
refreshButton.IsEnabled = true;
}
else
{
statusText.Text = "Authentication failed";
}
}
void OnAuthError(object sender, AuthenticatorErrorEventArgs e)
{
var authenticator = sender as OAuth2Authenticator;
if (authenticator != null)
{
authenticator.Completed -= OnAuthCompleted;
authenticator.Error -= OnAuthError;
}
statusText.Text = "Authentication error: " + e.Message;
}
// *
public List<string> UIFrameworks => _UIFrameworks;
List<string> _UIFrameworks = new List<string>()
{
"Embedded WebView",
"Native UI (Custom Tabs or SFSafariViewController",
};
bool native_ui = true;
protected void pickerUIFrameworks_SelectedIndexChanged(object sender, System.EventArgs e)
{
Picker p = sender as Picker;
if (((string)p.SelectedItem).Equals("Native UI (Custom Tabs or SFSafariViewController"))
{
native_ui = true;
pickerViews.IsEnabled = false;
}
else if (((string)p.SelectedItem).Equals("Embedded WebView"))
{
native_ui = false;
pickerViews.IsEnabled = true;
}
else
{
throw new ArgumentException("UIFramework error");
}
return;
}
bool forms_implementation_renderers = false;
public List<string> FormsImplementations => _FormsImplementations;
List<string> _FormsImplementations = new List<string>()
{
"Custom Renderers",
"Presenters (Dependency Service/Injection)",
};
protected void pickerFormsImplementations_SelectedIndexChanged(object sender, System.EventArgs e)
{
Picker p = sender as Picker;
string implementation = ((string)p.SelectedItem);
if (string.IsNullOrEmpty(implementation))
return;
if (implementation == "Presenters (Dependency Service/Injection)")
{
System.Diagnostics.Debug.WriteLine("Presenters (Dependency Service/Injection)");
forms_implementation_renderers = false;
}
else if (implementation == "Custom Renderers")
{
System.Diagnostics.Debug.WriteLine("Custom Renderers");
forms_implementation_renderers = true;
}
else
{
throw new ArgumentException("FormsImplementation error");
}
return;
}
public static bool navigation_push_modal = false;
public List<string> NavigationTypes => _NavigationTypes;
List<string> _NavigationTypes = new List<string>()
{
"PushModalAsync",
"PushAsync",
};
protected void pickerNavigationType_SelectedIndexChanged(object sender, System.EventArgs e)
{
Picker p = sender as Picker;
string navigation_type = ((string)p.SelectedItem);
if (string.IsNullOrEmpty(navigation_type))
return;
if (navigation_type == "PushAsync")
{
System.Diagnostics.Debug.WriteLine("PushAsync");
navigation_push_modal = false;
}
else if (navigation_type == "PushModalAsync")
{
System.Diagnostics.Debug.WriteLine("PushModalAsync");
navigation_push_modal = true;
}
else
{
throw new ArgumentException("NavigationTypes error");
}
return;
}
string web_view = null;
public List<string> Views => _Views;
List<string> _Views = new List<string>()
{
"UIWebView",
"WKWebView",
};
protected void pickerViews_SelectedIndexChanged(object sender, System.EventArgs e)
{
Picker p = sender as Picker;
web_view = ((string)p.SelectedItem);
IEmbeddedWebViewConfiguration cfg = DependencyService.Get<IEmbeddedWebViewConfiguration>();
if (null == cfg)
{
//TODO: check dependency service
return;
}
if (web_view == "UIWebView")
{
System.Diagnostics.Debug.WriteLine("UIWebView");
cfg.IsUsingWKWebView = false;
}
else if (web_view == "WKWebView")
{
System.Diagnostics.Debug.WriteLine("WKWebView");
cfg.IsUsingWKWebView = true;
}
else
{
throw new ArgumentException("WebView error");
}
return;
}
Xamarin.Auth.OAuth2Authenticator authenticator = null;
private void PresentUILoginScreen(OAuth2Authenticator authenticator)
{
if (forms_implementation_renderers)
{
// Renderers Implementaion
Xamarin.Auth.XamarinForms.AuthenticatorPage ap;
ap = new Xamarin.Auth.XamarinForms.AuthenticatorPage()
{
Authenticator = authenticator,
};
NavigationPage np = new NavigationPage(ap);
if (navigation_push_modal == true)
{
System.Diagnostics.Debug.WriteLine("Presenting");
System.Diagnostics.Debug.WriteLine(" PushModal");
System.Diagnostics.Debug.WriteLine(" Custom Renderers");
Navigation.PushModalAsync(np);
}
else
{
System.Diagnostics.Debug.WriteLine("Presenting");
System.Diagnostics.Debug.WriteLine(" Push");
System.Diagnostics.Debug.WriteLine(" Custom Renderers");
Navigation.PushAsync(np);
}
}
else
{
// Presenters Implementation
if (navigation_push_modal == true)
{
System.Diagnostics.Debug.WriteLine("Presenting");
System.Diagnostics.Debug.WriteLine(" PushModal");
System.Diagnostics.Debug.WriteLine(" Presenters");
Xamarin.Auth.Presenters.OAuthLoginPresenter presenter = null;
presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
presenter.Login(authenticator);
}
else
{
System.Diagnostics.Debug.WriteLine("Presenting");
System.Diagnostics.Debug.WriteLine(" Push");
System.Diagnostics.Debug.WriteLine(" Presenters");
Xamarin.Auth.Presenters.OAuthLoginPresenter presenter = null;
presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
presenter.Login(authenticator);
}
}
return;
}
}
}