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

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