예제 #1
0
        public async Task <bool> SignInWithGoogle(string tokenId)
        {
            String[] tokens     = tokenId.Split(new string[] { "###" }, StringSplitOptions.None);
            var      credential = GoogleAuthProvider.GetCredential(tokens[0], tokens[1]);

            Auth.DefaultInstance.SignIn(credential, HandleAuthResultHandlerGoogleSignin);
            token = tokenSource.Token;
            t     = Task.Factory.StartNew(async() =>
            {
                await Task.Delay(4000);
            }, token).Unwrap();
            await t;

            return(loginResult);
        }
예제 #2
0
        public async Task <string> LoginWithGoogle(string IdTok, string accessTok)
        {
            var cred = GoogleAuthProvider.GetCredential(IdTok, accessTok);

            var user = await FirebaseAuth.Instance.SignInWithCredentialAsync(cred);

            if (user != null)
            {
                return(user.User.Uid);
            }
            else
            {
                return(null);
            }
        }
예제 #3
0
        private async void FirebaseLogin(GoogleSignInAccount account)
        {
            var credentials = GoogleAuthProvider.GetCredential(account.IdToken, null);
            var instance    = FirebaseAuth.GetInstance(app);

            if (instance == null)
            {
                instance = new FirebaseAuth(app);
            }
            var result = await instance.SignInWithCredentialAsync(credentials);

            if (result.User != null)
            {
            }
        }
    public void GoogleLogIn()
    {
        auth = FirebaseAuth.DefaultInstance;
        GoogleSignIn.Configuration = new GoogleSignInConfiguration
        {
            RequestIdToken = true,
            // Copy this value from the google-service.json file.
            // oauth_client with type == 3
            WebClientId = "471308679030-umh5t7e244umvfkp29i05f24av0ojvjf.apps.googleusercontent.com"
        };
        Task <GoogleSignInUser> signIn = GoogleSignIn.DefaultInstance.SignIn();

        TaskCompletionSource <FirebaseUser> signInCompleted = new TaskCompletionSource <FirebaseUser>();

        signIn.ContinueWithOnMainThread(task => {
            if (task.IsCanceled)
            {
                signInCompleted.SetCanceled();
            }
            else if (task.IsFaulted)
            {
                signInCompleted.SetException(task.Exception);
            }
            else
            {
                Credential credential = GoogleAuthProvider.GetCredential(((Task <GoogleSignInUser>)task).Result.IdToken, null);
                auth.SignInWithCredentialAsync(credential).ContinueWith(authTask => {
                    if (authTask.IsCanceled)
                    {
                        signInCompleted.SetCanceled();
                    }
                    else if (authTask.IsFaulted)
                    {
                        signInCompleted.SetException(authTask.Exception);
                    }
                    else
                    {
                        signInCompleted.SetResult(((Task <FirebaseUser>)authTask).Result);
                    }
                });
            }
            DisplayUserName(true, signIn.Result);
            StartCoroutine(DisplayUserProfilePic(true, signIn.Result));
            cnt++;
        });

        PlayerPrefs.SetInt("Google", 1);
    }
 public void SignInWithGoogle(string idToken, string accessToken, Action <FirebaseUserResult> callback)
 {
     if ((Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer) && !Application.isEditor)
     {
         Credential credential = GoogleAuthProvider.GetCredential(idToken, accessToken);
         targetBehaviour.StartCoroutine(ProcessFirebaseUserTaskRoutine(auth.SignInWithCredentialAsync(credential), callback));
     }
     else
     {
         WWWForm form = new WWWForm();
         form.AddField("id_token", idToken);
         form.AddField("access_token", accessToken);
         WWW www = new WWW(serviceUrl + "/signInWithGoogle", form);
         targetBehaviour.StartCoroutine(ProcessWebServiceUserRoutine(www, callback));
     }
 }
        public void DidSignIn(GoogleSignIn signIn, GoogleUser user, NSError error)
        {
            if (error == null && user != null)
            {
                var authentication = user.Authentication;
                googleToken = authentication.IdToken;
                var credential = GoogleAuthProvider.GetCredential(authentication.IdToken, authentication.AccessToken);

                Auth.DefaultInstance.SignInWithCredential(credential, SignInOnCompletion);
            }
            else
            {
                googleToken = string.Empty;
                SetVerificationStatus(VerificationStatus.Failed, error.LocalizedDescription);
            }
        }
