public bool Create(AuthCredential credential)
        {
            dbContext.AuthCredentials.Add(credential);
            int result = dbContext.SaveChanges();

            return(result > 0);
        }
        private void FirebaseAuthWithGoogle(GoogleSignInAccount acct)
        {
            //Google Credential
            AuthCredential credential = GoogleAuthProvider.GetCredential(acct.IdToken, null);

            _auth.SignInWithCredential(credential).AddOnCompleteListener(this, this);
        }
        async System.Threading.Tasks.Task LinkAccount()
        {
            // Make sure form is valid
            if (!ValidateLinkForm())
            {
                return;
            }

            // Get email and password from form
            var email    = mEmailField.Text;
            var password = mPasswordField.Text;

            // Create EmailAuthCredential with email and password
            AuthCredential credential = EmailAuthProvider.GetCredential(email, password);

            // Link the anonymous user to the email credential
            ShowProgressDialog();


            // [START link_credential]
            try {
                var result = await mAuth.CurrentUser.LinkWithCredentialAsync(credential);
            } catch (Exception ex) {
                Toast.MakeText(this, "Authentication failed.", ToastLength.Short).Show();
            }

            // [START_EXCLUDE]
            HideProgressDialog();
            // [END_EXCLUDE]
            // [END link_credential]
        }
Beispiel #4
0
        public async Task <AuthCredential> ProcessApprovedAuthCallbackAsync(RequestToken token)
        {
            if (token == null)
            {
                throw new ArgumentNullException("token", "RequestToken cannot be null");
            }

            if (string.IsNullOrWhiteSpace(token.Token))
            {
                throw new ArgumentNullException("token", "RequestToken.Token must not be null");
            }

            var oauthRequestToken = new AsyncOAuth.RequestToken(token.Token, token.Secret);
            var authorizer        = new OAuthAuthorizer(ConsumerKey, ConsumerSecret);
            var accessToken       = await authorizer.GetAccessToken(Constants.BaseApiUrl + Constants.TemporaryCredentialsAccessTokenUri, oauthRequestToken, token.Verifier);

            var result = new AuthCredential
            {
                AuthToken       = accessToken.Token.Key,
                AuthTokenSecret = accessToken.Token.Secret,
                UserId          = accessToken.ExtraData["encoded_user_id"].FirstOrDefault()
            };

            return(result);
        }
Beispiel #5
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.activity_main);

            // To use this you have to set up a project in the Firebase console and add the google-services.json file
            var baseOptions = FirebaseOptions.FromResource(Application.Context);
            var options     = new FirebaseOptions.Builder(baseOptions)
                              .SetProjectId(baseOptions.StorageBucket.Split('.')[0])
                              .Build();

            var fa = FirebaseApp.InitializeApp(Application.Context, options, "Xamarin");

            //FirebaseApp fa = FirebaseApp.InitializeApp(Application.Context);

            mAuth = FirebaseAuth.GetInstance(fa);

            if (mAuth == null)
            {
                Console.WriteLine("mAuth is null");
            }

            AuthCredential credential = EmailAuthProvider.GetCredential("*****@*****.**", "password");

            var creds = mAuth.SignInWithEmailAndPassword("*****@*****.**", "password"); // Here the program crashes due to a null mAuth
        }
        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));
        }
Beispiel #7
0
        async Task <AccountResponse> LoginToFirebase(AuthCredential credential)
        {
            try
            {
                var signinResult = await FirebaseAuth.Instance.SignInWithCredentialAsync(credential);

                var user = signinResult.User;

                var split = user.DisplayName.Split(' ');
                return(new AccountResponse
                {
                    Success = true,
                    User = new Clients.Portable.User()
                    {
                        Id = user.Uid,
                        Email = user.Email,
                        FirstName = split?.FirstOrDefault(),
                        LastName = split?.LastOrDefault()
                    }
                });
            }
            catch (System.Exception ex)
            {
                return(new AccountResponse
                {
                    Success = false,
                    Error = ex.Message
                });
            }
        }
        /// <summary>
        /// Attaches the given phone 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="verificationId">The verification ID obtained by calling VerifyPhoneNumber.</param>
        /// <param name="verificationCode">The 6 digit SMS-code sent to the user.</param>
        /// <returns>Updated current account</returns>
        public IObservable <IFirebaseAuthResult> LinkWithPhoneNumber(string verificationId, string verificationCode)
        {
            AuthCredential credential = PhoneAuthProvider.GetCredential(verificationId, verificationCode);

            return(_user.LinkWithCredentialAsync(credential).ToObservable().Select(x => new FirebaseAuthResult(x)));
            //return LinkWithCredentialAsync(credential).ToObservable();
        }
        public async Task <IActionResult> Upload(UploadZipFileModel uploadZipFileModel)
        {
            if (ModelState.IsValid)
            {
                var result = ZipFileProcessor.Process(uploadZipFileModel.ZipFile);

                if (result.IsFailure)
                {
                    Logger.LogError(result.Error);
                    ModelState.AddModelError("ZipFile", result.Error);
                    return(View(uploadZipFileModel));
                }

                var auth = new AuthCredential
                {
                    Password = uploadZipFileModel.Password,
                    Username = uploadZipFileModel.Username
                };

                var responseMessage = await ZipContentStorageHelper.SendContent(result.Value, auth);

                if (responseMessage.IsFailure)
                {
                    Logger.LogError(responseMessage.Error, result.Value);
                    ModelState.AddModelError("ZipFile", responseMessage.Error);
                    return(View(uploadZipFileModel));
                }

                return(RedirectToAction("Success"));
            }

            return(View(uploadZipFileModel));
        }
