public Stage3(Stage1 stage1, Stage2 stage2Reader, bool passwordRequired, PasswordManager passwordManager) { Stage1 = stage1; Reader = stage2Reader; PasswordRequired = passwordRequired; PasswordManager = passwordManager; _Directive = new Lazy<RequestType>(() => { try { return (RequestType)Enum.Parse(typeof(RequestType), Reader.Directive); } catch (Exception ex) { throw new ParserException(ErrorType.InvalidRequest, "Directive", ex); } }); _KeyHashAlgorithm = new Lazy<Cryptography.HashAlgorithmType>(() => { try { return Cryptography.GetKeyHashType(Reader.KeyHashAlgorithm); } catch (Exception ex) { throw new ParserException(ErrorType.InvalidRequest, "KeyHashAlgorithm", ex); } }); _EncryptionAlgorithm = new Lazy<Cryptography.SymmetricAlgorithmType>(() => { try { return Cryptography.GetEncryptionType(Reader.EncryptionAlgorithm); } catch (Exception ex) { throw new ParserException(ErrorType.InvalidRequest, "EncryptionAlgorithm", ex); } }); }
public void GNTPParserTest() { var pw = new PasswordManager(); var info = new RequestInfo(); var parser = new GNTPParser(pw, false, true, true, true, info); var items = new List<IGNTPRequest>(); parser.MessageParsed += (req) => { items.Add(req); }; parser.Error += (error) => { Assert.Fail("ErrorCode={0}, Description={1}", error.ErrorCode, error.ErrorDescription); }; ParseAll(parser); Assert.IsTrue(items.Count > 0); foreach (var item in items) { if (item.Directive == RequestType.NOTIFY) { var nLog = NeithNotificationRec.FromHeaders(item.Headers); } if (item.Directive == RequestType.REGISTER) { var app = Application.FromHeaders(item.Headers); Assert.AreEqual("SurfWriter", app.Name); } } }
public static bool createNewUser(string username, string password) { PasswordManager passManager = new PasswordManager(username, password); bool created = passManager.createNewAccount(); return created; }
public void TestMinMaxIDs() { var mockTime = new MockTimeManager(); var passwordManager = new PasswordManager(mockTime); Assert.IsTrue(!String.IsNullOrEmpty(passwordManager.CreatePassword(0))); Assert.IsTrue(!String.IsNullOrEmpty(passwordManager.CreatePassword(uint.MinValue))); Assert.IsTrue(!String.IsNullOrEmpty(passwordManager.CreatePassword(uint.MaxValue))); }
//log the user in public static void login(string username, string password) { PasswordManager passManager = new PasswordManager(username, password); //password manager uses hashing to check passwords if (passManager.checkPassword()) { HttpContext.Current.Session["username"] = username; } }
public void CheckPassword_PasswordHasNotBeenGenerated_Test() { var userId = "user1"; var passwordRepository = new Mock<IRepository<Password>>(); var passwordGenerator = new PasswordManager(passwordRepository.Object); var isPasswordCorrect = passwordGenerator.CheckPassword(userId, "monkey"); Assert.IsFalse(isPasswordCorrect); }
public void TestOneTimeValidity() { var mockTime = new MockTimeManager(); var passwordManager = new PasswordManager(mockTime); Assert.IsTrue(passwordManager.NumPasswordsStored == 0); string pass1 = passwordManager.CreatePassword(1); Assert.IsTrue(passwordManager.NumPasswordsStored == 1); Assert.IsTrue(passwordManager.IsPasswordValid(1, pass1)); Assert.IsTrue(passwordManager.NumPasswordsStored == 0); Assert.IsFalse(passwordManager.IsPasswordValid(1, pass1)); }
public void CheckPassword_WrongPassword_Test() { var userId = "user1"; var password = "******"; var passwordHash = String.Concat(password, HardcodedSalt).GetHashCode().ToString(); var passwordFromRepo = new Password() { UserId = userId, ExpiryTime = DateTime.UtcNow.AddSeconds(30), PasswordHash = passwordHash, PasswordSalt = HardcodedSalt }; var passwordRepository = new Mock<IRepository<Password>>(); passwordRepository.Setup(u => u.Load(userId)).Returns(passwordFromRepo); var passwordGenerator = new PasswordManager(passwordRepository.Object); var isPasswordCorrect = passwordGenerator.CheckPassword(userId, "chicken"); Assert.IsFalse(isPasswordCorrect); }
public void TestTimeValidity() { var mockTime = new MockTimeManager(); var passwordManager = new PasswordManager(mockTime); // Check current time prior to pass creation mockTime.Time = 1000; string pass1 = passwordManager.CreatePassword(1); mockTime.Time -= 1; Assert.IsFalse(passwordManager.IsPasswordValid(1, pass1)); // Check max valid time mockTime.Time = 1000; pass1 = passwordManager.CreatePassword(1); mockTime.Time += passwordManager.TimeValidity; Assert.IsTrue(passwordManager.IsPasswordValid(1, pass1)); // Check max valid time plus 1 ms mockTime.Time = 1000; pass1 = passwordManager.CreatePassword(1); mockTime.Time += passwordManager.TimeValidity + 1; Assert.IsFalse(passwordManager.IsPasswordValid(1, pass1)); // Check time validity increment when generating password to the same user mockTime.Time = 1000; pass1 = passwordManager.CreatePassword(1); mockTime.Time += passwordManager.TimeValidity; string pass2 = passwordManager.CreatePassword(1); Assert.AreEqual(pass1, pass2); mockTime.Time += passwordManager.TimeValidity; Assert.IsTrue(passwordManager.IsPasswordValid(1, pass1)); // Check creating a new pass when time is expired gives a different pass mockTime.Time = 1000; pass1 = passwordManager.CreatePassword(1); mockTime.Time += passwordManager.TimeValidity + 1; pass2 = passwordManager.CreatePassword(1); Assert.AreNotEqual(pass1, pass2); mockTime.Time += passwordManager.TimeValidity; Assert.IsTrue(passwordManager.IsPasswordValid(1, pass2)); }
public void TestExpiredPasswordsDeletion() { var mockTime = new MockTimeManager(); var passwordManager = new PasswordManager(mockTime); mockTime.Time = 1000; string pass1 = passwordManager.CreatePassword(1); string pass2 = passwordManager.CreatePassword(2); string pass3 = passwordManager.CreatePassword(3); mockTime.Time += passwordManager.TimeValidity + 1; string pass4 = passwordManager.CreatePassword(4); string pass5 = passwordManager.CreatePassword(5); Assert.IsTrue(passwordManager.NumPasswordsStored == 5); passwordManager.RemoveExpiredPasswords(); Assert.IsTrue(passwordManager.NumPasswordsStored == 3); }
public async Task <IActionResult> TeacherRegister(TeacherIn teacher) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } foreach (var item in teacher.phones) { if (String.IsNullOrEmpty(item.phone_number)) { return(BadRequest(new { errorText = "Empty phone field!" })); } } byte[] salt = PasswordManager.GenerateSalt_128(); string saltStr = Encoding.ASCII.GetString(salt); Teachers withId = new Teachers(); withId.name = teacher.name; withId.surname = teacher.surname; withId.lastname = teacher.lastname; withId.email = teacher.email; withId.work_begin = DateTime.Now; withId.work_exp = 0; withId.hash = PasswordManager.PasswordSaveHashing(teacher.Password_temp, salt); withId.salt = saltStr; _context.Teachers.Add(withId); _context.SaveChanges(); int id = withId.id_teacher; foreach (Models.Teacher.PhonesIn phone in teacher.phones) { await _context.Database.ExecuteSqlInterpolatedAsync($"INSERT INTO Teacher_phones VALUES ({phone.phone_number}, {id});"); } //await _context.Database.ExecuteSqlInterpolatedAsync($"INSERT INTO Teachers VALUES ({null}, {teacher.name}, {teacher.surname}, {teacher.lastname}, {teacher.email}, {DateTime.Now}, {0}, {PasswordManager.PasswordSaveHashing(teacher.Password_temp, salt)} , {saltStr});"); return(Ok()); }
public async Task <bool> Login(string email, string password) { if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password)) { return(false); } var user = await _userRepository.Query().SingleOrDefaultAsync(x => x.Email == email); if (user == null) { return(false); } var md5Hash = MD5.Create(); if (!PasswordManager.VerifyMd5Hash(md5Hash, password, user.Password)) { return(false); } return(true); }
protected void SubmitApplicationBtn_Click(object sender, EventArgs e) { if (SQLDataAccess.IsUsernameAvailable(inputUsername.Value, "student")) { HideErrorMsg(); //validate input first string salt = PasswordManager.GenerateSalt(); StudentApplication application = new StudentApplication { Status = "Pending", FirstName = inputFirstName.Value, LastName = inputLastName.Value, CreateDate = DateTime.Now, UpdateDate = DateTime.Now, Username = inputUsername.Value, HashedPassword = PasswordManager.HashPassword(inputPassword.Value, salt), PasswordSalt = salt, Email = inputEmail.Value, PhoneNumber = inputPhoneNumber.Value, Address1 = inputAddress.Value, Address2 = inputAddress2.Value, City = inputCity.Value, State = inputState.Value, ZipCode = inputZip.Value, ApplicantType = "student" }; if (SQLDataAccess.SaveApplication(application)) { ApplicationPanel.Visible = false; SuccessMsg.Visible = true; } } else { ShowErrorMsg("That username already exists"); } }
/// <summary> /// Initializes a new instance of the <see cref="GNTPParser"/> class. /// </summary> /// <param name="passwordManager">The <see cref="PasswordManager"/> containing a list of allowed passwords</param> /// <param name="passwordRequired">Indicates if a password is required</param> /// <param name="allowNetworkNotifications">Indicates if network requests are allowed</param> /// <param name="allowBrowserConnections">Indicates if browser requests are allowed</param> /// <param name="allowSubscriptions">Indicates if SUBSCRIPTION requests are allowed</param> /// <param name="requestInfo">The <see cref="RequestInfo"/> associated with this request</param> public GNTPParser2(PasswordManager passwordManager, bool passwordRequired, bool allowNetworkNotifications, bool allowBrowserConnections, bool allowSubscriptions, RequestInfo requestInfo) { this.passwordManager = passwordManager; this.passwordRequired = passwordRequired; this.allowNetworkNotifications = allowNetworkNotifications; this.allowBrowserConnections = allowBrowserConnections; this.allowSubscriptions = allowSubscriptions; this.requestInfo = requestInfo; this.alreadyReceived = new StringBuilder(); this.headers = new HeaderCollection(); this.notificationsToBeRegistered = new List <HeaderCollection>(); this.pointers = new List <Pointer>(); this.callbackInfo = new CallbackInfo(); ms = new MemoryStream(); gntpReader = new GNTPStreamReader(ms); buffer = new List <byte>(); nextIndicator = AsyncSocket.CRLFData; tag = GNTP_IDENTIFIER_TAG; }
public Library(WebLibraryDetail web_library_detail) { this.web_library_detail = web_library_detail; Logging.Info("Library basepath is at {0}", LIBRARY_BASE_PATH); Logging.Info("Library document basepath is at {0}", LIBRARY_DOCUMENTS_BASE_PATH); Directory.CreateDirectory(LIBRARY_BASE_PATH); Directory.CreateDirectory(LIBRARY_DOCUMENTS_BASE_PATH); library_db = new LibraryDB(LIBRARY_BASE_PATH); folder_watcher_manager = new FolderWatcherManager(this); library_index = new LibraryIndex(this); ai_tag_manager = new AITagManager(this); recently_read_manager = new RecentlyReadManager(this); blackwhite_list_manager = new BlackWhiteListManager(this); password_manager = new PasswordManager(this); expedition_manager = new ExpeditionManager(this); // Start loading the documents in the background... SafeThreadPool.QueueUserWorkItem(o => BuildFromDocumentRepository()); }
static void Main(string[] args) { TodoList tdl = new TodoList(); tdl.Add("Invite friends"); tdl.Add("Buy decorations"); tdl.Add("Party"); PasswordManager pm = new PasswordManager("iluvopie", false); tdl.Display(); pm.Display(); //pm.ChangePassword("iluvopie","pieloveme"); //pm.Display(); //tdl.Reset(); //pm.Reset(); //tdl.Display(); //pm.Display(); }
public override async Task <ResponseDTO <UserResponseDTO> > update(UserRequestDTO dto) { if (dto.Id == 0) { new ResponseDTO <UserRequestDTO>("No ID was given for update"); } var oldEntity = await Repo.getById(dto.Id); if (dto.PasswordModified) { oldEntity.Password = PasswordManager.GeneratePasswordHash( Convert.FromBase64String(oldEntity.Salt), dto.Password); } oldEntity.FirstName = dto.FirstName; oldEntity.LastName = dto.LastName; oldEntity.AuthorizationLevel = dto.AuthorizationLevel; await Repo.update(oldEntity); return(new ResponseDTO <UserResponseDTO>()); }
public async Task <IActionResult> Register(RegisterViewModel registerViewModel) { if (ModelState.IsValid) { UserDTO userFromDB = await _usersService.GetUserByEmailAsync(registerViewModel.Email); if (userFromDB == null) { string passwordHash, passwordSalt; PasswordManager.CreatePasswordHash(registerViewModel.Password, out passwordHash, out passwordSalt); UserDTO newUserDTO = new UserDTO() { Id = Guid.NewGuid(), Name = registerViewModel.Name ?? registerViewModel.Email, Email = registerViewModel.Email, PasswordHash = passwordHash, PasswordSalt = passwordSalt }; CreatedUserRole newUserParams = await _usersService.CreateUserRoleAsync(newUserDTO, DefaultRolesList.User.ToString()); //, RolesList.Admin.ToString()"Admin", await AuthenticateAsync(newUserParams.Email, newUserParams.UserRolesID[0]); } else { ModelState.AddModelError("", "Такой пользователь существует"); //return Content("Такой пользователь существует"); return(View()); } return(Redirect(registerViewModel.ReturnURL ?? "/Home/Index")); } return(View()); }
public async Task <ActionResult> Login(string username, string password) { var passwordHash = PasswordManager.ComputeSha256Hash(password); var user = await _context.Users.Include(u => u.Role).SingleAsync(u => u.Username == username); if (user == null) { return(NotFound()); } else { if (user.Password == passwordHash) { return(Ok(new { data = TokenManager.GenerateToken(user), username = user.Username })); } else { return(NotFound()); } } }
public IActionResult Index(User user) { try { LoginUser = DataProvider.GetUserByEmail(user.Email).Result[0]; PasswordManager.SetKeys(user.Password, LoginUser.Name); string hash = PasswordManager.Encrypt(user.Password); if (LoginUser.Password == hash) { PasswordManager.SetKeys("", ""); //match! return(View("AfterLogin", LoginUser)); } else { return(View("WrongEmailOrPassword")); } } catch { } return(View("WrongEmailOrPassword")); }
public ViewResult Login(LoginViewModel loginViewModel) { if (ModelState.IsValid) { PasswordManager pwdManager = new PasswordManager(); Customer customer = repository.Customers.Single(c => c.Email == loginViewModel.Email); bool result = pwdManager.IsPasswordMatch(loginViewModel.Password, customer.Salt, customer.PasswordHash); if (result) { SaveCustomer(new CustomerViewModel(customer)); ViewBag.Customer = GetCustomer(); return(Countries()); } return(View()); } else { return(View()); } }
/// <summary> /// Logs a user into the vending machine system and throws exceptions on any failures /// </summary> /// <param name="username">The username of the user to authenicate</param> /// <param name="password">The password of the user to authenicate</param> public void LoginUser(string username, string password) { UserItem user = null; try { user = _db.GetUserItem(username); } catch (Exception) { throw new Exception("Either the username or the password is invalid."); } PasswordManager passHelper = new PasswordManager(password, user.Salt); if (!passHelper.Verify(user.Hash)) { throw new Exception("Either the username or the password is invalid."); } _roleMgr = new RoleManager(user); }
public ActionResult ChangePassword(ChangePassword model, string username) { try { if(ModelState.IsValid) { BTourGuideOp tourOp = new BTourGuideOp(); username = TempData["Username"].ToString(); AUser user = tourOp.GetUser(username); PasswordManager passMan = new PasswordManager(); if (passMan.IsPasswordMatch(model.OldPassword, user.Salt, user.UserPassword)) { // hash and salt the new password string salt = null; string hashPassword = passMan.GeneratePasswordHash(model.NewPassword, out salt); user.UserPassword = hashPassword; user.Salt = salt; tourOp.EditUser(user); return RedirectToAction("UserProfile", new { Username = username, msg = "Your password has changed" }); } else { return View(); } } else { return View(); } } catch(Exception e) { TempData["ChangePassException"] = "Something went wrong. " + e.Message; return View(); } }
private object OnChangePassword(object message) { var packet = ( ChangePasswordMessage )message; var ret = new OperationResult(); if (!this.CheckSession(packet.SessionKey)) { ret.Value = false; return(ret); } if (!this.IsPasswordCorrect(packet.OldPassword)) { ret.Value = false; return(ret); } if (!this.IsPasswordCorrect(packet.NewPassword)) { ret.Value = false; return(ret); } PasswordManager passwordManager = new PasswordManager(); string oldPassword = HashManager.Sha256(packet.OldPassword); bool result = passwordManager.CheckPassword(oldPassword); if (result) { string newPassword = HashManager.Sha256(packet.NewPassword); result = passwordManager.ChangePassword(oldPassword, newPassword); } ret.Value = result; return(ret); }
// Register button logic private void registerButton_Click(object sender, EventArgs e) { if (context.Readers.ToList().Where(r => r.nickname == nicknameTextBox.Text).Count() == 0) // Сheck nick's uniqueness { if (passwordTextBox.Text.Equals(confirmPasswordTextBox.Text)) // Check the password { // Creating a new user Reader reader = new Reader(); reader.name = nameTextBox.Text; reader.nickname = nicknameTextBox.Text; reader.password = PasswordManager.HashPassword(passwordTextBox.Text); reader.spentPoints = 0; reader.receivedPoints = 0; using (var ctx = new BooksContext()) { ctx.Readers.Add(reader); ctx.SaveChanges(); } // Open Main Form MessageBox.Show("User was successfully created", "Congrats"); LoginForm loginForm = new LoginForm(); loginForm.Show(); Hide(); } else // If passwords dont match { MessageBox.Show("Passwords don't match", "Pay attention"); passwordTextBox.Text = ""; confirmPasswordTextBox.Text = ""; } } else // If user already exists { MessageBox.Show("User already exists", "Something went wrong :c"); } }
public object AdminPasswordEdit(AdminInfo Info) { try { if (!ModelState.IsValid) { throw new FormatException(); } Info.PasswordHash = PasswordManager.encrypt(Info.PasswordHash); var result = bl_Admin.ChangePassword(new bl_Admin { userID = Info.userID, PasswordHash = Info.PasswordHash, }); if (result.hasError) { return(new { isSuccess = false, errorText = result.ErrorText }); } else { return(new { isSuccess = true }); } } catch (NullReferenceException e) { return(new { isSuccess = false, errorText = e.Message }); } catch (Exception ex) { return(new { isSuccess = false, errorText = ex.Message }); } return(new { isSuccess = true, errorText = "" }); }
public bool changePassword(int userId, string newpass) { bool success = false; try { accessManager.SqlConnectionOpen(DataBase.SQQeye); List <SqlParameter> aParameters = new List <SqlParameter>(); aParameters.Add(new SqlParameter("@userId", userId)); aParameters.Add(new SqlParameter("@newPass", PasswordManager.Encrypt(newpass))); success = accessManager.UpdateData("sp_changePassword", aParameters); return(success); } catch (Exception e) { accessManager.SqlConnectionClose(true); throw e; } finally { accessManager.SqlConnectionClose(); } }
public async Task <Guid> Handle(RegisterNewUserCommand request, CancellationToken cancellationToken) { var password = PasswordManager.HashPassword(request.Password); var registration = UserRegistration.RegisterNewUser( request.Login, password, request.Email, request.FirstName, request.LastName, _usersCounter); await _userRegistrationRepository.AddAsync(registration); var email = new EmailMessage(request.Email, "Football Banter - Please confirm your registration", "This should be link to confirmation page. For now, please execute HTTP request " + $"PATCH http://localhost:5000/userRegistration/{registration.Id.Value}/confirm"); await _emailSender.SendEmail(email); return(registration.Id.Value); }
/// <summary> /// Validates and returns a User using credentials (async) /// </summary> public async Task <ValidateResult> ValidateAsync(string credential_type, string identifier, string secret) { using (ValourDB context = new ValourDB(ValourDB.DBOptions)) { // Find the credential that matches the identifier and type Credential credential = await context.Credentials.FirstOrDefaultAsync( x => string.Equals(credential_type, x.Credential_Type, StringComparison.OrdinalIgnoreCase) && string.Equals(identifier, x.Identifier, StringComparison.OrdinalIgnoreCase)); // Use salt to validate secret hash byte[] hash = PasswordManager.GetHashForPassword(secret, credential.Salt); // Spike needs to remember how reference types work if (!hash.SequenceEqual(credential.Secret)) { return(new ValidateResult(new TaskResult(false, "Secret validation failed."), null)); } User user = await context.Users.FindAsync(credential.User_Id); return(new ValidateResult(new TaskResult(true, "Succeeded"), user)); } }
public void CanSetAndCheckPassword() { var pwd = new PasswordManager(); var user = new User { Login = "******" }; pwd.SetPassword(user, "cde3$RFV"); Assert.Less(20, user.Salt.Length); Assert.Less(20, user.Hash.Length); Console.WriteLine(user.Salt + "::" + user.Hash); Assert.True(pwd.MatchPassword(user, "cde3$RFV")); Assert.False(pwd.MatchPassword(user, "cde3$RFv")); var s = user.Salt; var h = user.Hash; pwd.SetPassword(user, "cde3$RFV"); //check that hash changed Assert.AreNotEqual(s, user.Salt); Assert.AreNotEqual(h, user.Hash); Assert.True(pwd.MatchPassword(user, "cde3$RFV")); Assert.False(pwd.MatchPassword(user, "cde3$RFv")); Console.WriteLine(user.Salt + "::" + user.Hash); }
public ActionResult <UserDTO> Post([FromBody] UserFormDTO userForm) { if (null != _userService.Get(u => u.Name == userForm.Name).FirstOrDefault()) { return(Conflict(new { error = "User alredy exist!" })); } var role = _roleService.Get(r => r.Name == userForm.Role.ToLower()).FirstOrDefault(); if (null == role) { return(BadRequest(new { error = "Role does not exist" })); } UserModel user = new UserModel() { Name = userForm.Name, RoleId = role.Id, CreatedAt = DateTime.UtcNow, Salt = PasswordManager.GenerateSalt(userForm.Name) }; user.Passhash = PasswordManager.GeneratePasshash(user.Salt, userForm.Password); return(Created("", _mapper.Map <UserDTO>(_userService.Create(user)))); }
public void UpdatePasswordController_Fail_InvalidSession() { // Arrange var expected = -5; var newUser = tu.CreateUserObject(); tu.CreateUserInDb(newUser); UpdatePasswordRequest request = new UpdatePasswordRequest(); request.sessionToken = "asdf"; request.oldPassword = "******"; request.newPassword = "******"; //Act using (_db = tu.CreateDataBaseContext()) { PasswordManager pm = new PasswordManager(_db); var actual = pm.UpdatePasswordController(request); //Assert Assert.AreEqual(expected, actual); } }
public Users Login(string userName, string password) { var q = unit.Users.Get() .Include(user => user.UsersRoles) .ThenInclude(urole => urole.Role) .FirstOrDefault(ur => (ur.Username == userName) || (ur.Email == userName)); if (q is null) { return(null); } var saltString = unit.Salts.Get().FirstOrDefault(slt => slt.UserId == q.Id).Salt; var actualSalt = Convert.FromBase64String(saltString.Trim()); if (PasswordManager.Match(password, q.PasswordHash, actualSalt)) { return(q); } return(null); }
public void FileTest() { var fileName = Path.GetTempFileName(); try { var source = new PasswordManager(); source.Set("john", "trustno1"); source.Set("jane", "trustsome1"); source.Save(fileName); var dest = PasswordManager.Load(fileName); Assert.IsTrue(dest.IsValid("john", "trustno1")); Assert.IsTrue(dest.IsValid("jane", "trustsome1")); Assert.IsFalse(dest.IsValid("john", "bad password")); Assert.IsFalse(dest.IsValid("jane", "bad password")); Assert.IsFalse(dest.IsValid("bad user", "bad password")); } finally { File.Delete(fileName); } }
public User Create(User user, string password) { // validation if (string.IsNullOrWhiteSpace(password)) { throw new AppException("Password is required"); } if (_context.Users.Any(x => x.Username == user.Username)) { throw new AppException("Username \"" + user.Username + "\" is already taken"); } byte[] passwordHash, passwordSalt; PasswordManager.CreatePasswordHash(password, out passwordHash, out passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; _context.Users.Add(user); _context.SaveChanges(); return(user); }
public async Task <IActionResult> ChangePassword( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "UserAccount/ChangePassword")] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function(ChangePassword) processed a request."); try { string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var userAccountUpdateModel = JsonConvert.DeserializeObject <UserAccountUpdateModel>(requestBody); var loginManager = new LoginManager(); var loginResult = loginManager.AttemptLogin(userAccountUpdateModel.EmailAddress, userAccountUpdateModel.Password); if (loginResult.Status == LoginStatus.Success) { var salt = PasswordManager.GenerateSalt(); var hash = PasswordManager.HashPassword(userAccountUpdateModel.NewPassword, salt); loginResult.UserAccount.Salt = salt; loginResult.UserAccount.Hash = hash; var userAccountRepo = new UserAccountRepository(); userAccountRepo.UpdateUserAccount(loginResult.UserAccount); return(new OkObjectResult($"Password updated.")); } else { // maybe change this so there's only 1 fail condition instead of having Error & Failure return(new BadRequestObjectResult(loginResult.FailureReason)); } } catch (Exception exception) { return(new BadRequestObjectResult(exception.Message)); } }
public static async Task AddUserToDb() { var repo = database.GetCollection <User>("Users"); var userList = new List <User> { new User { Email = "*****@*****.**", UserName = "******", Password = PasswordManager.Encrpyted("070695"), CreatedDate = DateTime.Now, ModifieddDate = DateTime.Now, Id = new ObjectId("59ee1ba3acf7c53bf4d2504c").ToString(), AvatarUrl = "https://avatars0.githubusercontent.com/u/13591213?s=460&v=4" }, new User { Email = "*****@*****.**", UserName = "******", Password = PasswordManager.Encrpyted("070695"), CreatedDate = DateTime.Now, ModifieddDate = DateTime.Now, Id = new ObjectId("59ee1ba3acf7c53bf4d2504d").ToString(), AvatarUrl = "https://avatars0.githubusercontent.com/u/13591213?s=460&v=4" } }; foreach (var user in userList) { var matchedProfile = repo.Find(x => x.Id == user.Id).Count(); if (matchedProfile == 0) { await repo.InsertManyAsync(userList); } } }
public ActionResult <UserModel> Login([FromBody] Login model) { var userInfo = new UserModel(); try { var u = _userService.CheckUserByEmail(model.Email); if (u != null) { var resultx = PasswordManager.VerifyHashedPassword(u.PasswordHash, model.Password); if (resultx) { userInfo.Id = u.Id; userInfo.FirstName = u.FirstName; userInfo.LastName = u.LastName; userInfo.Email = u.Email; userInfo.IsAuthenticated = true; userInfo.Code = 5; userInfo.UserName = u.UserName; userInfo.Role = u.Role; userInfo.Message = "User credential was successfully verified"; HttpContext.Session.SetObjectAsJson("_user", userInfo); return(userInfo); } } userInfo.Code = -1; userInfo.Message = "The provided email or password is incorrect"; return(userInfo); } catch (Exception e) { userInfo.Code = -1; userInfo.Message = e.Message != null ? e.Message : e.InnerException.Message; return(userInfo); } }
public static void Main(string[] args) { if (args.Length > 0) { Utilities.Auth = new Authentication(_serviceName, args[0].ToString()); Uri endpoint = new Uri(StringUtilities.RemoveTrailingBackSlash(System.Configuration.ConfigurationManager.AppSettings["AddNewPatientUri"].ToString())); Patient newPatient = FHIRUtilities.CreateTestFHIRPatientProfile(); WebSend ws = new WebSend(endpoint, Utilities.Auth, newPatient); try { ws.PostHttpWebRequest(); } catch (Exception ex) { MessageBox.Show("Status: Authentication Failed " + ex.Message + " Closing NoID."); return; } } if (Utilities.Auth != null || PasswordManager.GetPassword(_serviceName + "_Status") == "Successful") { //For Windows 7 and above, best to include relevant app.manifest entries as well Cef.EnableHighDPISupport(); //Perform dependency check to make sure all relevant resources are in our output directory. Cef.Initialize(new CefSettings(), performDependencyCheck: true, browserProcessHandler: null); var browser = new BrowserForm(); Application.Run(browser); } else { var login = new LoginForm(); Application.Run(login); } }
private void LoginYesOrNo() { //入力チェック if (string.IsNullOrEmpty(TbUserName.Text)) { OriginMBox.MBoxErrorOK(AppConst.USER_INPUT_ERROR); return; } if (string.IsNullOrEmpty(TbPassword.Text)) { OriginMBox.MBoxErrorOK(AppConst.PASSWORD_INPUT_ERROR); return; } // ログイン認証チェック Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); int userId = int.Parse(config.AppSettings.Settings["UserId"].Value); User user = User.SelectUserFromId(userId); bool isSuccess = PasswordManager.VerifyPassword(user.Password, TbPassword.Text, user.Salt); // ログイン合否によって処理分岐 if (isSuccess) { OriginMBox.MBoxInfoOK(AppConst.LOGIN_SUCCESS); controller.User = user; Hide(); MainHouseholdABookForm bookForm = new MainHouseholdABookForm(controller); if (bookForm.ShowDialog() != DialogResult.OK) { Close(); } } else { OriginMBox.MBoxErrorOK(AppConst.LOGIN_ERROR); } }
/// <summary> /// Adds a new user /// </summary> /// <param name="userModel">Model that contains all the user information</param> public void RegisterUser(UserItem userModel) { UserItem userItem = null; try { userItem = _db.GetUserItem(userModel.Username); } catch (Exception) { } if (userItem != null) { throw new UserExistsException("The username is already taken."); } if (userModel.Password != userModel.ConfirmPassword) { throw new PasswordMatchException("The password and confirm password do not match."); } PasswordManager passHelper = new PasswordManager(userModel.Password); UserItem newUser = new UserItem() { FirstName = userModel.FirstName, LastName = userModel.LastName, Email = userModel.Email, Username = userModel.Username, Salt = passHelper.Salt, Hash = passHelper.Hash, RoleId = (int)RoleManager.eRole.Customer }; _db.AddUserItem(newUser); LoginUser(newUser.Username, userModel.Password); }
public override bool ValidateUser(string username, string password) { var pas = new PasswordManager().GetPasswordMd5(password); return _endowmentRepositories.Users.IsAllowAccess(username, pas); }
public void GeneratingRandomPasswordTest() { var userId = "user1"; Password passwordSavedByRepo = new Password(); var datetimeAtStartOfTest = DateTime.UtcNow; var passwordRepository = new Mock<IRepository<Password>>(); passwordRepository.Setup(u => u.Save(It.IsAny<Password>())).Callback<Password>(p => passwordSavedByRepo = p); var passwordGenerator = new PasswordManager(passwordRepository.Object); var password = passwordGenerator.GeneratePassword(userId); passwordRepository.Verify(u => u.Save(It.IsAny<Password>()), Times.Once); Assert.IsFalse(string.IsNullOrEmpty(password), "Check password is not empty"); Assert.AreEqual(userId, passwordSavedByRepo.UserId, "Check saved password has userid"); Assert.AreEqual(HardcodedSalt, passwordSavedByRepo.PasswordSalt, "Check saved password has salt"); Assert.AreEqual(String.Concat(password, HardcodedSalt).GetHashCode().ToString(), passwordSavedByRepo.PasswordHash, "Check saved password has hash"); Assert.IsTrue(passwordSavedByRepo.ExpiryTime < datetimeAtStartOfTest.AddSeconds(35) && passwordSavedByRepo.ExpiryTime > datetimeAtStartOfTest.AddSeconds(25), "Check saved password has expiry date"); }
protected override IServer CreateServer(bool passwordCheckSucceedIfNotFound = true) { PasswordManager = new PasswordManager { CheckSucceedIfNotFound = passwordCheckSucceedIfNotFound }; BanManager = new BanManager(BanFilename); ClientManager = new ClientManager(10); AdminManager = new AdminManager(10); GameManager = new GameManager(10); return new Server(new Factory(), PasswordManager, BanManager, ClientManager, AdminManager, GameManager); }
private static void Main() { Log.Default.Logger = new NLogger(); Log.Default.Initialize(@"D:\TEMP\LOG\", "TETRINET2_SERVER.LOG"); IFactory factory = new Factory(); IPasswordManager passwordManager = new PasswordManager(); IBanManager banManager = new BanManager(@"D:\TEMP\ban.lst"); IClientManager clientManager = new ClientManager(50); IAdminManager adminManager = new AdminManager(5); IGameManager gameManager = new GameManager(10); IHost wcfHost = new WCFHost.WCFHost(banManager, clientManager, adminManager, gameManager) { Port = 7788 }; IServer server = new Server(factory, passwordManager, banManager, clientManager, adminManager, gameManager); server.AddHost(wcfHost); server.SetVersion(1, 0); server.SetAdminPassword("admin1", "123456"); server.PerformRestartServer += ServerOnPerformRestartServer; // try { server.Start(); } catch (Exception ex) { Log.Default.WriteLine(LogLevels.Error, "Cannot start server. Exception: {0}", ex); return; } bool stopped = false; while (!stopped) { if (Console.KeyAvailable) { ConsoleKeyInfo cki = Console.ReadKey(true); switch (cki.Key) { default: DisplayHelp(); break; case ConsoleKey.X: server.Stop(); stopped = true; break; case ConsoleKey.D: Console.WriteLine("Clients:"); foreach (IClient client in clientManager.Clients) Console.WriteLine("{0}) {1} [{2}] {3} {4} {5} {6:HH:mm:ss.fff} {7:HH:mm:ss.fff}", client.Id, client.Name, client.Team, client.State, client.Game == null ? "no in game" : client.Game.Name, client.PieceIndex, client.LastActionFromClient, client.LastActionToClient); Console.WriteLine("Admins:"); foreach (IAdmin admin in adminManager.Admins) Console.WriteLine("{0}) {1}", admin.Id, admin.Name); Console.WriteLine("Games:"); foreach (IGame game in gameManager.Games) Console.WriteLine("{0}) {1} {2} {3} #players:{4} #spectators:{5} password:{6} {7:HH:mm:ss}", game.Id, game.Name, game.State, game.Rule, game.PlayerCount, game.SpectatorCount, game.Password, game.CreationTime); break; } } else System.Threading.Thread.Sleep(100); } }
public ActionResult Login(LoginViewModel model, string returnUrl) { try { if (ModelState.IsValid) { BTourGuideOp tourOp = new BTourGuideOp(); List<AUser> users = tourOp.GetUsers(); AUser user = tourOp.GetUser(model.UserName); if (user != null) { // hasing & salting PasswordManager passMan = new PasswordManager(); bool result = passMan.IsPasswordMatch(model.Password, user.Salt, user.UserPassword); if (result) { FormsAuthentication.SetAuthCookie(model.UserName, false); return Redirect(returnUrl ?? Url.Action("Index", "Home")); } else { ModelState.AddModelError("", "Incorrect Username Or Password"); ViewBag.IncorrectInput = "Incorrect"; ViewBag.ReturnUrl = returnUrl; return View(); } } else ModelState.AddModelError("", "Incorrect Username Or Password"); ViewBag.IncorrectInput = "Incorrect"; ViewBag.ReturnUrl = returnUrl; return View(); } return View(); } catch (Exception e) { TempData["LoginException"] = "Login Error: " + e.Message; return View(); } }
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(); } }
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 void TestTimeManagerNotNull() { var passwordManager = new PasswordManager(null); }
public ActionResult Registration(UserDetails userdetails, string returnUrl) { 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)) { // password salting & hashing PasswordManager passMan = new PasswordManager(); string salt = null; string passwordHash = passMan.GeneratePasswordHash(userdetails.UserPassword, out salt); 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; user.UserPassword = passwordHash; user.Salt = salt; user.Username = userdetails.Username; user.UserBirthday = userdetails.UserBirthday; BTourGuideOp tourOp = new BTourGuideOp(); tourOp.AddUser(user); return RedirectToAction("Login", "Account"); } else { userdetails.Username = null; return View(); } } else { userdetails.Username = null; return View(); } } catch(Exception e) { TempData["Exception"] = "" + e.Message; return View(); } }