public void GetHashStringTest(string login, string password, string expectedResult) { var hashManager = new PasswordHashManager(); var result = hashManager.GetHashString(login, password); Assert.Equal(expectedResult, result); }
/// <summary> /// Authorize facebook user in system. /// </summary> /// <param name="loginFacebookViewModel">The login facebook view model.</param> /// <returns></returns> public UserInfoViewModel LoginFacebook(LoginFacebookViewModel loginFacebookViewModel) { User user = this._unitOfWork.UsersRepository.GetFacebookUser(loginFacebookViewModel.Email); var salt = GenerateSalt(); if (user == null) { user = loginFacebookViewModel; user.Salt = salt; user.Password = PasswordHashManager.GetPasswordHash(salt, loginFacebookViewModel.Password); User addedUser = this._unitOfWork.UsersRepository.Create(user); this._unitOfWork.SaveChanges(); return(this.InitializeUserInfoViewModel(addedUser)); } else { if (user.FB_Link == null) { user.FB_Link = "facebook.com/" + loginFacebookViewModel.FbLink; this._unitOfWork.UsersRepository.Update(user); this._unitOfWork.SaveChanges(); return(this.InitializeUserInfoViewModel(user)); } } return(this.InitializeUserInfoViewModel(user)); }
public User GetUserByCredentials(string login, string password) { if (String.IsNullOrEmpty(login) || String.IsNullOrEmpty(password)) { return(null); } var hashedPassword = PasswordHashManager.GetPasswordHash(password); string query = @"SELECT u.id, u.email as 'Email', u.Login, u.Password, r.Name as 'Role' FROM Users as u inner join Membershipes as m on u.Id = m.UserId inner join Roles as r on m.RoleId = r.Id where u.Login = @login and u.Password = @password ;"; User user; using (AuthContext db = new AuthContext()) { //Todo: add parametr password user = db.Database.SqlQuery <User>(query, new SqlParameter("@login", login), new SqlParameter("@password", hashedPassword)).FirstOrDefault(); } if (user != null) { user.Password = string.Empty; } return(user); }
/// <summary> /// Creates user in database /// </summary> /// <param name="registrationViewModel">RegistrationViewModel</param> /// <returns>Added user model</returns> public RegistrationViewModel CreateUser(RegistrationViewModel registrationViewModel) { bool isUserExists = this._unitOfWork.UsersRepository.isUserExisted(registrationViewModel.Email, registrationViewModel.Login); if (isUserExists) { throw new BusinessLogicException(ErrorMessages.UserExistsMessage); } try { string salt = GenerateSalt(); User userToAdd = registrationViewModel; userToAdd.Salt = salt; //userToAdd.Password = PasswordHashManager.GetPasswordHash(registrationViewModel.Password); userToAdd.Password = PasswordHashManager.GetPasswordHash(salt, registrationViewModel.Password); User addedUser = this._unitOfWork.UsersRepository.Create(userToAdd); Phone newUserPhoneNumber = new Phone { Number = registrationViewModel.Phone, UserId = addedUser.Id }; Phone addedUserPhoneNumber = _unitOfWork.PhoneRepository.Add(newUserPhoneNumber); this._unitOfWork.SaveChanges(); this.CreateUserRole(addedUser.Login); addedUser.Phones.Add(addedUserPhoneNumber); return(addedUser); } catch (Exception ex) { throw new BusinessLogicException(ErrorMessages.AddUserMessage, ex); } }
/// <summary> /// Changes password of specified User, by its login /// </summary> /// <param name="changePasswordViewModel">View model containing login, old password, new password and error message</param> /// <returns>Empty userInfoViewModel with errors in case if any arised</returns> public UserInfoViewModel ChangePassword(ChangePasswordViewModel changePasswordViewModel) { if (changePasswordViewModel != null) { if (changePasswordViewModel.login != null && changePasswordViewModel.newPassword != null & changePasswordViewModel.oldPassword != null) { User user = this._unitOfWork.UsersRepository.GetUser(changePasswordViewModel.login); if (user.Password == PasswordHashManager.GetPasswordHash(changePasswordViewModel.oldPassword)) { user.Password = PasswordHashManager.GetPasswordHash(changePasswordViewModel.newPassword); _unitOfWork.UsersRepository.Update(user); _unitOfWork.SaveChanges(); return(this.InitializeUserInfoViewModel(user)); } else { throw new Exception("Старий пароль невірний"); } } else { throw new Exception("Заповнені не всі поля"); } } else { throw new Exception("Не намагайтеся нас обманути!"); } }
/// <summary> /// Changes password of specified User, by its login /// </summary> /// <param name="changePasswordViewModel">View model containing login, old password, new password and error message</param> /// <returns>Empty userInfoViewModel with errors in case if any arised</returns> public UserInfoViewModel ChangePassword(ChangePasswordViewModel changePasswordViewModel) { if (changePasswordViewModel != null) { if (changePasswordViewModel.login != null && changePasswordViewModel.newPassword != null & changePasswordViewModel.oldPassword != null) { User user = this._unitOfWork.UsersRepository.GetUser(changePasswordViewModel.login); var userSalt = this._unitOfWork.UsersRepository.Read().Where(u => u.Login == changePasswordViewModel.login).Select(u => u.Salt).FirstOrDefault(); if (user.Password == PasswordHashManager.GetPasswordHash(userSalt, changePasswordViewModel.oldPassword)) { user.Password = PasswordHashManager.GetPasswordHash(userSalt, changePasswordViewModel.newPassword); _unitOfWork.UsersRepository.Update(user); _unitOfWork.SaveChanges(); return(this.InitializeUserInfoViewModel(user)); } else { throw new Exception(ErrorMessages.OldPasswordIncorrectErrorMessage); } } else { throw new Exception(ErrorMessages.NotAllRowsFilledInErrorMessage); } } else { throw new Exception(ErrorMessages.IncorectDataErrorMessage); } }
public object Post(CompletePasswordReset request) { //validate request params if (request == null || request.UserId < 1) { throw new ArgumentException("Missing parameter 'UserId'"); } if (request.UniqueId == null || request.UniqueId == Guid.Empty) { throw new ArgumentException("Missing parameter 'UniqueId'"); } if (string.IsNullOrWhiteSpace(request.NewPassword)) { throw new ArgumentException("Missing parameter 'NewPassword'"); } //find the user //validate the email address exists var user = Db.SingleById <User>(request.UserId); if (user == null) { throw new ArgumentException("Invalid user"); } //find the reseet record var resetRecord = Db.Single <PasswordReset>(r => r.UniqueId == request.UniqueId); if (resetRecord == null) { throw new ArgumentException("Invalid reset id"); } //validate the user matches the id from the URL if (resetRecord.UserId != request.UserId || resetRecord.UserId != user.Id) { throw new ArgumentException("Invalid reset id"); } var resetAge = DateTime.UtcNow - resetRecord.CreatedOn; if (resetAge > new TimeSpan(24, 0, 0)) { throw new ArgumentException("Invalid reset id"); } //update the user record user.Password = PasswordHashManager.CreateHash(request.NewPassword); Db.Save <User>(user); //delete the password reset record Db.DeleteById <PasswordReset>(resetRecord.Id); return(new PasswordResponse { Success = true }); }
/// <summary> /// Проверяет верный ли пароль для пользователя. /// </summary> /// <param name="user"></param> /// <param name="pass"></param> /// <returns></returns> public bool ValidatePassword(IUser user, string pass) { if (user is Admin && pass != null) { // сравниваем хеш пароля в базе с вычисленным по паролю return(PasswordHashManager.ValidatePassword(pass, user.Passport.HashAndSalt)); } // врач входит без пароля return(user is Doctor); }
/// <summary> /// Меняет пароль пользователю. /// </summary> /// <param name="user"></param> /// <param name="password"></param> /// <returns>False, если пароль совпадает с текущим.</returns> public bool ChangePassword(IUser user, string password) { if (ValidatePassword(user, password)) { return(false); } var hash = PasswordHashManager.CreateHash(password); user.Passport.HashAndSalt = hash; return(true); }
/// <summary> /// Gets user info view model /// </summary> /// <param name="userLogin">User login</param> /// <param name="rawPassword">User raw password</param> /// <returns>User info view model</returns> public UserInfoViewModel GetUserInfoViewModel(string login, string rawPassword) { if (login.Length != 0 && rawPassword.Length != 0) { var hashedPassword = PasswordHashManager.GetPasswordHash(rawPassword); return(this.InitializeUserInfoViewModel(this._unitOfWork.UsersRepository.GetUser(login, hashedPassword))); } else { throw new BusinessLogicException(ErrorMessages.MissedEnterData); } }
/// <summary> /// Gets user info view model /// </summary> /// <param name="userLogin">User login</param> /// <param name="rawPassword">User raw password</param> /// <returns>User info view model</returns> public UserInfoViewModel GetUserInfoViewModel(string login, string rawPassword) { if (login.Length != 0 && rawPassword.Length != 0) { var userSalt = this._unitOfWork.UsersRepository.Read().Where(u => u.Login == login).Select(u => u.Salt).FirstOrDefault(); var hashedPassword = PasswordHashManager.GetPasswordHash(userSalt, rawPassword); return(this.InitializeUserInfoViewModel(this._unitOfWork.UsersRepository.GetUser(login, hashedPassword))); } else { throw new BusinessLogicException(ErrorMessages.MissedEnterData); } }
public static bool TryToRegister(TcpAccountInfo accountInfo, bool accepted) { DataSet data = DBSelect("[교사 ID]", "[교사 목록]", $"[교사 ID]={accountInfo.ID.ToSQLString()}", null); if (data.Tables[0].Rows.Count != 0) { return(false); } DBInsert("[교사 목록]", accountInfo.ID.ToSQLString(), PasswordHashManager.HashPassword(accountInfo.Password).ToSQLString(), accountInfo.Name.ToSQLString(), accountInfo.Type.ToSQLString(), accepted ? "True" : "False"); return(true); }
//Login as normal user public object Post(AuthenticatedSessionRequest request) { long estimateCount = 0; //param validation if (request == null || string.IsNullOrWhiteSpace(request.DeviceId)) { throw new ArgumentException("Missing parameter 'DeviceId'"); } if (string.IsNullOrWhiteSpace(request.Email)) { throw new ArgumentException("Missing parameter 'Email'"); } if (string.IsNullOrWhiteSpace(request.Password)) { throw new ArgumentException("Missing parameter 'Password'"); } //find the user and validate the password var user = Db.Single <User>(u => u.Email == request.Email && u.Active == true); if (user != null && PasswordHashManager.ValidatePassword(request.Password, user.Password)) { //its good... give em a new session and carry on UpdateUserSession(user); //if the user is an agent, add in their zip codes if (user.IsAgent) { user.PostalCodes = PostalCodesForUser(user.Id); } else { estimateCount = Db.Count <Estimate>(e => e.UserId == user.Id); } return(new NewSessionResponse { SessionId = user.SessionId.Value, User = user, EstimateRequestCount = estimateCount }); } //if we get here we either could not find the user or the pw was bad throw new AuthenticationException("Invalid username or password."); }
/// <summary> /// Resets user password /// </summary> /// <param name="passwordReset">View model of PasswordResetViewModel</param> public void ResetPassword(PasswordResetViewModel passwordReset) { var user = _unitOfWork.UsersRepository.GetUserByGuid(passwordReset.Guid); if (user != null) { user.Password = PasswordHashManager.GetPasswordHash(passwordReset.NewPassword); _unitOfWork.UsersRepository.Update(user); _unitOfWork.UsersRepository.RemoveUserRecoveryLink(user.Id); _unitOfWork.SaveChanges(); } else { throw new BusinessLogicException(ErrorMessages.InvalidGuid); } }
public DeleteOrgAccountViewModel DeleteOrganizationAccount(DeleteOrgAccountViewModel model) { try { var userRole = this._unitOfWork.MembershipRepository.GetRole(model.UserId); User user = this._unitOfWork.UsersRepository.Get(model.UserId); if (user.Password == PasswordHashManager.GetPasswordHash(user.Salt, model.AdministratorPassword)) { if (this._unitOfWork.MembershipRepository.GetOrganizationId(model.UserId) == model.OrganizationId && userRole == "admin") { var orgAccount = this._unitOfWork.OrganizationAccountRepository.Read(model.OrgAccountId); this._unitOfWork.OrganizationAccountRepository.Delete(model.OrgAccountId); if (orgAccount.AccountType == "Банк") { var bankAccount = this._unitOfWork.BankAccountRepository.Get(orgAccount.BankAccount.Id); this._unitOfWork.BankAccountRepository.Delete(bankAccount.Id); } this._unitOfWork.SaveChanges(); return(new DeleteOrgAccountViewModel()); } else { return(new DeleteOrgAccountViewModel { Error = ErrorMessages.YouArentAdminOfThisOrganization }); } } else { return(new DeleteOrgAccountViewModel { Error = ErrorMessages.WrongAdminPasswond }); } } catch (Exception e) { return(new DeleteOrgAccountViewModel { Error = e.Message }); } }
/// <summary> /// Resets user password /// </summary> /// <param name="passwordReset">View model of PasswordResetViewModel</param> public void ResetPassword(PasswordResetViewModel passwordReset) { var user = _unitOfWork.UsersRepository.GetUserByGuid(passwordReset.Guid); var userSalt = this._unitOfWork.UsersRepository.Read().Where(u => u.Login == user.Login).Select(u => u.Salt).FirstOrDefault(); if (user != null) { user.Password = PasswordHashManager.GetPasswordHash(userSalt, passwordReset.NewPassword); _unitOfWork.UsersRepository.Update(user); _unitOfWork.UsersRepository.RemoveUserRecoveryLink(user.Id); _unitOfWork.SaveChanges(); } else { throw new BusinessLogicException(ErrorMessages.InvalidGuid); } }
public DeleteOrgAccountViewModel DeleteOrganizationAccount(DeleteOrgAccountViewModel model) { try { var userRole = this._unitOfWork.MembershipRepository.GetRole(model.UserId); User user = this._unitOfWork.UsersRepository.Get(model.UserId); if (user.Password == PasswordHashManager.GetPasswordHash(model.AdministratorPassword)) { if (this._unitOfWork.MembershipRepository.GetOrganizationId(model.UserId) == model.OrganizationId && userRole == "admin") { var orgAccount = this._unitOfWork.OrganizationAccountRepository.Read(model.OrgAccountId); this._unitOfWork.OrganizationAccountRepository.Delete(model.OrgAccountId); if (orgAccount.AccountType == "Банк") { var bankAccount = this._unitOfWork.BankAccountRepository.Get(orgAccount.BankAccount.Id); this._unitOfWork.BankAccountRepository.Delete(bankAccount.Id); } this._unitOfWork.SaveChanges(); return(new DeleteOrgAccountViewModel()); } else { return(new DeleteOrgAccountViewModel { Error = "Ви не адміністратор цієї організації" }); } } else { return(new DeleteOrgAccountViewModel { Error = "Невірний пароль адміністратора організації" }); } } catch (Exception e) { return(new DeleteOrgAccountViewModel { Error = e.Message }); } }
public static void FillData(Configuration cfg, dynamic session, bool server = false, bool alterIds = false) { var isSqlite = cfg.GetProperty(Environment.Dialect) == typeof(SQLiteDialect).AssemblyQualifiedName; using (ITransaction tx = session.BeginTransaction()) { foreach (var item in GetScript(!isSqlite, server, alterIds)) { session.CreateSQLQuery(item).ExecuteUpdate(); } if (!server) { session.CreateSQLQuery(string.Format("INSERT INTO {0} ([Id], [HashAndSalt]) Values ('{1}','{2}')", Names.Passport, Admin.DefaultId, PasswordHashManager.CreateHash(Admin.DefaultPassword))).ExecuteUpdate(); } tx.Commit(); } }
public override void Up() { //Create.Table(Names.Passport) // .WithColumn("Id").AsGuid().NotNullable().PrimaryKey("PK__Passport") // .WithColumn("HashAndSalt").AsFixedLengthString(PasswordHashManager.HASH_LENGTH).Nullable() // .WithColumn("Remember").AsBoolean().NotNullable().WithDefaultValue(0); // администратор с паролем по умолчанию Insert.IntoTable(Names.Passport) .Row(new { Id = Admin.DefaultId, HashAndSalt = PasswordHashManager.CreateHash(Admin.DefaultPassword) }); // для каждого врача - пасспорт без пароля // Execute.Sql(string.Format("INSERT INTO {0} ([Id]) Select Id from {1}", Names.Passport, Names.Doctor)); //Create.ForeignKey(Names.FK.Doctor_Passport).FromTable(Names.Doctor) // .ForeignColumn("Id") // .ToTable(Names.Passport) // .PrimaryColumn("Id"); }
public static TcpLoginResult MatchLoginInfo(TcpLoginInfo info) { DataSet data = DBSelect("*", "[교사 목록]", $"[교사 ID]={info.ID.ToSQLString()}", null); DataTable mainTable = data.Tables[0]; int rowsCount = mainTable.Rows.Count; if (rowsCount == 0) { return(new TcpLoginResult("", "", "", false, false, false)); } else if (rowsCount > 1) { throw new InvalidOperationException("데이터베이스에 같은 교사 ID가 여러개 있습니다."); } string id = info.ID; string name = mainTable.Rows[0]["성명"].ToString(); string type = mainTable.Rows[0]["계정 구분"].ToString(); string correctPWHash = mainTable.Rows[0]["PW 해시"].ToString(); bool pwCorrect = PasswordHashManager.ValidatePassword(info.Password, correctPWHash); bool accepted = (bool)mainTable.Rows[0]["가입 허가 여부"]; return(new TcpLoginResult(id, name, type, true, pwCorrect, accepted)); }
public AccountController(DataBaseContext context, PasswordHashManager getHash) { passwordHashManager = getHash; dataBaseContext = context; }
//Login as normal user public object Post(UpdateUserRequest request) { var user = ValidateAndGetCurrentUser(); if (user.Id != request.UserId) { throw new UnauthorizedAccessException("'UserId' must be the same as the authenticated user."); } if (!string.IsNullOrWhiteSpace(request.Company)) { user.Company = request.Company; } if (!string.IsNullOrWhiteSpace(request.AgentLicense)) { user.AgentLicense = request.AgentLicense; } if (!string.IsNullOrWhiteSpace(request.Email)) { user.Email = request.Email; } if (!string.IsNullOrWhiteSpace(request.FirstName)) { user.FirstName = request.FirstName; } if (!string.IsNullOrWhiteSpace(request.LastName)) { user.LastName = request.LastName; } if (!string.IsNullOrWhiteSpace(request.Password)) { user.Password = PasswordHashManager.CreateHash(request.Password); } if (!string.IsNullOrWhiteSpace(request.PhoneNumber)) { user.PhoneNumber = request.PhoneNumber; } user.CanReceiveEmail = request.CanReceiveEmail; user.PremiumInfo = request.PremiumInfo; using (var transaction = Db.BeginTransaction()) { Db.Save <User>(user); if (request.PostalCodes != null) { user.PostalCodes = request.PostalCodes; Db.Delete <AgentPostalCode>(p => p.UserId == user.Id); foreach (var code in request.PostalCodes.Where(p => p != null)) { Db.Save <AgentPostalCode>(new AgentPostalCode { PostalCode = code, UserId = user.Id }); } } if (user.IsPremium) { Db.Save <PremiumInfo>(request.PremiumInfo); } transaction.Commit(); } return(new UserResponse { User = user }); }
public UserController(DataBaseContext context, PasswordHashManager hashPassword) { getHashPassword = hashPassword; dataBaseContext = context; }
//Create a user public object Post(CreateUserRequest request) { //param validation if (request == null || string.IsNullOrWhiteSpace(request.Email)) { throw new ArgumentException("Missing parameter 'Email'"); } if (string.IsNullOrWhiteSpace(request.Password)) { throw new ArgumentException("Missing parameter 'Password'"); } if (string.IsNullOrWhiteSpace(request.FirstName)) { throw new ArgumentException("Missing parameter 'FirstName'"); } if (string.IsNullOrWhiteSpace(request.LastName)) { throw new ArgumentException("Missing parameter 'LastName'"); } if (string.IsNullOrWhiteSpace(request.Company) && request.IsAgent) { throw new ArgumentException("Missing parameter 'Company'"); } if (string.IsNullOrWhiteSpace(request.PhoneNumber) && request.IsAgent) { throw new ArgumentException("Missing parameter 'PhoneNumber'"); } //make sure there is not already a user with this email var user = Db.Single <User>(u => u.Email == request.Email); if (user != null) { throw new ArgumentException("A user with that email address already exists."); } using (var transaction = Db.BeginTransaction()) { //setup the new account user = new User { SessionId = Guid.NewGuid(), Email = request.Email, IsAgent = request.IsAgent, FirstName = request.FirstName, LastName = request.LastName, Company = request.Company, PhoneNumber = request.PhoneNumber, CreatedOn = DateTime.UtcNow, Password = PasswordHashManager.CreateHash(request.Password), AffiliateId = request.AffiliateId, IsPremium = false, IsAdmin = false, CanReceiveEmail = true, Active = true }; Db.Save <User>(user); if (request.PostalCodes != null) { foreach (var code in request.PostalCodes.Where(p => p != null)) { Db.Save <AgentPostalCode>(new AgentPostalCode { PostalCode = code, UserId = user.Id }); } } transaction.Commit(); //if (request.IsAgent) //{ // Task emailTask = new Task(() => // { // var to = "*****@*****.**"; // //var to = "*****@*****.**"; // var subject = $"New Agent Signup {user.FirstName} {user.LastName} - {user.Company}"; // var body = $"{user.FirstName} {user.LastName}\r\n{user.Company}\r\n{user.Email}\r\n\r\nHas signed up for an account with the following service area:\r\n"; // if (request.PostalCodes != null) // { // foreach (var code in request.PostalCodes) // { // body += $"{code}\r\n"; // } // } // if (!AwsBucket.ToLower().Contains("devel")) // SendEmailFromSupport(to, subject, body); // }); // emailTask.Start(); //} } return(new NewSessionResponse { User = AgentWithPostalCodes(user.Id), SessionId = user.SessionId.Value, EstimateRequestCount = 0 }); }