コード例 #1
0
        public async Task <IUsuario> RegisterUser(string email, string password, string nome)
        {
            try
            {
                IAuthResult result = await FirebaseAuth.Instance.CreateUserWithEmailAndPasswordAsync(email, password);

                await result.User.UpdateProfileAsync(new UserProfileChangeRequest.Builder().SetDisplayName(nome).Build());

                GetTokenResult tokenResult = await result.User.GetIdTokenAsync(false);

                return(new Usuario()
                {
                    Uid = result.User.Uid, Token = tokenResult.Token, Email = email, DtLastLogin = DateTime.Now, Nome = nome, IsAdmin = false, IsPro = false
                });
            }
            catch (FirebaseAuthUserCollisionException e)
            {
                throw new Exception("Já existe um usuário registrado com o e-mail informado: " + email);
            }
            catch (FirebaseAuthEmailException e)
            {
                throw new Exception("O e-mail informado está preenchido incorretamente: " + email);
            }
            catch (Exception e)
            {
                throw new Exception("Erro: " + e.Message);
            }
        }
コード例 #2
0
        /// <summary>
        /// Detaches credentials from a given provider type from this user. This prevents the user from signing in to this account in the future with credentials from such provider.
        /// </summary>
        /// <param name="providerId">A unique identifier of the type of provider to be unlinked.</param>
        /// <returns>Task of IFirebaseUser</returns>
        public IObservable <IFirebaseUser> Unlink(string providerId)
        {
            return(Observable.Create <IFirebaseUser>(
                       async observer =>
            {
                IAuthResult authResult = null;

                try
                {
                    authResult = await _user.UnlinkAsync(providerId);
                }
                catch (Exception ex)
                {
                    observer.OnError(GetFirebaseAuthException(ex));
                    return;
                }

                observer.OnNext(new FirebaseUser(authResult.User));
                observer.OnCompleted();
            }));

            //return Observable.Create<IFirebaseUser>(
            //    observer =>
            //    {
            //        var subscription = _user.UnlinkAsync(providerId)
            //            .ToObservable()
            //            .Select(authResult => new FirebaseUser(authResult.User))
            //            .Subscribe(x => observer.OnNext(x), ex => observer.OnError(GetFirebaseAuthException(ex)));

            //        return new CompositeDisposable(subscription);
            //    });
        }
