public ActionResult Login(string username, string password) { //Alex's password from database ("123456") var passwordFromDatabase = "1000:x4EDMqYUMVwARzOGy/KyINiGXJzmAnsj:6tE2G9/X4ZozQP699EKLzhWuf8NiOsEM"; if (PasswordHashHelper.ValidatePassword(password, passwordFromDatabase)) { FormsAuthentication.SetAuthCookie(username, true); } //var ticket = new FormsAuthenticationTicket( // 2, // username, // DateTime.Now, // DateTime.Now.AddMinutes(1), // false, // Value of IsPersistent property // String.Empty, // FormsAuthentication.FormsCookiePath //); //string encryptedTicket = FormsAuthentication.Encrypt(ticket); //var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); //authCookie.Expires = DateTime.Now.AddMinutes(1); //Response.Cookies.Add(authCookie); return(Redirect(FormsAuthentication.GetRedirectUrl(username, false))); }
public IHttpActionResult AddUser(EmployeeModel employee) { var findUser = DBContext.Employee.FirstOrDefault(x => x.UserName == employee.UserName); if (findUser != null) { } var newEmployee = new Employee(); newEmployee.Admin = employee.IsAdmin; newEmployee.UserName = employee.UserName; newEmployee.FirstName = employee.FirstName; newEmployee.LastName = employee.LastName; newEmployee.Salt = PasswordHashHelper.CreateSalt(employee.UserName); newEmployee.Pword = PasswordHashHelper.PasswordHasher(new HashModel() { Password = employee.Password, Salt = newEmployee.Salt }); try { DBContext.Employee.Add(newEmployee); DBContext.SaveChanges(); return(Ok()); } catch (Exception) { return(BadRequest()); throw; } }
public ActionResult Register(RegisterViewModel model) { if (!ModelState.IsValid) { return(RedirectToAction("Index", "Error")); } var user = _userService.CreateUser(new User { Email = model.Email, FirstName = model.FirstName, SecondName = model.SecondName, PasswordHash = PasswordHashHelper.GetHash(model.Password), UserRoles = new Collection <UserRole> { new UserRole { ObjectState = ObjectState.Added, RoleId = 2 } }, SentMessages = new Collection <Message>(), ReceivedMessages = new Collection <Message>(), ObjectState = ObjectState.Added }); AuthHelper.LogInUser(HttpContext, user.Email); return(RedirectToAction("Index", "Home")); }
public async Task <bool> CreateAdminAsync(string login, string password) { var isLoginUnavailable = _DBContext.Admins.Any(admin => admin.Login == login); if (isLoginUnavailable) { throw new BadArgumentException("This login is unavailable."); } PasswordHashHelper.CreatePasswordHash(password, out byte[] hash, out byte[] salt); AdminEntity createAdminEntity = new AdminEntity() { Login = login, PasswordHash = hash, PasswordSalt = salt }; await _DBContext.Admins.AddAsync(createAdminEntity); await _DBContext.SaveChangesAsync(); bool isAdminCreated = await _DBContext.Admins.AnyAsync(admin => admin.Login == login); return(isAdminCreated); }
public Result CreateAccount(UserAccountCreationInfo userInfo, out User user) { // Validate dto ValidationHelper.ValidateModel(userInfo); // Create user object user = Mapper.Map <User>(userInfo); user.PasswordHash = PasswordHashHelper.CreateHash(userInfo.Password); user.LastLoginDate = DateTime.Now; // Validate user ValidationHelper.ValidateModel(user); // Other validations string email = user.Email; if (dataAccessor.Users.Any(other => email == other.Email)) { throw new ValidationException(MsgAccountWithEmailExists); } // Do save dataAccessor.Create(user); dataAccessor.SaveChanges(); return(Login(new LoginInfo { Email = userInfo.Email, Password = userInfo.Password })); }
public Result Login(LoginInfo loginInfo) { // Check for null/empty if (loginInfo == null || string.IsNullOrWhiteSpace(loginInfo.Email) || string.IsNullOrWhiteSpace(loginInfo.Password)) { throw new ValidationException(MsgLoginInfoNotEntered); } // Get matching pwd and hash from db User userInfo = (from user in dataAccessor.Users.Include(u => u.Roles) where user.Email == loginInfo.Email select user).FirstOrDefault(); // Check match if (userInfo == null || !PasswordHashHelper.ValidatePassword(loginInfo.Password, userInfo.PasswordHash)) { throw new ValidationException(MsgInvalidUsernameOrPwd); } // Login succeeded, set forms cookie string token = SetAndReturnFormsAuthenticationCookie(userInfo.Email); // Set up cached user context UserContext userContext = new UserContext(token, userInfo); CacheItemPolicy cacheItemPolicy = new CacheItemPolicy { SlidingExpiration = TimeSpan.FromHours(1) }; cache.Set(token, cacheItemPolicy, userContext); return(new Result()); }
public async Task <AdminDTO> UpdateAdminAsync(UpdateAdminDTO updateAdminDTO) { if (string.IsNullOrWhiteSpace(updateAdminDTO.NewLogin) && string.IsNullOrWhiteSpace(updateAdminDTO.NewPassword)) { throw new BadArgumentException("The new login and password cannot be blank at the same time. There is nothing to update."); } AdminEntity admin = await _DBContext.Admins.FirstOrDefaultAsync(a => a.Id == updateAdminDTO.Id); if (admin == null) { throw new BadArgumentException($"Admin with id {updateAdminDTO.Id} not found."); } //Подумати!!! if (!string.IsNullOrWhiteSpace(updateAdminDTO.NewLogin)) { admin.Login = updateAdminDTO.NewLogin; } if (!string.IsNullOrWhiteSpace(updateAdminDTO.NewPassword)) { PasswordHashHelper.CreatePasswordHash(updateAdminDTO.NewPassword, out var hash, out var sail); admin.PasswordHash = hash; admin.PasswordSalt = sail; } _DBContext.Admins.Update(admin); await _DBContext.SaveChangesAsync(); var updatedAdminDTO = _mapper.Map <AdminDTO>(admin); return(updatedAdminDTO); }
public ActionResult Register(user_login user_Login) { try { using (var db = new HRISContext()) { var chkUser = (from s in db.user_login where s.user_id == user_Login.user_id select s).FirstOrDefault(); if (chkUser == null) { var keyNew = PasswordHashHelper.GeneratePassword(10); var pass = PasswordHashHelper.EncodePassword(user_Login.password, keyNew); user_Login.password = pass; user_Login.vcode = keyNew; db.user_login.Add(user_Login); db.SaveChanges(); ModelState.Clear(); return(RedirectToAction("LogIn", "Login")); } ViewBag.ErrorMessage = "User Already Exixts!"; return(View()); } } catch (Exception e) { ViewBag.ErrorMessage = "Some exception occured" + e; return(View()); } }
public HttpResponseMessage Login(LoginModel loginModel) { try { var user = DBContext.Employee.FirstOrDefault(x => x.UserName == loginModel.Username); if (user != null) { var hash = new HashModel() { Password = loginModel.Password, Salt = user.Salt }; var hashedPassword = PasswordHashHelper.PasswordHasher(hash); if (hashedPassword == user.Pword) { return(new HttpResponseMessage(HttpStatusCode.OK)); } } } catch (Exception) { throw; } return(new HttpResponseMessage(HttpStatusCode.Forbidden)); }
public async Task <IActionResult> Login([FromBody] LoginModel loginModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState.GetFirstError())); } var user = await _userService.GetByEmail(loginModel.Email); if (user == null) { return(BadRequest(ValidationResultMessages.LoginWrongCredentials)); } var result = PasswordHashHelper.VerifyHashedPassword(user.Password, loginModel.Password); if (!result || !user.IsAdmin) { return(BadRequest(ValidationResultMessages.LoginWrongCredentials)); } var tokens = GetJWTTokens(user); return(Ok(tokens)); }
public User Get(string email, string password) { User user = null; var resultUser = Get(email); if (resultUser == null) { return(null); } var saltForUser = resultUser.PasswordSalt; var passwordAndSalt = password + saltForUser; var hash = PasswordHashHelper.GetPasswordHashAndSalt(passwordAndSalt); var validUser = Data.FirstOrDefault(s => s.Email == email && s.Password == hash); if (validUser != null) { user = validUser; } return(user); }
private void btnLogin_Click(object sender, EventArgs e) { //create salt byte[] salt; new RNGCryptoServiceProvider().GetBytes(salt = new byte[SaltSize]); //generate hash with salt string hash = PasswordHashHelper.Hash(txtPassword.Text, salt, 1000); var checkLogin = from cc_users in db.cc_users where cc_users.UserName == txtusername.Text select new { username = cc_users.UserName, password = cc_users.Password, salt = cc_users.Salt }; foreach (var user in checkLogin) { //var saltByte = new byte[user.salt.Length]; if (PasswordHashHelper.Verify(txtPassword.Text, user.password)) { //MessageBox.Show("Passwords Match"); Properties.Settings.Default.Username = txtusername.Text; Properties.Settings.Default.Save(); Dashboard dashboard = new Dashboard(); dashboard.Show(); } else { MessageBox.Show("Login failed"); } } }
static UserService() { Data = new List <User> { new User { Id = 1, Name = "Fran01", Email = "*****@*****.**", Password = PasswordHashHelper.GetPasswordHashAndSalt(string.Format("{0}{1}", "hellspawn", SaltKey)), PasswordSalt = SaltKey, Roles = new List <string> { RoleConstants.Mananger } }, new User { Id = 2, Name = "Supervisor", Email = "*****@*****.**", Password = PasswordHashHelper.GetPasswordHashAndSalt(string.Format("{0}{1}", "hellspawn", SaltKey)), PasswordSalt = SaltKey, Roles = new List <string> { RoleConstants.Mananger, RoleConstants.Supervisor } } }; }
public async Task<ServiceResponse<int>> Register(User user, string password) { ServiceResponse<int> serviceResponse = new ServiceResponse<int>(); try { if (await UserExists(user.Username)) { serviceResponse.Success = false; serviceResponse.Message = "User alread exists."; return serviceResponse; } PasswordHashHelper.CreatePasswordHash(password, out byte[] passwordHash, out byte[] passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; await _dataContext.Users.AddAsync(user); await _dataContext.SaveChangesAsync(); serviceResponse.Data = user.Id; return serviceResponse; } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = ex.Message; } return serviceResponse; }
public async Task <IActionResult> Register([FromBody] RegistrationModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState.GetFirstError())); } var existingUser = await _userService.GetByEmail(model.Email); if (existingUser != null) { return(BadRequest(ValidationResultMessages.DuplicateEmail)); } var user = new User() { Email = model.Email, UserName = model.UserName, Password = PasswordHashHelper.HashPassword(model.Password), IsAdmin = true, }; if (!string.IsNullOrWhiteSpace(model.CompanyName)) { user.CompanyId = Guid.NewGuid(); user.CompanyName = model.CompanyName; } user = await _userService.CreateNew(user); var tokens = GetJWTTokens(user); return(Ok(tokens)); }
public async Task <AuthorizedAdminDTO> AuthorizeAsync(string login, string password) { var admin = await _DBContext.Admins.FirstOrDefaultAsync(x => x.Login == login); if (admin == null) { throw new AccessForbiddenException("Invalid login or password."); } if (!PasswordHashHelper.VerifyPasswordHash(password, admin.PasswordHash, admin.PasswordSalt)) { throw new AccessForbiddenException("Invalid login or password."); } var claims = new List <Claim> { new Claim("login", login) }; var authorizedAdmin = new AuthorizedAdminDTO() { Login = login }; authorizedAdmin.Token = GetToken(claims, TimeSpan.Parse(_appSettings.JwtSettings.Expires), Encoding.ASCII.GetBytes(_appSettings.JwtSettings.SecretKey)); return(authorizedAdmin); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); using (var db = new EmployeeContext()) { var user = db.Users.FirstOrDefault(x => x.Email.Equals(context.UserName)); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } if (!PasswordHashHelper.ValidatePassword(context.Password, user.PasswordHash)) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } var identity = new ClaimsIdentity(context.Options.AuthenticationType); var roles = db.UserRoles.Where(x => x.UserId.Equals(user.Id)).Select(x => x.RoleName).ToList(); identity.AddClaim(new Claim(ClaimTypes.Email, context.UserName)); identity.AddClaim(roles.Contains(Role.Admin) ? new Claim(ClaimTypes.Role, Role.Admin) : new Claim(ClaimTypes.Role, Role.User)); context.Validated(identity); } }
//[ValidateAntiForgeryToken] public async Task <IHttpActionResult> ResetPassword(AccountViewModels.ResetPasswordViewModel model, string returnUrl = null) { try { using (Entities db = new Entities()) { AspNetUser user = new AspNetUser(); user = db.AspNetUsers.FirstOrDefault(usr => usr.Email == model.Email); if (user != null) { using (MD5 md5Hash = MD5.Create()) { string passwordhash = PasswordHashHelper.GetMd5Hash(md5Hash, model.Password); user.PasswordHash = passwordhash; } db.AspNetUsers.AddOrUpdate(user); db.SaveChanges(); return(Ok(true)); } else { return(Ok(false)); } } } catch (Exception ex) { return(Ok(false)); } }
public void HashPassword_Verify_True() { var text = Guid.NewGuid().ToString(); var hashed = PasswordHashHelper.HashPassword(text); var hashed2 = PasswordHashHelper.HashPassword(text); Assert.True(hashed == hashed2); }
public CompanyDto CreateLoginInfo(CompanyDto compnayDto) { LoginInfoCreate loginInfo = PasswordHashHelper.CreatePasswordHash(compnayDto.Password); compnayDto.AccountDto = new AccountDto(); compnayDto.AccountDto.PasswordSalt = loginInfo.Salt; compnayDto.AccountDto.PasswordHash = loginInfo.PasswordHash; return(compnayDto); }
public bool VerifyPassword(string hash, string password, bool isDefault) { if (isDefault) { return(hash == password); } return(PasswordHashHelper.Verify(password, hash)); }
public long?SessionId => null; //TODO public bool VerifyPassword(string hash, string password, bool isDefault) { if (isDefault) { throw new InvalidOperationException("Not accessible with default password"); } return(PasswordHashHelper.Verify(password, hash)); }
public bool Register(UserModel userModel) { userRepository.Add(new User { Email = userModel.Email, PasswordHash = PasswordHashHelper.HashPassword(userModel.Password) }); return(unitOfWork.Commit()); }
/*// TODO: Here is where you would validate the username and password. * private static bool CheckPassword(string username, string password) * { * return username == "user" && password == "password"; * }*/ private static void AuthenticateUser(string credentials) { try { //var encoding = Encoding.GetEncoding("iso-8859-1"); var encoding = Encoding.UTF8; credentials = encoding.GetString(Convert.FromBase64String(credentials)); int separator = credentials.IndexOf(':'); string name = credentials.Substring(0, separator); string password = credentials.Substring(separator + 1); /*if (CheckPassword(name, password)) * { * var identity = new GenericIdentity(name); * SetPrincipal(new GenericPrincipal(identity, null)); * } * else * { * // Invalid username or password. * HttpContext.Current.Response.StatusCode = 401; * }*/ // name och password är variablerna du ska jobba med här var user = DBContext.Employee.FirstOrDefault(x => x.UserName == name); if (user != null && user.Pword == PasswordHashHelper.PasswordHasher(new HashModel() { Password = password, Salt = user.Salt })) { var identity = new GenericIdentity(name); if (user.Admin) { SetPrincipal(new GenericPrincipal(identity, new[] { "Admin" })); } else { SetPrincipal(new GenericPrincipal(identity, new[] { "Driver" })); } } else { // Invalid username or password. HttpContext.Current.Response.StatusCode = 401; } } catch (FormatException) { // Credentials were not formatted correctly. HttpContext.Current.Response.StatusCode = 401; } }
public async Task Login_Success(LoginModel model, User user) { user.PasswordHash = PasswordHashHelper.HashPassword(model.Password); _userRepository.Setup(c => c.GetUserByEmail(model.Email)).ReturnsAsync(user); var result = await _manager.Login(model); Assert.True(result.Id == user.Id); Assert.True(result.Name == user.Name); }
public async Task CreatePassword(PasswordRequest passwordRequest) { await _dynamoClient.PutItemAsync(DynamoConstants.CREDENTIALS_TABLE, new Dictionary <string, AttributeValue> { { DynamoConstants.UserIdKey, new AttributeValue(passwordRequest.UserId) }, { DynamoConstants.EmailKey, new AttributeValue(passwordRequest.Email) }, { DynamoConstants.PasswordHashKey, new AttributeValue( PasswordHashHelper.Generate(passwordRequest.Password)) } }); }
public override User GenerateEntity(int index) { return(new User { FirstName = Configurations.AdminFirstName, SecondName = Configurations.AdminSecondName, Email = Configurations.AdminEmail, PasswordHash = PasswordHashHelper.GetHash(Configurations.AdminPassword), ObjectState = ObjectState.Added }); }
public User GetUserByEmailAndPassword(string email, string password) { var passwordHash = PasswordHashHelper.GetHash(password); return(Query(x => x.Email.ToLower() == email.ToLower() && x.PasswordHash == passwordHash) .Include(user1 => user1.UserRoles) .Include(user1 => user1.UserRoles.Select(role => role.Role)) .Select().FirstOrDefault()); }
public UserController(IOptions <NanokaOptions> options, IUserRepository users, ILocker locker, IMapper mapper, IUserClaims claims, PasswordHashHelper hash, SnapshotHelper snapshot, TokenManager tokens) { _options = options.Value; _users = users; _locker = locker; _mapper = mapper; _claims = claims; _hash = hash; _snapshot = snapshot; _tokens = tokens; }
public async Task <int> AddUser(User user) { var context = _context.GetContext(); user.PasswordHash = PasswordHashHelper.HashPassword(user.PasswordHash); user.CreationDate = DateTime.Now; context.Users.Add(user); await context.SaveChangesAsync(); return(user.Id); }