예제 #7
0
    bool SignInInFirebaseWithGoogleCredential(string googleIdToken)
    {
        bool authed = false;

        if (googleIdToken != "")
        {
            if (loadingText != null)
            {
                loadingText.text = "local user authed, now trying the credential";
            }
            Debug.Log("local user authed, now trying the credential");

            Credential credential = GoogleAuthProvider.GetCredential(googleIdToken, null);
            auth.SignInWithCredentialAsync(credential).ContinueWith(task =>
            {
                authed = task.IsCompleted;
                if (task.IsCanceled)
                {
                    if (loadingText != null)
                    {
                        loadingText.text = "task was canceled";
                    }
                    Debug.Log("task was canceled");
                    authed = false;
                    //GameEvents.UserLoginStatusUpdateFirer(false);
                }
                else if (task.IsFaulted)
                {
                    if (loadingText != null)
                    {
                        loadingText.text = "task is faulted";
                    }
                    Debug.Log("task is faulted");
                    //GameEvents.UserLoginStatusUpdateFirer(false);
                }
                else
                {
                    if (loadingText != null)
                    {
                        loadingText.text = "allright";
                    }
                    Debug.Log("allright");
                }
            });
        }
        return(authed);
    }
        /// <summary>
        /// Handle google result
        /// </summary>
        /// <param name="result"></param>
        private void HandleGoogleSignInResult(GoogleSignInResult result)
        {
            if (result.IsSuccess)
            {
                var accountDetails = result.SignInAccount;
                var gCred          = GoogleAuthProvider.GetCredential(accountDetails.IdToken, null);
                fireBaseManager.mAuth.SignInWithCredential(gCred).AddOnCompleteListener(this, this);

                Toast.MakeText(this, "Google Authentication Success. -" + accountDetails.DisplayName, ToastLength.Short).Show();
                //StartActivity(typeof(HomeActivity));
            }
            else
            {
                Toast.MakeText(this, "Google Authentication failed. -" + result.Status, ToastLength.Short).Show();
                System.Console.WriteLine(result.Status.ToString());
            }
        }
        public void DidSignIn(SignIn signIn, GoogleUser user, NSError error)
        {
            if (error == null && user != null)
            {
                // Get Google ID token and Google access token and exchange them for a Firebase credential
                var authentication = user.Authentication;
                var credential     = GoogleAuthProvider.GetCredential(authentication.IdToken, authentication.AccessToken);

                // Authenticate with Firebase using the credential
                Auth.DefaultInstance.SignInWithCredential(credential, SignInOnCompletion);
            }
            else
            {
                BtnSignIn.Enabled = true;
                AppDelegate.ShowMessage("Could not login!", error.LocalizedDescription, NavigationController);
            }
        }