コード例 #3
0
        public static async Task <bool> FirebaseAuthWithGoogle(FirebaseAuth firebaseAuth, GoogleSignInAccount acct)
        {
            try
            {
                if (Connectivity.NetworkAccess == NetworkAccess.Internet)
                {
                    AuthCredential credential = GoogleAuthProvider.GetCredential(acct.IdToken, null);
                    IAuthResult    result     = await firebaseAuth.SignInWithCredentialAsync(credential);

                    if (result != null && result.User != null)
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
            catch (FirebaseNetworkException)
            {
                throw;
            }
            return(false);
        }
コード例 #4
0
        private async void MCallBacks_VerificationCompleted(object sender, EventArgs e)
        {
            IsLogin_InProgress(true);
            if (e == null)
            {
                throw new ArgumentNullException(nameof(e));
            }
            else
            {
                PhoneAuthCompletedEventArgs verifiedEvent = (PhoneAuthCompletedEventArgs)e;
                if (Dialog != null)
                {
                    Dialog.Dismiss();
                    Dialog.Dispose();
                }
                IAuthResult signinResult = await FirebaseAuth.SignInWithCredentialAsync(verifiedEvent.Credential);

                if (signinResult != null && signinResult.User != null)
                {
                    FirebaseUser user = signinResult.User;
                    Intent       mainactivityIntent = new Intent(this, typeof(MainActivity));
                    StartActivity(mainactivityIntent);
                    IsLogin_InProgress(false);
                    Finish();
                }
                else
                {
                    Toast.MakeText(this, "Authentication failed.", ToastLength.Long).Show();
                    IsLogin_InProgress(false);
                }
            }
        }
コード例 #5
0
        private async Task <IFirebaseAuthResult> LinkWithCredentialAsync(AuthCredential credential)
        {
            IAuthResult authResult = null;

            try
            {
                authResult = await _user.LinkWithCredentialAsync(credential);
            }
            catch (Firebase.Auth.FirebaseAuthException ex)
            {
                Console.WriteLine(ex.Message);
                throw GetFirebaseAuthException(ex);
            }
            catch (RuntimeWrappedException ex)
            {
                var authEx = ex.WrappedException as Firebase.Auth.FirebaseAuthException;
                throw GetFirebaseAuthException(ex);
            }
            catch
            {
                Console.WriteLine("Uh oh");
                throw;
            }

            return(new FirebaseAuthResult(authResult));
        }
コード例 #6
0
        async void ProcessSignInResult(Intent data)
        {
            GoogleSignInResult signInResult = Auth.GoogleSignInApi.GetSignInResultFromIntent(data);

            if (signInResult.IsSuccess)
            {
                AuthCredential credential = GoogleAuthProvider.GetCredential(signInResult.SignInAccount.IdToken, null);
                try
                {
                    IAuthResult authResult = await FirebaseAuth_.SignInWithCredentialAsync(credential);

                    FirebaseUser user = authResult.User;

                    User.myInfo.PhotoPath = signInResult.SignInAccount.PhotoUrl.ToString();

                    User.Uid             = signInResult.SignInAccount.Id;
                    User.Token           = signInResult.SignInAccount.IdToken;
                    User.myInfo.NickName = signInResult.SignInAccount.DisplayName;

                    StartActivity(new Intent(Application.Context, typeof(MainActivity)));
                }
                catch (Exception ex)
                {
                    //    new Handler(MainLooper).Post(() => new Android.App.AlertDialog.Builder(this).SetMessage("var_TeamRecord 등록 실패\n\n" + ex).Show());
                }
            }
            else
            {
                StartActivity(new Intent(Application.Context, typeof(MainActivity)));
            }
        }
コード例 #7
0
        async void ProcessSignInResult(Intent data)
        {
            GoogleSignInResult signInResult = Auth.GoogleSignInApi.GetSignInResultFromIntent(data);

            if (signInResult.IsSuccess)
            {
                AuthCredential credential = GoogleAuthProvider.GetCredential(signInResult.SignInAccount.IdToken, null);
                try
                {
                    User.PhotoPath = signInResult.SignInAccount.PhotoUrl.ToString();

                    User.Uid      = signInResult.SignInAccount.Id;
                    User.Token    = signInResult.SignInAccount.IdToken;
                    User.NickName = signInResult.SignInAccount.DisplayName;

                    IAuthResult authResult = await FirebaseAuth_.SignInWithCredentialAsync(credential);

                    FirebaseUser user = authResult.User;
                }
                catch (Exception ex)
                {
                    //                    new Handler(MainLooper).Post(() => new AlertDialog.Builder(this).SetMessage("파이어베이스 등록 실패\n\n" + ex).Show());
                }
            }
            else
            {
            }
        }
コード例 #8
0
        public async Task <string> LoginUser(string eMail, string password)
        {
            IAuthResult user = await FirebaseAuth.Instance.SignInWithEmailAndPasswordAsync(eMail, password);

            var token = await user.User.GetIdTokenAsync(false);

            return(token.Token);
        }
コード例 #9
0
 static MaybeNotNull <UserInfo> OAuthInfo(IAuthResult r)
 {
     return(from p in Maybe.Value(r as OAuthResult)
            select new UserInfo
     {
         Name = s(p, "name") ?? s(p, "first_name") + " " + s(p, "last_name"),
         Email = s(p, "email")
     });
 }
コード例 #10
0
        public override async Task <bool> LoginUserAsync(string username, string password)
        {
            IAuthResult result = await FirebaseAuth.Instance.SignInWithEmailAndPasswordAsync(username, password);

            user    = result.User;
            IsLogin = true;
            InitDatabase();
            return(user != null);
        }
コード例 #11
0
        private void TaskCompletionListener_Success(object sender, IAuthResult Result)
        {
            Animator.FadeOut();
            var User = Result.User as FullCustomerUser;

            UserUtil.SaveIfValid(User.Email, User.Password);
            StartActivity(typeof(MainActivity));
            Finish();
        }
コード例 #12
0
 static MaybeNotNull <UserInfo> OpenIdInfo(IAuthResult r)
 {
     return(from p in Maybe.Value(r as OpenIdAuthResult)
            from fetch in p.Response.GetExtension <FetchResponse>()
            select new UserInfo
     {
         Name = fetch.GetAttributeValue(WellKnownAttributes.Name.Alias),
         Email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email)
     });
 }
コード例 #13
0
 void webBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
 {
     AuthResult = AuthHelper.GetResult(e.Uri);
     if (AuthResult != null)
     {
         this.DialogResult = AuthResult.IsSuccessful;
         this.Close();
         MessageBox.Show(AuthResult.ToString());
     }
 }
コード例 #14
0
        void TaskCompletionListener_Success(object sender, IAuthResult Result)
        {
            Animator.FadeOut();
            Snackbar.Make(RootView, "¡Registro exitoso!", Snackbar.LengthShort).Show();
            var User = Result.User as FullCustomerUser;

            UserUtil.SaveIfValid(User.Email, User.Password);
            StartActivity(typeof(MainActivity));
            Finish();
        }
コード例 #15
0
        public async Task <string> registerWithEmailPassword(string email, string password)
        {
            mAuth = FirebaseAuth.Instance;
            IAuthResult result = await mAuth.CreateUserWithEmailAndPasswordAsync(email, password);

            var token = await result.User.GetIdTokenAsync(false);

            Xamarin.Forms.Application.Current.Properties["uid"] = result.User.Uid;
            return(token.Token);

            Console.WriteLine(result);
        }
コード例 #16
0
        public async Task <FirebaseAuthResponseModel> LoginWithEmailPassword(string email, string password)
        {
            try
            {
                FirebaseAuthResponseModel response = new FirebaseAuthResponseModel()
                {
                    Status = true, Response = "Login successful."
                };
                IAuthResult result = await FirebaseAuth.Instance.SignInWithEmailAndPasswordAsync(email, password);

                if (result.User.IsEmailVerified && email == result.User.Email)
                {
                    var document = await CrossCloudFirestore.Current
                                   .Instance
                                   .GetCollection("users")
                                   .GetDocument(result.User.Uid)
                                   .GetDocumentAsync();

                    var yourModel = document.ToObject <Account>();

                    dataClass.LoggedInUser = new Account()
                    {
                        Uid       = result.User.Uid,
                        Email     = result.User.Email,
                        UserName  = yourModel.UserName,
                        UserType  = yourModel.UserType,
                        CreatedAt = yourModel.CreatedAt,
                        contacts  = yourModel.contacts
                    };
                    dataClass.SignedIn = true;
                }
                else
                {
                    FirebaseAuth.Instance.CurrentUser.SendEmailVerification();
                    response.Status        = false;
                    response.Response      = "Email not verified. Sent another verification email.";
                    dataClass.LoggedInUser = new Account();
                    dataClass.SignedIn     = false;
                }

                return(response);
            }
            catch (Exception ex)
            {
                FirebaseAuthResponseModel response = new FirebaseAuthResponseModel()
                {
                    Status = false, Response = ex.Message
                };
                dataClass.SignedIn = false;
                return(response);
            }
        }
コード例 #17
0
        public async Task <string> Register(string eMail, string password, string name)
        {
            IAuthResult user = await FirebaseAuth.Instance.CreateUserWithEmailAndPasswordAsync(eMail, password);

            UserProfileChangeRequest.Builder profileUpdates = new UserProfileChangeRequest.Builder();
            profileUpdates.SetDisplayName(name);
            UserProfileChangeRequest updates = profileUpdates.Build();
            await user.User.UpdateProfileAsync(updates);

            var token = await user.User.GetIdTokenAsync(false);

            return(token.Token);
        }
コード例 #18
0
        private async Task <IFirebaseAuthResult> SignInAsync(AuthCredential credential)
        {
            try
            {
                IAuthResult authResult = await _auth.SignInWithCredentialAsync(credential);

                return(new FirebaseAuthResult(authResult));
            }
            catch (FirebaseException ex)
            {
                throw GetFirebaseAuthException(ex);
            }
        }
コード例 #19
0
        /// <summary>
        /// Signs in the user anonymously without requiring any credential.
        /// </summary>
        /// <returns>Task of IUserWrapper with the result of the operation</returns>
        public async Task <IFirebaseUser> SignInAnonymouslyAsync()
        {
            try
            {
                IAuthResult authResult = await _auth.SignInAnonymouslyAsync();

                return(new FirebaseUser(authResult.User));
            }
            catch (Exception ex)
            {
                throw GetFirebaseAuthException(ex);
            }
        }
コード例 #20
0
        /// <summary>
        /// Detaches credentials from a given provider type from this user. This prevents the user from signing in to this account in the future with credentials from such provider.
        /// </summary>
        /// <param name="providerId">A unique identifier of the type of provider to be unlinked.</param>
        /// <returns>Task of IUserWrapper</returns>
        public async Task <IFirebaseUser> UnlinkAsync(string providerId)
        {
            try
            {
                IAuthResult authResult = await _user.UnlinkAsync(providerId);

                return(new FirebaseUser(authResult.User));
            }
            catch (FirebaseException ex)
            {
                throw GetFirebaseAuthException(ex);
            }
        }
コード例 #21
0
        /// <summary>
        /// Signs the user in via email.
        /// </summary>
        /// <param name="email">The user’s email address.</param>
        /// <param name="password">The user’s password.</param>
        /// <returns>User account</returns>
        public async Task <IFirebaseAuthResult> SignInWithEmailAsync(string email, string password)
        {
            try
            {
                IAuthResult authResult = await _auth.SignInWithEmailAndPasswordAsync(email, password);

                return(new FirebaseAuthResult(authResult));
            }
            catch (Exception ex)
            {
                throw GetFirebaseAuthException(ex);
            }
        }
コード例 #22
0
        public override async Task SignInAsync(IAuthResult loginResult)
        {
            if (loginResult == null)
            {
                return;
            }
            var principal = GetPrincipalFromExpiredToken(loginResult.AccessToken);

            principal.Identities.First().AddClaim(new Claim("Token", loginResult.AccessToken));
            principal.Identities.First().AddClaim(new Claim("Refresh", loginResult.RefreshToken));
            /*for next request in this request*/
            httpContextAccessor.HttpContext.User = principal;
        }
コード例 #23
0
        private async void RegisterUser()
        {
            try
            {
                //editMail.Text = "*****@*****.**";
                //editUsername.Text = "TESTuSER";
                //editPassword.Text = "Tafra123";
                using IAuthResult authResult = await FirebaseHandler.Instance.Auth
                                               .CreateUserWithEmailAndPasswordAsync(editMail.Text, editPassword.Text)
                                               .ConfigureAwait(false);

                using UserProfileChangeRequest profile = new UserProfileChangeRequest.Builder()
                                                         .SetDisplayName(editUsername.Text)
                                                         .Build();

                await authResult.User
                .UpdateProfileAsync(profile)
                .ConfigureAwait(false);

                UserProfile up = new UserProfile(editUsername.Text, editMail.Text);
                UserGroups  ug = new UserGroups()
                {
                    Creator = new User(up)
                };

                System.Collections.Generic.List <Task> tasks = Instance.InitFirestoreUser(editUsername.Text, editMail.Text);
                Task.WaitAll(tasks.ToArray());
                if (tasks.All(t => t.IsCompletedSuccessfully))
                {
                    Instance.LoadUserData(editUsername.Text);
                    StartActivity(typeof(MainActivity));
                    Finish();
                }
                else
                {
                    MainThread.BeginInvokeOnMainThread(() =>
                    {
                        Toast.MakeText(ApplicationContext, Resource.String.err_failed_to_save_firestore, ToastLength.Short)
                        .Show();
                    });
                }
            }
            catch (FirebaseException excepion)
            {
                MainThread.BeginInvokeOnMainThread(() =>
                {
                    Toast.MakeText(ApplicationContext, excepion.Message, ToastLength.Short)
                    .Show();
                });
            }
        }
コード例 #24
0
ファイル: AuthDroid.cs プロジェクト: HunterComer49/chore-core
        public async Task <string> SignUpWithEmailPassword(string email, string password)
        {
            try
            {
                IAuthResult user = await FirebaseAuth.Instance.CreateUserWithEmailAndPasswordAsync(email, password);

                GetTokenResult token = await user.User.GetIdTokenAsync(false);

                return(token.Token);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
コード例 #25
0
        async public Task <string> LoginWithEmailPassword(string email, string password)
        {
            try
            {
                IAuthResult user = await FirebaseAuth.Instance.SignInWithEmailAndPasswordAsync(email, password);

                var token = await user.User.GetIdTokenAsync(false);

                return(token.Token);
            }
            catch (FirebaseAuthInvalidUserException e)
            {
                e.PrintStackTrace();
                return("");
            }
        }
コード例 #26
0
        public async Task <bool> LoginAsync(string email, string password)
        {
            try
            {
                this._authResult = await CrossFirebaseAuth.Current
                                   .GetInstance(ApiKeys.FirebaseName)
                                   .SignInWithEmailAndPasswordAsync(email, password);
            }
            catch (Exception ex)
            {
                throw;
            }


            return(this._authResult != null && this._authResult.User != null);
        }
コード例 #27
0
ファイル: ITokenService.cs プロジェクト: maximiliysiss/seac
        public virtual async Task SignInAsync(IAuthResult loginResult)
        {
            if (loginResult == null)
            {
                return;
            }
            var principal = GetPrincipalFromExpiredToken(loginResult.AccessToken);

            principal.Identities.First().AddClaim(new Claim("Token", loginResult.AccessToken));
            principal.Identities.First().AddClaim(new Claim("Refresh", loginResult.RefreshToken));
            await httpContextAccessor.HttpContext.SignOutAsync();

            await httpContextAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties());

            /*for next request in this request*/
            httpContextAccessor.HttpContext.User = principal;
        }
コード例 #28
0
        public Task <OnFireBaseCommandResult <string> > SignInAsync(string email, string password) =>
        Task <OnFireBaseCommandResult <string> > .Run(async() =>
        {
            OnFireBaseCommandResult <string> result = null;

            try
            {
                IAuthResult authResult = await _firebaseAuth.SignInWithEmailAndPasswordAsync(email, password);
                result = new OnFireBaseCommandResult <string>(authResult.User.Uid, true, SUCCESSFUL_MESSAGE);
            }
            catch (System.Exception exc)
            {
                return(new OnFireBaseCommandResult <string>(string.Empty, false, exc.Message));
            }

            return(result);
        });
コード例 #29
0
        /// <summary>
        /// Attempts to sign in to Firebase with the given phone number, or provides a verification ID if unable.
        /// </summary>
        /// <param name="phoneNumber">The phone number for the account the user is signing up for or signing into. Make sure to pass in a phone number with country code prefixed with plus sign ('+').</param>
        /// <returns>PhoneNumberSignInResult containing either a verification ID or an IAuthResultWrapper</returns>
        public async Task <PhoneNumberSignInResult> SignInWithPhoneNumberAsync(string phoneNumber)
        {
            var completionHandler = new PhoneNumberVerificationCallbackWrapper();

            PhoneAuthProvider.Instance.VerifyPhoneNumber(phoneNumber, 60, TimeUnit.Seconds, CrossCurrentActivity.Current.Activity, completionHandler);

            PhoneNumberVerificationResult result = null;

            try
            {
                result = await completionHandler.Verify();
            }
            catch (Exception ex)
            {
                throw GetFirebaseAuthException(ex);
            }

            if (result.AuthCredential != null)
            {
                IAuthResult authResult = null;
                try
                {
                    authResult = await _auth.SignInWithCredentialAsync(result.AuthCredential);
                }
                catch (Exception ex)
                {
                    throw GetFirebaseAuthException(ex);
                }

                IFirebaseAuthResult authResultWrapper = new FirebaseAuthResult(authResult);
                return(new PhoneNumberSignInResult()
                {
                    AuthResult = authResultWrapper
                });
            }
            else
            {
                return(new PhoneNumberSignInResult()
                {
                    VerificationId = result.VerificationId
                });
            }
        }
コード例 #30
0
 public static async Task <bool> FirebaseAuthWithFacebook(FirebaseAuth firebaseAuth, AccessToken fbUserToken)
 {
     try
     {
         if (Connectivity.NetworkAccess == NetworkAccess.Internet)
         {
             using (AuthCredential credential = FacebookAuthProvider.GetCredential(fbUserToken.Token))
             {
                 using (IAuthResult result = await firebaseAuth.SignInWithCredentialAsync(credential))
                 {
                     return(result != null && result.User != null);
                 }
             }
         }
     }
     catch (Exception e)
     {
         Crashlytics.Crashlytics.LogException(Java.Lang.Throwable.FromException(e));
     }
     return(false);
 }
コード例 #31
0
        public async Task <IUsuario> LoginWithEmailPassword(string email, string password)
        {
            try
            {
                IAuthResult user = await FirebaseAuth.Instance.SignInWithEmailAndPasswordAsync(email, password);

                GetTokenResult tokenResult = await user.User.GetIdTokenAsync(false);

                Usuario usr = new Usuario();
                usr.Uid         = user.User.Uid;
                usr.Token       = tokenResult.Token;
                usr.Nome        = user.User.DisplayName;
                usr.Email       = email;
                usr.DtLastLogin = DateTime.Now;

                return(usr);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }