Example #1
0
        public void OnAuthCompleted(GoogleSignInResult result)
        {
            GoogleUser googleUser = new GoogleUser();

            if (result.IsSuccess)
            {
                Task.Factory.StartNew(() => {
                    if (result.SignInAccount.Account == null)
                    {
                        MessagingCenter.Send <string>("access token bilgisi alınamadı", "NoInternet");
                    }
                    var accessToken        = GoogleAuthUtil.GetToken(Android.App.Application.Context, result.SignInAccount.Email, $"oauth2:{Scopes.Email} {Scopes.Profile}");
                    googleUser.AccessToken = accessToken;
                    MessagingCenter.Send <string>(accessToken, "googleAndroidAccessToken");
                });
                GoogleSignInAccount accountt = result.SignInAccount;
                googleUser.Email       = accountt.Email;
                googleUser.Name        = accountt.GivenName;
                googleUser.Surname     = accountt.FamilyName;
                googleUser.AccessToken = accountt.IdToken;
                //googleUser.Token = accountt.IdToken;

                googleUser.Picture = new Uri((accountt.PhotoUrl != null ? $"{accountt.PhotoUrl}" : $"https://autisticdating.net/imgs/profile-placeholder.jpg"));
                _onLoginComplete?.Invoke(googleUser, string.Empty);
            }
            else
            {
                _onLoginComplete?.Invoke(null, "An error occured!");
            }
        }
Example #2
0
        private async void OnLoginComplete(GoogleUser googleUser, string message)
        {
            if (googleUser != null)
            {
                GoogleUser = googleUser;
                try
                {
                    AppUser User = await DependencyService.Get <IFireBaseAuthenticator>().LoginWithGoogle(googleUser.token, null);

                    Application.Current.Properties["User"] = User.Uid;
                }
                catch (Exception e)
                {
                    await DisplayAlert("Oops", "Firebase Error", "Ok");

                    ChangeBackLook();
                }

                IsLogedIn = true;
                await DisplayAlert("Success", message, "Ok");

                ChangeBackLook();
            }
            else
            {
                ChangeBackLook();
                await DisplayAlert("Error", message, "Ok");
            }
        }
Example #3
0
        public async Task <IActionResult> Google([FromBody] GoogleUser model)
        {
            var user = await _userManager.FindByEmailAsync(model.email);

            if (user != null)
            {
                await _signInManager.SignInAsync(user, isPersistent : false);

                return(Ok(user));
            }
            else
            {
                user = new AppUser {
                    Email = model.email, UserName = model.email, AccountCreated = DateTime.Now
                };
                var result = await _userManager.CreateAsync(user, Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8) + "aA!");

                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, isPersistent : false);
                }
                else
                {
                    return(BadRequest(result.Errors));
                }
                return(Ok(user));
            }
        }
Example #4
0
        // For iOS 9 or newer
        //public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)
        //{
        //    var openUrlOptions = new UIApplicationOpenUrlOptions(options);
        //    return SignIn.SharedInstance.HandleUrl(url, openUrlOptions.SourceApplication, openUrlOptions.Annotation);
        //}

        //// For iOS 8 and older
        //public override bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
        //{
        //    return SignIn.SharedInstance.HandleUrl(url, sourceApplication, annotation);
        //}
        public void DidSignIn(SignIn signIn, GoogleUser user, NSError error)
        {
            if (user != null && error == null)
            {
            }
            Xamarin.Forms.Application.Current.Properties["Boff"] = "Is it working";
        }
        async public void DidSignIn(SignIn signIn, GoogleUser user, NSError error)
        {
            if (user != null && error == null)
            {
                ShowHud(Strings.Hud.please_wait);

                GoogleNameLabel.Text = user.Profile.Name;
                UserId = user.UserID;

                var outlet = new Outlet();
                outlet.Name   = user.Profile.Name;
                outlet.Handle = user.UserID;
                outlet.Type   = Outlet.outlet_type_google;
                RealmServices.SaveOutlet(outlet);


                var url = await GoogleAuthenticator.GetProfileURL(UserId);

                ImageView.Hidden = false;
                ImageView.SetImage(url, "NoProfile", "NoProfile", async() =>
                {
                    HideHud();

                    await Task.Delay(TimeSpan.FromSeconds(2));
                    SignIn.SharedInstance.SignOutUser();

                    var popToViewController = NavigationController.ViewControllers.Where(c => c.GetType() == typeof(MyOutletsViewController)).First();
                    NavigationController.PopToViewController(popToViewController, true);
                });
            }
        }
