private void HashCustomerPassword()
        {
            var cryptoService = new CryptoService();
            var hash          = cryptoService.ComputeHash(NewCustomer.password, cryptoService.GenerateSalt(), 10101, 24);

            NewCustomer.password = Convert.ToBase64String(hash);
        }
Ejemplo n.º 2
0
        public bool Register(string email, string login, string password)
        {
            if (_authRep.VerifyUserExistence(login))
            {
                return(false);
            }

            var salt = CryptoService.GenerateSalt(login);

            _authRep.CreateAccount(email, login, CryptoService.ComputeHash(password, salt), salt);

            return(true);
        }
Ejemplo n.º 3
0
        public static User GetUser()
        {
            User user = new User();

            user.Username               = Username;
            user.DisplayName            = DisplayName;
            user.PasswordSalt           = CryptoService.GenerateSalt();
            user.PasswordHash           = CryptoService.ComputeHash(Password, user.PasswordSalt);
            user.AccessJobParams        = true;
            user.AccessMainMenu         = true;
            user.AccessMainParams       = true;
            user.AccessAdditionalParams = true;
            user.AccessAdminParams      = true;
            return(user);
        }
        public async Task <BankCustomer> RegisterNewUser(string firstName, string lastName, string username, string password)
        {
            BankCustomer customer = new BankCustomer
            {
                FirstName    = firstName,
                LastName     = lastName,
                Usernname    = username,
                passwordHash = CryptoService.ComputeHash(password)
            };

            // the server replies with added fields
            LoggedInCustomer = await HttpMgr.Instance.PostCustomerAsync(customer);

            return(LoggedInCustomer);
        }
Ejemplo n.º 5
0
        private void ButFromFile_Click(object sender, EventArgs e)
        {
            if (OpenFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    Filename.Text = Path.GetFileName(OpenFileDialog.FileName);
                    Filename_Validated(this, EventArgs.Empty);

                    Hash.Text = ByteHelper.ByteToString(CryptoService.ComputeHash(OpenFileDialog.FileName));
                    Hash_Validated(this, EventArgs.Empty);
                } catch (Exception)
                {
                }
            }
        }
Ejemplo n.º 6
0
        private void SaveUser(object userInstance)
        {
            UserViewModel userViewModel = userInstance as UserViewModel;

            if (!userViewModel.IsValidUsername)
            {
                Application.Current.MainPage.DisplayAlert("Ошибка", "Имя пользователя не указано", "Ok");
                return;
            }

            if (IsExistUser(userViewModel.User))
            {
                Application.Current.MainPage.DisplayAlert("Ошибка", "Пользователь с таким именем существует", "Ok");
                return;
            }

            if (!userViewModel.IsValidPassword)
            {
                Application.Current.MainPage.DisplayAlert("Ошибка", "Пароль пользователя не задан", "Ok");
                return;
            }

            if (userViewModel.User != null && userViewModel.IsValidUsername && userViewModel.IsValidPassword)
            {
                using (UserDbContext db = App.GetUserContext())
                {
                    userViewModel.User.PasswordSalt = CryptoService.GenerateSalt();
                    userViewModel.User.PasswordHash = CryptoService.ComputeHash(userViewModel.Password, userViewModel.User.PasswordSalt);

                    if (userViewModel.User.UserId == 0)
                    {
                        db.Entry(userViewModel.User).State = EntityState.Added;
                    }
                    else
                    {
                        db.Users.Update(userViewModel.User);
                    }
                    db.SaveChanges();
                }
            }
            Back();
        }
