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 15KB

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