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

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