CommonLogic.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. using System.Data;
  2. using System.Globalization;
  3. using System.IdentityModel.Tokens.Jwt;
  4. using System.Net;
  5. using System.Net.Http.Headers;
  6. using System.Net.Http.Json;
  7. using System.Security.Claims;
  8. using System.Security.Cryptography;
  9. using System.Text;
  10. using Database;
  11. using Database.Database;
  12. using log4net;
  13. using Microsoft.AspNetCore.Http;
  14. using Microsoft.AspNetCore.Server.Kestrel.Core;
  15. using Microsoft.Extensions.Configuration;
  16. using Microsoft.IdentityModel.Tokens;
  17. using Newtonsoft.Json;
  18. using static Common.Request;
  19. namespace Common;
  20. public static class CommonLogic
  21. {
  22. private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(CommonLogic));
  23. public static List<List<DateTime>> GetTimeWeekly(int numOfWeek)
  24. {
  25. List<List<DateTime>> timeWeek = new List<List<DateTime>>();
  26. DateTime timeNow = DateTime.Now;
  27. var day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(timeNow);
  28. //int end = DayOfWeek.Saturday - day;
  29. //int start = day - DayOfWeek.Sunday;
  30. DateTime timeStart =
  31. day == 0
  32. ? timeNow.AddDays(-(7 - day - DayOfWeek.Sunday) + 1)
  33. : timeNow.AddDays(-(day - DayOfWeek.Sunday) + 1);
  34. DateTime timeEnd =
  35. day == 0 ? timeNow.AddDays(0) : timeNow.AddDays(DayOfWeek.Saturday - day + 1);
  36. // add for 4 weeks
  37. for (int i = 0; i <= numOfWeek; i++)
  38. {
  39. List<DateTime> time = new List<DateTime>();
  40. DateTime start = timeStart.AddDays(-7 * i);
  41. DateTime end = timeEnd.AddDays(-7 * i + 1);
  42. time.Add(new DateTime(start.Year, start.Month, start.Day, 0, 0, 0));
  43. time.Add(new DateTime(end.Year, end.Month, end.Day, 0, 0, 0));
  44. timeWeek.Add(time);
  45. }
  46. return timeWeek;
  47. }
  48. public static List<List<DateTime>> GetTimeMonthly(int numOfMonth)
  49. {
  50. List<List<DateTime>> timeMonth = new List<List<DateTime>>();
  51. DateTime timeNow = DateTime.Now;
  52. // add for 4 weeks
  53. for (int i = 0; i <= numOfMonth; i++)
  54. {
  55. List<DateTime> time = new List<DateTime>();
  56. DateTime start = timeNow.AddMonths(-i);
  57. DateTime end = timeNow.AddMonths(-i + 1);
  58. time.Add(new DateTime(start.Year, start.Month, 1, 0, 0, 0));
  59. time.Add(new DateTime(end.Year, end.Month, 1, 0, 0, 0));
  60. timeMonth.Add(time);
  61. }
  62. return timeMonth;
  63. }
  64. public static string? SendPost(ILog log, string Url, dynamic data)
  65. {
  66. var json = JsonConvert.SerializeObject(data);
  67. log.Info("request: " + Url + " data: " + json);
  68. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
  69. request.Method = "POST";
  70. request.ContentType = "application/json";
  71. request.ContentLength = json.Length;
  72. // CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
  73. // log.Debug("Lang: " + currentCulture.Name);
  74. // request.Headers.Add("Lang", currentCulture.Name);
  75. using (Stream webStream = request.GetRequestStream())
  76. using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
  77. {
  78. requestWriter.Write(json);
  79. }
  80. try
  81. {
  82. WebResponse webResponse = request.GetResponse();
  83. using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
  84. using (StreamReader responseReader = new StreamReader(webStream))
  85. {
  86. string response = responseReader.ReadToEnd();
  87. log.Info("request: " + Url + " /nData: " + json + " /n response: " + response);
  88. return response;
  89. }
  90. }
  91. catch (Exception e)
  92. {
  93. log.Error("Exception: ", e);
  94. }
  95. return null;
  96. }
  97. public static async Task<ReturnDataPost?>? SendPostWithAuthen(
  98. string? url,
  99. Object? data,
  100. string? token,
  101. string? refreshToken,
  102. string? signature,
  103. string? lang
  104. )
  105. {
  106. ReturnDataPost returnDataPost = new ReturnDataPost
  107. {
  108. token = token,
  109. refreshToken = refreshToken
  110. };
  111. var json = JsonConvert.SerializeObject(data);
  112. try
  113. {
  114. var client = new HttpClient();
  115. log.Debug("token: " + token);
  116. log.Info(
  117. Thread.CurrentThread.ManagedThreadId
  118. + " | "
  119. + "Request: "
  120. + url
  121. + " /nData: "
  122. + json
  123. );
  124. client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
  125. client.DefaultRequestHeaders.Add("Signature", signature);
  126. client.DefaultRequestHeaders.Add("Accept-Language", lang == "en-US" ? "en" : "my");
  127. client.DefaultRequestHeaders.Add("Language", lang == "en-US" ? "en" : "my");
  128. var result = await client.PostAsJsonAsync(url, data!);
  129. if (result.IsSuccessStatusCode)
  130. {
  131. var response = await result.Content.ReadAsStringAsync();
  132. log.Info(
  133. Thread.CurrentThread.ManagedThreadId
  134. + " | "
  135. + "Request: "
  136. + url
  137. + " /nData: "
  138. + json
  139. + " /n Response: "
  140. + response
  141. );
  142. returnDataPost.data = response;
  143. return returnDataPost;
  144. }
  145. else if (result.StatusCode == HttpStatusCode.Unauthorized)
  146. {
  147. log.Error(Thread.CurrentThread.ManagedThreadId + " | " + "401");
  148. returnDataPost.needToLogin = true;
  149. return returnDataPost;
  150. }
  151. else if (result.StatusCode == HttpStatusCode.BadRequest)
  152. {
  153. var response = await result.Content.ReadAsStringAsync();
  154. log.Info(
  155. Thread.CurrentThread.ManagedThreadId
  156. + " | "
  157. + "Request: "
  158. + url
  159. + " /nData: "
  160. + json
  161. + " /n Response: "
  162. + response
  163. );
  164. returnDataPost.data = response;
  165. return returnDataPost;
  166. }
  167. else
  168. {
  169. log.Info(
  170. Thread.CurrentThread.ManagedThreadId
  171. + " | "
  172. + "Request: "
  173. + url
  174. + " /nData: "
  175. + json
  176. + " /n Response: "
  177. + result
  178. );
  179. }
  180. }
  181. catch (Exception e)
  182. {
  183. log.Info(Thread.CurrentThread.ManagedThreadId + " | " + "-----------------");
  184. log.Error(Thread.CurrentThread.ManagedThreadId + " | " + e.Message);
  185. if (e is Microsoft.AspNetCore.Http.BadHttpRequestException)
  186. {
  187. //400 exception.
  188. }
  189. if (e is UnauthorizedAccessException) { }
  190. }
  191. return null;
  192. }
  193. public static async Task<string?> SendPostWithSignatureAsync(
  194. ILog log,
  195. string url,
  196. dynamic data,
  197. string? signature,
  198. string? username,
  199. string? password
  200. )
  201. {
  202. // var json = JsonConvert.SerializeObject(data);
  203. // HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  204. // request.Method = "POST";
  205. // request.ContentType = "application/json";
  206. // request.ContentLength = json.Length;
  207. // request.Headers.Add("signature", signature);
  208. // request.Headers.Add("Username", username);
  209. // request.Headers.Add("Password", password);
  210. // using (Stream webStream = request.GetRequestStream())
  211. // using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
  212. // {
  213. // requestWriter.Write(json);
  214. // }
  215. // try
  216. // {
  217. // WebResponse webResponse = request.GetResponse();
  218. // using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
  219. // using (StreamReader responseReader = new StreamReader(webStream))
  220. // {
  221. // string response = responseReader.ReadToEnd();
  222. // log.Info("request: " + url + " /nData: " + json + " /n response: " + response);
  223. // return response;
  224. // }
  225. // }
  226. // catch (Exception e)
  227. // {
  228. // log.Info("-----------------");
  229. // log.Info(e.Message);
  230. // }
  231. // return null;
  232. var json = JsonConvert.SerializeObject(data);
  233. var body = new StringContent(json, Encoding.UTF8, "application/json");
  234. try
  235. {
  236. log.Debug("url: " + url);
  237. log.Debug("Request: " + json);
  238. string svcCredentials = Convert.ToBase64String(
  239. ASCIIEncoding.ASCII.GetBytes(username + ":" + password)
  240. );
  241. // request.Headers.Add("Authorization", "Basic " + svcCredentials);
  242. using (var client = new HttpClient())
  243. {
  244. client.DefaultRequestHeaders.Add("signature", signature);
  245. client.DefaultRequestHeaders.Add("Authorization", "Basic " + svcCredentials);
  246. // client.DefaultRequestHeaders.Add("Password", password);
  247. var response = client.PostAsync(url, body).Result;
  248. // log.Debug("Error req: " + client);
  249. if (response.IsSuccessStatusCode)
  250. {
  251. var responseContent = response.Content;
  252. // by calling .Result you are synchronously reading the result
  253. string responseString = responseContent.ReadAsStringAsync().Result;
  254. log.Debug("Response: " + responseString);
  255. return responseString;
  256. }
  257. log.Debug("Error res: " + response);
  258. return null;
  259. // return response.StatusCode.ToString();
  260. }
  261. }
  262. catch (Exception e)
  263. {
  264. log.Error("Exception: ", e);
  265. }
  266. return null;
  267. }
  268. public static DateTime? ParseToDateTime(string input)
  269. {
  270. if (string.IsNullOrWhiteSpace(input))
  271. return null;
  272. if (DateTime.TryParseExact(
  273. input,
  274. CommonConstants.ListDateTimeFormat,
  275. CultureInfo.InvariantCulture,
  276. DateTimeStyles.None,
  277. out DateTime result))
  278. {
  279. return result;
  280. }
  281. return null;
  282. }
  283. public static string SendGetWithAuthen(ILog log, string url, string token)
  284. {
  285. log.Debug("GET url: " + url);
  286. using (var client = new HttpClient())
  287. {
  288. client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
  289. var response = client.GetAsync(url).Result;
  290. if (response.IsSuccessStatusCode)
  291. {
  292. var responseContent = response.Content;
  293. // by calling .Result you are synchronously reading the result
  294. string responseString = responseContent.ReadAsStringAsync().Result;
  295. log.Debug("Response: " + responseString);
  296. return responseString;
  297. }
  298. log.Debug("Error res: " + response);
  299. return response.StatusCode.ToString();
  300. }
  301. }
  302. public static string? ValidateMsisdn(string countryCode, string? input)
  303. {
  304. if (input == null || input.Length == 0 || !long.TryParse(input, out long temp))
  305. {
  306. return null;
  307. }
  308. else if (input.Length == 9)
  309. {
  310. return countryCode + input.Trim();
  311. }
  312. else
  313. {
  314. return input.Trim();
  315. }
  316. }
  317. public static DateTime ConvertStringToDateTime(string time)
  318. {
  319. return DateTime.ParseExact(
  320. time,
  321. "dd/MM/yyyy HH:mm:ss",
  322. System.Globalization.CultureInfo.InvariantCulture
  323. );
  324. }
  325. public static string GenerateUniqueNumber()
  326. {
  327. var bytes = new byte[4];
  328. var rng = RandomNumberGenerator.Create();
  329. rng.GetBytes(bytes);
  330. uint random = BitConverter.ToUInt32(bytes, 0) % 10;
  331. return String.Format("{0:D8}", random);
  332. }
  333. public static string GetTimeStampMiliSecond()
  334. {
  335. // Get the offset from current time in UTC time
  336. DateTimeOffset dto = new DateTimeOffset(DateTime.UtcNow);
  337. // Get the unix timestamp in seconds
  338. string unixTime = dto.ToUnixTimeMilliseconds().ToString();
  339. return unixTime.Substring(2, 8);
  340. }
  341. public static string GenerateUUID()
  342. {
  343. Guid myuuid = Guid.NewGuid();
  344. return myuuid.ToString();
  345. }
  346. public static string? CreateSignature(ILog log, Object data, string key)
  347. {
  348. string bodyString = JsonConvert.SerializeObject(data);
  349. log.Debug("body to signature: " + bodyString + key);
  350. return ComputeSHA256Hash(bodyString + key);
  351. }
  352. public static string ComputeSHA256Hash(string text)
  353. {
  354. using (var sha256 = new SHA256Managed())
  355. {
  356. return Convert
  357. .ToHexString(sha256.ComputeHash(Encoding.UTF8.GetBytes(text)))
  358. .Replace("-", "")
  359. .ToLower();
  360. }
  361. }
  362. private static byte[] HashHMAC(byte[] key, byte[] message)
  363. {
  364. var hash = new HMACSHA256(key);
  365. return hash.ComputeHash(message);
  366. }
  367. public static string HashHMACHex(string key, string message)
  368. {
  369. byte[] ba = Encoding.Default.GetBytes(key);
  370. var keyHexConvert = BitConverter.ToString(ba).Replace("-", "");
  371. var keyHex = Convert.FromHexString(keyHexConvert);
  372. byte[] baMes = Encoding.Default.GetBytes(message);
  373. var mesHexConvert = BitConverter.ToString(baMes).Replace("-", "");
  374. var messageHex = Convert.FromHexString(mesHexConvert);
  375. var hash = new HMACSHA256(keyHex);
  376. var compute = hash.ComputeHash(messageHex);
  377. return Convert.ToHexString(compute).ToLower();
  378. }
  379. public static bool CheckTime(string time)
  380. {
  381. try
  382. {
  383. DateTime dateTime = DateTime.ParseExact(time, "HH:mm:ss", CultureInfo.InvariantCulture);
  384. return true;
  385. }
  386. catch (Exception)
  387. {
  388. return false;
  389. }
  390. }
  391. public static bool CheckPermission(
  392. ModelContext dbContext,
  393. IConfiguration configuration,
  394. HttpRequest httpRequest
  395. )
  396. {
  397. return true;
  398. try
  399. {
  400. string realToken = "";
  401. var token = httpRequest.Headers["Authorization"];
  402. if (token.Count == 0)
  403. {
  404. return false;
  405. }
  406. realToken = token[0];
  407. // Trim 'Bearer ' from the start since its just a prefix for the token
  408. var jwtEncodedString = realToken.Substring(7);
  409. string? pathsString = GetPath(configuration, jwtEncodedString, "Paths");
  410. if (pathsString == null)
  411. {
  412. return false;
  413. }
  414. string url = httpRequest.Path;
  415. // log.Info("url: " + url + " || paths: " + pathsString);
  416. // convert string to list
  417. List<string>? paths = JsonConvert.DeserializeObject<List<string>>(pathsString);
  418. if (paths == null || paths.Count == 0)
  419. {
  420. return false;
  421. }
  422. if (!paths.Contains(url))
  423. {
  424. return false;
  425. }
  426. else
  427. {
  428. return true;
  429. }
  430. }
  431. catch (Exception e)
  432. {
  433. // log.Error("Exception: " + e);
  434. }
  435. return false;
  436. }
  437. public static String GenToken(IConfiguration configuration, String user, List<String> paths)
  438. {
  439. var issuer = configuration["Jwt:Issuer"];
  440. var audience = configuration["Jwt:Audience"];
  441. var key = Encoding.ASCII.GetBytes(configuration["Jwt:Key"]);
  442. string pathsJson = JsonConvert.SerializeObject(paths);
  443. var tokenDescriptor = new SecurityTokenDescriptor
  444. {
  445. Subject = new ClaimsIdentity(
  446. new[]
  447. {
  448. new Claim("Id", Guid.NewGuid().ToString()),
  449. new Claim("Role", user),
  450. new Claim("Paths", pathsJson),
  451. new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
  452. }
  453. ),
  454. Expires = DateTime.UtcNow.AddMinutes(5),
  455. Issuer = issuer,
  456. Audience = audience,
  457. SigningCredentials = new SigningCredentials(
  458. new SymmetricSecurityKey(key),
  459. SecurityAlgorithms.HmacSha512Signature
  460. )
  461. };
  462. var tokenHandler = new JwtSecurityTokenHandler();
  463. var token = tokenHandler.CreateToken(tokenDescriptor);
  464. var jwtToken = tokenHandler.WriteToken(token);
  465. var stringToken = tokenHandler.WriteToken(token);
  466. return stringToken;
  467. }
  468. public static String GenRefreshToken(IConfiguration configuration, String user)
  469. {
  470. var issuer = configuration["Jwt:Issuer"];
  471. var audience = configuration["Jwt:Audience"];
  472. var key = Encoding.ASCII.GetBytes(configuration["Jwt:Key"]);
  473. var tokenDescriptor = new SecurityTokenDescriptor
  474. {
  475. Subject = new ClaimsIdentity(
  476. new[]
  477. {
  478. new Claim("Id", Guid.NewGuid().ToString()),
  479. new Claim("Role", user),
  480. new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
  481. }
  482. ),
  483. Expires = DateTime.UtcNow.AddMinutes(2 * 24 * 60),
  484. Issuer = issuer,
  485. Audience = audience,
  486. SigningCredentials = new SigningCredentials(
  487. new SymmetricSecurityKey(key),
  488. SecurityAlgorithms.HmacSha512Signature
  489. )
  490. };
  491. var tokenHandler = new JwtSecurityTokenHandler();
  492. var token = tokenHandler.CreateToken(tokenDescriptor);
  493. var jwtToken = tokenHandler.WriteToken(token);
  494. var stringToken = tokenHandler.WriteToken(token);
  495. return stringToken;
  496. }
  497. public static String GenRequestId(String msisdn)
  498. {
  499. // get time in tik tac
  500. long epochTime = (DateTime.UtcNow.Ticks - 621355968000000000);
  501. return msisdn + "-" + epochTime.ToString();
  502. }
  503. public static string? GetPath(IConfiguration configuration, string token, string nameKey)
  504. {
  505. var key = Encoding.ASCII.GetBytes(configuration["Jwt:Key"] ?? "");
  506. var handler = new JwtSecurityTokenHandler();
  507. var validations = new TokenValidationParameters
  508. {
  509. ValidateIssuerSigningKey = true,
  510. IssuerSigningKey = new SymmetricSecurityKey(key),
  511. ValidateIssuer = false,
  512. ValidateAudience = false
  513. };
  514. var claims = handler.ValidateToken(token, validations, out var tokenSecure);
  515. var data = claims.Claims.First(x => x.Type == nameKey).Value;
  516. return data;
  517. }
  518. public static string GetLanguage(HttpRequest httpRequest)
  519. {
  520. var language = httpRequest.Headers["Language"];
  521. if (!language.IsNullOrEmpty())
  522. {
  523. return language.ToString();
  524. ;
  525. }
  526. return "en";
  527. }
  528. public static string GetLocalizedValue(string json, string language = "en")
  529. {
  530. try
  531. {
  532. var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
  533. if (dict != null && dict.ContainsKey(language))
  534. {
  535. return dict[language];
  536. }
  537. }
  538. catch (Exception e)
  539. {
  540. log.Error("Exception: ", e);
  541. }
  542. return "Unknown";
  543. }
  544. public static async Task<bool> SendMtToUserAsync(
  545. ModelContext dbContext,
  546. string msisdn,
  547. string? message
  548. )
  549. {
  550. if (message == null)
  551. {
  552. return true;
  553. }
  554. // send mt to user
  555. decimal seq = (decimal)await Database.DbLogic.GenIdAsync(dbContext, "mt_seq");
  556. Mt mt = new Mt();
  557. mt.MtId = seq;
  558. mt.MoHisId = (int)seq;
  559. mt.ReceiveTime = DateTime.Now;
  560. mt.Channel = CommonConstants.Channel;
  561. mt.Message = message;
  562. mt.Msisdn = msisdn;
  563. dbContext.Mts.Add(mt);
  564. await dbContext.SaveChangesAsync();
  565. return true;
  566. }
  567. public static string GetShortDecadeFromYear(int year)
  568. {
  569. if (year < 0)
  570. {
  571. throw new ArgumentException("Year cannot be negative.");
  572. }
  573. // Tìm năm bắt đầu của thập niên
  574. var decadeStart = (year / 10) * 10;
  575. // Trả về dạng đầy đủ
  576. return $"{decadeStart}s";
  577. }
  578. }