Пример #1
0
        internal GoogleClientManager()
        {
            if (CurrentActivity == null)
            {
                throw new GoogleClientNotInitializedErrorException(GoogleClientBaseException.ClientNotInitializedErrorMessage);
            }

            var gopBuilder = new GoogleSignInOptions.Builder(GoogleSignInOptions.DefaultSignIn)
                             .RequestEmail();

            if (!string.IsNullOrWhiteSpace(_serverClientId))
            {
                gopBuilder.RequestServerAuthCode(_serverClientId, false);
            }

            if (!string.IsNullOrWhiteSpace(_clientId))
            {
                gopBuilder.RequestIdToken(_clientId);
            }

            foreach (var s in _initScopes)
            {
                gopBuilder.RequestScopes(new Scope(s));
            }

            GoogleSignInOptions googleSignInOptions = gopBuilder.Build();

            // Build a GoogleSignInClient with the options specified by gso.
            mGoogleSignInClient = GoogleSignIn.GetClient(CurrentActivity, googleSignInOptions);
        }
        //======================================================

        #region Google

        //Event Click login using google
        private void GoogleSignInButtonOnClick(object sender, EventArgs e)
        {
            try
            {
                if (MGoogleSignInClient == null)
                {
                    // Configure sign-in to request the user's ID, email address, and basic profile. ID and basic profile are included in DEFAULT_SIGN_IN.
                    var gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DefaultSignIn)
                              .RequestIdToken(AppSettings.ClientId)
                              .RequestScopes(new Scope(Scopes.Profile))
                              .RequestScopes(new Scope(Scopes.PlusMe))
                              .RequestScopes(new Scope(Scopes.DriveAppfolder))
                              .RequestServerAuthCode(AppSettings.ClientId)
                              .RequestProfile().RequestEmail().Build();

                    MGoogleSignInClient ??= GoogleSignIn.GetClient(this, gso);
                }

                var signInIntent = MGoogleSignInClient.SignInIntent;
                StartActivityForResult(signInIntent, 0);
            }
            catch (Exception exception)
            {
                Methods.DisplayReportResultTrack(exception);
            }
        }
        public static async Task OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            if (requestCode == RC_SIGN_IN)
            {
                var result = await GoogleSignIn.GetSignedInAccountFromIntent(data).AsAsync <GoogleSignInAccount>();

                if (result != null)
                {
                    googleToken = result.IdToken;

                    var credential     = GoogleAuthProvider.GetCredential(result.IdToken, null);
                    var firebaseResult = await FirebaseAuth.Instance.SignInWithCredentialAsync(credential);

                    if (firebaseResult != null)
                    {
                        (CrossFirebaseEssentials.Authentication as FirebaseAuthenticationManager).SetVerificationStatus(VerificationStatus.Success);
                    }
                    else
                    {
                        (CrossFirebaseEssentials.Authentication as FirebaseAuthenticationManager).SetVerificationStatus(VerificationStatus.Failed);
                    }
                }
                else
                {
                    googleToken = string.Empty;
                    (CrossFirebaseEssentials.Authentication as FirebaseAuthenticationManager).SetVerificationStatus(VerificationStatus.Failed);
                }
            }
            else
            {
                callbackManager?.OnActivityResult(requestCode, (int)resultCode, data);
            }
        }
        public async Task <(string IdToken, string AccessToken)> GetCredentialAsync()
        {
            if (_tcs != null && !_tcs.Task.IsCompleted)
            {
                _tcs.TrySetCanceled();
            }
            _tcs = new TaskCompletionSource <string>();

            var account = GoogleSignIn.GetLastSignedInAccount(_activity);

            if (account != null && !account.IsExpired)
            {
                return(account.IdToken, null);
            }

            try
            {
                account = await _client.SilentSignInAsync().ConfigureAwait(false);

                return(account.IdToken, null);
            }
            catch
            {
                _activity.StartActivityForResult(_client.SignInIntent, SignInRequestCode);

                var idToken = await _tcs.Task.ConfigureAwait(false);

                return(idToken, null);
            }
        }
Пример #5
0
 public async Task HandleActivityResultAsync(int requestCode, Result resultCode, Intent data)
 {
     if (requestCode == RequestCodeSignIn)
     {
         await HandleSignInResultAsync(GoogleSignIn.GetSignedInAccountFromIntent(data));
     }
 }
Пример #6
0
        //Result
        protected override async void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            try
            {
                base.OnActivityResult(requestCode, resultCode, data);

                Log.Debug("Login_Activity", "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);

                if (requestCode == 0)
                {
                    var task = await GoogleSignIn.GetSignedInAccountFromIntentAsync(data);

                    SetContentGoogle(task);
                }
                else
                {
                    // Logins Facebook
                    MFbCallManager.OnActivityResult(requestCode, (int)resultCode, data);
                }
            }
            catch (Exception e)
            {
                Methods.DisplayReportResultTrack(e);
            }
        }
Пример #7
0
        public async Task <LoginResult> AuthenticateAsync(GoogleAccount account, RemoteUser user)
        {
            bool validationResult = Task.Run(() => this.ValidateAsync(account.Token)).GetAwaiter().GetResult();

            if (!validationResult)
            {
                return(new LoginResult
                {
                    Status = false,
                    Message = Resources.AccessIsDenied
                });
            }

            var gUser = new GoogleUserInfo
            {
                Email = account.Email,
                Name  = account.Name
            };

            var result = await GoogleSignIn.SignInAsync(this.Tenant, account.Email, account.OfficeId, account.Name, account.Token, user.Browser, user.IpAddress, account.Culture).ConfigureAwait(false);

            if (result.Status)
            {
                if (!await Registrations.HasAccountAsync(this.Tenant, account.Email).ConfigureAwait(false))
                {
                    string template     = "~/Tenants/{tenant}/Areas/Frapid.Account/EmailTemplates/welcome-email-other.html";
                    var    welcomeEmail = new WelcomeEmail(gUser, template, ProviderName);
                    await welcomeEmail.SendAsync(this.Tenant).ConfigureAwait(false);
                }
            }

            return(result);
        }
Пример #8
0
        protected override void OnClick()
        {
            base.OnClick();

            switch (_group)
            {
            case "Google":
                GoogleSignIn gSignIn = new GoogleSignIn(true);
                gSignIn.Owner         = Window.GetWindow(this);
                gSignIn.Email         = _email;
                gSignIn.EmailReadOnly = true;
                gSignIn.ShowDialog();
                break;

            default:
                break;
            }

            //AccountEdit edit = new AccountEdit(title.Text, detail.Text);
            //edit.Owner = Window.GetWindow(this);

            //if (edit.ShowDialog() == true)
            //{
            //	if (edit.Deleted)
            //	{
            //		(Parent as Panel).Children.Remove(this);
            //		SyncDatabase.Delete(detail.Text);
            //	}
            //}
        }
Пример #9
0
        public async Task <LoginResult> AuthenticateAsync(GoogleAccount account, RemoteUser user)
        {
            bool validationResult = Task.Run(() => ValidateAsync(account.Token)).Result;

            if (!validationResult)
            {
                return(new LoginResult
                {
                    Status = false,
                    Message = "Access is denied"
                });
            }

            var gUser = new GoogleUserInfo
            {
                Email = account.Email,
                Name  = account.Name
            };
            var result = GoogleSignIn.SignIn(account.Email, account.OfficeId, account.Name, account.Token, user.Browser, user.IpAddress, account.Culture);

            if (result.Status)
            {
                if (!Registrations.HasAccount(account.Email))
                {
                    string template     = "~/Catalogs/{catalog}/Areas/Frapid.Account/EmailTemplates/welcome-email-other.html";
                    var    welcomeEmail = new WelcomeEmail(gUser, template, ProviderName);
                    await welcomeEmail.SendAsync();
                }
            }

            return(result);
        }
Пример #10
0
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            if (requestCode == REQUEST_GOOGLE_FITNESS_AUTH)
            {
                authInProgress = false;
                HasGoogleFitnessAuthentication = resultCode == Result.Ok;
                System.Diagnostics.Debug.WriteLine($"Result after auth is: {HasGoogleFitnessAuthentication}");
                GoogleFitnessAuthenticationUpdated?.Invoke(HasGoogleFitnessAuthentication);
            }

            if (requestCode == REQUEST_GOOGLE_SIGN_IN)
            {
                googleLoginInProgress = false;
                var signInTask = GoogleSignIn.GetSignedInAccountFromIntent(data);
                if (signInTask.IsSuccessful)
                {
                    account = (GoogleSignInAccount)signInTask.Result;
                    RequestFitnessPermissions();
                }
            }

            if (requestCode == REQUEST_FITNESS_PERMISSIONS)
            {
                HasGoogleFitnessPermissions = resultCode == Result.Ok;
                GoogleFitnessPermissionsUpdated?.Invoke(HasGoogleFitnessPermissions);
            }
        }
