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

RegisterRepository.cs 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. using Microsoft.AspNetCore.Authorization;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Microsoft.EntityFrameworkCore;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Drawing.Text;
  7. using System.Linq;
  8. using System.Text;
  9. using UnivateProperties_API.Containers.Users;
  10. using UnivateProperties_API.Containers.Users.Simple;
  11. using UnivateProperties_API.Context;
  12. using UnivateProperties_API.Helpers;
  13. using UnivateProperties_API.Model.Communication;
  14. using UnivateProperties_API.Model.Users;
  15. using UnivateProperties_API.Repository.Communication;
  16. namespace UnivateProperties_API.Repository.Users
  17. {
  18. public class RegisterRepository : IRegisterRepository
  19. {
  20. private readonly DataContext _dbContext;
  21. public RegisterRepository(DataContext dbContext)
  22. {
  23. _dbContext = dbContext;
  24. }
  25. public User Authenticate(string username, string password)
  26. {
  27. if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
  28. return null;
  29. var user = _dbContext.Users.SingleOrDefault(x => x.Username == username);
  30. // check if username exists
  31. if (user == null)
  32. throw new AppException("Username is incorrect");
  33. // check if password is correct
  34. if (!MyCommon.VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt))
  35. throw new AppException("Password is incorrect");
  36. // authentication successful
  37. return user;
  38. }
  39. public User Create(User user, string password, bool save, bool terms)
  40. {
  41. // validation
  42. if (string.IsNullOrWhiteSpace(password))
  43. throw new AppException("Password is required");
  44. if (_dbContext.Users.Any(x => x.Username == user.Username))
  45. throw new AppException("Username \"" + user.Username + "\" is already taken");
  46. MyCommon.CreatePasswordHash(password, out byte[] passwordHash, out byte[] passwordSalt);
  47. user.PasswordHash = passwordHash;
  48. user.PasswordSalt = passwordSalt;
  49. user.AcceptedTerms = terms;
  50. //user.Id = NewUserId();
  51. _dbContext.Users.Add(user);
  52. if (save)
  53. {
  54. _dbContext.SaveChanges();
  55. }
  56. return user;
  57. }
  58. public Agency CreateAgency(AgencyDto agency)
  59. {
  60. // validation
  61. /* if (string.IsNullOrWhiteSpace(agency.EaabeffcNumber))
  62. throw new AppException("eaabeffcNumber is required");
  63. if (_dbContext.Agencies.Any(x => x.EAABEFFCNumber == agency.EaabeffcNumber))
  64. throw new AppException("eaabeffcNumber \"" + agency.EaabeffcNumber + "\" already exists");*/
  65. if (!string.IsNullOrEmpty(agency.EaabeffcNumber))
  66. {
  67. var savedAgency = _dbContext.Agencies.Where(x => x.EAABEFFCNumber == agency.EaabeffcNumber).FirstOrDefault();
  68. if (savedAgency == null)
  69. {
  70. Agency a = new Agency()
  71. {
  72. AgencyName = agency.Name,
  73. EAABEFFCNumber = agency.EaabeffcNumber,
  74. CompanyRegNumber = agency.RegNo
  75. };
  76. _dbContext.Agencies.Add(a);
  77. CreatePerson(agency.User, PersonType.Agent, false, a);
  78. return a;
  79. }
  80. else
  81. {
  82. CreatePerson(agency.User, PersonType.Agent, false, savedAgency);
  83. _dbContext.SaveChanges();
  84. return savedAgency;
  85. }
  86. }
  87. else
  88. {
  89. CreatePerson(agency.User, PersonType.Agent, false, null);
  90. _dbContext.SaveChanges();
  91. return null;
  92. }
  93. }
  94. public void CreatePerson(UserDto individual, PersonType personType, bool save, Agency agency)
  95. {
  96. // validation
  97. if (string.IsNullOrWhiteSpace(individual.Password))
  98. throw new AppException("Password is required");
  99. if (_dbContext.Users.Any(x => x.Username == individual.Username))
  100. throw new AppException("Individual \"" + individual.Username + "\" is already taken");
  101. MyCommon.CreatePasswordHash(individual.Password, out byte[] passwordHash, out byte[] passwordSalt);
  102. User createUser = new User(individual.Username, individual.Password);
  103. Create(createUser, individual.Password, false, individual.AcceptedTerms);
  104. Person p = null;
  105. if (personType == PersonType.Agent)
  106. {
  107. Agent agent = new Agent()
  108. {
  109. Name = individual.Name,
  110. Surname = individual.Surname,
  111. User = createUser,
  112. Email = individual.Email,
  113. CellNumber = individual.CellNumber,
  114. Telephone = individual.Telephone,
  115. Agency = agency
  116. };
  117. //agent.Id = NewAgentId();
  118. agent.User.Role = Role.Agency;
  119. p = agent;
  120. _dbContext.Agents.Add(agent);
  121. }
  122. else if (personType == PersonType.Individual)
  123. {
  124. Individual i = new Individual()
  125. {
  126. Name = individual.Name,
  127. Surname = individual.Surname,
  128. User = createUser,
  129. Email = individual.Email,
  130. CellNumber = individual.CellNumber,
  131. Telephone = individual.Telephone
  132. };
  133. //i.Id = NewIndividualId();
  134. i.User.Role = Role.PrivateUser;
  135. p = i;
  136. _dbContext.Individuals.Add(i);
  137. }
  138. Template template = _dbContext.Templates.FirstOrDefault(x => x.Name == "IndivRegEmail");
  139. if (template != null && personType == PersonType.Individual)
  140. {
  141. TemplateRepository templateRepository = new TemplateRepository(_dbContext);
  142. templateRepository.SendEmailTemplate(template, p, new List<Model.BaseEntity>() { p });
  143. }
  144. Template templ = _dbContext.Templates.FirstOrDefault(x => x.Name == "AgencyRegEmail");
  145. if (templ != null)
  146. {
  147. TemplateRepository templateRepository = new TemplateRepository(_dbContext);
  148. templateRepository.SendEmailTemplate(templ, p, new List<Model.BaseEntity>() { p });
  149. }
  150. Template temp = _dbContext.Templates.FirstOrDefault(x => x.Name == "VerificationEmail");
  151. if (temp != null)
  152. {
  153. TemplateRepository templateRepository = new TemplateRepository(_dbContext);
  154. templateRepository.SendEmailTemplate(temp, p, new List<Model.BaseEntity>() { p });
  155. }
  156. if (save)
  157. {
  158. Save();
  159. }
  160. }
  161. public void Update(User userParam, string password = null)
  162. {
  163. var user = _dbContext.Users.Find(userParam.Id);
  164. if (user == null)
  165. throw new AppException("User not found");
  166. if (userParam.Username != user.Username)
  167. {
  168. // username has changed so check if the new username is already taken
  169. if (_dbContext.Users.Any(x => x.Username == userParam.Username))
  170. throw new AppException("Username " + userParam.Username + " is already taken");
  171. }
  172. // update user properties
  173. user.Username = userParam.Username;
  174. // update password if it was entered
  175. if (!string.IsNullOrWhiteSpace(password))
  176. {
  177. MyCommon.CreatePasswordHash(password, out byte[] passwordHash, out byte[] passwordSalt);
  178. user.PasswordHash = passwordHash;
  179. user.PasswordSalt = passwordSalt;
  180. }
  181. //_dbContext.Users.Update(user);
  182. _dbContext.Entry(user).State = EntityState.Modified;
  183. _dbContext.SaveChanges();
  184. }
  185. [Authorize(Roles = Role.SuperAdmin)]
  186. public IEnumerable<User> GetAllUsers()
  187. {
  188. return _dbContext.Users;
  189. }
  190. [Authorize(Roles = Role.SuperAdmin)]
  191. public IEnumerable<Agency> GetAllAgencies()
  192. {
  193. return _dbContext.Agencies;
  194. }
  195. [Authorize(Roles = Role.SuperAdmin)]
  196. public IEnumerable<Individual> GetAllIndividuals()
  197. {
  198. return _dbContext.Individuals.Where(x => x.IsDeleted != true);
  199. }
  200. public User GetById(int id)
  201. {
  202. return _dbContext.Users.Find(id);
  203. }
  204. public Agency GetByAgencyId(int id)
  205. {
  206. return _dbContext.Agencies.Find(id);
  207. }
  208. public Individual GetByIndividualId(int id)
  209. {
  210. return _dbContext.Individuals.Find(id);
  211. }
  212. public void Delete(int id)
  213. {
  214. var user = _dbContext.Users.Find(id);
  215. if (user != null)
  216. {
  217. _dbContext.Users.Remove(user);
  218. _dbContext.SaveChanges();
  219. }
  220. }
  221. public void DeleteAgency(int id)
  222. {
  223. var agency = _dbContext.Agencies.Find(id);
  224. if (agency != null)
  225. {
  226. _dbContext.Remove(agency);
  227. _dbContext.SaveChanges();
  228. }
  229. }
  230. public void DeleteIndividual(int id)
  231. {
  232. var individual = _dbContext.Individuals.Find(id);
  233. if (individual != null)
  234. {
  235. _dbContext.Individuals.Remove(individual);
  236. _dbContext.SaveChanges();
  237. }
  238. }
  239. public void UpdatePassword(UserDto userParam)
  240. {
  241. var indiv = _dbContext.Individuals.Where(x => x.Email == userParam.Email).FirstOrDefault();
  242. var user = _dbContext.Users.Where(x => x.Id == indiv.UserId).FirstOrDefault();
  243. MyCommon.CreatePasswordHash(userParam.Password, out byte[] passwordHash, out byte[] passwordSalt);
  244. user.PasswordHash = passwordHash;
  245. user.PasswordSalt = passwordSalt;
  246. user.FPToken = "";
  247. //_dbContext.Users.Update(user);
  248. _dbContext.Entry(user).State = EntityState.Modified;
  249. Save();
  250. }
  251. private void Save()
  252. {
  253. _dbContext.SaveChanges();
  254. }
  255. //public int NewAgencyId()
  256. //{
  257. // int id = 0;
  258. // if (_dbContext.Agencies.Count() > 0)
  259. // {
  260. // id = _dbContext.Agencies.Max(x => x.Id);
  261. // }
  262. // id += 1;
  263. // return id;
  264. //}
  265. //public int NewAgentId()
  266. //{
  267. // int id = 0;
  268. // if (_dbContext.Agents.Count() > 0)
  269. // {
  270. // id = _dbContext.Agents.Max(x => x.Id);
  271. // }
  272. // id += 1;
  273. // return id;
  274. //}
  275. //public int NewIndividualId()
  276. //{
  277. // int id = 0;
  278. // if (_dbContext.Individuals.Count() > 0)
  279. // {
  280. // id = _dbContext.Individuals.Max(x => x.Id);
  281. // }
  282. // id += 1;
  283. // return id;
  284. //}
  285. //public int NewUserId()
  286. //{
  287. // int id = 0;
  288. // if (_dbContext.Users.Count() > 0)
  289. // {
  290. // id = _dbContext.Users.Max(x => x.Id);
  291. // }
  292. // id += 1;
  293. // return id;
  294. //}
  295. public SimplePersonDto UserDetails(int userId)
  296. {
  297. var individual = _dbContext.Individuals.Where(i => i.UserId == userId).FirstOrDefault();
  298. if (individual == null)
  299. {
  300. var agent = _dbContext.Agents.Where(i => i.UserId == userId).FirstOrDefault();
  301. if (agent != null)
  302. {
  303. return new SimplePersonDto()
  304. {
  305. Name = agent.Name,
  306. Surname = agent.Surname,
  307. Email = agent.Email
  308. };
  309. }
  310. else
  311. {
  312. return new SimplePersonDto(); ;
  313. }
  314. }
  315. else
  316. {
  317. return new SimplePersonDto()
  318. {
  319. Name = individual.Name,
  320. Surname = individual.Surname,
  321. Email = individual.Email
  322. };
  323. }
  324. }
  325. public Individual GetIndividualByFPToken(string fpToken)
  326. {
  327. string linkStr = fpToken.Replace('!', '/');
  328. var user = _dbContext.Users.Where(usr => usr.FPToken == linkStr).FirstOrDefault();
  329. if (user != null)
  330. {
  331. var indiv = _dbContext.Individuals.Where(x => x.UserId == user.Id).FirstOrDefault();
  332. return indiv;
  333. }
  334. else
  335. {
  336. throw new Exception();
  337. }
  338. }
  339. public void ForgotPasswordMailCheck(string mail)
  340. {
  341. var indiv = _dbContext.Individuals.Where(x => x.Email.ToUpper() == mail.ToUpper()).FirstOrDefault();
  342. var mailer = new MailRepository(_dbContext);
  343. if (indiv != null)
  344. {
  345. byte[] time = BitConverter.GetBytes(GetTime());
  346. byte[] mailByte = Encoding.ASCII.GetBytes(mail);
  347. var timeStr = GetTime().ToString();
  348. byte[] timeArr = Encoding.ASCII.GetBytes(timeStr);
  349. byte[] key = Guid.NewGuid().ToByteArray();
  350. string token = Convert.ToBase64String((timeArr.Concat(key).ToArray()).Concat(mailByte).ToArray());
  351. string secureKey = "EGV~A8pn;:9&zC]6";
  352. //encrypt token
  353. ClsCrypto lockey = new ClsCrypto(secureKey);
  354. var encryptedToken = lockey.Encrypt(token);
  355. var individual = _dbContext.Individuals.Where(e => e.Email == mail).FirstOrDefault();
  356. var user = _dbContext.Users.Where(x => x.Id == individual.UserId).FirstOrDefault();
  357. //send ecrypted token to db
  358. user.FPToken = encryptedToken;
  359. _dbContext.Entry(user).State = EntityState.Modified;
  360. //_dbContext.Users.Update(user);
  361. _dbContext.SaveChanges();
  362. string linkStr = encryptedToken.Replace('/', '!');
  363. //change below to test locally or QA
  364. //string url = "http://localhost:8080/#/forgotPasswordReset/" + linkStr;
  365. //string url = "http://training.provision-sa.com:122/#/forgotPasswordReset/" + linkStr;
  366. //string url = "https://www.pvsl.co.za:97/#/forgotPasswordReset/" + linkStr;
  367. string url = "https://www.univateproperties.co.za/#/forgotPasswordReset/" + linkStr;
  368. mailer.ForgotPassword(indiv, url);
  369. }
  370. else
  371. {
  372. throw new Exception();
  373. }
  374. }
  375. private double GetTime()
  376. {
  377. return DateTime.Now.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds;
  378. }
  379. }
  380. }