예제 #10
0
        public async Task SignInWithGoogle(string token)
        {
            try
            {
                AuthCredential credential = GoogleAuthProvider.GetCredential

                                                (token, null);
                await Firebase.Auth.FirebaseAuth.GetInstance(MainActivity.app)

                .SignInWithCredentialAsync(credential);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
예제 #11
0
        private void OnGoogleAuthenticationFinished(Task <GoogleSignInUser> task)
        {
            if (task.IsFaulted)
            {
                Utils.ShowMessage("Login Failed");
            }
            else if (task.IsCanceled)
            {
            }
            else
            {
                var credential = GoogleAuthProvider.GetCredential(task.Result.IdToken, null);

                _showLoading.Raise();

                _auth.SignInWithCredentialAsync(credential).ContinueWith(OnSignInWithCredentialsFinished);
            }
        }
        // [END onactivityresult]

        // [START auth_with_google]
        async Task FirebaseAuthWithGoogle(GoogleSignInAccount acct)
        {
            Android.Util.Log.Debug(TAG, "firebaseAuthWithGoogle:" + acct.Id);
            // [START_EXCLUDE silent]
            ShowProgressDialog();
            // [END_EXCLUDE]

            AuthCredential credential = GoogleAuthProvider.GetCredential(acct.IdToken, null);

            try {
                await mAuth.SignInWithCredentialAsync(credential);
            } catch {
                Toast.MakeText(this, "Authentication failed.", ToastLength.Short).Show();
            }
            // [START_EXCLUDE]
            HideProgressDialog();
            // [END_EXCLUDE]
        }
        private async Task <bool> SignInWithGoogle(string token)
        {
            try
            {
                Log.Debug("TOOLBELT", $"Signing in with Google using token: {token}");
                AuthCredential credential = GoogleAuthProvider.GetCredential(token, null);

                Log.Debug("TOOLBELT", $"Signing in to Firebase");
                await GetFirebaseAuthInstance().SignInWithCredentialAsync(credential);

                return(true);
            }
            catch (Exception ex)
            {
                Log.Error("TOOLBELT", ex.ToString());
                this.Log().ErrorException("Error signing in with Google", ex);
                return(false);
            }
        }
예제 #14
0
        public static async Task AuthWithGoogleAsync(Intent data)
        {
            var result = Android.Gms.Auth.Api.Auth.GoogleSignInApi.GetSignInResultFromIntent(data);

            var credential = GoogleAuthProvider.GetCredential(result.SignInAccount.IdToken, null);

            CurrentFirebaseInstance.SignInWithCredential(credential);
            var user = CurrentFirebaseInstance.CurrentUser;

            QSN.Helpers.Settings.UserId = user.Uid;
            var tokenObject = await user.GetIdTokenAsync(false);

            QSN.Helpers.Settings.UserToken = tokenObject.Token;

            QSN.Helpers.Settings.UserImage = result.SignInAccount.PhotoUrl.ToString();
            QSN.Helpers.Settings.UserName  = result.SignInAccount.DisplayName;

            Xamarin.Forms.Application.Current.MainPage = new Xamarin.Forms.MasterDetailPage()
            {
                Master = new MasterPage()
                {
                    Title = "Main Page"
                },
                Detail = new Xamarin.Forms.NavigationPage(new QuotesPage())
            };


            // Get info from Google if needed ?
            #region GetInfo
            //await CurrentFirebaseInstance.SignInWithCredentialAsync(credential);
            //var user = CurrentFirebaseInstance.CurrentUser;

            //var userModel = new UserModel()
            //{
            //    Email = result.SignInAccount.Email,
            //    FirebaseId = user.Uid,
            //    Name = result.SignInAccount.DisplayName,
            //    PhotoUrl = result.SignInAccount.PhotoUrl.ToString(),
            //    ProviderId = result.SignInAccount.Id

            //};
            #endregion
        }
예제 #15
0
    IEnumerator FireBaseAuthorization()
    {
        Debug.Log($"-----------FireBaseAuthorization-----------");
        string idToken = string.Empty;

        while (true)
        {
            var playGamesLocalUser = (PlayGamesLocalUser)Social.localUser;
            idToken = playGamesLocalUser.GetIdToken();
            if (!string.IsNullOrEmpty(idToken))
            {
                break;
            }
            yield return(null);
        }
        Debug.Log($"--------------------> token: {idToken}");
        var auth = FirebaseAuth.DefaultInstance;

        Debug.Log($"auth: {auth}");
        Credential credential = GoogleAuthProvider.GetCredential(idToken, null);

        auth.SignInWithCredentialAsync(credential).ContinueWith(task =>
        {
            Debug.Log($"task.Status: {task.Status}");

            if (task.IsCanceled)
            {
                Debug.LogError("SignInWithCredentialAsync was canceled.");
                return;
            }
            if (task.IsFaulted)
            {
                Debug.LogError("SignInWithCredentialAsync encountered an error: " + task.Exception);
                return;
            }

            Firebase.Auth.FirebaseUser newUser = task.Result;
            Debug.LogFormat("User signed in successfully: {0} ({1})",
                            newUser.DisplayName, newUser.UserId);
            this.firbaseUser = newUser;
        });
    }
예제 #16
0
    private void SignInWithGoogleOnFirebase(string idToken)
    {
        Credential credential = GoogleAuthProvider.GetCredential(idToken, null);

        auth.SignInWithCredentialAsync(credential).ContinueWith(task =>
        {
            AggregateException ex = task.Exception;
            if (ex != null)
            {
                if (ex.InnerExceptions[0] is FirebaseException inner && (inner.ErrorCode != 0))
                {
                    AddToInformation("\nError code = " + inner.ErrorCode + " Message = " + inner.Message);
                }
            }
            else
            {
                AddToInformation("Sign In Successful.");
            }
        });
    }
예제 #17
0
        public async Task <bool> LoginWithFirebase(GoogleSignInAccount account)
        {
            bool isLoggin    = false;
            var  credentials = GoogleAuthProvider.GetCredential(account.IdToken, null);


            await firebaseAuth.SignInWithCredentialAsync(credentials).ContinueWith(task =>
            {
                if (task.IsCompletedSuccessfully)
                {
                    isLoggin = true;
                }
                else
                {
                    isLoggin = false;
                }
            });

            return(isLoggin);
        }
예제 #18
0
    IEnumerator coFirebaseManager()
    {
        while (System.String.IsNullOrEmpty(((PlayGamesLocalUser)Social.localUser).GetIdToken()))
        {
            yield return(null);
        }

        string idToken     = ((PlayGamesLocalUser)Social.localUser).GetIdToken();
        string accessToken = null;

        Credential credential = GoogleAuthProvider.GetCredential(idToken, accessToken);

        auth.SignInWithCredentialAsync(credential).ContinueWith(task => {
            if (task.IsCanceled)
            {
                Debug.LogError("SignInWithCredentialAsync was canceled.");
                return;
            }
            if (task.IsFaulted)
            {
                Debug.LogError("SignInWithCredentialAsync encountered an error: " + task.Exception);
                return;
            }

            FirebaseUser newUser = task.Result;
            Debug.LogFormat("User signed in successfully: {0} ({1})",
                            newUser.Email, newUser.UserId);

            Firebase.Auth.FirebaseUser user = auth.CurrentUser;
            userName  = newUser.DisplayName;
            userEmail = newUser.Email;
            userId    = newUser.UserId;
            //          loginResult.text = "이름" + userName + "메일" + userEmail + "아이디" + userId + "구글 로그인 굿럭";
        });
        if (userId != null)
        {
            SceneManager.LoadScene("GoogleSuccessSignup");
        }
    }
예제 #19
0
        public async Task <AppUser> LoginWithGoogle(string IdTok, string accessTok)
        {
            var cred = GoogleAuthProvider.GetCredential(IdTok, accessTok);

            var user = await FirebaseAuth.Instance.SignInWithCredentialAsync(cred);

            if (user != null)
            {
                AppUser appUser = new AppUser()
                {
                    Email   = user.User.Email,
                    Name    = user.User.DisplayName,
                    Picture = user.User.PhotoUrl.ToString(),
                    Uid     = user.User.Uid
                };
                return(appUser);
            }
            else
            {
                return(null);
            }
        }
예제 #20
0
    public async void SignInWithGoogleOnFirebase(string idToken)
    {
        try
        {
            Credential credential = GoogleAuthProvider.GetCredential(idToken, null);

            FirebaseUser newUser = await auth.SignInWithCredentialAsync(credential);

            // UpdateStatusSignIn("User with Google SignIn: " + newUser.Email + " " + newUser.UserId);
            FirebaseAnalytics.LogEvent(FirebaseAnalytics.EventLogin);

            // Checking email key node under users/userId exists or not
            var emailVar = await Router.UserWithUID(newUser.UserId).Child("email").GetValueAsync();

            if (emailVar.Exists)
            {
                SceneManager.LoadScene("App_Splash");
            }
            else
            {
                // Post to Firebase Database
                UserManager.emailVerified = "Email Terverifikasi";
                UserManager.authType      = "Google";
                UserManager.email         = newUser.Email;
                UserManager.levelUnlocked = "3";

                PostToDatabase(newUser.UserId);
                SceneManager.LoadScene("App_Splash");
            }
        }
        catch (AggregateException ex)
        {
            if (ex.InnerExceptions[0] is FirebaseException inner && (inner.ErrorCode != 0))
            {
                UpdateStatusSignIn("\nError Code= " + inner.ErrorCode + "Message= " + inner.Message);
            }
        }
    }
예제 #21
0
    private void SignInWithGoogleOnFirebase(string idToken)
    {
        Credential credential = GoogleAuthProvider.GetCredential(idToken, null);

        auth.SignInWithCredentialAsync(credential).ContinueWith(task =>
        {
            AggregateException ex = task.Exception;
            if (ex != null)
            {
                if (ex.InnerExceptions[0] is FirebaseException inner && (inner.ErrorCode != 0))
                {
                    AddToInformation("\nError code = " + inner.ErrorCode + " Message = " + inner.Message);
                }
            }
            else
            {
                UnityWebRequest www = UnityWebRequest.Post(string.Format("https://touchcrawler.appspot.com/addscore?key={0}&score={1}", idToken, UserSettings.score), "");
                www.SendWebRequest();
                SceneManager.LoadScene(MainMenu, LoadSceneMode.Single);
                AddToInformation("Sign In Successful.");
            }
        });
    }
예제 #22
0
    private void Start()
    {
        FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;

        Credential credential = GoogleAuthProvider.GetCredential(googleIdToken, googleAccessToken);

        auth.SignInWithCredentialAsync(credential).ContinueWith(task => {
            if (task.IsCanceled)
            {
                Debug.LogError("SignInWithCredentialAsync was canceled.");
                return;
            }
            if (task.IsFaulted)
            {
                Debug.LogError("SignInWithCredentialAsync encountered an error: " + task.Exception);
                return;
            }

            Firebase.Auth.FirebaseUser newUser = task.Result;
            Debug.LogFormat("User signed in successfully: {0} ({1})",
                            newUser.DisplayName, newUser.UserId);
        });
    }
예제 #23
0
    private IEnumerator WaitForTokenAndAuthenticateFirebase()
    {
        Debug.Log("Waiting for Google Token");
        while (PlayGamesPlatform.Instance.GetIdToken() == null)
        {
            yield return(new WaitForSeconds(1));
        }

        var auth       = FirebaseAuth.DefaultInstance;
        var token      = PlayGamesPlatform.Instance.GetIdToken();
        var credential = GoogleAuthProvider.GetCredential(token, null);

        auth.SignInWithCredentialAsync(credential).ContinueWith(task =>
        {
            if (task.IsCanceled)
            {
                Debug.LogError("SignInWithCredentialAsync was canceled.");
                return;
            }
            else if (task.IsFaulted)
            {
                Debug.LogError("SignInWithCredentialAsync encountered an error: " + task.Exception);
                return;
            }
            else if (task.IsCompleted)
            {
                var user = task.Result;
                Debug.LogFormat("User signed in to Firebase successfully: {0} ({1})",
                                user.DisplayName, user.UserId);

                LoadUserData(user.UserId);

                Debug.Log("Attempting to load user data");
            }
        });
    }
예제 #24
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie);

            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AuthorizeEndpointPath     = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(24),
                Provider             = new SimpleAuthorizationServerProvider(),
                RefreshTokenProvider = new SimpleRefreshTokenProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);

            KaribouAlpha.DAL.KaribouAlphaContext db = new DAL.KaribouAlphaContext();

            LinkedInAuthClient linkedInAuthClient = db.LinkedInAuthClients.SingleOrDefault(_linked => _linked.Active);

            if (linkedInAuthClient != null)
            {
                ILinkedInAuthenticationProvider providerLnk = new KaribouAlpha.Authentication.LinkedInAuthenticationProvider();
                LinkedInAuthenticationOptions = new LinkedInAuthenticationOptions()
                {
                    ClientId     = linkedInAuthClient.ClientId,
                    ClientSecret = linkedInAuthClient.ClientSecret,
                    Provider     = providerLnk,
                    CallbackPath = new PathString("/AuthCallBack."),
                    Scope        = { "r_basicprofile", "r_emailaddress" },
                    //BackchannelHttpHandler = new LinkedInBackChannelHandler()
                };
            }
            //http://www.c-sharpcorner.com/article/implementing-oauth2-0-authorization-for-google-in-asp-net/
            //https://developers.google.com/actions/identity/oauth2-code-flow

            GoogleAuthClient googleClient = db.GoogleAuthClients.SingleOrDefault(_google => _google.Active);

            if (googleClient != null)
            {
                GoogleAuthProvider gProvider = new GoogleAuthProvider();
                googleAuthOptions = new GoogleOAuth2AuthenticationOptions()
                {
                    ClientId     = googleClient.ClientId,
                    ClientSecret = googleClient.ClientSecret,
                    Provider     = gProvider
                };
            }

            KaribouAlpha.Models.FaceBookClient clientFb = db.FaceBookClients.SingleOrDefault(_fb => _fb.Active);
            if (clientFb != null)
            {
                var fbProvider          = new FacebookAuthProvider();
                var facebookAuthOptions = new FacebookAuthenticationOptions()
                {
                    AppId     = clientFb.AppId,
                    AppSecret = clientFb.AppSecret,
                    Provider  = fbProvider,
                };
                app.UseFacebookAuthentication(facebookAuthOptions);
            }
        }