Beispiel #10
0
        //Final step. Take this authorization information and use it in the app
        public async Task <ActionResult> Callback()
        {
            RequestToken token = new RequestToken();

            token.Token    = Request.Params["oauth_token"];
            token.Secret   = Session["FitbitRequestTokenSecret"].ToString();
            token.Verifier = Request.Params["oauth_verifier"];

            string consumerKey    = ConfigurationManager.AppSettings["FitbitConsumerKey"];
            string consumerSecret = ConfigurationManager.AppSettings["FitbitConsumerSecret"];

            //this is going to go back to Fitbit one last time (server to server) and get the user's permanent auth credentials

            //create the Authenticator object
            var authenticator = new Authenticator(consumerKey, consumerSecret);

            //execute the Authenticator request to Fitbit
            AuthCredential credential = await authenticator.ProcessApprovedAuthCallbackAsync(token);

            //here, we now have everything we need for the future to go back to Fitbit's API (STORE THESE):
            //  credential.AuthToken;
            //  credential.AuthTokenSecret;
            //  credential.UserId;

            // For demo, put this in the session managed by ASP.NET
            Session["FitbitAuthToken"]       = credential.AuthToken;
            Session["FitbitAuthTokenSecret"] = credential.AuthTokenSecret;
            Session["FitbitUserId"]          = credential.UserId;

            return(RedirectToAction("Index", "Home"));
        }
Beispiel #11
0
        private object Upload(byte[] data, string filename, AuthCredential credential, string remotePath = null)
        {
            string     file  = System.IO.Path.GetFileName(filename);
            OAuthToken token = new OAuthToken();

            token.AccessToken         = credential.Token;
            token.AuthenticationToken = credential.Authentication;
            token.RefreshToken        = credential.Refresh;
            dynamic    result = null;
            OAuthError error  = null;
            string     destinationFolderId = null;

            try
            {
                destinationFolderId = createFolderIfNotExists("", remotePath, token, out error);
            }
            catch (UnauthorizedAccessException)
            {
                RequestAccessTokenByRefreshToken(token.RefreshToken, MogConstants.SKYDRIVE_REDIRECTURL, out token, out error);
                credential.Token          = token.AccessToken;
                credential.Authentication = token.AuthenticationToken;
                credential.Refresh        = token.RefreshToken;
                this.repoAuthCredential.SaveChanges(credential);
                destinationFolderId = createFolderIfNotExists("", remotePath, token, out error);
            }



            var url = string.Format("{0}/{1}/files/{2}?access_token={3}",
                                    skydriveApiUrl,
                                    destinationFolderId,
                                    filename,
                                    token.AccessToken);


            try
            {
                var request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Method        = "PUT";
                request.ContentLength = data.Length;


                using (var dataStream = request.GetRequestStream())
                {
                    dataStream.Write(data, 0, data.Length);
                }

                WebResponse response = request.GetResponse();

                StreamReader reader = new StreamReader(response.GetResponseStream());

                string json = reader.ReadToEnd();
                result = JsonConvert.DeserializeObject <dynamic>(json);
            }
            catch (Exception e)
            {
                //todo : do something with exception
            }
            return(result);
        }
Beispiel #12
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)));
            }
        }
Beispiel #13
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
            {
            }
        }
Beispiel #14
0
 public MogFile UploadFile(string filename, AuthCredential credential, string remotePath = null)
 {
     //upload file to skydrive
     //if everything is OK, return the file
     byte[] data = System.IO.File.ReadAllBytes(filename);
     return(UploadFile(data, filename, credential, remotePath));
 }
