public async Task <IActionResult> Registrate([FromForm] RegistrationViewModel model) { RegistrationValidator validator = new RegistrationValidator(_userManager); var results = validator.Validate(model); if (!results.IsValid) { TempData[TextConstants.TempDataErrorText] = ValidatorHelper.GetErrorString(results.Errors); return(View("Registration", model)); } List <KeyValuePair <string, ProductRoleEnum> > products = null; if (!string.IsNullOrEmpty(model.ProductKey) && !string.IsNullOrEmpty(model.Role)) { products = new List <KeyValuePair <string, ProductRoleEnum> >() { new KeyValuePair <string, ProductRoleEnum>(model.ProductKey, (ProductRoleEnum)Int32.Parse(model.Role)) }; } _userManager.AddUser(model.Username, null, null, HashComputer.ComputePasswordHash(model.Password), false, products); await Authenticate(model.Username, true); if (!string.IsNullOrEmpty(model.TicketId)) { _ticketManager.RemoveTicket(Guid.Parse(model.TicketId)); } return(RedirectToAction("Index", "Home")); }
private void AddDefaultUser() { AddUser(CommonConstants.DefaultUserUsername, CommonConstants.DefaultClientCertificateThumbprint, CommonConstants.DefaultClientCrtCertificateName, HashComputer.ComputePasswordHash(CommonConstants.DefaultUserUsername), true); }
public static string AuthenticationUrlFrom(Credentials credentials) { return(@"/gk.php?" + $"an={credentials.Account}" + $"&us={credentials.User}" + $"&k2={HashComputer.Hash(credentials.Combined)}"); }
public User Authenticate(string login, string password) { var passwordHash = HashComputer.ComputePasswordHash(password); var existingUser = Users.SingleOrDefault(u => u.UserName.Equals(login) && !string.IsNullOrEmpty(u.Password) && u.Password.Equals(passwordHash)); //var existingUser = _userManager.Users.SingleOrDefault(u => u.UserName.Equals(login)); return(existingUser?.WithoutPassword()); }
public HttpResponseMessage registerAdmn([FromUri] string user, [FromUri] string email, [FromUri] string password) { if (UserManager.checkUserAvailability(user) && UserManager.checkEmailAvailability(email)) { User newUser = new Admin(user, email, HashComputer.GetHashString(password)); UserManager.registerUser(newUser); return(new HttpResponseMessage(HttpStatusCode.Accepted)); } return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Username or email already in use")); }
public User Authenticate(string login, string password) { var passwordHash = HashComputer.ComputePasswordHash(password); bool IsAskedUser(KeyValuePair <Guid, User> userPair) { var user = userPair.Value; return(user.UserName.Equals(login) && !string.IsNullOrEmpty(user.Password) && user.Password.Equals(passwordHash)); } var existingUser = _users.SingleOrDefault(IsAskedUser); return(existingUser.Value?.WithoutPassword()); }
public HttpResponseMessage registerClient([FromUri] string user, [FromUri] string email, [FromUri] string password, [FromUri] string cedula, [FromUri] string realName, [FromUri] string lastName1, [FromUri] string lastName2, [FromUri] string provincia, [FromUri] string canton, [FromUri] string distrito, [FromUri] int month, [FromUri] int day, [FromUri] int year, [FromUri] string phoneNumber) { if (UserManager.checkUserAvailability(user) && UserManager.checkEmailAvailability(email)) { User newUser = new Client(user, email, HashComputer.GetHashString(password), cedula, realName, lastName1, lastName2, provincia, canton, distrito, month, day, year, phoneNumber); UserManager.registerUser(newUser); return(new HttpResponseMessage(HttpStatusCode.Accepted)); } return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Username or email already in use")); }
public void CreateUser([FromBody] UserViewModel model) { UserValidator validator = new UserValidator(_userManager); var results = validator.Validate(model); if (!results.IsValid) { TempData[TextConstants.TempDataErrorText] = ValidatorHelper.GetErrorString(results.Errors); } else { _userManager.AddUser(model.Username, string.Empty, string.Empty, HashComputer.ComputePasswordHash(model.Password), model.IsAdmin); } }
protected void LogIn(object sender, EventArgs e) { if (IsValid) { DataSet ds = new DataSet(); String cmd = "UserName='******'"; FileStream fs = new FileStream(Server.MapPath("../App_Data/Users.xml"), FileMode.Open, FileAccess.Read); StreamReader reader = new StreamReader(fs); ds.ReadXml(reader); fs.Close(); DataTable users = ds.Tables[0]; DataRow[] matches = users.Select(cmd); if (matches != null && matches.Length > 0) { DataRow row = matches[0]; HashComputer hashComputer = new HashComputer(); string hashedpwd = hashComputer.hash(Password.Text); String pass = (String)row["Password"]; if (0 != String.Compare(pass, hashedpwd, false)) { // Tell the user if no password match is found. It is good // security practice give no hints about what parts of the // logon credentials are invalid. FailureText.Text = "Invalid username or password."; ErrorMessage.Visible = true; } else { // If a password match is found, redirect the request // to the originally requested resource (Default.aspx). FormsAuthentication.RedirectFromLoginPage (UserName.Text, RememberMe.Checked); } } else { FailureText.Text = "Invalid username or password."; ErrorMessage.Visible = true; } } }
/// <summary> ///task to check form input to users list ///change to work with same USERNAME /// </summary> /// <param name="user"></param> /// <param name="pass"></param> /// <returns></returns> private Task <bool> Validate(String user, String pass) { return(Task.Run(() => { int mid; int min = 0; int max = usersList.Count - 1; while (min <= max) { mid = (max + min) / 2; bool test = String.Compare(user, usersList[mid].gsName, StringComparison.Ordinal) == 0; if (test) { String hash; String salt; String compare = HashComputer.GetPasswordHashAndSalt(pass + usersList[mid].gsSalt); bool test1 = compare == usersList[mid].gsPass; if (PasswordManager.IsPasswordMatch(pass, usersList[mid].gsSalt, usersList[mid].gsPass)) { return true; } else { //fix this return false; } } else if (String.Compare(user, usersList[mid].gsName, StringComparison.Ordinal) < 0) { max = mid - 1; } else { min = mid + 1; } } return false; })); }
protected void CreateUser_Click(object sender, EventArgs e) { if (0 != String.Compare(captchaBox.Text, "v4xbg", true)) { ErrorMessage.Text = "The text doesn't match that in the image."; return; } DataSet ds = new DataSet(); String userFile = "../App_Data/Users.xml"; FileStream fs = new FileStream(Server.MapPath(userFile), FileMode.Open, FileAccess.Read); StreamReader reader = new StreamReader(fs); ds.ReadXml(reader); fs.Close(); HashComputer hashComputer = new HashComputer(); string hashedpwd = hashComputer.hash(Password.Text); DataRow newUser = ds.Tables[0].NewRow(); newUser["UserName"] = UserName.Text; newUser["Password"] = hashedpwd; newUser["Role"] = roleList.SelectedItem.Text; ds.Tables[0].Rows.Add(newUser); ds.AcceptChanges(); fs = new FileStream(Server.MapPath(userFile), FileMode.Create, FileAccess.Write | FileAccess.Read); StreamWriter writer = new StreamWriter(fs); ds.WriteXml(writer); writer.Close(); fs.Close(); if (!String.IsNullOrEmpty(Request.QueryString["ReturnUrl"])) { Response.Redirect(Request.QueryString["ReturnUrl"]); } else { Response.Redirect("~/Account/Login"); } }
public (X509Certificate2, X509Certificate2) SignClientCertificate(User user, string subject, string commonName, RSAParameters rsaParameters) { (X509Certificate2, X509Certificate2)result; var rsa = RSA.Create(rsaParameters); X509Certificate2 clientCert = CertificatesProcessor.CreateAndSignCertificate(subject, rsa, CertificatesConfig.CACertificate); string fileName = $"{commonName}.crt"; _certificateManager.InstallClientCertificate(clientCert); _certificateManager.SaveClientCertificate(clientCert, fileName); _userManager.AddUser(commonName, clientCert.Thumbprint, fileName, HashComputer.ComputePasswordHash(commonName), true); result.Item1 = clientCert; result.Item2 = CertificatesConfig.CACertificate; return(result); }
private void MigrateUsersToDatabase() { List <User> usersFromFile = ParseUsersFile(); foreach (var user in usersFromFile) { if (user.UserName.Equals("default")) { user.IsAdmin = true; } if (string.IsNullOrEmpty(user.Password)) { AddUser(user.UserName, user.CertificateThumbprint, user.CertificateFileName, HashComputer.ComputePasswordHash(user.UserName), user.IsAdmin); } } _logger.LogInformation($"{usersFromFile.Count} successfully migrated from file to database"); }
private void GenerateHash(string filename, int hashType, bool last) { pool.WaitOne(); try { try { UIThread(() => { labelFile.Text = "Please wait..."; this.Cursor = Cursors.WaitCursor; }); HashComputer hashComputer = new HashComputer(); String hash = hashComputer.compute(filename, hashType); UIThread(() => { labelFile.Text = "Drop files here"; listBox1.Items.Add(Path.GetFileName(filename) + " - " + hash); this.Cursor = Cursors.Default; if (last) WinAPI.SetForegroundWindow(Handle); }); } catch (Exception) { UIThread(() => { String error = "Error generating the hash"; labelFile.Text = error; this.Cursor = Cursors.Default; WinAPI.SetForegroundWindow(Handle); MessageBox.Show(this, error, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); }); } } finally { pool.Release(); } }
public ActionResult ForgotPassword(ForgotPassword model) { try { if (ModelState.IsValid) { // Get the user by email: BTourGuideOp tourOp = new BTourGuideOp(); List<AUser> users = tourOp.GetUsers(); AUser user = users.FirstOrDefault(u => u.UserEmail == model.Email); if (user != null) // If a user with the email provided was found { // Generae password token that will be used in the email link to authenticate user string resetToken = Guid.NewGuid().ToString(); // Hash the reset token HashComputer hashComp = new HashComputer(); string resetTokenHash = hashComp.GetPasswordHashAndSalt(resetToken); // Generate the html link sent via email user.ResetToken = resetTokenHash; tourOp.EditUser(user); string resetLink = "<a href='" + Url.Action("ResetPassword", "Account", new { rt = resetToken }, "http") + "'>Reset Password Link</a>"; // Email stuff string subject = "Reset your password for TourGuideWebsite"; string body = "Your link: " + resetLink; string from = "*****@*****.**"; MailMessage message = new MailMessage(from, model.Email); message.Subject = subject; message.Body = body; message.IsBodyHtml = true; SmtpClient client = new SmtpClient("smtp.gmail.com", 587) { UseDefaultCredentials = false, EnableSsl = true, Timeout = 20000, Credentials = new NetworkCredential("*****@*****.**", "henhqwcfvmtzplgb") }; // Attempt to send the email try { client.Send(message); ViewBag.Message = "A reset password email has been sent."; return View(); } catch (Exception e) { TempData["EmailException"] = "Issue sending email: " + e.Message; } } // For testing: //else // Email not found //{ // /* Note: You may not want to provide the following information // * since it gives an intruder information as to whether a // * certain email address is registered with this website or not. // * If you're really concerned about privacy, you may want to // * forward to the same "Success" page regardless whether an // * user was found or not. This is only for illustration purposes. // */ // ModelState.AddModelError("", "No user found by that email."); //} } return View(model); } catch (Exception e) { TempData["Exception"] = "" + e.Message; return View(model); } }
public User CreateThirdUser() { return(CreateUser(ThirdUserName, HashComputer.ComputePasswordHash(ThirdUserName))); }
public User CreateSecondUser() { return(CreateUser(SecondUserName, HashComputer.ComputePasswordHash(SecondUserName))); }
public User CreateFirstUser() { return(CreateUser(FirstUserName, HashComputer.ComputePasswordHash(FirstUserName))); }
public ActionResult Create(UserDetails userdetails) { try { if (ModelState.IsValid) { // Checking the username availability in the server BTourGuideOp op = new BTourGuideOp(); List<AUser> users = op.GetUsers(); if (!users.Any(u => u.Username == userdetails.Username)) { BTourGuideOp tourOp = new BTourGuideOp(); AUser user = new AUser(); user.RegTime = DateTime.Now; user.UserIP = Request.ServerVariables["REMOTE_ADDR"]; user.UserFirstName = userdetails.UserFirstName; user.UserLastName = userdetails.UserLastName; user.UserEmail = userdetails.UserEmail; user.UserPhone = userdetails.UserPhone; // Create a random password string password = System.Web.Security.Membership.GeneratePassword(8, 2); // hash and salt the password PasswordManager passMan = new PasswordManager(); string salt = null; string hashPassword = passMan.GeneratePasswordHash(password, out salt); user.UserPassword = hashPassword; user.Salt = salt; user.Username = userdetails.Username; user.UserBirthday = userdetails.UserBirthday; tourOp.AddUser(user); // Generae password token that will be used in the email link to authenticate user string resetToken = Guid.NewGuid().ToString(); // Hash the reset token HashComputer hashComp = new HashComputer(); string resetTokenHash = hashComp.GetPasswordHashAndSalt(resetToken); AUser theNewUser = tourOp.GetUser(user.Username); // Generate the html link sent via email theNewUser.ResetToken = resetTokenHash; tourOp.EditUser(theNewUser); // Email stuff string subject = "New account in TourGuideWebsite"; string body = "You have a new account in TourGuideWebsite. " + "To reset your password <a href='" + Url.Action("ResetPassword", "Account", new { rt = resetToken }, "http") + "'>Click here</a>"; string from = "*****@*****.**"; MailMessage message = new MailMessage(from, user.UserEmail); message.Subject = subject; message.Body = body; message.IsBodyHtml = true; SmtpClient client = new SmtpClient("smtp.gmail.com", 587) { UseDefaultCredentials = false, EnableSsl = true, Timeout = 20000, Credentials = new NetworkCredential("*****@*****.**", "henhqwcfvmtzplgb") }; // Attempt to send the email try { client.Send(message); } catch (Exception e) { TempData["EmailException"] = "Issue sending email: " + e.Message; } return RedirectToAction("Index"); } else { userdetails.Username = null; return View(); } } else { return View(userdetails); } } catch(Exception e) { TempData["Exception"] = "" + e.Message; return View(userdetails); } }
public static string GenerateProductKey(string productName) { return(HashComputer.ComputeSha256Hash( $"{productName}_{DateTime.Now.ToLongTimeString()}").Substring(0, 30)); //return Convert.ToBase64String(Encoding.ASCII.GetBytes($"{productName}_{DateTime.Now.ToShortTimeString()}_{DateTime.Now.ToShortDateString()}")); }
public static string GenerateExtraProductKey(string productName, string extraProductName) { return(HashComputer.ComputeSha256Hash( $"{productName}_{extraProductName}").Substring(0, 30)); }
public ActionResult ResetPassword(ResetPassword model) { try { if (ModelState.IsValid) { BTourGuideOp tourOp = new BTourGuideOp(); List<AUser> users = tourOp.GetUsers(); // hasing the resetToken from the url HashComputer hashComp = new HashComputer(); string hashedResetToken = hashComp.GetPasswordHashAndSalt(model.ReturnToken); // Checking if the hash matches the resetToken from the DB AUser user = users.FirstOrDefault(u => u.ResetToken == hashedResetToken); if (user != null) { // password salting & hashing PasswordManager passMan = new PasswordManager(); string salt = null; string passwordHash = passMan.GeneratePasswordHash(model.Password, out salt); user.UserPassword = passwordHash; user.Salt = salt; user.ResetToken = null; tourOp.EditUser(user); ViewBag.Message = "Successfully Changed"; } else { ViewBag.Message = "Something went wrong!"; } } return View(model); } catch(Exception e) { TempData["Exception"] = "" + e.Message; return View(); } }