BaseController.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net.Http;
  8. using System.Security.Cryptography;
  9. using System.ServiceModel;
  10. using System.Text;
  11. using log4net;
  12. using Microsoft.AspNetCore.Hosting;
  13. using Microsoft.AspNetCore.Http;
  14. using Microsoft.AspNetCore.Mvc;
  15. using Microsoft.Extensions.Configuration;
  16. using Newtonsoft.Json;
  17. using Newtonsoft.Json.Linq;
  18. using WebPortal.Extensions;
  19. using WebPortal.Models;
  20. using WebService;
  21. namespace WebPortal.Controllers
  22. {
  23. public class BaseController : Controller
  24. {
  25. private readonly ILog log = LogManager.GetLogger(typeof(BaseController));
  26. private readonly IWebHostEnvironment webHostEnvironment;
  27. protected IConfiguration configuration;
  28. public static String CountryCode = "";
  29. public static int numWs = 0;
  30. //public static String FacebookAppId = "";
  31. //public static String FacebookShareHref = "";
  32. public static String channel = "";
  33. public static String serviceId = "";
  34. public static String RootHref = "";
  35. public static String wsUser = "";
  36. public static String wsPassword = "";
  37. public static String wsUrl1 = "";
  38. public static String wsLoginFail1 = "";
  39. public static String wsSubUser = "";
  40. public static String wsSubPassword = "";
  41. public static int coin1Spin = 5;
  42. public static int testMode = 0;
  43. public static String wsLoad = "";
  44. public static int enableCounter = 0;
  45. // Top no
  46. public static String TopNo0 = "";
  47. public static String TopNo1 = "";
  48. public static String TopNoUrl = "";
  49. private Random ran = new Random();
  50. private WsWebPortalClient wsClient = new WsWebPortalClient();
  51. private static readonly object syncLock = new object();
  52. private static readonly object syncCounter = new object();
  53. public static List<string> listMsisdn = new List<string>();
  54. public static DateTime? lastReload = null;
  55. public static int reloadPeriod = 120;
  56. //public static String CountryCode = ConfigurationManager.AppSettings["countryCode"];
  57. //public static int numWs = int.Parse(ConfigurationManager.AppSettings["numWs"]);
  58. //public static String FacebookAppId = ConfigurationManager.AppSettings["FacebookAppId"];
  59. //public static String channel = ConfigurationManager.AppSettings["channel"];
  60. //public static String serviceId = ConfigurationManager.AppSettings["serviceId"];
  61. public static String CaptchaSiteKey;// = ConfigurationManager.AppSettings["recaptchaPublicKey"];
  62. public static String CaptchaSecretKey;// = ConfigurationManager.AppSettings["recaptchaPrivateKey"];
  63. public BaseController() { }
  64. public BaseController(IConfiguration _configuration, IWebHostEnvironment hostEnvironment)
  65. {
  66. configuration = _configuration;
  67. webHostEnvironment = hostEnvironment;
  68. // load config
  69. CountryCode = configuration["countryCode"];
  70. numWs = int.Parse(configuration["numWs"]);
  71. try
  72. {
  73. enableCounter = int.Parse(configuration["enableCounter"]);
  74. }
  75. catch
  76. {
  77. enableCounter = 0;
  78. }
  79. //FacebookAppId = configuration["FacebookAppId"];
  80. //FacebookShareHref = configuration["FacebookShareHref"];
  81. channel = configuration["channel"];
  82. serviceId = configuration["serviceId"];
  83. wsUser = configuration["wsUser"];
  84. wsPassword = configuration["wsPassword"];
  85. wsUrl1 = configuration["wsUrl1"];
  86. wsLoginFail1 = configuration["wsLoginFail1"];
  87. //RootHref = configuration["RootHref"];
  88. //coin1Spin = int.Parse(configuration["coin1Spin"]);
  89. testMode = int.Parse(configuration["testMode"]);
  90. CaptchaSiteKey = configuration["recaptchaPublicKey"];
  91. CaptchaSecretKey = configuration["recaptchaPrivateKey"];
  92. wsSubUser = configuration["wsSubUser"];
  93. wsSubPassword = configuration["wsSubPassword"];
  94. wsLoad = configuration["wsUrl1"];
  95. reloadPeriod = int.Parse(configuration["reloadPeriod"]);
  96. //
  97. TopNo0 = configuration["TopNo0"];
  98. TopNo1 = configuration["TopNo1"];
  99. TopNoUrl = configuration["TopNoUrl"];
  100. }
  101. private static productObj[] hotPromotion;
  102. public static productObj[] GetHotPromotion()
  103. {
  104. if (hotPromotion != null)
  105. {
  106. return hotPromotion;
  107. }
  108. WsWebPortalClient wsClient = new WsWebPortalClient();
  109. wsClient.Endpoint.Address = new EndpointAddress(wsLoad);
  110. string lang = CultureInfo.CurrentCulture.Name.ToUpper() == "EN" ? "1" : "0";
  111. wsLoadProductRequest wsRequest = new wsLoadProductRequest(
  112. BaseController.wsUser,
  113. BaseController.wsPassword,
  114. null,
  115. null,
  116. "1",
  117. "3",
  118. "2",
  119. "1",
  120. null,
  121. lang);
  122. var wsResponse = wsClient.wsLoadProduct(wsRequest);
  123. hotPromotion = wsResponse.@return.listProduct;
  124. return hotPromotion;
  125. }
  126. protected void LoadBanner(WsWebPortalClient wsClient, String type, String status)
  127. {
  128. ViewBag.productType = type;
  129. // load banner
  130. SetWsClient(ref wsClient);
  131. wsLoadBannerByCodeRequest wsRequest = new wsLoadBannerByCodeRequest(
  132. BaseController.wsUser,
  133. BaseController.wsPassword,
  134. "BANNER_" + type,
  135. "1",
  136. "12",
  137. status,
  138. DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"),
  139. DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"),
  140. getCurrentLang());
  141. var wsResponse = wsClient.wsLoadBannerByCode(wsRequest);
  142. if (wsResponse.@return.listBanner != null)
  143. {
  144. HttpContext.Session.SetComplexData("listBanner", wsResponse.@return.listBanner);
  145. }
  146. }
  147. public String GetParameter(String key)
  148. {
  149. return configuration.GetSection(key).Value;
  150. }
  151. public String GetParameter(String parentKey, String key)
  152. {
  153. var configs = configuration.GetSection(parentKey).GetChildren();
  154. foreach (IConfiguration config in configs)
  155. {
  156. if (config[key] != null)
  157. {
  158. return config[key];
  159. }
  160. }
  161. return "";
  162. }
  163. public string RandomString(int size, bool lowerCase)
  164. {
  165. StringBuilder builder = new StringBuilder();
  166. Random random = new Random();
  167. char ch;
  168. for (int i = 0; i < size; i++)
  169. {
  170. ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
  171. builder.Append(ch);
  172. }
  173. if (lowerCase)
  174. return builder.ToString().ToLower();
  175. return builder.ToString();
  176. }
  177. protected string convertToDateTimeServer(String date)
  178. {
  179. // date:
  180. DateTime oDateFrom = DateTime.Parse(date);
  181. string hour = oDateFrom.Hour < 10 ? "0" + oDateFrom.Hour : oDateFrom.Hour.ToString();
  182. string minute = oDateFrom.Minute < 10 ? "0" + oDateFrom.Minute : oDateFrom.Minute.ToString();
  183. string second = oDateFrom.Second < 10 ? "0" + oDateFrom.Second : oDateFrom.Second.ToString();
  184. string month = oDateFrom.Month < 10 ? "0" + oDateFrom.Month : oDateFrom.Month.ToString();
  185. string day = oDateFrom.Day < 10 ? "0" + oDateFrom.Day : oDateFrom.Day.ToString();
  186. string fromCheck = day + "/" + month + "/" + oDateFrom.Year + " " + hour + ":" + minute + ":" + second;
  187. return fromCheck; //MM/dd/yyyy HH24:mm:ss
  188. }
  189. protected void CreateAuthToken(String account, Object userObj)
  190. {
  191. // create session authen
  192. // Create the random value we will use to secure the session.
  193. string authId = GenerateAuthId();
  194. // Store the value in both our Session and a Cookie.
  195. HttpContext.Session.SetString("AuthorizationCookieId", authId);
  196. string sessionValue = HttpContext.Session.GetString("AuthorizationCookieId");
  197. //CookieOptions option = new CookieOptions
  198. //{
  199. // Expires = DateTime.Now.AddMinutes(1)
  200. //};
  201. //Response.Cookies.Append("Key Name", "Value", option);
  202. CookieOptions options = new CookieOptions()
  203. {
  204. //Path = "/",
  205. //HttpOnly = true,
  206. //Secure = false,
  207. //SameSite = SameSiteMode.None
  208. Expires = DateTime.Now.AddMinutes(60)
  209. };
  210. HttpContext.Response.Cookies.Append("AuthorizationCookie", authId, options);
  211. string cookieValue = HttpContext.Request.Cookies["AuthorizationCookie"];
  212. HttpContext.Session.SetString("account", account);
  213. HttpContext.Session.SetComplexData("userInfo", userObj);
  214. }
  215. protected bool ClearCache()
  216. {
  217. HttpContext.Session.Clear();
  218. foreach (var cookieKey in HttpContext.Request.Cookies.Keys)
  219. {
  220. HttpContext.Response.Cookies.Delete(cookieKey);
  221. }
  222. return true;
  223. }
  224. private string GenerateAuthId()
  225. {
  226. using (RandomNumberGenerator rng = new RNGCryptoServiceProvider())
  227. {
  228. byte[] tokenData = new byte[32];
  229. rng.GetBytes(tokenData);
  230. return Convert.ToBase64String(tokenData);
  231. }
  232. }
  233. public void SetWsClient(ref WsWebPortalClient wsClient, String sessionId)
  234. {
  235. int lastNum = sessionId[sessionId.Length - 1];
  236. int wsId = lastNum % numWs + 1;
  237. wsClient.Endpoint.Address = new EndpointAddress(configuration["wsUrl" + wsId]);
  238. }
  239. public void SetWsClient(ref WsWebPortalClient wsClient)
  240. {
  241. int wsId = ran.Next(1, numWs);
  242. wsClient.Endpoint.Address = new EndpointAddress(configuration["wsUrl" + wsId]);
  243. }
  244. public String validateMsisdn(String input)
  245. {
  246. if (input == null || input.Length == 0)
  247. {
  248. return "";
  249. }
  250. // check is number
  251. try
  252. {
  253. input = long.Parse(input) + "";
  254. }
  255. catch
  256. {
  257. return "";
  258. }
  259. //
  260. if (input.StartsWith("0"))
  261. {
  262. input = CountryCode + input.Substring(1);
  263. }
  264. else if (!input.StartsWith(CountryCode))
  265. {
  266. input = CountryCode + input;
  267. }
  268. if (!input.StartsWith(CountryCode + "75") && !input.StartsWith(CountryCode + "76"))
  269. {
  270. return "";
  271. }
  272. if (input.Length != 11)
  273. {
  274. return "";
  275. }
  276. return input.Trim();
  277. }
  278. public static String getCurrentLang()
  279. {
  280. if (CultureInfo.CurrentCulture.Name.ToUpper() == "EN")
  281. {
  282. return "1";
  283. }
  284. return "0";
  285. }
  286. public String getCurrentLangTxt()
  287. {
  288. if (CultureInfo.CurrentCulture.Name.ToUpper() == "EN")
  289. {
  290. return "en";
  291. }
  292. return "te";
  293. }
  294. public class WsType
  295. {
  296. //public const String MochaMsisdn = "urlMochaMsisdn";
  297. //public const String LaoAppLogin = "laoAppUrlLogin";
  298. //public const String LaoAppVerify = "laoAppUrlVerify";
  299. //public const String LaoAppFind = "laoAppUrlFind";
  300. public const String wsLoadVoucher = "wsLoadVoucher";
  301. public const String wsGetLoyaltyInfo = "wsGetLoyaltyInfo";
  302. }
  303. private String GetWsClient(String type)
  304. {
  305. return configuration[type];
  306. }
  307. public String SendPost(log4net.ILog log, Object obj, String type)
  308. {
  309. StringBuilder sb = new StringBuilder();
  310. sb.Append("Send post " + type + ": ").Append("\n");
  311. sb.Append("\tRequest:" + JsonConvert.SerializeObject(obj)).Append("\n");
  312. String result = SendPost(obj, type);
  313. sb.Append("\tResponse:" + result);
  314. log.Info(sb);
  315. return result;
  316. }
  317. public String SendPost(Object obj, String type)
  318. {
  319. var json = JsonConvert.SerializeObject(obj);
  320. var data = new StringContent(json, Encoding.UTF8, "application/json");
  321. var url = GetWsClient(type);
  322. using (var client = new HttpClient())
  323. {
  324. var response = client.PostAsync(url, data).Result;
  325. if (response.IsSuccessStatusCode)
  326. {
  327. var responseContent = response.Content;
  328. // by calling .Result you are synchronously reading the result
  329. string responseString = responseContent.ReadAsStringAsync().Result;
  330. return responseString;
  331. }
  332. else
  333. {
  334. try
  335. {
  336. var responseContent = response.Content;
  337. string responseString = responseContent.ReadAsStringAsync().Result;
  338. return responseString;
  339. }
  340. catch
  341. {
  342. return response.StatusCode.ToString();
  343. }
  344. }
  345. }
  346. }
  347. public String SendPostParam(log4net.ILog log, Object obj, String type)
  348. {
  349. StringBuilder sb = new StringBuilder();
  350. sb.Append("Send post param " + type + ": ").Append("\n");
  351. sb.Append("\tRequest:" + JsonConvert.SerializeObject(obj)).Append("\n");
  352. String result = SendPostParam(obj, type);
  353. sb.Append("\tResponse:" + result);
  354. log.Info(sb);
  355. return result;
  356. }
  357. public String SendPostParam(Object obj, String type)
  358. {
  359. //var json = JsonConvert.SerializeObject(obj);
  360. //var data = new StringContent(json, Encoding.UTF8, "application/json");
  361. var url = GetWsClient(type) + AppendUrlParam(obj);
  362. using (var client = new HttpClient())
  363. {
  364. var response = client.PostAsync(url, null).Result;
  365. if (response.IsSuccessStatusCode)
  366. {
  367. var responseContent = response.Content;
  368. // by calling .Result you are synchronously reading the result
  369. string responseString = responseContent.ReadAsStringAsync().Result;
  370. return responseString;
  371. }
  372. else
  373. {
  374. try
  375. {
  376. var responseContent = response.Content;
  377. string responseString = responseContent.ReadAsStringAsync().Result;
  378. return responseString;
  379. }
  380. catch
  381. {
  382. return response.StatusCode.ToString();
  383. }
  384. }
  385. }
  386. }
  387. public String SendGetHeader(ILog log, Object obj, Dictionary<String, String> headers, String type)
  388. {
  389. StringBuilder sb = new StringBuilder();
  390. sb.Append("Send get " + type + ": ").Append("\n");
  391. sb.Append("\tRequest:" + JsonConvert.SerializeObject(obj)).Append("\n");
  392. sb.Append("\tHeaders:").Append("\n");
  393. foreach (var key in headers.Keys)
  394. {
  395. sb.Append(key + "=" + headers[key] + "\n");
  396. }
  397. String result = SendGetHeader(obj, headers, type);
  398. sb.Append("\tResponse:" + result);
  399. log.Info(sb);
  400. return result;
  401. }
  402. public String SendGetHeader(Object obj, Dictionary<String, String> headers, String type)
  403. {
  404. //var json = JsonConvert.SerializeObject(obj);
  405. var url = GetWsClient(type) + AppendUrlParam(obj);
  406. using (var client = new HttpClient())
  407. {
  408. if (headers != null)
  409. {
  410. foreach (String key in headers.Keys)
  411. {
  412. client.DefaultRequestHeaders.Add(key, headers[key]);
  413. }
  414. }
  415. var response = client.GetAsync(url).Result;
  416. if (response.IsSuccessStatusCode)
  417. {
  418. var responseContent = response.Content;
  419. // by calling .Result you are synchronously reading the result
  420. string responseString = responseContent.ReadAsStringAsync().Result;
  421. return responseString;
  422. }
  423. else
  424. {
  425. try
  426. {
  427. var responseContent = response.Content;
  428. string responseString = responseContent.ReadAsStringAsync().Result;
  429. return responseString;
  430. }
  431. catch
  432. {
  433. return response.StatusCode.ToString();
  434. }
  435. }
  436. }
  437. }
  438. public String SendPostHeader(ILog log, Object obj, Dictionary<String, String> headers, String type)
  439. {
  440. StringBuilder sb = new StringBuilder();
  441. sb.Append("Send post header " + type + ": ").Append("\n");
  442. sb.Append("\tRequest:" + JsonConvert.SerializeObject(obj)).Append("\n");
  443. sb.Append("\tHeaders:").Append("\n");
  444. foreach (var key in headers.Keys)
  445. {
  446. sb.Append(key + "=" + headers[key] + "\n");
  447. }
  448. String result = SendPostHeader(obj, headers, type);
  449. sb.Append("\tResponse:" + result);
  450. log.Info(sb);
  451. return result;
  452. }
  453. public String SendPostHeader(Object obj, Dictionary<String, String> headers, String type)
  454. {
  455. var json = JsonConvert.SerializeObject(obj);
  456. var data = new StringContent(json, Encoding.UTF8, "application/json");
  457. var url = GetWsClient(type);
  458. using (var client = new HttpClient())
  459. {
  460. foreach (String key in headers.Keys)
  461. {
  462. client.DefaultRequestHeaders.Add(key, headers[key]);
  463. }
  464. var response = client.PostAsync(url, data).Result;
  465. if (response.IsSuccessStatusCode)
  466. {
  467. var responseContent = response.Content;
  468. // by calling .Result you are synchronously reading the result
  469. string responseString = responseContent.ReadAsStringAsync().Result;
  470. return responseString;
  471. }
  472. else
  473. {
  474. try
  475. {
  476. var responseContent = response.Content;
  477. string responseString = responseContent.ReadAsStringAsync().Result;
  478. return responseString;
  479. }
  480. catch
  481. {
  482. return response.StatusCode.ToString();
  483. }
  484. }
  485. }
  486. }
  487. public String AppendUrlParam(Object obj)
  488. {
  489. Type type = obj.GetType();
  490. String append = "?";
  491. foreach (var f in type.GetProperties())
  492. {
  493. append += f.Name + "=" + f.GetValue(obj) + "&";
  494. }
  495. return append.Substring(0, append.Length - 1);
  496. }
  497. public String DetectMsisdn()
  498. {
  499. string msisdn = null;
  500. // get header
  501. //foreach (var header in Request.Headers)
  502. //{
  503. // if (header.Key.Trim().ToUpper() == "X-UP-CALLING-LINE-ID")
  504. // {
  505. // msisdn = header.Value;
  506. // log.Info("MSISDN: " + msisdn);
  507. // return msisdn;
  508. // }
  509. //}
  510. if (msisdn == null)
  511. {
  512. msisdn = Request.Query["isdn"];
  513. }
  514. ViewBag.msisdn = msisdn;
  515. return msisdn;
  516. }
  517. public String DetectMsisdn(WsWebPortalClient wsClient)
  518. {
  519. string ipAddress = "";
  520. string msisdn = null;
  521. // get header
  522. log.Info("Header:");
  523. foreach (var header in Request.Headers)
  524. {
  525. log.Info(header.Key + "=" + header.Value);
  526. if (header.Key.Trim().ToUpper() == "X-FORWARDED-FOR")
  527. {
  528. //10.234.94.250 , 103.238.116.58
  529. ipAddress = header.Value.ToString().Split(",", StringSplitOptions.RemoveEmptyEntries)[0].Trim();
  530. log.Info("IPADDRESS: " + ipAddress);
  531. }
  532. if (header.Key.Trim().ToUpper() == "X-UP-CALLING-LINE-ID")
  533. {
  534. msisdn = header.Value;
  535. log.Info("MSISDN: " + msisdn);
  536. }
  537. }
  538. // detect msisdn
  539. if (ipAddress != "")
  540. {
  541. wsGetMsisdnFromIpRequest req = new wsGetMsisdnFromIpRequest(wsUser, wsPassword, ipAddress);
  542. string phoneNumber = wsClient.wsGetMsisdnFromIp(req).@return.content;
  543. if (phoneNumber != null && phoneNumber != "")
  544. {
  545. phoneNumber = validateMsisdn(phoneNumber);
  546. if (phoneNumber == msisdn)
  547. {
  548. CreateAuthToken(phoneNumber, null);
  549. return msisdn;
  550. }
  551. }
  552. }
  553. return null;
  554. }
  555. }
  556. }