예제 #25
0
    private void SignInWithGoogleOnFirebase(string idToken)
    {
        AddToInformation("SignInWithGoogleOnFirebase!" + idToken);
        Credential credential = GoogleAuthProvider.GetCredential(idToken, null);

        AddToInformation("SignInWithGoogleOnFirebase credential:" + credential);


        auth.SignInWithCredentialAsync(credential).ContinueWith(authTask =>
        {
            if (authTask.IsCanceled)
            {
                Debug.LogError("HandleSigninFirebaseGoogleResult was canceled.");
                AddToInformation("Login is Canceled!:");
                return;
            }
            if (authTask.IsFaulted)
            {
                Debug.LogError("HandleSigninFirebaseGoogleResult encountered an error: " + authTask.Exception);
                AddToInformation("Invalid Username or Password!");
                return;
            }
            SceneManager.LoadSceneAsync("scene_01");
        });
        AddToInformation("The End!");

        /*  auth.SignInWithCredentialAsync(credential).ContinueWith(authTask =>
         * {
         *   AggregateException ex = authTask.Exception;
         *   if (ex != null)
         *   {
         *         AddToInformation("Error!");
         *      // if (ex.InnerExceptions[0] is FirebaseException inner && (inner.ErrorCode != 0))
         *        //   AddToInformation("\nError code = " + inner.ErrorCode + " Message = " + inner.Message);
         *   }
         *   else
         *   {
         *         Firebase.Auth.FirebaseUser newUser = authTask.Result;
         *         statusText.text = "Google Sign In Successful.";
         *        AddToInformation("Google Sign In Successful.");
         *           // StartCoroutine(updateLastLoginTime(newUser.UserId));
         *       //SceneManager.LoadSceneAsync("Menu");
         *         playerReadRef=FirebaseDatabase.DefaultInstance.GetReference("players");
         *
         *         playerReadRef.Child(newUser.UserId).GetValueAsync().ContinueWith(task => {
         *     if (task.IsFaulted) {
         *               // Handle the error...
         *                AddToInformation("User Exist error task.IsFaulted.");
         *                Debug.Log("User Exist error task.IsFaulted");
         *           }
         *           else if (task.IsCompleted) {
         *             Debug.Log("User Exist checkTask Completed get User Detail :");
         *
         *               AddToInformation("User Exist checkTask Completed get User Detail.");
         *              DataSnapshot snapshot = task.Result;
         *             if(snapshot.Value!=null){
         *                 AddToInformation("Firebase Google user  Database Entry Exist = " + newUser.UserId);
         *
         *                     SceneManager.LoadSceneAsync("scene_01");
         *
         *
         *             }
         *             else {
         *                   AddToInformation("Firebase Google user  New User not found in  DB = " + newUser.UserId);
         *
         *                  SceneManager.LoadSceneAsync("GoogleAuthUserNameScene");
         *
         *             }
         *           }else {
         *               statusText.text = "Else Condtion";
         *                Debug.Log("Else condtion");
         *           }
         * });
         *   }
         *
         *
         * });   */
    }
        /// <summary>
        /// Attaches the given Google credentials to the user. This allows the user to sign in to this account in the future with credentials for such provider.
        /// </summary>
        /// <param name="idToken"></param>
        /// <param name="accessToken"></param>
        /// <returns>Updated current account</returns>
        public IObservable <IFirebaseAuthResult> LinkWithGoogle(string idToken, string accessToken)
        {
            AuthCredential credential = GoogleAuthProvider.GetCredential(idToken, accessToken);

            return(LinkWithCredentialAsync(credential).ToObservable());
        }
        /// <summary>
        /// Attaches the given Google credentials to the user. This allows the user to sign in to this account in the future with credentials for such provider.
        /// </summary>
        /// <param name="idToken">The ID Token from Google.</param>
        /// <param name="accessToken">The Access Token from Google.</param>
        /// <returns>Task of IUserWrapper</returns>
        public async Task <IFirebaseAuthResult> LinkWithGoogleAsync(string idToken, string accessToken)
        {
            AuthCredential credential = GoogleAuthProvider.GetCredential(idToken, accessToken);

            return(await LinkWithCredentialAsync(credential));
        }
