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.

343 lines
16 KiB

11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
  1. using CustomerOnlineV2.Common.Helper;
  2. using CustomerOnlineV2.Common.Models;
  3. using CustomerOnlineV2.Common.Models.AccountModel;
  4. using CustomerOnlineV2.Common.Models.Notification;
  5. using CustomerOnlineV2.Repository.Repository.AccountRepository;
  6. using Microsoft.Extensions.Logging;
  7. using Newtonsoft.Json;
  8. using System.Text;
  9. using static CustomerOnlineV2.Common.Models.Notification.PasswordGenerator;
  10. namespace CustomerOnlineV2.Business.Business.AccountBusiness
  11. {
  12. public class AccountBusiness : IAccountBusiness
  13. {
  14. private readonly ILogger<AccountBusiness> _logger;
  15. private readonly IAccountRepository _accountRepo;
  16. public AccountBusiness(ILogger<AccountBusiness> logger, IAccountRepository accountRepo)
  17. {
  18. _logger = logger;
  19. _accountRepo = accountRepo;
  20. }
  21. public async Task<LoginResponse> Login(LoginModel model)
  22. {
  23. return await _accountRepo.Login(model);
  24. }
  25. public async Task<CommonResponse> ChangePassword(ForceChangePasswordModel model, LoginResponse logindetails)
  26. {
  27. if (model.NewPassword != model.ConfirmNewPassword)
  28. {
  29. return new CommonResponse(ResponseHelper.FAILED, "New Password and confirm new password does not match!");
  30. }
  31. return await _accountRepo.ChangePassword(model, logindetails);
  32. }
  33. public async Task<CommonResponse> PasswordReset(PasswordResetModel model, LoginResponse logindetails)
  34. {
  35. //var randomPassword = PasswordGenerator.GenerateRandomPassword();
  36. //model.RandomPassword = randomPassword;
  37. SendNotificationRequest request = new SendNotificationRequest()
  38. {
  39. IsBulkNotification = false,
  40. UserName = model.Username,
  41. //ProcessId = processId,
  42. ProviderId = "ResetPassword",
  43. NotificationTypeId = NOTIFICATION_TYPE.EMAIL.ToString(),
  44. //Template = Common.Model.Enum.NotifyTemplate.RESET_PASSWORD_EMAIL,
  45. Recipients = new List<RecipientViewModel>()
  46. {
  47. new RecipientViewModel()
  48. {
  49. NotificationContent = new NotificationDTO() {
  50. // Body = JsonConvert.SerializeObject(bodyMappings),
  51. //Title will be set by mapping json
  52. },
  53. Address= model.Username
  54. }
  55. }
  56. };
  57. return await _accountRepo.PasswordReset(model, logindetails);
  58. }
  59. public static string GenerateRandomPassword(PasswordOptions opts = null)
  60. {
  61. if (opts == null) opts = new PasswordOptions()
  62. {
  63. RequiredLength = 8,
  64. RequiredUniqueChars = 4,
  65. RequireDigit = true,
  66. RequireLowercase = true,
  67. RequireNonAlphanumeric = true,
  68. RequireUppercase = true
  69. };
  70. string[] randomChars = new[] {
  71. "ABCDEFGHJKMNPQRSTUVWXYZ", // uppercase
  72. "abcdefghjkmnpqrstuvwxyz", // lowercase
  73. "23456789", // digits
  74. "@#" // non-alphanumeric
  75. };
  76. string[] randomChars1 = new[] {
  77. // uppercase
  78. "abcdefghjkmnpqrstuvwxyz", // lowercase
  79. "23456789", // digits
  80. // non-alphanumeric
  81. };
  82. Random rand = new Random();
  83. List<char> chars = new List<char>();
  84. if (opts.RequireUppercase)
  85. chars.Insert(rand.Next(0, chars.Count),
  86. randomChars[0][rand.Next(0, randomChars[0].Length)]);
  87. if (opts.RequireLowercase)
  88. chars.Insert(rand.Next(0, chars.Count),
  89. randomChars[1][rand.Next(0, randomChars[1].Length)]);
  90. if (opts.RequireDigit)
  91. chars.Insert(rand.Next(0, chars.Count),
  92. randomChars[2][rand.Next(0, randomChars[2].Length)]);
  93. if (opts.RequireNonAlphanumeric)
  94. chars.Insert(rand.Next(0, chars.Count),
  95. randomChars[3][rand.Next(0, randomChars[3].Length)]);
  96. for (int i = chars.Count; i < opts.RequiredLength
  97. || chars.Distinct().Count() < opts.RequiredUniqueChars; i++)
  98. {
  99. string rcs = randomChars1[rand.Next(0, randomChars1.Length)];
  100. chars.Insert(rand.Next(0, chars.Count),
  101. rcs[rand.Next(0, rcs.Length)]);
  102. }
  103. return new string(chars.ToArray());
  104. }
  105. public async Task<JsonRxResponse> VerifyOtp(RequestOTPModel requestOTPModel, LoginResponse loginDetails)
  106. {
  107. JsonRxResponse jsonRx = new JsonRxResponse();
  108. try
  109. {
  110. jsonRx = await _accountRepo.VerifyOtp(requestOTPModel, loginDetails);
  111. _logger.LogDebug("SubmitOTP | DB RESPONSE : " + JsonConvert.SerializeObject(jsonRx));
  112. //if (jsonRx.ErrorCode.Equals("0"))
  113. //{
  114. // List<Mapping> bodyMappings = new List<Mapping>();
  115. // bodyMappings.Add(new Mapping() { SValue = "CustomerName", SText = loginDetails.FullName });
  116. // bodyMappings.Add(new Mapping() { SValue = "CustomerId", SText = loginDetails.MembershipId.ToString() });
  117. // bodyMappings.Add(new Mapping() { SValue = "UserId", SText = loginDetails.MembershipId });
  118. // bodyMappings.Add(new Mapping() { SValue = "FirstName", SText = loginDetails.FullName });
  119. // bodyMappings.Add(new Mapping() { SValue = "MiddleName", SText = loginDetails.FullName });
  120. // bodyMappings.Add(new Mapping() { SValue = "LastName", SText = loginDetails.FullName });
  121. // bodyMappings.Add(new Mapping() { SValue = "MobileNo", SText = loginDetails.MobileNumber });
  122. // bodyMappings.Add(new Mapping() { SValue = "Address", SText = loginDetails.UserName });
  123. // bodyMappings.Add(new Mapping() { SValue = "EMAIL_ID", SText = loginDetails.Email });
  124. // bodyMappings.Add(new Mapping() { SValue = "RegisteredDate", SText = "" });
  125. // SendNotificationRequest request = new SendNotificationRequest()
  126. // {
  127. // IsBulkNotification = false,
  128. // UserName = loginDetails.Email,
  129. // ProviderId = "BasicRegistration",
  130. // NotificationTypeId = NOTIFICATION_TYPE.EMAIL.ToString(),
  131. // Template = NotifyTemplate.BASIC_REGISTRATION_EMAIL,
  132. // Recipients = new List<RecipientViewModel>()
  133. // {
  134. // new RecipientViewModel()
  135. // {
  136. // NotificationContent = new NotificationDTO() {
  137. // Body = JsonConvert.SerializeObject(bodyMappings),
  138. // //Title will be set by mapping json
  139. // },
  140. // Address= loginDetails.Email
  141. // }
  142. // }
  143. // };
  144. // jsonRx = NotifierV2.SendNotification(request, NOTIFICATION_TYPE.EMAIL);
  145. //}
  146. //return jsonRx;
  147. return await Task.FromResult(jsonRx);
  148. }
  149. catch (Exception ex)
  150. {
  151. _logger.LogError("Something Went Wrong, Please Try Again!!", ex);
  152. jsonRx.SetResponse("1", "Error occurred while calling RequestOTP.");
  153. return await Task.FromResult(jsonRx);
  154. }
  155. }
  156. public JsonRxResponse RequestOTP(RequestOTPModel requestOTPModel)
  157. {
  158. JsonRxResponse jsonRx = new JsonRxResponse();
  159. try
  160. {
  161. requestOTPModel.OTP = Utilities.GenerateOTP();
  162. jsonRx = _accountRepo.RequestOTP(requestOTPModel);
  163. _logger.LogDebug("GenerateOTP | RESPONSE : " + JsonConvert.SerializeObject(jsonRx));
  164. if (jsonRx.ErrorCode == "0")
  165. {
  166. bool emailSent = false;
  167. bool smsSent = false;
  168. if (requestOTPModel.userId.IsValidEmail())
  169. {
  170. if (!string.IsNullOrEmpty(jsonRx.ErrorCode) && jsonRx.ErrorCode.Equals("0"))
  171. {
  172. List<Mapping> bodyMappings = new List<Mapping>();
  173. bodyMappings.Add(new Mapping() { SValue = "CustomerName", SText = requestOTPModel.CreatedBy });
  174. //bodyMappings.Add(new Mapping() { SValue = "OTP_CODE", SText = requestOTPModel.OTP });
  175. bodyMappings.Add(new Mapping() { SValue = "OTP_CODE", SText = jsonRx.Id });
  176. bodyMappings.Add(new Mapping() { SValue = "TYPE", SText = requestOTPModel.requestFor });
  177. try
  178. {
  179. SendNotificationRequest request = new SendNotificationRequest()
  180. {
  181. IsBulkNotification = false,
  182. UserName = requestOTPModel.CreatedBy,
  183. ControlNo = requestOTPModel.receiverId,
  184. ProviderId = "REQUESTOTP_EMAIL",
  185. Template = NotifyTemplate.OTP_EMAIL,
  186. Recipients = new List<RecipientViewModel>()
  187. {
  188. new RecipientViewModel()
  189. {
  190. NotificationContent = new NotificationDTO() {
  191. Body = JsonConvert.SerializeObject(bodyMappings),
  192. //Title will be set by mapping json
  193. },
  194. Address= requestOTPModel.CreatedBy,
  195. DeviceType = requestOTPModel.DeviceType,
  196. } }
  197. };
  198. _logger.LogDebug("SendNotification.EMAIL | REQUEST : " + JsonConvert.SerializeObject(request));
  199. var jsonRx1 = NotifierV2.SendNotification(request, NOTIFICATION_TYPE.EMAIL);
  200. _logger.LogDebug("SendNotification.EMAIL | RESPONSE : " + JsonConvert.SerializeObject(jsonRx1));
  201. emailSent = true;
  202. }
  203. catch (Exception emailException)
  204. {
  205. _logger.LogError("Error sending email", emailException);
  206. }
  207. try
  208. {
  209. string ProcessId = Guid.NewGuid().ToString().Replace("-", "") + ":sendSms";
  210. string mobileNum = jsonRx.Extra2;
  211. var mobNum = getSenderFormattedNumber(mobileNum);
  212. SendSMSApiService _sendAPI = new SendSMSApiService();
  213. StringBuilder s = new StringBuilder();
  214. s.AppendLine($"Dear {jsonRx.Extra}");
  215. s.AppendLine($"Your OTP code for Customer Registration is {requestOTPModel.OTP}.");
  216. s.AppendLine("Regards, IME London");
  217. SMSRequestModel _req = new SMSRequestModel
  218. {
  219. ProviderId = "onewaysms",
  220. MobileNumber = mobileNum,
  221. SMSBody = s.ToString(),
  222. ProcessId = ProcessId.Substring(ProcessId.Length - 40, 40),
  223. RequestedBy = requestOTPModel.userId,
  224. UserName = requestOTPModel.userId,
  225. method = "send",
  226. ControlNo = "", // GetControlNo()
  227. };
  228. _logger.LogDebug("SendNotification.SMS | REQUEST : " + JsonConvert.SerializeObject(_req));
  229. APIJsonResponse _resp = _sendAPI.SMSTPApi(_req);
  230. _logger.LogDebug("SendNotification.SMS | RESPONSE : " + JsonConvert.SerializeObject(_resp));
  231. smsSent = true;
  232. }
  233. catch (Exception smsException)
  234. {
  235. _logger.LogError("Error sending SMS", smsException);
  236. }
  237. if (emailSent || smsSent)
  238. {
  239. jsonRx.ErrorCode = "0";
  240. jsonRx.SetResponse("0", "OTP has been Sent.");
  241. return jsonRx;
  242. }
  243. }
  244. }
  245. }
  246. else
  247. {
  248. jsonRx.ErrorCode = "1";
  249. return new JsonRxResponse { ErrorCode = jsonRx.ErrorCode, Msg = jsonRx.Msg };
  250. }
  251. jsonRx.ErrorCode = jsonRx.ErrorCode == "103" ? "0" : jsonRx.ErrorCode;//103 = previous OTP was not expired so same was used
  252. return jsonRx;
  253. }
  254. catch (Exception ex)
  255. {
  256. _logger.LogError("Something Went Wrong, Please Try Again!!", ex);
  257. jsonRx.SetResponse("1", "Error occurred while calling RequestOTP.");
  258. return jsonRx;
  259. }
  260. }
  261. private string getSenderFormattedNumber(string number)
  262. {
  263. string finalNo = number;
  264. if (!number.Contains("+44"))
  265. {
  266. string mobileFirst = number.Substring(0, 1);
  267. if (mobileFirst == "0")
  268. {
  269. if (number.Length == 11)
  270. {
  271. finalNo = "+44" + number.Substring(1, number.Length - 1);
  272. return finalNo;
  273. }
  274. else if (number.Length < 11)
  275. {
  276. finalNo = $"+44{number}";
  277. }
  278. }
  279. else if (number.Substring(0, 1) != "0" && number.Length == 10)
  280. {
  281. finalNo = $"+44{number}";
  282. }
  283. }
  284. else if (number.Contains("+44"))
  285. {
  286. string MobN = number.Substring(4, 1);
  287. if (MobN == "0" && number.Length > 14)
  288. {
  289. finalNo = number.Remove(4, 1);
  290. }
  291. }
  292. if (!finalNo.Substring(0, 1).Contains("+"))
  293. finalNo = $"+{finalNo}";
  294. return finalNo;
  295. }
  296. }
  297. }