Example #6
0
        private async void OnGoogleLoginComplete(GoogleUser googleUser, string message)
        {
            if (googleUser != null)
            {
                var takenModel = googleUser;
                switch (Device.RuntimePlatform)
                {
                case Device.Android:
                {
                    MessagingCenter.Subscribe <string>(this, "googleAndroidAccessToken", (obj) =>
                        {
                            takenModel.AccessToken = obj;
                            // TODO: service calling
                        });
                    break;
                }

                case Device.iOS:
                {
                    var takenAccessToken = takenModel.AccessToken;
                    // TODO: service calling
                    break;
                }

                default:

                    break;
                }
            }
        }
Example #7
0
        /// <summary>
        /// Stores the given value for the given key. It creates a new file (named <see cref="GenerateStoredKey"/>) in
        /// <see cref="FolderPath"/>.
        /// </summary>
        /// <typeparam name="T">The type to store in the data store</typeparam>
        /// <param name="key">The key</param>
        /// <param name="value">The value to store in the data store</param>
        public async Task StoreAsync <T>(string key, T value)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("Key MUST have a value");
            }

            var serialized = NewtonsoftJsonSerializer.Instance.Serialize(value);
            var entity     = await _applicationDbContext.GoogleUsers.SingleOrDefaultAsync(x => x.UserName == key);

            if (entity != null)
            {
                entity.RefreshToken = serialized;
                _applicationDbContext.Update(entity);
            }
            else
            {
                var insert = new GoogleUser
                {
                    Id           = Guid.NewGuid(),
                    UserName     = key,
                    RefreshToken = serialized
                };

                await _applicationDbContext.AddAsync(insert);
            }

            await _applicationDbContext.SaveChangesAsync();
        }
Example #8
0
 public async Task <ResponseDto <GoogleUser> > AddAsync(GoogleUser entity)
 {
     return(await Task.Run(async() =>
     {
         _logger.Information($"AddAsync: Trying to add a new user {entity.ID}");
         var response = new ResponseDto <GoogleUser>
         {
             Message = string.Empty,
             Succeed = false
         };
         using (var context = new MiraiNotesContext())
         {
             try
             {
                 await context.AddAsync(entity);
                 response.Succeed = await context.SaveChangesAsync() > 0;
                 response.Result = entity;
                 _logger.Information("AddAsync: Completed successfully");
             }
             catch (Exception e)
             {
                 _logger.Error(e, "AddAsync: An unknown error occurred");
                 response.Message = GetExceptionMessage(e);
             }
         }
         return response;
     }).ConfigureAwait(false));
 }
        public async Task AuthWithGoogleTokenAsync(SignIn signIn, GoogleUser user, Foundation.NSError error)
        {
            try {
                if (error == null)
                {
                    IsAuthenticating = true;

                    var token       = user.Authentication.AccessToken;
                    var authManager = ServiceContainer.Resolve <AuthManager> ();
                    var authRes     = await authManager.SignupWithGoogleAsync(token);

                    // No need to keep the users Google account access around anymore
                    signIn.DisconnectUser();

                    if (authRes != AuthResult.Success)
                    {
                        var email = user.Profile.Email;
                        AuthErrorAlert.Show(this, email, authRes, AuthErrorAlert.Mode.Signup, googleAuth: true);
                    }
                }
                else if (error.Code != -5)     // Cancel error code.
                {
                    new UIAlertView(
                        "WelcomeGoogleErrorTitle".Tr(),
                        "WelcomeGoogleErrorMessage".Tr(),
                        null, "WelcomeGoogleErrorOk".Tr(), null).Show();
                }
            } catch (InvalidOperationException ex) {
                var log = ServiceContainer.Resolve <ILogger> ();
                log.Info(Tag, ex, "Failed to authenticate (G+) the user.");
            } finally {
                IsAuthenticating = false;
            }
        }
