API
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RegisterRepository.cs 9.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. using Microsoft.AspNetCore.Authorization;
  2. using Microsoft.EntityFrameworkCore;
  3. using Microsoft.Extensions.Options;
  4. using Microsoft.IdentityModel.Tokens;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.IdentityModel.Tokens.Jwt;
  8. using System.Linq;
  9. using System.Security.Claims;
  10. using System.Text;
  11. using UnivateProperties_API.Containers;
  12. using UnivateProperties_API.Containers.Users;
  13. using UnivateProperties_API.Context;
  14. using UnivateProperties_API.Helpers;
  15. using UnivateProperties_API.Model.Users;
  16. namespace UnivateProperties_API.Repository.Users
  17. {
  18. public class RegisterRepository : IRegisterRepository
  19. {
  20. private readonly DataContext _dbContext;
  21. private readonly AppSettings _appSettings;
  22. public RegisterRepository(DataContext dbContext, IOptions<AppSettings> appSettings)
  23. {
  24. _dbContext = dbContext;
  25. _appSettings = appSettings.Value;
  26. }
  27. public User Authenticate(string username, string password)
  28. {
  29. if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
  30. return null;
  31. var user = _dbContext.Users.SingleOrDefault(x => x.Username == username);
  32. // check if username exists
  33. if (user == null)
  34. return null;
  35. // check if password is correct
  36. if (!VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt))
  37. return null;
  38. // authentication successful
  39. return user;
  40. }
  41. public User Create(User user, string password, bool save)
  42. {
  43. // validation
  44. if (string.IsNullOrWhiteSpace(password))
  45. throw new AppException("Password is required");
  46. if (_dbContext.Users.Any(x => x.Username == user.Username))
  47. throw new AppException("Username \"" + user.Username + "\" is already taken");
  48. byte[] passwordHash, passwordSalt;
  49. CreatePasswordHash(password, out passwordHash, out passwordSalt);
  50. user.PasswordHash = passwordHash;
  51. user.PasswordSalt = passwordSalt;
  52. _dbContext.Users.Add(user);
  53. if (save)
  54. {
  55. _dbContext.SaveChanges();
  56. }
  57. return user;
  58. }
  59. public Agency CreateAgency(AgencyDto agency)
  60. {
  61. // validation
  62. if (string.IsNullOrWhiteSpace(agency.EaabeffcNumber))
  63. throw new AppException("eaabeffcNumber is required");
  64. if (_dbContext.Agencies.Any(x => x.EAABEFFCNumber == agency.EaabeffcNumber))
  65. throw new AppException("eaabeffcNumber \"" + agency.EaabeffcNumber + "\" already exists");
  66. Agency a = new Agency()
  67. {
  68. AgencyName = agency.Name,
  69. EAABEFFCNumber = agency.EaabeffcNumber,
  70. CompanyRegNumber = agency.RegNo
  71. };
  72. _dbContext.Agencies.Add(a);
  73. CreatePerson(agency.User, PersonType.Agent, false, a);
  74. _dbContext.SaveChanges();
  75. return a;
  76. }
  77. public void CreatePerson(UserDto individual, PersonType personType, bool save, Agency agency)
  78. {
  79. // validation
  80. if (string.IsNullOrWhiteSpace(individual.Password))
  81. throw new AppException("Password is required");
  82. if (_dbContext.Users.Any(x => x.Username == individual.Username))
  83. throw new AppException("Individual \"" + individual.Username + "\" is already taken");
  84. byte[] passwordHash, passwordSalt;
  85. CreatePasswordHash(individual.Password, out passwordHash, out passwordSalt);
  86. User createUser = new User()
  87. {
  88. Username = individual.Username,
  89. PasswordHash = passwordHash,
  90. PasswordSalt = passwordSalt
  91. };
  92. Create(createUser, individual.Password, save);
  93. Person person = new Person()
  94. {
  95. };
  96. if (personType == PersonType.Agent)
  97. {
  98. Agent agent = new Agent()
  99. {
  100. Name = individual.Name,
  101. Surname = individual.Surname,
  102. User = createUser,
  103. Email = individual.Email,
  104. CellNumber = individual.CellNumber,
  105. Telephone = individual.Telephone,
  106. Agency = agency
  107. };
  108. _dbContext.Agents.Add(agent);
  109. }
  110. else if (personType == PersonType.Individual)
  111. {
  112. Individual i = new Individual()
  113. {
  114. Name = individual.Name,
  115. Surname = individual.Surname,
  116. User = createUser,
  117. Email = individual.Email,
  118. CellNumber = individual.CellNumber,
  119. Telephone = individual.Telephone
  120. };
  121. _dbContext.Individuals.Add(i);
  122. }
  123. if (save)
  124. {
  125. Save();
  126. }
  127. }
  128. public void Update(User userParam, string password = null)
  129. {
  130. var user = _dbContext.Users.Find(userParam.Id);
  131. if (user == null)
  132. throw new AppException("User not found");
  133. if (userParam.Username != user.Username)
  134. {
  135. // username has changed so check if the new username is already taken
  136. if (_dbContext.Users.Any(x => x.Username == userParam.Username))
  137. throw new AppException("Username " + userParam.Username + " is already taken");
  138. }
  139. // update user properties
  140. user.Username = userParam.Username;
  141. // update password if it was entered
  142. if (!string.IsNullOrWhiteSpace(password))
  143. {
  144. byte[] passwordHash, passwordSalt;
  145. CreatePasswordHash(password, out passwordHash, out passwordSalt);
  146. user.PasswordHash = passwordHash;
  147. user.PasswordSalt = passwordSalt;
  148. }
  149. _dbContext.Users.Update(user);
  150. _dbContext.SaveChanges();
  151. }
  152. [Authorize(Roles = Role.SuperAdmin)]
  153. public IEnumerable<User> GetAllUsers()
  154. {
  155. return _dbContext.Users;
  156. }
  157. [Authorize(Roles = Role.SuperAdmin)]
  158. public IEnumerable<Agency> GetAllAgencies()
  159. {
  160. return _dbContext.Agencies;
  161. }
  162. [Authorize(Roles = Role.SuperAdmin)]
  163. public IEnumerable<Individual> GetAllIndividuals()
  164. {
  165. return _dbContext.Individuals;
  166. }
  167. public User GetById(int id)
  168. {
  169. return _dbContext.Users.Find(id);
  170. }
  171. public Agency GetByAgencyId(int id)
  172. {
  173. return _dbContext.Agencies.Find(id);
  174. }
  175. public Individual GetByIndividualId(int id)
  176. {
  177. return _dbContext.Individuals.Find(id);
  178. }
  179. public void Delete(int id)
  180. {
  181. var user = _dbContext.Users.Find(id);
  182. if (user != null)
  183. {
  184. _dbContext.Users.Remove(user);
  185. _dbContext.SaveChanges();
  186. }
  187. }
  188. public void DeleteAgency(int id)
  189. {
  190. var agency = _dbContext.Agencies.Find(id);
  191. if (agency != null)
  192. {
  193. _dbContext.Remove(agency);
  194. _dbContext.SaveChanges();
  195. }
  196. }
  197. public void DeleteIndividual(int id)
  198. {
  199. var individual = _dbContext.Individuals.Find(id);
  200. if (individual != null)
  201. {
  202. _dbContext.Individuals.Remove(individual);
  203. _dbContext.SaveChanges();
  204. }
  205. }
  206. private void Save()
  207. {
  208. _dbContext.SaveChanges();
  209. }
  210. private static void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
  211. {
  212. if (password == null) throw new ArgumentNullException("password");
  213. if (string.IsNullOrWhiteSpace(password)) throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
  214. using (var hmac = new System.Security.Cryptography.HMACSHA512())
  215. {
  216. passwordSalt = hmac.Key;
  217. passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
  218. }
  219. }
  220. private static bool VerifyPasswordHash(string password, byte[] storedHash, byte[] storedSalt)
  221. {
  222. if (password == null) throw new ArgumentNullException("password");
  223. if (string.IsNullOrWhiteSpace(password)) throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
  224. if (storedHash.Length != 64) throw new ArgumentException("Invalid length of password hash (64 bytes expected).", "passwordHash");
  225. if (storedSalt.Length != 128) throw new ArgumentException("Invalid length of password salt (128 bytes expected).", "passwordHash");
  226. using (var hmac = new System.Security.Cryptography.HMACSHA512(storedSalt))
  227. {
  228. var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
  229. for (int i = 0; i < computedHash.Length; i++)
  230. {
  231. if (computedHash[i] != storedHash[i]) return false;
  232. }
  233. }
  234. return true;
  235. }
  236. }
  237. }