Guest User

Untitled

a guest
Apr 5th, 2018
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.66 KB | None | 0 0
  1. public interface IUserService
  2. {
  3. User Authenticate(string username, string password);
  4. IEnumerable<User> GetAll();
  5. User GetById(int id);
  6. User Create(User user, string password);
  7. void Update(User user, string password = null);
  8. void Delete(int id);
  9. }
  10.  
  11. public class UserService : IUserService
  12. {
  13. private TestContext _context;
  14.  
  15. public UserService(TestContext context)
  16. {
  17. _context = context;
  18. }
  19.  
  20. public User Authenticate(string username, string password)
  21. {
  22. if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
  23. return null;
  24.  
  25. var user = _context.Users.SingleOrDefault(x => x.Username == username);
  26.  
  27. // check if username exists and here it returns null
  28. if (user == null)
  29. return null;
  30.  
  31.  
  32. if (!VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt))
  33. return null;
  34.  
  35.  
  36. return user;
  37. }
  38.  
  39. public IEnumerable<User> GetAll()
  40. {
  41. return _context.Users;
  42. }
  43.  
  44. public User GetById(int id)
  45. {
  46. return _context.Users.Find(id);
  47. }
  48.  
  49. public User Create(User user, string password)
  50. {
  51.  
  52. if (string.IsNullOrWhiteSpace(password))
  53. throw new AppException("Password is required");
  54.  
  55. if (_context.Users.Any(x => x.Username == user.Username))
  56. throw new AppException("Username " + user.Username + " is already taken");
  57.  
  58. byte[] passwordHash, passwordSalt;
  59. CreatePasswordHash(password, out passwordHash, out passwordSalt);
  60.  
  61. user.PasswordHash = passwordHash;
  62. user.PasswordSalt = passwordSalt;
  63.  
  64. _context.Users.Add(user);
  65. _context.SaveChanges();
  66.  
  67. return user;
  68. }
  69.  
  70. public void Update(User userParam, string password = null)
  71. {
  72. var user = _context.Users.Find(userParam.ID);
  73.  
  74. if (user == null)
  75. throw new AppException("User not found");
  76.  
  77. if (userParam.Username != user.Username)
  78. {
  79. if (_context.Users.Any(x => x.Username == userParam.Username))
  80. throw new AppException("Username " + userParam.Username + " is already taken");
  81. }
  82.  
  83.  
  84. user.FirstName = userParam.FirstName;
  85. user.LastName = userParam.LastName;
  86. user.Username = userParam.Username;
  87.  
  88.  
  89. if (!string.IsNullOrWhiteSpace(password))
  90. {
  91. byte[] passwordHash, passwordSalt;
  92. CreatePasswordHash(password, out passwordHash, out passwordSalt);
  93.  
  94. user.PasswordHash = passwordHash;
  95. user.PasswordSalt = passwordSalt;
  96. }
  97.  
  98. _context.Users.Update(user);
  99. _context.SaveChanges();
  100. }
  101.  
  102. public void Delete(int id)
  103. {
  104. var user = _context.Users.Find(id);
  105. if (user != null)
  106. {
  107. _context.Users.Remove(user);
  108. _context.SaveChanges();
  109. }
  110. }
  111.  
  112. private static void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
  113. {
  114. if (password == null) throw new ArgumentNullException("password");
  115. if (string.IsNullOrWhiteSpace(password)) throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
  116.  
  117. using (var hmac = new System.Security.Cryptography.HMACSHA512())
  118. {
  119. passwordSalt = hmac.Key;
  120. passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
  121. }
  122. }
  123.  
  124. private static bool VerifyPasswordHash(string password, byte[] storedHash, byte[] storedSalt)
  125. {
  126. if (password == null) throw new ArgumentNullException("password");
  127. if (string.IsNullOrWhiteSpace(password)) throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
  128. if (storedHash.Length != 64) throw new ArgumentException("Invalid length of password hash (64 bytes expected).", "passwordHash");
  129. if (storedSalt.Length != 128) throw new ArgumentException("Invalid length of password salt (128 bytes expected).", "passwordHash");
  130.  
  131. using (var hmac = new System.Security.Cryptography.HMACSHA512(storedSalt))
  132. {
  133. var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
  134. for (int i = 0; i < computedHash.Length; i++)
  135. {
  136. if (computedHash[i] != storedHash[i]) return false;
  137. }
  138. }
  139.  
  140. return true;
  141. }
  142. }
  143.  
  144. namespace TestContext.Data.Helpers
  145. {
  146. public class TestContext: DbContext
  147. {
  148. public TestContext(DbContextOptions<TestContext>
  149. options): base(options) { }
  150. public DbSet<User> Users { get; set; }
  151. public DbSet<AddressBook> AddressBooks { get;set; }
  152.  
  153. }
  154.  
  155. namespace Test.Data.Controllers
  156. {
  157. [Authorize]
  158. [Route("[controller]")]
  159. public class UsersController : Controller
  160. {
  161. private IUserService _userService;
  162. private IMapper _mapper;
  163. private readonly AppSettings _appSettings;
  164.  
  165. public UsersController(
  166. IUserService userService,
  167. IMapper mapper,
  168. IOptions<AppSettings> appSettings)
  169. {
  170. _userService = userService;
  171. _mapper = mapper;
  172. _appSettings = appSettings.Value;
  173. }
  174.  
  175. [AllowAnonymous]
  176. [HttpPost("authenticate")]
  177. public IActionResult Authenticate([FromBody]UserDto userDto)
  178. {
  179. var user = _userService.Authenticate(userDto.Username, userDto.Password);
  180.  
  181. if (user == null)
  182. return Unauthorized();
  183.  
  184. var tokenHandler = new JwtSecurityTokenHandler();
  185. var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
  186. var tokenDescriptor = new SecurityTokenDescriptor
  187. {
  188. Subject = new ClaimsIdentity(new Claim[]
  189. {
  190. new Claim(ClaimTypes.Name, user.ID.ToString())
  191. }),
  192. Expires = DateTime.UtcNow.AddDays(7),
  193. SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
  194. };
  195. var token = tokenHandler.CreateToken(tokenDescriptor);
  196. var tokenString = tokenHandler.WriteToken(token);
  197.  
  198.  
  199. return Ok(new
  200. {
  201. Id = user.ID,
  202. Username = user.Username,
  203. Firstname = user.FirstName,
  204. Lastname = user.LastName,
  205. Token = tokenString
  206. });
  207. }
  208.  
  209. [AllowAnonymous]
  210. [HttpPost]
  211. public IActionResult Register([FromBody]UserDto userDto)
  212. {
  213. // map dto to entity
  214. var user = _mapper.Map<User>(userDto);
  215.  
  216. try
  217. {
  218. // save
  219. _userService.Create(user, userDto.Password);
  220. return Ok();
  221. }
  222. catch (AppException ex)
  223. {
  224. // return error message if there was an exception
  225. return BadRequest(ex.Message);
  226. }
  227. }
  228.  
  229. [HttpGet]
  230. public IActionResult GetAll()
  231. {
  232. var users = _userService.GetAll();
  233. var userDtos = _mapper.Map<IList<UserDto>>(users);
  234. return Ok(userDtos);
  235. }
  236.  
  237. [HttpGet("{id}")]
  238. public IActionResult GetById(int id)
  239. {
  240. var user = _userService.GetById(id);
  241. var userDto = _mapper.Map<UserDto>(user);
  242. return Ok(userDto);
  243. }
  244.  
  245. [HttpPut("{id}")]
  246. public IActionResult Update(int id, [FromBody]UserDto userDto)
  247. {
  248. // map dto to entity and set id
  249. var user = _mapper.Map<User>(userDto);
  250. user.ID = id;
  251.  
  252. try
  253. {
  254. // save
  255. _userService.Update(user, userDto.Password);
  256. return Ok();
  257. }
  258. catch (AppException ex)
  259. {
  260. // return error message if there was an exception
  261. return BadRequest(ex.Message);
  262. }
  263. }
  264.  
  265. [HttpDelete("{id}")]
  266. public IActionResult Delete(int id)
  267. {
  268. _userService.Delete(id);
  269. return Ok();
  270. }
  271. }
Add Comment
Please, Sign In to add comment