Example #10
0
        /// <summary>
        /// <c a="HandleAuth"/>
        /// This handles the Navigation process, Removing the LoginView from thr stack and replacing it with the homepage/MasterView
        ///
        /// </summary>
        private async Task HandleAuth(GoogleUser googleUser)
        {
            IsBusy = true;
            try
            {
                _patient = await authenticationService.GoogleLogin(googleUser, "TOKEN");

                _patient.SocialID = googleUser.Id;
                _patient.PatientProfilePicture = googleUser.Picture.ToString();

                //DoGoogleDBTransaction(googleUser);
                DoDBTransaction(_patient);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                IsBusy = false;
                //MessagingCenter.Send(this, "", _patient.id);
                App.Current.MainPage.Navigation.InsertPageBefore(new MasterView(), App.Current.MainPage.Navigation.NavigationStack.First());
                await App.Current.MainPage.Navigation.PopAsync();
            }
        }
        public GoogleUser GetGoogleUserInformation(string accessToken)
        {
            GoogleUser userInfo = null;
            string     url      = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" + accessToken + "";

            try
            {
                WebRequest request = WebRequest.Create(url);
                request.Credentials = CredentialCache.DefaultCredentials;
                using (var response = request.GetResponse())
                {
                    using (var stream = response.GetResponseStream())
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            string result = reader.ReadToEnd();
                            userInfo = JsonConvert.DeserializeObject <GoogleUser>(result);
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                var response = ex.Response as HttpWebResponse;
                if (response != null && response.StatusCode == HttpStatusCode.BadRequest)
                {
                    return(null);
                }
            }
            return(userInfo);
        }
 private async void OnLoginCompleteGoogle(GoogleUser googleUser, string message)
 {
     if (googleUser != null)
     {
         try
         {
             //aqui você coloca o codigo que invoca sua app de registro e cadastrar o usuario com os dados do google
         }
         catch (Exception ex)
         {
             Debug.WriteLine(ex.Message);
             throw;
         }
         finally
         {
             var p = new Object[2];
             p[0] = googleUser;
             p[1] = null;
             await Navigation.PushAsync <UserViewModel>(false, p);
         }
     }
     else
     {
         await DisplayAlert("Error", message, "Ok");
     }
 }
        async void OnGoogleLogin(object sender, EventArgs args)
        {
            var userdata = await CrossGoogleClient.Current.LoginAsync();

            GoogleUser data = userdata.Data;

            ExternalUserModel userinfo = new ExternalUserModel();

            userinfo.id           = data.Id;
            userinfo.idToken      = data.Id;
            userinfo.name         = data.Name;
            userinfo.email        = data.Email;
            userinfo.profileImage = data.Picture.AbsoluteUri;

            userinfo.LoginProvider = "GOOGLE".ToUpper();
            userinfo.provider      = "GOOGLE".ToUpper();
            bool result = await(new LoginServices()).ExternalLogin(userinfo);

            if (result)
            {
                await Navigation.PopAsync();
            }
            else
            {
                await DisplayAlert("", "Not able to Login!", "Ok");
            }
        }
Example #14
0
        async void OnGoogleAuthCompleted(object sender, AuthenticatorCompletedEventArgs e)
        {
            var authenticator = sender as OAuth2Authenticator;

            if (authenticator != null)
            {
                authenticator.Completed -= OnGoogleAuthCompleted;
                authenticator.Error     -= OnGoogleAuthError;
            }

            if (e.IsAuthenticated)
            {
                //
                var request  = new OAuth2Request("GET", new Uri(Constants.GoogleAPI.UserInfoUrl), null, e.Account);
                var response = await request.GetResponseAsync();

                if (response != null)
                {
                    string userJson = await response.GetResponseTextAsync();

                    GoogleUser user = JsonConvert.DeserializeObject <GoogleUser>(userJson);
                    viewModel.SocialLogin(user);
                }
                else
                {
                    await Shell.Current.DisplayAlert("", "Không thể kết nối đến Google !", "Đóng");
                }
            }
            else
            {
                //await accountPage.DisplayAlert("", "Không thể kết nối đến Google .", "Đóng");
            }
            await Task.Delay(2000);
        }
Example #15
0
 /// <summary>
 /// The GoogleClient_OnLogin
 /// </summary>
 /// <param name="sender">The sender<see cref="object"/></param>
 /// <param name="e">The e<see cref="GoogleClientResultEventArgs{Plugin.GoogleClient.Shared.GoogleUser}"/></param>
 private void GoogleClient_OnLogin(object sender, GoogleClientResultEventArgs <Plugin.GoogleClient.Shared.GoogleUser> e)
 {
     this.userData         = e.Data;
     this.IsGoogleSignedIn = true;
     this.Email            = e.Data.Email;
     this.FullName         = e.Data.Name;
 }
Example #16
0
 public ProfileView(GoogleUser googleUser)
 {
     InitializeComponent();
     CachedImage.Source = googleUser.Picture;
     ProfileName.Text   = googleUser.Name;
     Email.Text         = googleUser.Email;
 }
        public void TestGoogleAuthenticate()
        {
            //Mock<IAccountService> moqaccountService = new Mock<IAccountService>();
            string  token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IjVkMGExNzcwMWEwYTQyMDAwMTdkZTZjOCIsInJvbGUiOiJtZW1iZXIiLCJ1c2VyX2lkIjoiNWQwYTE3NzAxYTBhNDIwMDAxN2RlNmM3IiwibmJmIjoxNTYyOTA2NjI3LCJleHAiOjE1NjI5MjgyMjcsImlhdCI6MTU2MjkwNjYyNywiaXNzIjoiYXV0aC50cmlwc2hhcmluZy5jb20ifQ.ou0CVGErEDI7DNGSpHsm3Q6aT5g8u2tVekWM9jklvY0";
            Account acc   = new Account()
            {
                UserId       = "5d027f10de896f17a87b1044",
                Email        = "*****@*****.**",
                Password     = "******",
                Role         = "member",
                PasswordSalt = "LQ993XXKV5Eo6/IBmoytuQ==",
                Token        = "asvaanbfbsgnnsn",
                Id           = "5d027f10de896f17a87b1045"
            };
            GoogleUser googleUser = new GoogleUser()
            {
                Email      = "*****@*****.**",
                Gender     = "Nam",
                Given_name = "Phongtv",
                Id         = "5d027f10de896f17a87b104s",
                Name       = "Tran Van Phong",
                Picture    = ""
            };

            moqIAccountRepository.Setup(x => x.GetByEmail(It.IsAny <string>())).Returns(acc);
            moqIAccountRepository.Setup(x => x.Add(It.IsAny <Account>())).Returns(acc);
            //moqaccountService.Setup(x => x.GetGoogleUserInformation(It.IsAny<string>())).Returns(googleUser);
            var accountService = new AccountService(moqIAccountRepository.Object, Options.Create(_setting), moqIpublishtotopic.Object);
            var account        = accountService.GoogleAuthenticate(token);

            Assert.IsNull(account);
        }
Example #18
0
        public async Task <IActionResult> Login(GoogleUser gUser)
        {
            var user = await _userManager.FindByEmailAsync(gUser.Email);

            if (user == null)
            {
                var confirmationLink = Url.Action("Register",
                                                  "User", new
                {
                    email    = gUser.Email, firstName = gUser.GivenName,
                    lastName = gUser.FamilyName,
                    imageUrl = gUser.ImageUrl, id = gUser.GoogleId
                },
                                                  HttpContext.Request.Scheme);

                var mailbody = "<p>A new user would like to register:<p>" +
                               $"<p>Name: {gUser.GivenName} {gUser.FamilyName}</p>" +
                               $"<p>Email: {gUser.Email}</p>" +
                               $"<p><a href='{confirmationLink}'>Confirm user</a></p>";

                _emailService.Send("*****@*****.**", "new user", mailbody);

                return(Ok(new { status = "newUser" }));
            }

            await _signInManager.SignInAsync(user, true);

            var publicUser = await _accountManager.GeneratePublicProfileAsync(user);

            return(Ok(publicUser));
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            SignIn.SharedInstance.UIDelegate = this;

            SignIn.SharedInstance.SignedIn += (object sender, SignInDelegateEventArgs e) => {
                if (e.User != null && e.Error == null)
                {
                    User = e.User;

                    InvokeOnMainThread(() => {
                        lbStatus.Text = e.User.Profile.Name;

                        PerformSegue("moveFromGoogleLoginToMenuViewSegue", this);
                    });
                }
            };

            SignIn.SharedInstance.Disconnected += (object sender, SignInDelegateEventArgs e) => {
                if (e.User != null && e.Error == null)
                {
                    User = null;
                    InvokeOnMainThread(() => {
                        lbStatus.Text = string.Empty;
                    });
                }
            };

            SignIn.SharedInstance.SignInUserSilently();
        }
        public void TestGetGoogleUserInformation()
        {
            var        accountService = new AccountService(moqIAccountRepository.Object, Options.Create(_setting), moqIpublishtotopic.Object);
            string     token          = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IjVkMGExNzcwMWEwYTQyMDAwMTdkZTZjOCIsInJvbGUiOiJtZW1iZXIiLCJ1c2VyX2lkIjoiNWQwYTE3NzAxYTBhNDIwMDAxN2RlNmM3IiwibmJmIjoxNTYyOTA2NjI3LCJleHAiOjE1NjI5MjgyMjcsImlhdCI6MTU2MjkwNjYyNywiaXNzIjoiYXV0aC50cmlwc2hhcmluZy5jb20ifQ.ou0CVGErEDI7DNGSpHsm3Q6aT5g8u2tVekWM9jklvY0";
            GoogleUser googleUser     = accountService.GetGoogleUserInformation(token);

            Assert.IsNull(googleUser);
        }
Example #21
0
        public async Task <GoogleUser> RegisterGoogleUser(GoogleUser googleUser)
        {
            await _context.GoogleUsers.AddAsync(googleUser);

            await _context.SaveChangesAsync();

            return(googleUser);
        }
Example #22
0
 private void OnLoginCompleted(object sender, GoogleClientResultEventArgs <GoogleUser> e)
 {
     if (e != null)
     {
         GoogleUser user = e.Data;
         NombrePersona = user.Name;
     }
 }
Example #23
0
        public JsonResult GetGoogleTokensTask(string userEmail)
        {
            var _userinfo = GoogleUser.GenerateVerificationCodes(userEmail);

            var json = JsonConvert.SerializeObject(_userinfo);

            return(Json(json));
        }
Example #24
0
        public JsonResult GetGoogleUserInfoTask(string userEmail)
        {
            var _userinfo = GoogleUser.GetGoogleUserInfo(userEmail);

            var json = JsonConvert.SerializeObject(_userinfo);

            return(Json(json));
        }
Example #25
0
        public async void CheckAppUser(String email, String password)
        {
            using (UserDialogs.Instance.Loading("Loading", null, null, true, MaskType.Black))
            {
                HttpClient client       = new HttpClient();
                String     JsonResponse = await client.GetStringAsync(HIVE.Constants.Web_Url_Server + "/" + email + "/" + password);

                if (JsonResponse.Equals("error"))
                {
                    await DisplayAlert("Error", "Invalid Login, try again", "OK");

                    Password.Text = string.Empty;
                }
                else
                {
                    await Navigation.PushModalAsync(new MainPage());
                }


                var objects = JObject.Parse(JsonResponse);
                email    = objects.Value <String>("email");
                username = objects.Value <String>("username");


                GoogleUser googleUser = new GoogleUser
                {
                    Email = email,
                    Name  = username,
                };
            }

            /*
             * HttpClient client = new HttpClient();
             * String JsonResponse = await client.GetStringAsync(HIVE.Constants.Web_Url_Server+ "/"+email+"/"+password);
             *
             * if (JsonResponse.Equals("error"))
             *  {
             *      await DisplayAlert("Error", "Invalid Login, try again", "OK");
             *      Password.Text = string.Empty;
             *  }
             *  else
             *  {
             *      await Navigation.PushModalAsync(new MainPage());
             *  }
             *
             *
             * var objects = JObject.Parse(JsonResponse);
             * email = objects.Value<String>("email");
             * username = objects.Value<String>("username");
             *
             *
             * GoogleUser googleUser = new GoogleUser
             * {
             *  Email = email,
             *  Name = username,
             * };
             */
        }
Example #26
0
 private void onLoginComplete(GoogleUser arg1, string arg2)
 {
     MessagingCenter.Send(new MessagingCenterAlert
     {
         Title   = "Info",
         Message = arg2,
         Cancel  = "OK"
     }, "message");
 }
Example #27
0
 public TabbedPage1(GoogleUser googleUser)
 {
     SetValue(NavigationPage.HasNavigationBarProperty, false);
     On <Xamarin.Forms.PlatformConfiguration.Android>().SetToolbarPlacement(ToolbarPlacement.Top);
     InitializeComponent();
     Children.Add(new HomeView());
     Children.Add(new CandidateView());
     Children.Add(new ProfileView(googleUser));
 }
Example #28
0
        private static async void OnAuthLinkedCompleted(object sender, AuthenticatorCompletedEventArgs e)
        {
            var authenticator = sender as OAuth2Authenticator;

            if (authenticator != null)
            {
                authenticator.Completed -= OnAuthLinkedCompleted;
                authenticator.Error     -= OnAuthLinkedError;
            }
            //LoginUser = null;
            if (e.IsAuthenticated)
            {
                // If the user is authenticated, request their basic user data from Google
                // UserInfoUrl = https://www.googleapis.com/oauth2/v2/userinfo
                var request  = new OAuth2Request("GET", new Uri(UserInfoUrl), null, e.Account);
                var response = await request.GetResponseAsync();

                if (response != null)
                {
                    // Deserialize the data and store it in the account store
                    // The users email address will be used to identify data in SimpleDB
                    string userJson = await response.GetResponseTextAsync();

                    GoogleUser googleUser = JsonConvert.DeserializeObject <GoogleUser>(userJson);

                    var ggUser = new User()
                    {
                        FullName  = googleUser.Name,
                        Email     = googleUser.Email,
                        GoogleId  = googleUser.Id,
                        AvatarUrl = googleUser.Picture
                    };

                    try
                    {
                        ApiResponse apiResponse = await ApiHelper.Put("api/auth/sociallinked", ggUser, true);

                        if (apiResponse.IsSuccess)
                        {
                            var user = JsonConvert.DeserializeObject <User>(apiResponse.Content.ToString());
                            UserLogged.SaveProfile(user);
                            await Application.Current.MainPage.DisplayAlert("", Language.lien_ket_google_thanh_cong, Language.dong);

                            //MessagingCenter.Send<GoogleHelper, bool>(this, "UpdateSocialLinked", true);
                        }
                        else
                        {
                            throw new Exception(apiResponse.Message);
                        }
                    }
                    catch (Exception ex)
                    {
                        await Application.Current.MainPage.DisplayAlert("", Language.loi_he_thong_vui_long_thu_lai, Language.dong);
                    }
                }
            }
        }
        public void Setup()
        {
            CurrentUser = Fixture.Create <GoogleUser>();

            // Reset any calls made to the mocks.
            NavigationServiceMock.Reset();
            PageDialogServiceMock.Reset();
            AuthServiceMock.Reset();
            DatabaseServiceMock.Reset();
        }
Example #30
0
 private void OnLoginComplete(GoogleUser googleUser, string message)
 {
     if (googleUser != null)
     {
         this.googleUser = googleUser;
     }
     else
     {
         DisplayAlert("Hata", message, "Tamam");
     }
 }
		public void DidSignIn(SignIn signIn, GoogleUser gUser, Foundation.NSError error)
		{
			Device.BeginInvokeOnMainThread(async () => {

				UIAlertView alert = new UIAlertView("Login", "In DidSignIn", null, "OK", null);
				alert.Show ();
					Debug.WriteLine("DidSignIn");

					if (error != null)
					{
						Debug.WriteLine("In DidSignIn: Failure Google Error: " + error.Description, "Login");
						return;
					}

					if (gUser == null)
					{
						Debug.WriteLine("In DidSignIn: Failure Google User == null", "Login");
						return;
					}

					if (gUser != null)
					{
//						//Azure Login Process:
//						try
//						{
//							var jToken = JObject.FromObject(new {
//								access_token = SignIn.SharedInstance.CurrentUser.Authentication.AccessToken,
//								authorization_code = SignIn.SharedInstance.CurrentUser.ServerAuthCode,
//								id_token = SignIn.SharedInstance.CurrentUser.Authentication.IdToken,
//							});
//							var user = await DependencyService.Get<IMobileClient>().Authenticate(MobileServiceAuthenticationProvider.Google, jToken);
//							if (user == null)
//							{
//								Debug.WriteLine("Azure Google User == null. Logging out.");
//								App.Logout();
//							}
//						}
//						catch (Exception ex)
//						{
//							Debug.WriteLine("Azure Google Signin Exception: " + ex.ToString());
//						}
					}
				});
		}
        public void DidSignIn(SignIn signIn, GoogleUser user, NSError error)
        {
            // Perform any operations on signed in user here.
            if (user != null && error == null) {

                // VERY IMPORTANT: We create an OAuth2Authentication instance here
                // to use later with the google plus API since it expects this old
                // type of object
                currentAuth = new Google.OpenSource.OAuth2Authentication {
                    ClientId = signIn.ClientID,
                    AccessToken = user.Authentication.AccessToken,
                    ExpirationDate = user.Authentication.AccessTokenExpirationDate,
                    RefreshToken = user.Authentication.RefreshToken,
                    TokenURL = new NSUrl ("https://accounts.google.com/o/oauth2/token")
                };

                // Start fetching the signed in user's info
                GetUserInfo ();

                status.Caption = string.Format ("{0} (Tap to Sign Out)", user.Profile.Name);

                ToggleAuthUI ();
            }
        }
 public async Task AuthWithGoogleTokenAsync (SignIn signIn, GoogleUser user, Foundation.NSError error)
 {
     try {
         if (error == null) {
             IsAuthenticating = true;
             var token = user.Authentication.AccessToken;
             var authManager = ServiceContainer.Resolve<AuthManager> ();
             var authRes = await authManager.AuthenticateWithGoogleAsync (token);
             // No need to keep the users Google account access around anymore
             signIn.DisconnectUser ();
             if (authRes != AuthResult.Success) {
                 var email = user.Profile.Email;
                 AuthErrorAlert.Show (this, email, authRes, AuthErrorAlert.Mode.Login, true);
             } else {
                 // Start the initial sync for the user
                 ServiceContainer.Resolve<ISyncManager> ().Run ();
             }
         } else if (error.Code != -5) { // Cancel error code.
             new UIAlertView ("WelcomeGoogleErrorTitle".Tr (), "WelcomeGoogleErrorMessage".Tr (), null, "WelcomeGoogleErrorOk".Tr (), null).Show ();
         }
     } catch (InvalidOperationException ex) {
         var log = ServiceContainer.Resolve<ILogger> ();
         log.Info (Tag, ex, "Failed to authenticate (G+) the user.");
     } finally {
         IsAuthenticating = false;
     }
 }
 public CreateUserAction( GoogleUser user )
     : base("Google.Apps.Provisioning.XmlTemplates.CreateUser.xml",
     "https://www.google.com/a/services/v1.0/Create/Account/Email")
 {
     this.user = user;
 }
 public virtual void DidDisconnect(SignIn signIn, GoogleUser user, NSError error)
 {
     currentAuth = null;
     Root [1].Clear ();
     ToggleAuthUI ();
 }
 public void DidSignIn (SignIn signIn, GoogleUser user, Foundation.NSError error)
 {
     InvokeOnMainThread (async delegate {
         await AuthWithGoogleTokenAsync (signIn, user, error);
     });
 }
Example #37
0
        /// <summary>
        /// Gets the name of the Google user.
        /// </summary>
        /// <param name="googleUser">The Google user.</param>
        /// <param name="accessToken">The access token.</param>
        /// <returns></returns>
        public static string GetGoogleUser( GoogleUser googleUser, string accessToken = "" )
        {
            string username = string.Empty;
            string googleId = googleUser.id;
            string googleLink = googleUser.link;

            string userName = "******" + googleId;
            UserLogin user = null;

            using (var rockContext = new RockContext() )
            {

                // Query for an existing user
                var userLoginService = new UserLoginService(rockContext);
                user = userLoginService.GetByUserName(userName);

                // If no user was found, see if we can find a match in the person table
                if ( user == null )
                    {
                    // Get name/email from Google login
                    string lastName = googleUser.family_name.ToString();
                    string firstName = googleUser.given_name.ToString();
                    string email = string.Empty;
                    try { email = googleUser.email.ToString(); }
                    catch { }

                    Person person = null;

                    // If person had an email, get the first person with the same name and email address.
                    if ( !string.IsNullOrWhiteSpace(email) )
                    {
                        var personService = new PersonService(rockContext);
                        var people = personService.GetByMatch(firstName, lastName, email);
                        if ( people.Count() == 1 )
                        {
                            person = people.First();
                        }
                    }

                    var personRecordTypeId = DefinedValueCache.Read(SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                    var personStatusPending = DefinedValueCache.Read(SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid()).Id;

                    rockContext.WrapTransaction(( ) =>
                    {
                        if ( person == null )
                        {
                            person = new Person();
                            person.IsSystem = false;
                            person.RecordTypeValueId = personRecordTypeId;
                            person.RecordStatusValueId = personStatusPending;
                            person.FirstName = firstName;
                            person.LastName = lastName;
                            person.Email = email;
                            person.IsEmailActive = true;
                            person.EmailPreference = EmailPreference.EmailAllowed;
                            try
                            {
                                if ( googleUser.gender.ToString() == "male" )
                                {
                                    person.Gender = Gender.Male;
                                }
                                else if ( googleUser.gender.ToString() == "female" )
                                {
                                    person.Gender = Gender.Female;
                                }
                                else
                                {
                                    person.Gender = Gender.Unknown;
                                }
                            }
                            catch { }

                            if ( person != null )
                            {
                                PersonService.SaveNewPerson(person, rockContext, null, false);
                            }
                        }

                        if ( person != null )
                        {
                            int typeId = EntityTypeCache.Read(typeof(Google)).Id;
                            user = UserLoginService.Create(rockContext, person, AuthenticationServiceType.External, typeId, userName, "goog", true);
                        }

                    });
                }
                if ( user != null )
                {
                    username = user.UserName;

                    if ( user.PersonId.HasValue )
                    {
                        var converter = new ExpandoObjectConverter();

                        var personService = new PersonService(rockContext);
                        var person = personService.Get(user.PersonId.Value);
                    }
                }

                return username;
            }
        }