Пример #11
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            DependencyService.Register <ILocalize, Localize>();
            DependencyService.Register <IAuthRepository, AuthRepository>();

            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            Forms.Init(this, savedInstanceState);

            LocalNotificationsImplementation.NotificationIconId = Resource.Drawable.ic_stat_futurelife;
            ImageCircleRenderer.Init();
            Rg.Plugins.Popup.Popup.Init(this, savedInstanceState);

            GoogleSignInAccount account = GoogleSignIn.GetLastSignedInAccount(this);

            if (account == null)
            {
                ConfigureGoogleSignIn();
                GoogleSignInLaunch();
            }
            LoadApplication(new App());
        }
Пример #12
0
        public void Logout()
        {
            var gsoBuilder = new GoogleSignInOptions.Builder(GoogleSignInOptions.DefaultSignIn).RequestEmail();

            GoogleSignIn.GetClient(_context, gsoBuilder.Build())?.SignOut();

            _googleApiClient.Disconnect();
        }
Пример #13
0
 public static void ActivityResult(int requestCode, Result resultCode, Intent data)
 {
     if (requestCode == SIGNIN_RESP)
     {
         var task = GoogleSignIn.GetSignedInAccountFromIntent(data);
         _client.HandleSignIn(task);
     }
 }
Пример #14
0
        public static void OnAuthCompleted(int requestCode, Intent data)
        {
            if (requestCode != authActivityID)
            {
                return;
            }

            GoogleSignIn.GetSignedInAccountFromIntent(data).AddOnCompleteListener(CrossGoogleClient.Current as IOnCompleteListener);
        }
        public GoogleService(Activity activity)
        {
            _activity = activity;

            var gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DefaultSignIn)
                      .RequestIdToken(activity.GetString(Resource.String.default_web_client_id))
                      .RequestEmail()
                      .Build();

            _client = GoogleSignIn.GetClient(activity, gso);
        }
Пример #16
0
        // Third partys
        private void ImgGooglePlay_Click(object sender, EventArgs e)
        {
            string serverClientId = Resources.GetString(Resource.String.server_client_id);
            GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DefaultGamesSignIn)
                                                      .RequestServerAuthCode(serverClientId)
                                                      .Build();

            GoogleSignInClient googleSignInClient = GoogleSignIn.GetClient(this, googleSignInOptions);
            Intent             signInIntent       = googleSignInClient.SignInIntent;

            StartActivityForResult(signInIntent, 9003);
        }
Пример #17
0
        public void Logout()
        {
            if (currentActivity == null || googleSignInClient == null)
            {
                throw new GoogleClientNotInitializedErrorException(GoogleClientBaseException.ClientNotInitializedErrorMessage);
            }

            if (GoogleSignIn.GetLastSignedInAccount(currentActivity) != null)
            {
                idToken = null;
                googleSignInClient.SignOut();
            }
        }
Пример #18
0
        private GoogleSignInClient BuildSignInClient()
        {
            var signInOptions = new GoogleSignInOptions
                                .Builder(GoogleSignInOptions.DefaultSignIn)
                                //.RequestScopes(DriveClass.ScopeFile, DriveClass.ScopeAppfolder)
                                .RequestProfile()
                                .RequestEmail()
                                .Build();

            var activity = _fromActivity ? _activity : _fragment.Activity;

            return(GoogleSignIn.GetClient(activity, signInOptions));
        }
Пример #19
0
 /// <summary>
 /// Checks that the user is signed in, and if so, executes the specified function. If the user is
 /// not signed in, initiates the sign in flow, specifying the post-sign in function to execute.
 /// </summary>
 /// <param name="requestCode">The request code corresponding to the action to perform after sign in.</param>
 private void FitSignIn(FitActionRequestCode requestCode)
 {
     if (IsOAuthPermissionsApproved)
     {
         PerformActionForRequestCode(requestCode);
     }
     else
     {
         GoogleSignIn.RequestPermissions(
             this,
             (int)requestCode,
             GoogleAccount,
             _fitnessOptions);
     }
 }