예제 #28
0
        /// <inheritdoc/>
        public IObservable <Unit> SignInWithGoogle(string idToken, string accessToken)
        {
            AuthCredential credential = GoogleAuthProvider.GetCredential(idToken, accessToken);

            return(SignInAsync(credential).ToObservable().Select(_ => Unit.Default));
        }
        public IAuthCredential GetCredential(string idToken, string accessToken)
        {
            var credential = GoogleAuthProvider.GetCredential(idToken, accessToken);

            return(new AuthCredentialWrapper(credential));
        }
//Firebase autnetication using google Id token
    private void SignInWithGoogleOnFirebase(string idToken)
    {
        Credential credential = GoogleAuthProvider.GetCredential(idToken, null);

        // firebase aunthntication class function for login using google id oken
        auth.SignInWithCredentialAsync(credential).ContinueWith(task =>
        {
            AggregateException ex = task.Exception;
            if (ex != null)
            {
                AddToInformation("Firebase Sign in Error ! ");
                // if (ex.InnerExceptions[0] is FirebaseException inner && (inner.ErrorCode != 0))
                //     AddToInformation("\nError code = " + inner.ErrorCode + " Message = " + inner.Message);
            }
            else
            {
                AddToInformation("Sign In Successful Using Google Account!.");

                // take the user detail from the response Result
                Firebase.Auth.FirebaseUser newUser = task.Result;
                // set user deital to static variable to user as session
                loggedUser = newUser;
                // take the instance of player node in firebase
                playerReadRef = FirebaseDatabase.DefaultInstance.GetReference("players");
                //check weather user exist in the db
                playerReadRef.Child(newUser.UserId).GetValueAsync().ContinueWith(task2 => {
                    if (task2.IsFaulted)
                    {
                        // user mostly not exist , rare chance of error
                        // AddToInformation("Most porpably  User Not exist !");
                        Debug.Log("Most porpably  User Not exist !");
                        //So need to move user to screen which need to collect username and save to db
                        SceneManager.LoadSceneAsync("GoogleAuthUserNameScene");
                    }
                    else if (task2.IsCompleted)
                    {
                        //  AddToInformation("User Exist checkTask Completed get User Detail ");
                        Debug.Log("User Exist checkTask Completed get User Detail !");
                        DataSnapshot snapshot = task2.Result;
                        if (snapshot.Value != null)
                        {
                            //AddToInformation("User logged with current credintals: " + newUser.UserId);
                            Debug.Log("User logged with current credintals: " + newUser.UserId);
                            //call the function which wait until save the logged time
                            StartCoroutine(updateLastLoginTime(newUser.UserId));
                            //get the user name and profile picture for menu scene
                            StartCoroutine(GetIntailDbValues(newUser.UserId));
                            // redirect to menu scene
                            SceneManager.LoadSceneAsync("Menu");
                            // SceneManager.LoadSceneAsync("scene_01");
                        }
                        else
                        {
                            //if snapshot is null user not exist , not worked for unity
                            //  AddToInformation("The User is new User = "******"The User is new User = "******"GoogleAuthUserNameScene");
                        }
                    }
                    else
                    {
                        Debug.Log("Else condtion");
                    }
                });
            }
        });
    }