Ejemplo n.º 7
0
        private void ButFromFile_Click(object sender, EventArgs e)
        {
            if (OpenFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            try
            {
                Filename.Text = Path.GetFileName(OpenFileDialog.FileName);
                Filename_Validated(this, EventArgs.Empty);

                Hash.Text = ByteHelper.ByteToString(CryptoService.ComputeHash(OpenFileDialog.FileName));
                Hash_Validated(this, EventArgs.Empty);
            }
            // ReSharper disable once EmptyGeneralCatchClause
            catch
            {
            }
        }
Ejemplo n.º 8
0
        public LoginDTO Authenticate(string login, string password)
        {
            if (!_authRep.VerifyUserExistence(login))
            {
                return(null);
            }

            var userData = _authRep.GetUserData(login);

            if (!userData.PassHash.SequenceEqual(CryptoService.ComputeHash(password, userData.Salt)))
            {
                return(null);
            }

            var token = CryptoService.GenerateToken();

            _authRep.StartSession(userData.Id, token);

            return(new LoginDTO {
                Id = userData.Id, Login = login, Token = token
            });
        }
Ejemplo n.º 9
0
        public async Task ValidateAsync(ExtensionGrantValidationContext context)
        {
            var inputToken  = context.Request.Raw.Get("input_token");
            var accessToken = context.Request.Raw.Get("access_token");

            if (string.IsNullOrEmpty(inputToken))
            {
                context.Result = new GrantValidationResult(OidcConstants.TokenErrors.InvalidRequest, null);
                return;
            }

            if (string.IsNullOrEmpty(accessToken))
            {
                context.Result = new GrantValidationResult(OidcConstants.TokenErrors.InvalidRequest, null);
                return;
            }

            var client        = new HttpClient();
            var tokenResponse = await client.GetAsync($"https://graph.facebook.com/debug_token?input_token={inputToken}&access_token={accessToken}");

            if (tokenResponse.StatusCode == System.Net.HttpStatusCode.OK)
            {
                //Get token response and check wheather ist from valid application or not
                var tokenResponseData = await tokenResponse.Content.ReadAsStringAsync();

                var fbTokenResponseData = TokenResponseDserializer.DserializeIdToken <FacebookAuthTokenResponse>(tokenResponseData);

                //Make sure issuer client is valid
                //if (fbTokenResponseData.Data.App_id != FacebookAuthConstants.FacebookAppId)
                //{
                //    context.Result = new GrantValidationResult(OidcConstants.TokenErrors.UnauthorizedClient, null);
                //    return;
                //}

                //Get user profile information using access_token from Facebook Graph API
                var profileResponse = await client.GetAsync($"https://graph.facebook.com/me?fields=id,email,gender,picture&access_token={inputToken}");

                if (profileResponse.IsSuccessStatusCode)
                {
                    //Parse fb response
                    var responseData = await profileResponse.Content.ReadAsStringAsync();

                    var fbTokenResponse = TokenResponseDserializer.DserializeIdToken <FacebookAuthResponse>(responseData);


                    //Check if user is available in Auth Database yet.
                    var requestedUser = _userStore.FindByProviderAndSubjectId(ProviderConstants.Facebook, fbTokenResponse.Id);


                    if (requestedUser == null)
                    {
                        #region Password Hash and Salt

                        var pwdSalt = CryptoService.GenerateSalt();
                        var pwdHash = CryptoService.ComputeHash(PasswordGenerator.GetRandomPassword(), pwdSalt);
                        #endregion

                        //Get User Information

                        //Create new User
                        var customUser = new CustomUser
                        {
                            SubjectId    = fbTokenResponse.Id,
                            Email        = string.IsNullOrEmpty(fbTokenResponse.Email)?"": fbTokenResponse.Email.ToLower(),
                            PasswordHash = Convert.ToBase64String(pwdHash),
                            PasswordSalt = Convert.ToBase64String(pwdSalt),
                            Provider     = ProviderConstants.Facebook,
                            CreatedDate  = DateTime.UtcNow,
                            LastUpdated  = DateTime.UtcNow
                        };

                        _userStore.AddNewUser(customUser);
                    }

                    context.Result = new GrantValidationResult(fbTokenResponse.Id, ExternalGrantTypes.Facebok);
                }
                else
                {
                    context.Result = new GrantValidationResult(OidcConstants.TokenErrors.InvalidRequest, null);
                }
            }
            else
            {
                context.Result = new GrantValidationResult(OidcConstants.TokenErrors.InvalidRequest, null);
            }
        }
        public async Task <BankCustomer> GetCustomerWithPasswordAsync(string username, string password)
        {
            string passwordHash = CryptoService.ComputeHash(password);

            return(await HttpMgr.Instance.LoginCustomerAsync(username, passwordHash));
        }
        public async Task ValidateAsync(ExtensionGrantValidationContext context)
        {
            try
            {
                var idToken = context.Request.Raw.Get("id_token");

                if (string.IsNullOrEmpty(idToken))
                {
                    context.Result = new GrantValidationResult(OidcConstants.TokenErrors.InvalidRequest, null);
                    return;
                }

                //https://www.googleapis.com/auth/userinfo.profile scope is required to get user profile image for app team
                // get user's identity
                var client = new HttpClient();

                var request = await client.GetAsync($"https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={idToken}");

                if (request.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var responseData = await request.Content.ReadAsStringAsync();

                    var googleAuthResponse = TokenResponseDserializer.DserializeIdToken <GoogleAuthResponse>(responseData);

                    if (!string.Equals(googleAuthResponse.Iss, GoogleAuthConstants.Issuer, StringComparison.CurrentCultureIgnoreCase))
                    {
                        context.Result = new GrantValidationResult("Invalid Issuer.", null);
                        return;
                    }

                    //Make sure issuer client is valid
                    //if (googleAuthResponse.Azp != GoogleAuthConstants.ClinetId)
                    //{
                    //    context.Result = new GrantValidationResult(OidcConstants.TokenErrors.UnauthorizedClient, null);
                    //    return;

                    //}

                    var requestedUser = _userStore.FindByProviderAndEmail(ProviderConstants.Google, googleAuthResponse.Email);


                    if (requestedUser == null)
                    {
                        #region Password Hash and Salt

                        var pwdSalt = CryptoService.GenerateSalt();
                        var pwdHash = CryptoService.ComputeHash(PasswordGenerator.GetRandomPassword(), pwdSalt);
                        #endregion

                        //Create new User
                        var customUser = new CustomUser
                        {
                            SubjectId    = googleAuthResponse.Sub,
                            Email        = googleAuthResponse.Email.ToLower(),
                            PasswordHash = Convert.ToBase64String(pwdHash),
                            PasswordSalt = Convert.ToBase64String(pwdSalt),
                            Provider     = ProviderConstants.Google,
                            CreatedDate  = DateTime.UtcNow,
                            LastUpdated  = DateTime.UtcNow
                        };

                        _userStore.AddNewUser(customUser);
                    }

                    context.Result = new GrantValidationResult(googleAuthResponse.Sub, ExternalGrantTypes.Google);
                }
            }
            catch (Exception)
            {
                context.Result = new GrantValidationResult("Internal Server Error.", null);
            }
        }