API
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

RegisterRepository.cs 9.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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.Name = userParam.Name;
  141. user.Surname = userParam.Surname;
  142. user.Username = userParam.Username;
  143. // update password if it was entered
  144. if (!string.IsNullOrWhiteSpace(password))
  145. {
  146. byte[] passwordHash, passwordSalt;
  147. CreatePasswordHash(password, out passwordHash, out passwordSalt);
  148. user.PasswordHash = passwordHash;
  149. user.PasswordSalt = passwordSalt;
  150. }
  151. _dbContext.Users.Update(user);
  152. _dbContext.SaveChanges();
  153. }
  154. [Authorize(Roles = Role.SuperAdmin)]
  155. public IEnumerable<User> GetAllUsers()
  156. {
  157. return _dbContext.Users;
  158. }
  159. [Authorize(Roles = Role.SuperAdmin)]
  160. public IEnumerable<Agency> GetAllAgencies()
  161. {
  162. return _dbContext.Agencies;
  163. }
  164. [Authorize(Roles = Role.SuperAdmin)]
  165. public IEnumerable<Individual> GetAllIndividuals()
  166. {
  167. return _dbContext.Individuals;
  168. }
  169. public User GetById(int id)
  170. {
  171. return _dbContext.Users.Find(id);
  172. }
  173. public Agency GetByAgencyId(int id)
  174. {
  175. return _dbContext.Agencies.Find(id);
  176. }
  177. public Individual GetByIndividualId(int id)
  178. {
  179. return _dbContext.Individuals.Find(id);
  180. }
  181. public void Delete(int id)
  182. {
  183. var user = _dbContext.Users.Find(id);
  184. if (user != null)
  185. {
  186. _dbContext.Users.Remove(user);
  187. _dbContext.SaveChanges();
  188. }
  189. }
  190. public void DeleteAgency(int id)
  191. {
  192. var agency = _dbContext.Agencies.Find(id);
  193. if (agency != null)
  194. {
  195. _dbContext.Remove(agency);
  196. _dbContext.SaveChanges();
  197. }
  198. }
  199. public void DeleteIndividual(int id)
  200. {
  201. var individual = _dbContext.Individuals.Find(id);
  202. if (individual != null)
  203. {
  204. _dbContext.Individuals.Remove(individual);
  205. _dbContext.SaveChanges();
  206. }
  207. }
  208. private void Save()
  209. {
  210. _dbContext.SaveChanges();
  211. }
  212. private static void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
  213. {
  214. if (password == null) throw new ArgumentNullException("password");
  215. if (string.IsNullOrWhiteSpace(password)) throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
  216. using (var hmac = new System.Security.Cryptography.HMACSHA512())
  217. {
  218. passwordSalt = hmac.Key;
  219. passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
  220. }
  221. }
  222. private static bool VerifyPasswordHash(string password, byte[] storedHash, byte[] storedSalt)
  223. {
  224. if (password == null) throw new ArgumentNullException("password");
  225. if (string.IsNullOrWhiteSpace(password)) throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
  226. if (storedHash.Length != 64) throw new ArgumentException("Invalid length of password hash (64 bytes expected).", "passwordHash");
  227. if (storedSalt.Length != 128) throw new ArgumentException("Invalid length of password salt (128 bytes expected).", "passwordHash");
  228. using (var hmac = new System.Security.Cryptography.HMACSHA512(storedSalt))
  229. {
  230. var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
  231. for (int i = 0; i < computedHash.Length; i++)
  232. {
  233. if (computedHash[i] != storedHash[i]) return false;
  234. }
  235. }
  236. return true;
  237. }
  238. }
  239. }