API
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

RegisterRepository.cs 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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 UpdatePerson(Person person, PersonType personType)
  129. {
  130. if (personType == PersonType.Agent)
  131. {
  132. var item = (person as Agent);
  133. _dbContext.Entry(item).State = EntityState.Modified;
  134. Save();
  135. }
  136. else if (personType == PersonType.Individual)
  137. {
  138. var item = (person as Individual);
  139. _dbContext.Entry(item).State = EntityState.Modified;
  140. Save();
  141. }
  142. }
  143. public void Update(User userParam, string password = null)
  144. {
  145. var user = _dbContext.Users.Find(userParam.Id);
  146. if (user == null)
  147. throw new AppException("User not found");
  148. if (userParam.Username != user.Username)
  149. {
  150. // username has changed so check if the new username is already taken
  151. if (_dbContext.Users.Any(x => x.Username == userParam.Username))
  152. throw new AppException("Username " + userParam.Username + " is already taken");
  153. }
  154. // update user properties
  155. user.Name = userParam.Name;
  156. user.Surname = userParam.Surname;
  157. user.Username = userParam.Username;
  158. // update password if it was entered
  159. if (!string.IsNullOrWhiteSpace(password))
  160. {
  161. byte[] passwordHash, passwordSalt;
  162. CreatePasswordHash(password, out passwordHash, out passwordSalt);
  163. user.PasswordHash = passwordHash;
  164. user.PasswordSalt = passwordSalt;
  165. }
  166. _dbContext.Users.Update(user);
  167. _dbContext.SaveChanges();
  168. }
  169. public void UpdateAgency(Agency agencyParam, string agencyname = null)
  170. {
  171. var agency = _dbContext.Agencies.Find(agencyParam.Id);
  172. if (agency == null)
  173. throw new AppException("Agency not found");
  174. if (agencyParam.AgencyName != agency.AgencyName)
  175. {
  176. // username has changed so check if the new username is already taken
  177. if (_dbContext.Agencies.Any(x => x.AgencyName == agencyParam.AgencyName))
  178. throw new AppException("AgencyName " + agencyParam.AgencyName + " is already taken");
  179. }
  180. // update user properties
  181. agency.AgencyName = agencyParam.AgencyName;
  182. agency.EAABEFFCNumber = agencyParam.EAABEFFCNumber;
  183. agency.CompanyRegNumber = agencyParam.CompanyRegNumber;
  184. // update password if it was entered
  185. _dbContext.Agencies.Update(agency);
  186. _dbContext.SaveChanges();
  187. }
  188. [Authorize(Roles = Role.SuperAdmin)]
  189. public IEnumerable<User> GetAllUsers()
  190. {
  191. return _dbContext.Users;
  192. }
  193. [Authorize(Roles = Role.SuperAdmin)]
  194. public IEnumerable<Agency> GetAllAgencies()
  195. {
  196. return _dbContext.Agencies;
  197. }
  198. [Authorize(Roles = Role.SuperAdmin)]
  199. public IEnumerable<Individual> GetAllIndividuals()
  200. {
  201. return _dbContext.Individuals;
  202. }
  203. public User GetById(int id)
  204. {
  205. return _dbContext.Users.Find(id);
  206. }
  207. public Agency GetByAgencyId(int id)
  208. {
  209. return _dbContext.Agencies.Find(id);
  210. }
  211. public Individual GetByIndividualId(int id)
  212. {
  213. return _dbContext.Individuals.Find(id);
  214. }
  215. public void Delete(int id)
  216. {
  217. var user = _dbContext.Users.Find(id);
  218. if (user != null)
  219. {
  220. _dbContext.Users.Remove(user);
  221. _dbContext.SaveChanges();
  222. }
  223. }
  224. public void DeleteAgency(int id)
  225. {
  226. var agency = _dbContext.Agencies.Find(id);
  227. if (agency != null)
  228. {
  229. _dbContext.Remove(agency);
  230. _dbContext.SaveChanges();
  231. }
  232. }
  233. public void DeleteIndividual(int id)
  234. {
  235. var individual = _dbContext.Individuals.Find(id);
  236. if (individual != null)
  237. {
  238. _dbContext.Individuals.Remove(individual);
  239. _dbContext.SaveChanges();
  240. }
  241. }
  242. private void Save()
  243. {
  244. _dbContext.SaveChanges();
  245. }
  246. private static void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
  247. {
  248. if (password == null) throw new ArgumentNullException("password");
  249. if (string.IsNullOrWhiteSpace(password)) throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
  250. using (var hmac = new System.Security.Cryptography.HMACSHA512())
  251. {
  252. passwordSalt = hmac.Key;
  253. passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
  254. }
  255. }
  256. private static bool VerifyPasswordHash(string password, byte[] storedHash, byte[] storedSalt)
  257. {
  258. if (password == null) throw new ArgumentNullException("password");
  259. if (string.IsNullOrWhiteSpace(password)) throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
  260. if (storedHash.Length != 64) throw new ArgumentException("Invalid length of password hash (64 bytes expected).", "passwordHash");
  261. if (storedSalt.Length != 128) throw new ArgumentException("Invalid length of password salt (128 bytes expected).", "passwordHash");
  262. using (var hmac = new System.Security.Cryptography.HMACSHA512(storedSalt))
  263. {
  264. var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
  265. for (int i = 0; i < computedHash.Length; i++)
  266. {
  267. if (computedHash[i] != storedHash[i]) return false;
  268. }
  269. }
  270. return true;
  271. }
  272. }
  273. }