CommonLogic.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. using System.Globalization;
  2. using System.IdentityModel.Tokens.Jwt;
  3. using System.Security.Claims;
  4. using System.Text;
  5. using System.Xml.Linq;
  6. using System.Xml.Serialization;
  7. using Common.Constant;
  8. using log4net;
  9. using Microsoft.AspNetCore.Http;
  10. using Microsoft.Extensions.Configuration;
  11. using Microsoft.IdentityModel.Tokens;
  12. using Newtonsoft.Json;
  13. using System.Net;
  14. namespace Common.Logic;
  15. public class CommonLogic
  16. {
  17. private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(CommonLogic));
  18. public static String GenToken(IConfiguration configuration, String msisdn, String accountId)
  19. {
  20. var issuer = configuration["Jwt:Issuer"];
  21. var audience = configuration["Jwt:Audience"];
  22. var key = Encoding.ASCII.GetBytes(configuration["Jwt:Key"]!);
  23. var tokenDescriptor = new SecurityTokenDescriptor
  24. {
  25. Subject = new ClaimsIdentity(
  26. new[]
  27. {
  28. new Claim("Id", Guid.NewGuid().ToString()),
  29. new Claim("Msisdn", msisdn),
  30. new Claim("AccountId", accountId),
  31. new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
  32. }
  33. ),
  34. Expires = DateTime.UtcNow.AddMinutes(int.Parse(configuration["Jwt:Time"] ?? "900")),
  35. Issuer = issuer,
  36. Audience = audience,
  37. SigningCredentials = new SigningCredentials(
  38. new SymmetricSecurityKey(key),
  39. SecurityAlgorithms.HmacSha512Signature
  40. )
  41. };
  42. var tokenHandler = new JwtSecurityTokenHandler();
  43. var token = tokenHandler.CreateToken(tokenDescriptor);
  44. var jwtToken = tokenHandler.WriteToken(token);
  45. var stringToken = tokenHandler.WriteToken(token);
  46. return stringToken;
  47. }
  48. public static string GenRefreshToken(IConfiguration configuration, string msisdn)
  49. {
  50. var issuer = configuration["Jwt:Issuer"];
  51. var audience = configuration["Jwt:Audience"];
  52. var key = Encoding.ASCII.GetBytes(configuration["Jwt:Key"]);
  53. var tokenDescriptor = new SecurityTokenDescriptor
  54. {
  55. Subject = new ClaimsIdentity(
  56. new[]
  57. {
  58. new Claim("Id", Guid.NewGuid().ToString()),
  59. new Claim("Msisdn", msisdn),
  60. new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
  61. }
  62. ),
  63. Expires = DateTime.UtcNow.AddMinutes(int.Parse(configuration["Jwt:Time"] ?? "900")),
  64. Issuer = issuer,
  65. Audience = audience,
  66. SigningCredentials = new SigningCredentials(
  67. new SymmetricSecurityKey(key),
  68. SecurityAlgorithms.HmacSha512Signature
  69. )
  70. };
  71. var tokenHandler = new JwtSecurityTokenHandler();
  72. var token = tokenHandler.CreateToken(tokenDescriptor);
  73. var jwtToken = tokenHandler.WriteToken(token);
  74. var stringToken = tokenHandler.WriteToken(token);
  75. return stringToken;
  76. }
  77. public static string? GetDataFromToken(
  78. IConfiguration configuration,
  79. HttpRequest httpRequest,
  80. string nameKey
  81. )
  82. {
  83. string realToken = "";
  84. var token = httpRequest.Headers["Authorization"];
  85. if (token.Count == 0)
  86. {
  87. return null;
  88. }
  89. realToken = token[0];
  90. // Trim 'Bearer ' from the start since its just a prefix for the token
  91. var jwtEncodedString = realToken.Substring(7);
  92. string? value = GetPath(configuration, jwtEncodedString, nameKey);
  93. if (value == null)
  94. {
  95. return null;
  96. }
  97. string url = httpRequest.Path;
  98. log.Info("url: " + url + " || nameKey: " + nameKey + " value: " + value);
  99. return value;
  100. }
  101. public static string? GetPath(IConfiguration configuration, string token, string nameKey)
  102. {
  103. var key = Encoding.ASCII.GetBytes(configuration["Jwt:Key"] ?? "");
  104. var handler = new JwtSecurityTokenHandler();
  105. var validations = new TokenValidationParameters
  106. {
  107. ValidateIssuerSigningKey = true,
  108. IssuerSigningKey = new SymmetricSecurityKey(key),
  109. ValidateIssuer = false,
  110. ValidateAudience = false,
  111. ValidateLifetime = true
  112. };
  113. var claims = handler.ValidateToken(token, validations, out var tokenSecure);
  114. var data = claims.Claims.First(x => x.Type == nameKey).Value;
  115. return data;
  116. }
  117. public static string? ValidateMsisdn(string? input)
  118. {
  119. if (input == null || input.Length == 0 || !long.TryParse(input, out long temp))
  120. {
  121. return null;
  122. }
  123. else if (input.StartsWith("255") && input.Length == 12)
  124. {
  125. return input.Trim();
  126. }
  127. else if (input.StartsWith("0") && input.Length == 10)
  128. {
  129. input = "255" + input.Substring(1);
  130. return input.Trim();
  131. }
  132. return null;
  133. }
  134. public static string GenPassword(int length)
  135. {
  136. const string chars = "0123456789";
  137. var random = new Random();
  138. var password = new StringBuilder();
  139. for (int i = 0; i < length; i++)
  140. {
  141. password.Append(chars[random.Next(chars.Length)]);
  142. }
  143. return password.ToString();
  144. }
  145. public static string ConvertIntStatus(int? status)
  146. {
  147. switch (status)
  148. {
  149. case CommonConstant.StatusActive:
  150. return "Active";
  151. case CommonConstant.StatusInactive:
  152. return "Inactive";
  153. case CommonConstant.StatusClaimed:
  154. return "Claimed";
  155. case CommonConstant.StatusNotClaimed:
  156. return "Not Claimed";
  157. default:
  158. return "All";
  159. }
  160. }
  161. public static DateTime ConvertStringToTime(string? time)
  162. {
  163. return DateTime.ParseExact(
  164. time!,
  165. CommonConstant.ListDateTimeFormat,
  166. System.Globalization.CultureInfo.InvariantCulture,
  167. DateTimeStyles.None
  168. );
  169. }
  170. public static string GetClassNameByIntStatus(int status)
  171. {
  172. switch (status)
  173. {
  174. case CommonConstant.StatusActive:
  175. return "bg-success";
  176. case CommonConstant.StatusClaimed:
  177. return "bg-success";
  178. case CommonConstant.StatusNotClaimed:
  179. return "bg-danger";
  180. case CommonConstant.StatusInactive:
  181. return "bg-black";
  182. default:
  183. return "bg-success";
  184. }
  185. }
  186. public static string? SendPostWithAuthen(ILog log, string Url, dynamic data, string authenToken,string lang = "tu")
  187. {
  188. var json = JsonConvert.SerializeObject(data);
  189. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
  190. request.Method = "POST";
  191. request.ContentType = "application/json";
  192. request.ContentLength = json.Length;
  193. request.Headers.Add("Authorization", "Bearer " + authenToken);
  194. request.Headers.Add("Accept-Language", lang);
  195. log.Info("request: " + Url + " data: " + json);
  196. using (Stream webStream = request.GetRequestStream())
  197. using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
  198. {
  199. requestWriter.Write(json);
  200. }
  201. try
  202. {
  203. WebResponse webResponse = request.GetResponse();
  204. using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
  205. using (StreamReader responseReader = new StreamReader(webStream))
  206. {
  207. string response = responseReader.ReadToEnd();
  208. log.Info("request: " + Url + " /nData: " + json + " /n response: " + response);
  209. return response;
  210. }
  211. }
  212. catch (Exception e)
  213. {
  214. log.Info("-----------------");
  215. log.Info(e.Message);
  216. }
  217. return null;
  218. }
  219. public static string? SendPost(ILog log, string Url, dynamic data)
  220. {
  221. var json = JsonConvert.SerializeObject(data);
  222. log.Info("request: " + Url + " data: " + json);
  223. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
  224. request.Method = "POST";
  225. request.ContentType = "application/json";
  226. request.ContentLength = json.Length;
  227. // CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
  228. // log.Debug("Lang: " + currentCulture.Name);
  229. // request.Headers.Add("Lang", currentCulture.Name);
  230. using (Stream webStream = request.GetRequestStream())
  231. using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
  232. {
  233. requestWriter.Write(json);
  234. }
  235. try
  236. {
  237. WebResponse webResponse = request.GetResponse();
  238. using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
  239. using (StreamReader responseReader = new StreamReader(webStream))
  240. {
  241. string response = responseReader.ReadToEnd();
  242. log.Info("request: " + Url + " /nData: " + json + " /n response: " + response);
  243. return response;
  244. }
  245. }
  246. catch (Exception e)
  247. {
  248. log.Info("-----------------");
  249. log.Info(e.Message);
  250. }
  251. return null;
  252. }
  253. public static string GetErrorDescription(string code)
  254. {
  255. switch (code)
  256. {
  257. case "0":
  258. return "SUBSCRIBER put to queue Success";
  259. case "1":
  260. return "SUBSCRIBER put to Queue failed";
  261. case "2":
  262. return "Unauthentic";
  263. case "15":
  264. return "Missing value (Input params null) / Invalid Parameter(s)";
  265. case "200":
  266. return "Invalid username or password";
  267. case "201":
  268. return "Invalid Request Type";
  269. case "202":
  270. return "Invalid Request";
  271. case "203":
  272. return "Invalid package";
  273. case "204":
  274. return "Server too busy";
  275. case "400":
  276. return "Not register";
  277. case "401":
  278. return "Not enough money";
  279. case "403":
  280. return "Already register";
  281. case "408":
  282. return "Get price charge error";
  283. case "411":
  284. return "Subscriber was cancel service";
  285. case "412":
  286. return "Subscriber not use service";
  287. case "413":
  288. return "Conflict package. Subscriber is using other package in same service";
  289. case "418":
  290. return "MO command not support";
  291. case "419":
  292. return "3rd Party is incorrect";
  293. case "420":
  294. return "Wrong format datetime: yyyy-MM-dd";
  295. case "504":
  296. return "Unknown error";
  297. default:
  298. return "Unknown error code";
  299. }
  300. }
  301. //public static EnvelopeNoNs ParseSoapResponse(string xml)
  302. //{
  303. // // Bỏ namespace để dễ deserialize
  304. // XDocument doc = XDocument.Parse(xml);
  305. // foreach (var elem in doc.Descendants())
  306. // elem.Name = elem.Name.LocalName;
  307. // string cleanXml = doc.ToString();
  308. // var serializer = new XmlSerializer(typeof(EnvelopeNoNs));
  309. // using var reader = new StringReader(cleanXml);
  310. // return (EnvelopeNoNs)serializer.Deserialize(reader)!;
  311. //}
  312. }