public void SetPasswords() { var hashOptions = new HashOptions(); Configuration.GetSection("HashOptions").Bind(hashOptions); var optionsList = Options.Create(hashOptions); var hashService = new HashService(optionsList); var pathToFile = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "conturi.txt"; using (var newfile = File.Create("conturi-cu-parole.txt")) { using (var logWriter = new StreamWriter(newfile)) using (var reader = File.OpenText(pathToFile)) { while (reader.Peek() >= 0) { var fileContent = reader.ReadLine(); var data = fileContent.Split('\t'); var hashed = hashService.GetHash(data[1]); logWriter.WriteLine(fileContent + '\t' + hashed); } } } }
public async Task <IActionResult> OnPostAsync() { if (ModelState.IsValid) { User user = await db.Users.Include(u => u.Role).FirstOrDefaultAsync(u => u.Email == AuthData.Email); if (user == null) { ModelState.AddModelError("AuthData.Password", "Аккаунта с таким e-mail не существует"); return(Page()); } if (!user.IsVerified) { return(RedirectToPage("NonVerified")); } if (user.Password == hashService.GetHash(AuthData.Password)) { await Authenticate(user); return(RedirectToPage("Acc")); } else { ModelState.AddModelError("AuthData.Password", "Пароль неверен"); return(Page()); } } return(Page()); }
public void TestHashVeryLongString() { var service = new HashService(); Assert.AreEqual("D174AB98D277D9F5A5611C2C9F419D9F", service.GetHash(Encoding.ASCII.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"))); }
public void TestHashNumbersString() { var service = new HashService(); Assert.AreEqual("57EDF4A22BE3C955AC49DA2E2107B67A", service.GetHash(Encoding.ASCII.GetBytes("12345678901234567890123456789012345678901234567890123456789012345678901234567890"))); }
public void SetPasswords() { var hashService = new HashService(new OptionsManager <HashOptions>(new List <IConfigureOptions <HashOptions> > { new ConfigureFromConfigurationOptions <HashOptions>( Configuration.GetSection("HashOptions")) })); var pathToFile = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar.ToString() + "conturi.txt"; using (var newfile = File.Create("conturi-cu-parole.txt")) { using (var logWriter = new System.IO.StreamWriter(newfile)) using (StreamReader reader = File.OpenText(pathToFile)) { while (reader.Peek() >= 0) { var fileContent = reader.ReadLine(); var data = fileContent.Split('\t'); var hashed = hashService.GetHash(data[1]); logWriter.WriteLine(fileContent + '\t' + hashed); } } } }
public bool RegisterUser(UserModel userModel, out string erros) { if (userModel.IsValidToInsert(out erros) == false) { return(false); } if (ExistsUserWhithEmailOrUserName(userModel)) { erros = " • Já existe um usuário com este UserName ou Email. "; return(false); } try { erros = ""; ExecuteNonQuery("INSERT INTO Usuarios(Name,Email,UserName,Password,BirthDate)" + "values" + "(@Name,@Email,@UserName,@Password,@BirthDate)", new List <SqlParameter>() { new SqlParameter("Name", userModel.Name), new SqlParameter("Email", userModel.Email), new SqlParameter("UserName", userModel.UserName), new SqlParameter("Password", HashService.GetHash(userModel.Password)), new SqlParameter("BirthDate", userModel.BirthDate), }); return(true); } catch (Exception) { erros = "Houve um erro ao salvar o usuário"; return(false); } }
public UserModel GetUser(UserLoginModel loginModel) { if (string.IsNullOrWhiteSpace(loginModel.UserName) || string.IsNullOrWhiteSpace(loginModel.Password)) { throw new CustomMessageException("Usuário e/ou senha inválidos"); } string comando = "SELECT * FROM Usuarios WHERE UserName = @UserName AND Password = @Password"; var res = ExecuteReader(comando, new List <SqlParameter> { new SqlParameter("UserName", loginModel.UserName), new SqlParameter("Password", HashService.GetHash(loginModel.Password)), }); if (res == null) { return(null); } foreach (var current in res) { var retorno = new UserModel(); retorno.Id = Convert.ToInt32(current.Id); retorno.BirthDate = Convert.ToDateTime(current.BirthDate); retorno.Email = current.Email; retorno.Name = current.Name; retorno.UserName = current.UserName; retorno.Password = null; return(retorno); } return(null); }
public void TestHashLongString() { var service = new HashService(); Assert.AreEqual("C3FCD3D76192E4007DFB496CCA67E13B", service.GetHash(Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwxyz"))); }
public void VerifyText(string text) { var salt = service.GetSalt(); var hash = service.GetHash(text, salt); Assert.True(service.VerifyText(text, hash, salt), $"Couldn't verify password {text}"); Assert.False(service.VerifyText(text, hash, service.GetSalt()), $"Hash still succeeded with different salt! {text}"); }
public async Task <IActionResult> OnPostAsync() { User profile = await db.Users.FirstOrDefaultAsync(u => u.UserId.ToString() == User.Identity.Name); profile.Password = hashService.GetHash(NewPass); await db.SaveChangesAsync(); await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return(RedirectToPage("Auth")); }
public JsonResult GetHash(InputVewModel input) { string result; if (input.IsManualInput) { result = HashService.GetHash(Encoding.ASCII.GetBytes(input.InputText ?? string.Empty)); } else { result = FileService.GetFileHash(input.FileInputPath); } return(Json(new { Result = result }, JsonRequestBehavior.AllowGet)); }
public void Throw_error_when_client_response_status_code_is_not_200( Credentials credentials, MockHttpMessageHandler mockHttp) { mockHttp.When(HttpMethod.Post, _calculateHashUri) .WithContent(JsonConvert.SerializeObject(credentials)) .Respond(HttpStatusCode.InternalServerError); var client = new HttpClient(mockHttp) { BaseAddress = new Uri(Options.BaseUrl) }; var sut = new HashService(client, Options); Should.Throw <HttpRequestException>(async() => await sut.GetHash(credentials)); }
public async Task <IActionResult> OnPostAsync() { if (ModelState.IsValid) { School userSchool = await db.Schools.Include(s => s.Classes).FirstOrDefaultAsync(s => s.SchoolNumber == RegData.SchoolNumber); if (userSchool == null) { ModelState.AddModelError("RegData.SchoolNumber", "Такая школа не зарегистрирована в нашей системе."); return(Page()); } Class userClass = userSchool.Classes.FirstOrDefault(c => ((c.ClassNumber == RegData.ClassNumber) && (c.ClassChar.ToLower() == RegData.ClassChar.ToLower()))); if (userClass == null) { ModelState.AddModelError("RegData.ClassNumber", "Такой класс не зарегистрирован в нашей системе."); return(Page()); } User newUser = new User() { Email = RegData.Email, FirstName = RegData.FirstName, LastName = RegData.LastName, Class = userClass, Password = hashService.GetHash(RegData.Password), Role = db.Roles.First(), IsVerified = false }; bool isAdded = await userService.TryAddUserAsync(newUser); if (!isAdded) { ModelState.AddModelError("RegData.Email", "Пользователь с таким Email уже существует."); return(Page()); } return(RedirectToPage("NonVerified")); } return(Page()); }
public async Task Return_hash_for_correct_credentials( Credentials credentials, MockHttpMessageHandler mockHttp, string hash) { mockHttp.When(HttpMethod.Post, _calculateHashUri) .WithContent(JsonConvert.SerializeObject(credentials)) .Respond("application/json", hash); var client = new HttpClient(mockHttp) { BaseAddress = new Uri(Options.BaseUrl) }; var sut = new HashService(client, Options); var result = await sut.GetHash(credentials); result.ShouldBe(hash); }
public async Task Call_http_client_with_correct_request( Credentials credentials, MockHttpMessageHandler mockHttp, string hash) { var request = mockHttp.When(HttpMethod.Post, _calculateHashUri) .WithContent(JsonConvert.SerializeObject(credentials)) .Respond("application/json", hash); var client = new HttpClient(mockHttp) { BaseAddress = new Uri(Options.BaseUrl) }; var sut = new HashService(client, Options); await sut.GetHash(credentials); mockHttp.GetMatchCount(request).ShouldBe(1); }
public static IServiceCollection AddDefaultModelsToStorage(this IServiceCollection services, IConfiguration config) { var hashService = new HashService(); var storage = new Storage(config.GetConnectionString("DbConnection")); var roleRepository = storage.GetRepository <IRoleRepository>(); var userRepository = storage.GetRepository <IUserRepository>(); if (!roleRepository.Any()) { roleRepository.CreateAsync(new Role() { Name = roleRepository.DefaultUserRole }); roleRepository.CreateAsync(new Role() { Name = roleRepository.DefaultAdminRole }); storage.Save(); } var adminData = config.GetSection("Admin"); if (!userRepository.Any()) { userRepository.CreateAsync(new User() { Nickname = adminData.GetValue <string>("Nickname"), Email = adminData.GetValue <string>("Email"), Password = Encoding.UTF8.GetString(hashService.GetHash(adminData.GetValue <string>("Password"))), Role = roleRepository.GetAsync(roleRepository.DefaultAdminRole).Result }).Wait(); storage.Save(); } return(services); }
private async void LoginButton_Click_1(object sender, RoutedEventArgs e) { var stateContainer = StateContainer.GetStateContainer(); string errorMessage = ""; if (stateContainer.registrationStateService.IsLogin) { errorMessage = ValidateLogin(LoginBox.Text, PasswordBox.Password, EmailBox.Text, false); } else { errorMessage = ValidateLogin(LoginBox.Text, PasswordBox.Password, EmailBox.Text, true); } if (!string.IsNullOrEmpty(errorMessage)) { LoginMessageBlock.Text = errorMessage; LoginMessageBlock.Visibility = Visibility.Visible; return; } Dictionary <string, string> parameters = new Dictionary <string, string>(); parameters.Add("userName", LoginBox.Text); parameters.Add("password", PasswordBox.Password); if (stateContainer.registrationStateService.IsLogin) { var users = await userProvider.GetAllUsersAsync(); var currentUser = users.FirstOrDefault(x => x.Login == LoginBox.Text && x.Password == HashService.GetHash(PasswordBox.Password)); if (currentUser != null) { var strongKey = await userProvider.GetStrongKeyAsync(currentUser.Id); var session = await userProvider.GetSessionAsync(currentUser.Id); tokenService = new TokenService(currentUser.Id); string acessToken = await tokenService.MakeAuthTokenAsync(currentUser.Id); stateContainer.sessionStateService.SetStateAsync(strongKey: strongKey.Key, clientPrivateKey: session.ClientPrivateKey, clientPublicKey: session.ClientPublicKey, serverPublicKey: session.ServerPublicKey, acessToken: acessToken); ContactsForm contactForm = new ContactsForm(); contactForm.Show(); Close(); } else { var httpRequestMessage = new HttpRequestMessage(); httpRequestMessage.Method = HttpMethod.Post; httpRequestMessage.RequestUri = new Uri(ConfigurationManager.AppSettings.Get("devUrl") + Urls.AuthUrl); var form = new MultipartFormDataContent(); foreach (var parameter in parameters) { form.Add(new StringContent(parameter.Value), parameter.Key); } httpRequestMessage.Content = form; var authResponse = await baseHttpRequest.httpClient.SendAsync(httpRequestMessage); switch (authResponse.StatusCode) { case HttpStatusCode.BadRequest: LoginMessageBlock.Text = "Wrong login or password!"; LoginMessageBlock.Visibility = Visibility.Visible; break; case HttpStatusCode.Unauthorized: LoginMessageBlock.Text = "Wrong login or password!"; LoginMessageBlock.Visibility = Visibility.Visible; break; case HttpStatusCode.InternalServerError: LoginMessageBlock.Text = "Internal server error!"; LoginMessageBlock.Visibility = Visibility.Visible; break; case HttpStatusCode.OK: string content = await authResponse.Content.ReadAsStringAsync(); var authResult = JsonConvert.DeserializeObject <AuthResult>(content); await userProvider.СreateOrUpdateAuthStorageAsync(authResult.UserId, authResult.AccessToken, authResult.RefreshToken); var sessionService = new SessionService(authResult.UserId); await sessionService.MakeSessionAsync(authResult.AccessToken, authResult.RefreshToken); await userProvider.CreateUserAsync(authResult.UserId, LoginBox.Text, HashService.GetHash(PasswordBox.Password)); ContactsForm contactForm = new ContactsForm(); contactForm.Show(); Close(); break; } } } else { var httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(ConfigurationManager.AppSettings.Get("devUrl") + Urls.RegisterUrl); var form = new MultipartFormDataContent(); foreach (var parameter in parameters) { form.Add(new StringContent(parameter.Value), parameter.Key); } httpRequest.Content = form; var registerResult = await baseHttpRequest.httpClient.SendAsync(httpRequest); switch (registerResult.StatusCode) { case HttpStatusCode.OK: string testerToken = ConfigurationManager.AppSettings.Get("testerToken"); var authUserInfo = JsonConvert.DeserializeObject <AuthResult>( await registerResult.Content.ReadAsStringAsync() ); var phoneConfirmRequestMessage = new HttpRequestMessage(); phoneConfirmRequestMessage.Method = HttpMethod.Get; phoneConfirmRequestMessage.RequestUri = new Uri(ConfigurationManager.AppSettings.Get("devUrl") + $"{Urls.ConfirmPhoneTestUrl}/{authUserInfo.UserId}"); phoneConfirmRequestMessage.Headers.Add("TesterToken", testerToken); var phoneConfirmResult = await baseHttpRequest.httpClient.SendAsync(phoneConfirmRequestMessage); if (phoneConfirmResult.StatusCode == HttpStatusCode.OK) { var sessionService = new SessionService(authUserInfo.UserId); await userProvider.СreateOrUpdateAuthStorageAsync(authUserInfo.UserId, authUserInfo.AccessToken, authUserInfo.RefreshToken); await sessionService.MakeSessionAsync(authUserInfo.AccessToken, authUserInfo.RefreshToken); await userProvider.CreateUserAsync(authUserInfo.UserId, LoginBox.Text, HashService.GetHash(PasswordBox.Password)); ContactsForm contact = new ContactsForm(); contact.Show(); Close(); } else { MessageBox.Show($"Something was error"); } break; case HttpStatusCode.BadRequest: break; case HttpStatusCode.InternalServerError: break; } } //LoginMessageBlock.Text = "Wrong login or password!"; //LoginMessageBlock.Visibility = Visibility.Visible; }
public void TestHashMessageDigest() { var service = new HashService(); Assert.AreEqual("F96B697D7CB7938D525A2F31AAF161D0", service.GetHash(Encoding.ASCII.GetBytes("message digest"))); }
public void TestHashABC() { var service = new HashService(); Assert.AreEqual("900150983CD24FB0D6963F7D28E17F72", service.GetHash(Encoding.ASCII.GetBytes("abc"))); }
public void TestHashA() { var service = new HashService(); Assert.AreEqual("0CC175B9C0F1B6A831C399E269772661", service.GetHash(Encoding.ASCII.GetBytes("a"))); }
public void TestHashEmpty() { var service = new HashService(); Assert.AreEqual("D41D8CD98F00B204E9800998ECF8427E", service.GetHash(Encoding.ASCII.GetBytes(string.Empty))); }