public OperationResult<UserWithRoles> CreateUser(string username, string email, string password, string[] roles) { var existingUser = _userRepository.GetAll().Any( x => x.Name == username); if (existingUser) { return new OperationResult<UserWithRoles>(false); } var passwordSalt = _cryptoService.GenerateSalt(); var user = new User() { Name = username, Salt = passwordSalt, Email = email, IsLocked = false, HashedPassword = _cryptoService.EncryptPassword(password, passwordSalt), CreatedOn = DateTime.Now }; _userRepository.Add(user); _userRepository.Save(); if (roles != null && roles.Length > 0) { foreach (var roleName in roles) { addUserToRole(user, roleName); } } return new OperationResult<UserWithRoles>(true) { Entity = GetUserWithRoles(user) }; }
private UserWithRoles GetUserWithRoles(User user) { if (user != null) { var userRoles = GetUserRoles(user.Key); return new UserWithRoles() { User = user, Roles = userRoles }; } return null; }
private void addUserToRole(User user, string roleName) { var role = _roleRepository.GetSingleByRoleName(roleName); if (role == null) { var tempRole = new Role() { Name = roleName }; _roleRepository.Add(tempRole); _roleRepository.Save(); role = tempRole; } var userInRole = new UserInRole() { RoleKey = role.Key, UserKey = user.Key }; _userInRoleRepository.Add(userInRole); _userInRoleRepository.Save(); }
private bool isPasswordValid(User user, string password) { return string.Equals( _cryptoService.EncryptPassword( password, user.Salt), user.HashedPassword); }
// Private helpers private bool isUserValid(User user, string password) { if (isPasswordValid(user, password)) { return !user.IsLocked; } return false; }
public UserWithRoles UpdateUser( User user, string username, string email) { user.Name = username; user.Email = email; user.LastUpdatedOn = DateTime.Now; _userRepository.Edit(user); _userRepository.Save(); return GetUserWithRoles(user); }