BaseController.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. using System;
  2. using System.Globalization;
  3. using System.IO;
  4. using System.Net.Http;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Xml;
  9. using log4net;
  10. using LotteryWebApp.Common;
  11. using LotteryWebApp.Languages;
  12. using LotteryWebApp.Service;
  13. using Microsoft.AspNetCore.Http;
  14. using Microsoft.AspNetCore.Mvc;
  15. using Microsoft.Extensions.Configuration;
  16. using NcGamesWebView.Extensions;
  17. namespace LotteryWebApp.Controllers
  18. {
  19. public class BaseController : Controller
  20. {
  21. private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
  22. public static string[] formats =
  23. {
  24. "M/d/yyyy h:mm:ss tt",
  25. "M/d/yyyy h:mm tt",
  26. "MM/dd/yyyy hh:mm:ss",
  27. "M/d/yyyy h:mm:ss",
  28. "M/d/yyyy hh:mm tt",
  29. "M/d/yyyy hh tt",
  30. "M/d/yyyy h:mm",
  31. "M/d/yyyy h:mm",
  32. "MM/dd/yyyy hh:mm",
  33. "M/dd/yyyy hh:mm",
  34. "MM/d/yyyy HH:mm:ss.ffffff, dd/MM/yyyy hh:mm",
  35. "M/dd/yyyy h:mm:ss tt",
  36. "dd/MM/yyyy HH:mm:ss"
  37. };
  38. public static string RandomString(int size, bool lowerCase)
  39. {
  40. StringBuilder builder = new StringBuilder();
  41. Random random = new Random();
  42. char ch;
  43. for (int i = 0; i < size; i++)
  44. {
  45. ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
  46. builder.Append(ch);
  47. }
  48. if (lowerCase)
  49. return builder.ToString().ToLower();
  50. return builder.ToString();
  51. }
  52. // validate phone number
  53. public static String validateMsisdn(String input)
  54. {
  55. String CountryCode = Constants.COUNTRY_CODE;
  56. if (input == null || input.Length == 0 || !long.TryParse(input, out long temp))
  57. {
  58. return "";
  59. }
  60. if (input.StartsWith("0"))
  61. {
  62. input = input.Substring(1);
  63. }
  64. if (input.StartsWith(CountryCode))
  65. {
  66. input = input.Substring(CountryCode.Length);
  67. }
  68. if (input.Length >= 7 && input.Length <= 8)
  69. {
  70. input = CountryCode + input;
  71. return input.Trim();
  72. }
  73. else
  74. {
  75. return "";
  76. }
  77. }
  78. public string ConvertToGameID(string termType, string ticketType)
  79. {
  80. if (termType == Constants.GameGroup.Singapore)
  81. {
  82. switch (ticketType)
  83. {
  84. case Constants.TicketType._4D:
  85. return Constants.GameId.Direct4D;
  86. case Constants.TicketType._3D:
  87. return Constants.GameId.Direct3D;
  88. default:
  89. return Constants.GameId.Direct2D;
  90. }
  91. }
  92. return Constants.GameId.Direct4D;
  93. }
  94. public string ConvertToListGameID(String gameIDCode)
  95. {
  96. switch (gameIDCode)
  97. {
  98. case Constants.GameId.Direct4D:
  99. return Constants.GameId.Direct4D + "," + Constants.GameId.Ibet4D;
  100. case Constants.GameId.Direct3D:
  101. return Constants.GameId.Direct3D + "," + Constants.GameId.Ibet3D;
  102. default:
  103. return Constants.GameId.Direct2D + "," + Constants.GameId.Ibet2D;
  104. }
  105. }
  106. public static string ConvertToWinType(String winType)
  107. {
  108. switch (winType)
  109. {
  110. case Constants.NOT_DRAW_CODE:
  111. return Lang.not_draw;
  112. case Constants.WIN_CODE:
  113. return Lang.win;
  114. default:
  115. return Lang.not_win;
  116. }
  117. }
  118. public static string ConvertGameIdToTerm(string gameId)
  119. {
  120. switch (gameId)
  121. {
  122. case Constants.GameId.Direct4D:
  123. return "Singapore";
  124. case Constants.GameId.Direct3D:
  125. return "Singapore";
  126. case Constants.GameId.Direct2D:
  127. return "Singapore";
  128. default:
  129. return "Singapore";
  130. }
  131. }
  132. public static string ConvertGameIdToPlayType(string gameId)
  133. {
  134. switch (gameId)
  135. {
  136. case Constants.GameId.Direct4D:
  137. return "Direct";
  138. case Constants.GameId.Direct3D:
  139. return "Direct";
  140. case Constants.GameId.Direct2D:
  141. return "Direct";
  142. default:
  143. return "IBet";
  144. }
  145. }
  146. public static string ConvertGameIdToName(string gameId)
  147. {
  148. switch (gameId)
  149. {
  150. case Constants.GameId.Direct4D:
  151. return "4D Direct";
  152. case Constants.GameId.Direct3D:
  153. return "3D Direct";
  154. case Constants.GameId.Direct2D:
  155. return "2D Direct";
  156. default:
  157. return "4D";
  158. }
  159. }
  160. public static string GetLangFromCode(string code)
  161. {
  162. switch (code)
  163. {
  164. case "1":
  165. return Lang.login_fail_wrong_pass;
  166. case "0":
  167. return Lang.success;
  168. case "-1":
  169. return Lang.error_happened;
  170. case "-2":
  171. return Lang.system_update;
  172. case "2":
  173. return Lang.term_timeout;
  174. case "3":
  175. return Lang.ticket_invalid;
  176. case "7":
  177. return "User was locked";
  178. case "9":
  179. return Lang.reset_after_1_minute;
  180. case "4":
  181. return Lang.params_invalid;
  182. case "20":
  183. return Lang.wallet_not_existed;
  184. case "21":
  185. return Lang.wallet_not_active;
  186. case "22":
  187. return Lang.younger_to_use;
  188. case "23":
  189. return Lang.account_not_existed;
  190. case "24":
  191. return Lang.internet_error;
  192. case "25":
  193. return Lang.pin_wrong;
  194. case "26":
  195. return Lang.in_blacklist;
  196. case "30":
  197. return Lang.otp_timeout;
  198. case "31":
  199. return Lang.otp_invalid;
  200. case "100":
  201. return Lang.no_permission;
  202. case "32":
  203. return Lang.not_enough_money_to_exchange;
  204. case "33":
  205. return Lang.over_each_exchange;
  206. case "34":
  207. return Lang.over_exchange_per_day;
  208. case "38":
  209. return Lang.promotion_code_invalid;
  210. case "39":
  211. return Lang.promotion_code_used;
  212. case "40":
  213. return Lang.promotion_code_inactive;
  214. case "41":
  215. return Lang.buying_code_not_existed;
  216. default:
  217. return code + " " + Lang.not_defined;
  218. }
  219. }
  220. public static string ConvertWalletTicket(string type)
  221. {
  222. switch (type)
  223. {
  224. case Constants.BASIC_WALLET_TICKET:
  225. return Lang.basic_account;
  226. default:
  227. return Lang.NatCash;
  228. }
  229. }
  230. // dateTime : MM/dd/yyyy
  231. public static long getCountTimeToTimestamp(string time)
  232. {
  233. // convert to Datetime
  234. DateTime endTime = DateTime.ParseExact(
  235. time,
  236. formats,
  237. new CultureInfo("en-US"),
  238. DateTimeStyles.None
  239. );
  240. TimeSpan elapsedTime = endTime - DateTime.Now;
  241. return (long)elapsedTime.TotalSeconds;
  242. }
  243. protected void CreateAuthToken()
  244. {
  245. // create session authen
  246. // Create the random value we will use to secure the session.
  247. string authId = GenerateAuthId();
  248. // Store the value in both our Session and a Cookie.
  249. HttpContext.Session.SetString("AuthorizationCookieId", authId);
  250. string sessionValue = HttpContext.Session.GetString("AuthorizationCookieId");
  251. //CookieOptions option = new CookieOptions
  252. //{
  253. // Expires = DateTime.Now.AddMinutes(1)
  254. //};
  255. //Response.Cookies.Append("Key Name", "Value", option);
  256. CookieOptions options = new CookieOptions()
  257. {
  258. //Path = "/",
  259. //HttpOnly = true,
  260. //Secure = false,
  261. //SameSite = SameSiteMode.None
  262. Expires = DateTime.Now.AddMinutes(60)
  263. };
  264. HttpContext.Response.Cookies.Append("AuthorizationCookie", authId, options);
  265. string cookieValue = HttpContext.Request.Cookies["AuthorizationCookie"];
  266. }
  267. protected bool CheckAuthToken()
  268. {
  269. //return true;
  270. string cookieValue = HttpContext.Request.Cookies["AuthorizationCookie"];
  271. string sessionValue = HttpContext.Session.GetString("AuthorizationCookieId");
  272. if (cookieValue == null || sessionValue == null || cookieValue != sessionValue)
  273. {
  274. // Invalidate the session and log out the current user.
  275. return false;
  276. //return true;
  277. }
  278. //if (sessionValue == null)
  279. //{
  280. // // Invalidate the session and log out the current user.
  281. // return false;
  282. //}
  283. else
  284. {
  285. return true;
  286. }
  287. }
  288. protected bool ClearCache()
  289. {
  290. HttpContext.Session.Clear();
  291. foreach (var cookieKey in HttpContext.Request.Cookies.Keys)
  292. {
  293. HttpContext.Response.Cookies.Delete(cookieKey);
  294. }
  295. return true;
  296. }
  297. private string GenerateAuthId()
  298. {
  299. using (RandomNumberGenerator rng = new RNGCryptoServiceProvider())
  300. {
  301. byte[] tokenData = new byte[32];
  302. rng.GetBytes(tokenData);
  303. return Convert.ToBase64String(tokenData);
  304. }
  305. }
  306. protected String DecryptRSA(IConfiguration _configuration, String data)
  307. {
  308. RSACryptoServiceProvider rsaPrivate = new RSACryptoServiceProvider();
  309. rsaPrivate.FromXmlFile(
  310. Path.Combine(
  311. Directory.GetCurrentDirectory(),
  312. "",
  313. _configuration["rsaPrivateKeyXml"]
  314. )
  315. );
  316. byte[] byteEntry = Convert.FromBase64String(data);
  317. byte[] byteText = rsaPrivate.Decrypt(byteEntry, false);
  318. return Encoding.UTF8.GetString(byteText);
  319. }
  320. protected async Task<string> CheckAutoLogin(ILog log, String uuid)
  321. {
  322. string res = null;
  323. try
  324. {
  325. HttpClient httpClient = new HttpClient();
  326. MultipartFormDataContent form = new MultipartFormDataContent();
  327. form.Add(new StringContent(uuid), "uuid");
  328. HttpResponseMessage response = await httpClient.PostAsync(
  329. Constants.URL_GET_MSISDN,
  330. form
  331. );
  332. response.EnsureSuccessStatusCode();
  333. httpClient.Dispose();
  334. res = response.Content.ReadAsStringAsync().Result;
  335. }
  336. catch (Exception ex)
  337. {
  338. Console.WriteLine(ex.Message);
  339. log.Debug("Exp: " + ex);
  340. }
  341. return res;
  342. }
  343. public static string CreatePrivateURL(
  344. IConfiguration _configuration,
  345. string urlString,
  346. string durationUnits,
  347. string durationNumber,
  348. string startIntervalFromNow,
  349. string pathToPolicyStmnt
  350. )
  351. {
  352. TimeSpan timeSpanInterval = GetDuration(durationUnits, durationNumber);
  353. TimeSpan timeSpanToStart = GetDurationByUnits(durationUnits, startIntervalFromNow);
  354. if (null == timeSpanToStart)
  355. return "Invalid duration units. Valid options: seconds, minutes, hours, or days";
  356. string strPolicy = urlString;
  357. // Read the policy into a byte buffer.
  358. byte[] bufferPolicy = Encoding.ASCII.GetBytes(strPolicy);
  359. // Base64 encode URL-safe policy statement.
  360. //string urlSafePolicy = ToUrlSafeBase64String(bufferPolicy);
  361. // Initialize the SHA1CryptoServiceProvider object and hash the policy data.
  362. byte[] bufferPolicyHash;
  363. using (SHA1CryptoServiceProvider cryptoSHA1 = new SHA1CryptoServiceProvider())
  364. {
  365. bufferPolicyHash = cryptoSHA1.ComputeHash(bufferPolicy);
  366. // Initialize the RSACryptoServiceProvider object.
  367. RSACryptoServiceProvider providerRSA = new RSACryptoServiceProvider();
  368. XmlDocument xmlPrivateKey = new XmlDocument();
  369. // Load the PrivateKey.xml file generated by ConvertPEMtoXML.
  370. xmlPrivateKey.Load(_configuration["rsaPrivateKeyXml"]);
  371. // Format the RSACryptoServiceProvider providerRSA and create the signature.
  372. providerRSA.FromXmlString(xmlPrivateKey.InnerXml);
  373. RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(
  374. providerRSA
  375. );
  376. RSAFormatter.SetHashAlgorithm("SHA1");
  377. byte[] signedHash = RSAFormatter.CreateSignature(bufferPolicyHash);
  378. // Convert the signed policy to URL safe base 64 encoding.
  379. string strSignedPolicy = ToUrlSafeBase64String(signedHash);
  380. return urlString + "&signature=" + strSignedPolicy;
  381. }
  382. }
  383. public static string ToUrlSafeBase64String(byte[] bytes)
  384. {
  385. return System.Convert.ToBase64String(bytes);
  386. //.Replace('+', '-')
  387. //.Replace('=', '_')
  388. //.Replace('/', '~');
  389. }
  390. public static string CreatePolicyStatement(
  391. string policyStmnt,
  392. string resourceUrl,
  393. DateTime startTime,
  394. DateTime endTime
  395. )
  396. {
  397. // Create the policy statement.
  398. FileStream streamPolicy = new FileStream(policyStmnt, FileMode.Open, FileAccess.Read);
  399. using (StreamReader reader = new StreamReader(streamPolicy))
  400. {
  401. string strPolicy = reader.ReadToEnd();
  402. TimeSpan startTimeSpanFromNow = (startTime - DateTime.Now);
  403. TimeSpan endTimeSpanFromNow = (endTime - DateTime.Now);
  404. TimeSpan intervalStart =
  405. (DateTime.UtcNow.Add(startTimeSpanFromNow))
  406. - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  407. TimeSpan intervalEnd =
  408. (DateTime.UtcNow.Add(endTimeSpanFromNow))
  409. - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  410. int startTimestamp = (int)intervalStart.TotalSeconds; // START_TIME
  411. int endTimestamp = (int)intervalEnd.TotalSeconds; // END_TIME
  412. if (startTimestamp > endTimestamp)
  413. return "Error!";
  414. // Replace variables in the policy statement.
  415. strPolicy = strPolicy.Replace("RESOURCE", resourceUrl);
  416. //strPolicy = strPolicy.Replace("START_TIME", startTimestamp.ToString());
  417. //strPolicy = strPolicy.Replace("END_TIME", endTimestamp.ToString());
  418. //strPolicy = strPolicy.Replace("EXPIRES", endTimestamp.ToString());
  419. return resourceUrl;
  420. }
  421. }
  422. public static TimeSpan GetDuration(string units, string numUnits)
  423. {
  424. TimeSpan timeSpanInterval = new TimeSpan();
  425. switch (units)
  426. {
  427. case "seconds":
  428. timeSpanInterval = new TimeSpan(0, 0, 0, int.Parse(numUnits));
  429. break;
  430. case "minutes":
  431. timeSpanInterval = new TimeSpan(0, 0, int.Parse(numUnits), 0);
  432. break;
  433. case "hours":
  434. timeSpanInterval = new TimeSpan(0, int.Parse(numUnits), 0, 0);
  435. break;
  436. case "days":
  437. timeSpanInterval = new TimeSpan(int.Parse(numUnits), 0, 0, 0);
  438. break;
  439. default:
  440. Console.WriteLine("Invalid time units; use seconds, minutes, hours, or days");
  441. break;
  442. }
  443. return timeSpanInterval;
  444. }
  445. private static TimeSpan GetDurationByUnits(
  446. string durationUnits,
  447. string startIntervalFromNow
  448. )
  449. {
  450. TimeSpan timeSpanInterval = new TimeSpan();
  451. switch (durationUnits)
  452. {
  453. case "seconds":
  454. timeSpanInterval = new TimeSpan(0, 0, int.Parse(startIntervalFromNow));
  455. break;
  456. case "minutes":
  457. timeSpanInterval = new TimeSpan(0, int.Parse(startIntervalFromNow), 0);
  458. break;
  459. case "hours":
  460. timeSpanInterval = new TimeSpan(int.Parse(startIntervalFromNow), 0, 0);
  461. break;
  462. case "days":
  463. timeSpanInterval = new TimeSpan(int.Parse(startIntervalFromNow), 0, 0, 0);
  464. break;
  465. default:
  466. timeSpanInterval = new TimeSpan(0, 0, 0, 0);
  467. break;
  468. }
  469. return timeSpanInterval;
  470. }
  471. public static string ConvertDrawnTimeFromTerm(string type, TermObj termObj)
  472. {
  473. string drawnTime = DateTime
  474. .ParseExact(termObj.randomDate, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture)
  475. .ToString("HH:mm");
  476. string endTime = DateTime
  477. .ParseExact(termObj.endDate, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture)
  478. .ToString("HH:mm");
  479. return drawnTime;
  480. }
  481. public static string ConvertDrawnTimeFromTicket(string type, Ticket ticket)
  482. {
  483. string drawnTime = DateTime
  484. .ParseExact(
  485. ticket.termRandomDate,
  486. "dd/MM/yyyy HH:mm:ss",
  487. CultureInfo.InvariantCulture
  488. )
  489. .ToString("HH:mm");
  490. string endTime = DateTime
  491. .ParseExact(ticket.termEndDate, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture)
  492. .ToString("HH:mm");
  493. return drawnTime;
  494. }
  495. }
  496. }