LoginPageRenderer.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.Json;
  3. using Android.App;
  4. using Xamarin.Auth;
  5. using Xamarin.Forms;
  6. using Xamarin.Forms.Platform.Android;
  7. using XamarinFormsGoogleDriveAPI;
  8. using XamarinFormsGoogleDriveAPI.Droid.Renderer;
  9. using XamarinFormsGoogleDriveAPI.Pages;
  10. using XamarinFormsGoogleDriveAPI.Services;
  11. [assembly: ExportRenderer(typeof(LoginPage), typeof(LoginPageRenderer))]
  12. namespace XamarinFormsGoogleDriveAPI.Droid.Renderer
  13. {
  14. public class LoginPageRenderer : PageRenderer
  15. {
  16. string userJson;
  17. protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
  18. {
  19. base.OnElementChanged(e);
  20. if (App.inAuthentication) return;
  21. App.inAuthentication = true;
  22. // this is a ViewGroup - so should be able to load an AXML file and FindView<>
  23. var activity = Forms.Context as Activity;
  24. var auth = new RefreshOAuth2Authenticator(
  25. Constants.ClientId,
  26. Constants.ClientSecret,
  27. Constants.Scopes,
  28. new Uri(Constants.AuthorizationUri),
  29. new Uri(Constants.RedirectUri),
  30. new Uri(Constants.AccessTokenUri));
  31. auth.AllowCancel = true;
  32. auth.Completed += async (sender, eventArgs) =>
  33. {
  34. if (eventArgs.IsAuthenticated)
  35. {
  36. App.SuccessfulLoginAction.Invoke();
  37. }
  38. var request = new OAuth2Request("GET", new Uri("https://www.googleapis.com/oauth2/v2/userinfo"), null,
  39. eventArgs.Account);
  40. var response = await request.GetResponseAsync();
  41. if (response != null)
  42. {
  43. userJson = response.GetResponseText();
  44. }
  45. StoringDataIntoCache(userJson, eventArgs.Account);
  46. };
  47. //TODO: Fix the output error
  48. //auth.ShowErrors = false;
  49. activity.StartActivity(auth.GetUI(activity));
  50. }
  51. /// <summary>
  52. /// Method to cache the authorized user data
  53. /// </summary>
  54. /// <param name="userData"></param>
  55. void StoringDataIntoCache(string userData, Account accountdata)
  56. {
  57. var data = JsonValue.Parse(userData);
  58. //var account = new Account();
  59. accountdata.Properties.Add("User", data["name"]);
  60. accountdata.Properties.Add("Email", data["email"]);
  61. accountdata.Properties.Add("scopes", Constants.Scopes);
  62. (Forms.Context as Activity)?.RunOnUiThread(() =>
  63. {
  64. AccountStore.Create(Forms.Context).Save(accountdata, "Google");
  65. });
  66. MessagingCenter.Send("Authentication Successful", "Authenticated");
  67. }
  68. }
  69. }