Beispiel #15
0
        private void FirebaseAuthWithGoogle(GoogleSignInAccount acct)
        {
            Log.Debug(Tag, "FirebaseAuthWithGoogle:" + acct.Id);
            AuthCredential credential = GoogleAuthProvider.GetCredential(acct.IdToken, null);

            mAuth.SignInWithCredential(credential).AddOnCompleteListener(this, this);
        }
Beispiel #16
0
        public async void OnAuthenticationCompleted(GoogleOAuthToken token)
        {
            // SFSafariViewController doesn't dismiss itself
            DismissViewController(true, null);

            DisplayLoadingIndicator();

            var googleUserInfo = await _authViewModel.RetrieveGoogleUserInfoAsync(token.TokenType, token.AccessToken);

            var firebaseUserInfo = await _authViewModel.AuthenticateUserWithFirebaseAsync(googleUserInfo);

            if (firebaseUserInfo != null)
            {
                AuthCredential credential = GoogleAuthProvider.GetCredential(token.IdToken, token.AccessToken);
                AuthDataResult result     = await FirebaseManager.Auth.SignInAndRetrieveDataWithCredentialAsync(credential);

                token.SaveToDevice();
                googleUserInfo.SaveToDevice();
                firebaseUserInfo.SaveToDevice();

                PerformSegueToHome(googleUserInfo.GivenName);
            }
            else
            {
                await _authViewModel.RevokeTokenAsync(token.TokenType, token.AccessToken);

                RemoveLoadingIndicator();

                txtNotAuthorizedMessage.Text = _authViewModel.FirebaseNotAuthorizedErrorMessage;
                GoogleLoginButton.Hidden     = true;
            }
        }
Beispiel #17
0
        public string AskForRegistrationUrl(UserProfileInfo user, string redirectUrl, out int tempCredentialId)
        {
            var       _client = new DropNetClient(MogConstants.DROPBOX_KEY, MogConstants.DROPBOX_SECRET);
            UserLogin login   = _client.GetToken();
            // UserLogin login = _client.GetAccessToken();
            var url   = _client.BuildAuthorizeUrl(login, redirectUrl);
            var query = repoAuthCredential.GetByUserId(user.Id);
            List <AuthCredential> existingCredentials = null;

            if (query != null)
            {//TODO : gerer le cas des accounts multiples
                existingCredentials = query.Where(a => a.CloudService == CloudStorageServices.Dropbox).ToList();
                foreach (var credential in existingCredentials)
                {
                    repoAuthCredential.Delete(credential);
                }
            }

            AuthCredential newCredential = new AuthCredential();

            newCredential.Token        = login.Token;
            newCredential.Secret       = login.Secret;
            newCredential.UserId       = user.Id;
            newCredential.CloudService = CloudStorageServices.Dropbox;
            this.repoAuthCredential.Create(newCredential);
            tempCredentialId = newCredential.Id;

            return(url);
        }
        private void handleFacebookAccessToken(AccessToken accessToken)
        {
            //Facebook Credential
            AuthCredential credential = FacebookAuthProvider.GetCredential(accessToken.Token);

            _auth.SignInWithCredential(credential).AddOnCompleteListener(this, this);
        }
        //Final step. Take this authorization information and use it in the app
        public ActionResult Callback()
        {
            string OAuthToken    = Request.Params["oauth_token"];
            string OAuthVerifier = Request.Params["oauth_verifier"];

            string ConsumerKey    = ConfigurationManager.AppSettings["FitbitConsumerKey"];
            string ConsumerSecret = ConfigurationManager.AppSettings["FitbitConsumerSecret"];

            //this is going to go back to Fitbit one last time (server to server) and get the user's permanent auth credentials

            //create the Authenticator object
            Fitbit.Api.Authenticator authenticator = new Fitbit.Api.Authenticator(ConsumerKey,
                                                                                  ConsumerSecret,
                                                                                  "http://api.fitbit.com/oauth/request_token",
                                                                                  "http://api.fitbit.com/oauth/access_token",
                                                                                  "http://api.fitbit.com/oauth/authorize");
            //execute the Authenticator request to Fitbit
            AuthCredential credential = authenticator.ProcessApprovedAuthCallback(OAuthToken, OAuthVerifier);

            //here, we now have everything we need for the future to go back to Fitbit's API (STORE THESE):
            //  credential.AuthToken;
            //  credential.AuthTokenSecret;
            //  credential.UserId;

            // For demo, put this in the session managed by ASP.NET
            Session["FitbitAuthToken"]       = credential.AuthToken;
            Session["FitbitAuthTokenSecret"] = credential.AuthTokenSecret;
            Session["FitbitUserId"]          = credential.UserId;

            return(RedirectToAction("Index", "Home"));
        }
        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);
        }