Пример #20
0
        private GoogleClientManager()
        {
            if (currentActivity == null)
            {
                throw new GoogleClientNotInitializedErrorException(GoogleClientBaseException.ClientNotInitializedErrorMessage);
            }

            var googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DefaultSignIn)
                                      .RequestIdToken(Constants.GoogleRequestIdToken)
                                      .RequestEmail()
                                      .RequestScopes(new Scope(Scopes.Profile))
                                      .Build();

            googleSignInClient = GoogleSignIn.GetClient(currentActivity, googleSignInOptions);
        }
Пример #21
0
        private async void SigninButton_Click(object sender, System.EventArgs e)
        {
            //await Auth.GoogleSignInApi.SignOut(mGoogleApiClient);
            GoogleSignInAccount account = GoogleSignIn.GetLastSignedInAccount(this);

            if (account == null)
            {
                var signInIntent = Auth.GoogleSignInApi.GetSignInIntent(mGoogleApiClient);
                StartActivityForResult(signInIntent, SIGN_IN_CODE);
            }
            else
            {
                FirebaseLogin(account);
            }
        }
Пример #22
0
        public ApplicationUser GetUser()
        {
            GoogleSignInAccount account = GoogleSignIn.GetLastSignedInAccount(Context);

            if (account != null)
            {
                return(new ApplicationUser
                {
                    DisplayName = account.DisplayName,
                    Email = account.Email,
                    PhotoUrl = account.PhotoUrl.ToString()
                });
            }
            return(null);
        }
Пример #23
0
        private void ImgGoogle_Click(object sender, EventArgs e)
        {
            string    serverClientId = Resources.GetString(Resource.String.server_client_id);
            const int RcSignIn       = 9001;
            // Configure sign-in to request the user's ID, email address, and basic
            // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
            GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DefaultSignIn)
                                      .RequestProfile()
                                      .RequestIdToken(serverClientId)
                                      .Build();

            GoogleSignInClient googleSignClient = GoogleSignIn.GetClient(this, gso);
            Intent             signInIntent     = googleSignClient.SignInIntent;

            StartActivityForResult(signInIntent, RcSignIn);
        }
Пример #24
0
        public void OnActivityResult(int requestCode, Result resultCode, object data)
        {
            switch (requestCode)
            {
            case RequestCodeGoogleSignIn:
                if (resultCode == Result.Ok)
                {
                    GoogleSignIn
                    .GetSignedInAccountFromIntent(data as Intent)
                    .AddOnSuccessListener(this);
                }
                break;

            default:
                break;
            }
        }
Пример #25
0
        private void AddGoogleService()
        {
            GoogleSignIn gSignIn = new GoogleSignIn();

            gSignIn.Owner = Window.GetWindow(this);

            if (gSignIn.ShowDialog() == true)
            {
                AccountDisplay display = new AccountDisplay(new BitmapImage(new Uri("pack://application:,,,/Daytimer.Images;component/Images/google.png", UriKind.Absolute)), "Google", gSignIn.Email);
                servicesPanel.Children.Add(display);

                if (SyncDatabase.GetSyncObject(gSignIn.Email) == null)
                {
                    SyncDatabase.Add(new SyncObject(gSignIn.Email, DateTime.Now, SyncType.EntireAccount));
                }
            }
        }
        public void OnActivetyResult(int requestCode, Result resultCode, Intent data)
        {
            if (requestCode == SignInRequestCode)
            {
                var task = GoogleSignIn.GetSignedInAccountFromIntent(data);

                if (task.IsSuccessful)
                {
                    var account = task.Result.JavaCast <GoogleSignInAccount>();
                    _tcs.TrySetResult(account.IdToken);
                }
                else
                {
                    _tcs.TrySetException(task.Exception);
                }
            }
        }
        protected override void beforeEach()
        {
            theUrl     = "login/test";
            theRequest = new GoogleLoginRequest();
            theSignIn  = new GoogleSignIn();

            MockFor <IFubuRequest>().Stub(x => x.Get <GoogleSignIn>()).Return(theSignIn);

            MockFor <IUrlRegistry>().Stub(x => x.UrlFor(theSignIn)).Return(theUrl);

            ClassUnderTest.Write(MimeType.Html.Value, theRequest);

            string html = MimeType.Html.ToString();

            theTag = MockFor <IOutputWriter>()
                     .GetArgumentsForCallsMadeOn(x => x.Write(Arg <string> .Is.Same(html), Arg <string> .Is.NotNull))
                     [0][1].As <string>();
        }
