Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public interface IUserService
- {
- User Authenticate(string username, string password);
- IEnumerable<User> GetAll();
- User GetById(int id);
- User Create(User user, string password);
- void Update(User user, string password = null);
- void Delete(int id);
- }
- public class UserService : IUserService
- {
- private TestContext _context;
- public UserService(TestContext context)
- {
- _context = context;
- }
- public User Authenticate(string username, string password)
- {
- if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
- return null;
- var user = _context.Users.SingleOrDefault(x => x.Username == username);
- // check if username exists and here it returns null
- if (user == null)
- return null;
- if (!VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt))
- return null;
- return user;
- }
- public IEnumerable<User> GetAll()
- {
- return _context.Users;
- }
- public User GetById(int id)
- {
- return _context.Users.Find(id);
- }
- public User Create(User user, string password)
- {
- 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;
- CreatePasswordHash(password, out passwordHash, out passwordSalt);
- user.PasswordHash = passwordHash;
- user.PasswordSalt = passwordSalt;
- _context.Users.Add(user);
- _context.SaveChanges();
- return user;
- }
- public void Update(User userParam, string password = null)
- {
- var user = _context.Users.Find(userParam.ID);
- if (user == null)
- throw new AppException("User not found");
- if (userParam.Username != user.Username)
- {
- if (_context.Users.Any(x => x.Username == userParam.Username))
- throw new AppException("Username " + userParam.Username + " is already taken");
- }
- user.FirstName = userParam.FirstName;
- user.LastName = userParam.LastName;
- user.Username = userParam.Username;
- if (!string.IsNullOrWhiteSpace(password))
- {
- byte[] passwordHash, passwordSalt;
- CreatePasswordHash(password, out passwordHash, out passwordSalt);
- user.PasswordHash = passwordHash;
- user.PasswordSalt = passwordSalt;
- }
- _context.Users.Update(user);
- _context.SaveChanges();
- }
- public void Delete(int id)
- {
- var user = _context.Users.Find(id);
- if (user != null)
- {
- _context.Users.Remove(user);
- _context.SaveChanges();
- }
- }
- private static void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
- {
- if (password == null) throw new ArgumentNullException("password");
- if (string.IsNullOrWhiteSpace(password)) throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
- using (var hmac = new System.Security.Cryptography.HMACSHA512())
- {
- passwordSalt = hmac.Key;
- passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
- }
- }
- private static bool VerifyPasswordHash(string password, byte[] storedHash, byte[] storedSalt)
- {
- if (password == null) throw new ArgumentNullException("password");
- if (string.IsNullOrWhiteSpace(password)) throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
- if (storedHash.Length != 64) throw new ArgumentException("Invalid length of password hash (64 bytes expected).", "passwordHash");
- if (storedSalt.Length != 128) throw new ArgumentException("Invalid length of password salt (128 bytes expected).", "passwordHash");
- using (var hmac = new System.Security.Cryptography.HMACSHA512(storedSalt))
- {
- var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
- for (int i = 0; i < computedHash.Length; i++)
- {
- if (computedHash[i] != storedHash[i]) return false;
- }
- }
- return true;
- }
- }
- namespace TestContext.Data.Helpers
- {
- public class TestContext: DbContext
- {
- public TestContext(DbContextOptions<TestContext>
- options): base(options) { }
- public DbSet<User> Users { get; set; }
- public DbSet<AddressBook> AddressBooks { get;set; }
- }
- namespace Test.Data.Controllers
- {
- [Authorize]
- [Route("[controller]")]
- public class UsersController : Controller
- {
- private IUserService _userService;
- private IMapper _mapper;
- private readonly AppSettings _appSettings;
- public UsersController(
- IUserService userService,
- IMapper mapper,
- IOptions<AppSettings> appSettings)
- {
- _userService = userService;
- _mapper = mapper;
- _appSettings = appSettings.Value;
- }
- [AllowAnonymous]
- [HttpPost("authenticate")]
- public IActionResult Authenticate([FromBody]UserDto userDto)
- {
- var user = _userService.Authenticate(userDto.Username, userDto.Password);
- if (user == null)
- return Unauthorized();
- var tokenHandler = new JwtSecurityTokenHandler();
- var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
- var tokenDescriptor = new SecurityTokenDescriptor
- {
- Subject = new ClaimsIdentity(new Claim[]
- {
- new Claim(ClaimTypes.Name, user.ID.ToString())
- }),
- Expires = DateTime.UtcNow.AddDays(7),
- SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
- };
- var token = tokenHandler.CreateToken(tokenDescriptor);
- var tokenString = tokenHandler.WriteToken(token);
- return Ok(new
- {
- Id = user.ID,
- Username = user.Username,
- Firstname = user.FirstName,
- Lastname = user.LastName,
- Token = tokenString
- });
- }
- [AllowAnonymous]
- [HttpPost]
- public IActionResult Register([FromBody]UserDto userDto)
- {
- // map dto to entity
- var user = _mapper.Map<User>(userDto);
- try
- {
- // save
- _userService.Create(user, userDto.Password);
- return Ok();
- }
- catch (AppException ex)
- {
- // return error message if there was an exception
- return BadRequest(ex.Message);
- }
- }
- [HttpGet]
- public IActionResult GetAll()
- {
- var users = _userService.GetAll();
- var userDtos = _mapper.Map<IList<UserDto>>(users);
- return Ok(userDtos);
- }
- [HttpGet("{id}")]
- public IActionResult GetById(int id)
- {
- var user = _userService.GetById(id);
- var userDto = _mapper.Map<UserDto>(user);
- return Ok(userDto);
- }
- [HttpPut("{id}")]
- public IActionResult Update(int id, [FromBody]UserDto userDto)
- {
- // map dto to entity and set id
- var user = _mapper.Map<User>(userDto);
- user.ID = id;
- try
- {
- // save
- _userService.Update(user, userDto.Password);
- return Ok();
- }
- catch (AppException ex)
- {
- // return error message if there was an exception
- return BadRequest(ex.Message);
- }
- }
- [HttpDelete("{id}")]
- public IActionResult Delete(int id)
- {
- _userService.Delete(id);
- return Ok();
- }
- }
Add Comment
Please, Sign In to add comment