Beispiel #21
0
 public static IAuthCredential Create(AuthCredential authCredential)
 {
     return(authCredential switch
     {
         OAuthCredential oAuthCredential => new OAuthCredentialWrapper(oAuthCredential),
         PhoneAuthCredential phoneAuthCredential => new PhoneAuthCredentialWrapper(phoneAuthCredential),
         _ => new AuthCredentialWrapper(authCredential)
     });
Beispiel #22
0
        private void FacebookAuthComplete(object sender, AuthenticatorCompletedEventArgs e)
        {
            Log.Debug(Tag, "FacebookAuthComplete:" + e.IsAuthenticated);

            if (e.IsAuthenticated)
            {
                var            token      = e.Account.Properties["access_token"];
                AuthCredential credential = FacebookAuthProvider.GetCredential(token);
                mAuth.SignInWithCredential(credential);
            }
        }
Beispiel #23
0
        public void Can_Retrieve_Access_Token_And_Access_Token_Secret()
        {
            AuthCredential authCredential = authenticator.ProcessApprovedAuthCallback(Configuration.TempAuthToken, Configuration.TempAuthVerifier);

            Assert.IsNotNull(authCredential.AuthToken);
            Console.WriteLine("AuthToken: " + authCredential.AuthToken);

            Assert.IsNotNull(authCredential.AuthTokenSecret);
            Console.WriteLine("AuthTokenSecret: " + authCredential.AuthTokenSecret);

            Assert.IsNotNull(authCredential.UserId); //encoded Fitbit UserId
            Console.WriteLine("Fitbit UserId: " + authCredential.UserId);
        }
Beispiel #24
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);
            }
        }
        private async Task <IFirebaseAuthResult> SignInAsync(AuthCredential credential)
        {
            try
            {
                AuthDataResult authResult = await Auth.DefaultInstance.SignInAndRetrieveDataAsync(credential);

                return(new FirebaseAuthResult(authResult));
            }
            catch (NSErrorException ex)
            {
                throw GetFirebaseAuthException(ex);
            }
        }
        private async Task <IFirebaseAuthResult> LinkWithCredentialAsync(AuthCredential credential)
        {
            try
            {
                AuthDataResult authResult = await _user.LinkAndRetrieveDataAsync(credential);

                return(new FirebaseAuthResult(authResult));
            }
            catch (NSErrorException ex)
            {
                throw GetFirebaseAuthException(ex);
            }
        }
Beispiel #27
0
        private void TwitterAuthComplete(object sender, AuthenticatorCompletedEventArgs e)
        {
            Log.Debug(Tag, "TwitterAuthComplete:" + e.IsAuthenticated);

            if (e.IsAuthenticated)
            {
                var token  = e.Account.Properties["oauth_token"];
                var secret = e.Account.Properties["oauth_token_secret"];

                AuthCredential credential = TwitterAuthProvider.GetCredential(token, secret);
                mAuth.SignInWithCredential(credential);
            }
        }
Beispiel #28
0
        public async Task <bool> SignInWithGoogle(string token)
        {
            try
            {
                AuthCredential credential = GoogleAuthProvider.GetCredential(token, null);
                await FirebaseAuth.GetInstance(MainActivity.app).SignInWithCredentialAsync(credential);

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Beispiel #29
0
 static void SaveCredentials(AuthCredential credentials, string userName)
 {
     try
     {
         var        path       = GetAppDataPath(userName);
         var        serializer = new XmlSerializer(typeof(AuthCredential));
         TextWriter writer     = new StreamWriter(path);
         serializer.Serialize(writer, credentials);
         writer.Close();
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
Beispiel #30
0
        public void RegisterAccount(OAuthToken token, UserProfileInfo user)
        {
            LiveAuthClient auth = new LiveAuthClient(clientId, clientSecret, MogConstants.SKYDRIVE_REDIRECTURL);

            AuthCredential credential = new AuthCredential();

            credential.CloudService   = CloudStorageServices.Skydrive;
            credential.Token          = token.AccessToken;
            credential.Refresh        = token.RefreshToken;
            credential.Authentication = token.AuthenticationToken;
            credential.Status         = CredentialStatus.Approved;
            credential.UserId         = user.Id;
            credential.Login          = auth.GetUserId(token.AuthenticationToken);
            this.repoAuthCredential.Create(credential);
        }