Пример #28
0
        public override Task <bool> RequestPermissionAsync(params HealthDataType[] dataTypes)
        {
            var fitnessOptions = GetFitnessOptions(dataTypes);

            _tcsAuth = new TaskCompletionSource <bool>();

            if (HasOAuthPermission(fitnessOptions))
            {
                _tcsAuth.SetResult(true);
            }
            else
            {
                GoogleSignIn.RequestPermissions(CurrentActivity, REQUEST_CODE,
                                                GoogleSignIn.GetLastSignedInAccount(_currentContext), fitnessOptions);
            }

            return(_tcsAuth.Task);
        }
Пример #29
0
        // utility function that gets the basal metabolic rate averaged over a week
        private async Task <double> GetBasalAvg(DateTime endDate)
        {
            float basalAvg  = 0;
            long  startDate = endDate.AddDays(-7).ToJavaTimeStamp();

            var readRequest = new DataReadRequest.Builder()
                              .Aggregate(DataType.TypeBasalMetabolicRate, DataType.AggregateBasalMetabolicRateSummary)
                              .BucketByTime(1, TimeUnit.Days)
                              .SetTimeRange(startDate, endDate.ToJavaTimeStamp(), TimeUnit.Milliseconds).Build();

            var response = await FitnessClass.GetHistoryClient(_currentActivity, GoogleSignIn.GetLastSignedInAccount(_currentActivity))
                           .ReadDataAsync(readRequest);

            if (response.Status.IsSuccess)
            {
                var avgsN = 0;
                foreach (var bucket in response.Buckets)
                {
                    // in the com.google.bmr.summary data type, each data point represents
                    // the average, maximum and minimum basal metabolic rate, in kcal per day, over the time interval of the data point.
                    var dataSet = bucket.GetDataSet(DataType.AggregateBasalMetabolicRateSummary);
                    foreach (var dataPoint in dataSet.DataPoints)
                    {
                        var avg = dataPoint.GetValue(Field.FieldAverage).AsFloat();
                        if (avg > 0)
                        {
                            basalAvg += avg;
                            avgsN++;
                        }
                    }
                }

                // do the average of the averages
                if (avgsN != 0)
                {
                    basalAvg /= avgsN;             // this a daily average
                }
                return(basalAvg);
            }

            throw new Exception(response.Status.StatusMessage);
        }
Пример #30
0
        public void RequestFitnessPermissions()
        {
            //we have to do all this hullaballoo because Xamarin.PlayServices.Fitness does not contain a constructor for FitnessOptions
            //IntPtr classRef = JNIEnv.FindClass("com/google/android/gms/fitness/FitnessOptions$Builder");
            //IntPtr constructorId = JNIEnv.GetMethodID(classRef, "<init>", "I(V)");
            //IntPtr referenceInstance = JNIEnv.NewObject(classRef, constructorId);

            //var fitnessApiOptions = new FitnessOptions.Builder()
            var fitnessApiOptions = FitnessOptions.InvokeBuilder()
                                    .AddDataType(Android.Gms.Fitness.Data.DataType.AggregateActivitySummary, FitnessOptions.AccessWrite)
                                    .AddDataType(Android.Gms.Fitness.Data.DataType.AggregateSpeedSummary, FitnessOptions.AccessWrite)
                                    .Build();

            account = GoogleSignIn.GetLastSignedInAccount(this);

            if (account == null && !googleLoginInProgress)
            {
                GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DefaultSignIn)
                                          .RequestEmail()
                                          .Build();

                var signInClient = GoogleSignIn.GetClient(this, gso);
                googleLoginInProgress = true;
                StartActivityForResult(signInClient.SignInIntent, REQUEST_GOOGLE_SIGN_IN);
                return;
            }

            if (!GoogleSignIn.HasPermissions(account, fitnessApiOptions))
            {
                GoogleSignIn.RequestPermissions(
                    this,
                    REQUEST_FITNESS_PERMISSIONS,
                    account,
                    fitnessApiOptions);
            }
            else
            {
                HasGoogleFitnessPermissions = true;
                GoogleFitnessPermissionsUpdated?.Invoke(HasGoogleFitnessPermissions);
            }
        }