| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545 |
- using System;
- using System.Globalization;
- using System.IO;
- using System.Net.Http;
- using System.Security.Cryptography;
- using System.Text;
- using System.Threading.Tasks;
- using System.Xml;
- using log4net;
- using LotteryWebApp.Common;
- using LotteryWebApp.Languages;
- using LotteryWebApp.Service;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using NcGamesWebView.Extensions;
- namespace LotteryWebApp.Controllers
- {
- public class BaseController : Controller
- {
- private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
- public static string[] formats =
- {
- "M/d/yyyy h:mm:ss tt",
- "M/d/yyyy h:mm tt",
- "MM/dd/yyyy hh:mm:ss",
- "M/d/yyyy h:mm:ss",
- "M/d/yyyy hh:mm tt",
- "M/d/yyyy hh tt",
- "M/d/yyyy h:mm",
- "M/d/yyyy h:mm",
- "MM/dd/yyyy hh:mm",
- "M/dd/yyyy hh:mm",
- "MM/d/yyyy HH:mm:ss.ffffff, dd/MM/yyyy hh:mm",
- "M/dd/yyyy h:mm:ss tt",
- "dd/MM/yyyy HH:mm:ss"
- };
- public static string RandomString(int size, bool lowerCase)
- {
- StringBuilder builder = new StringBuilder();
- Random random = new Random();
- char ch;
- for (int i = 0; i < size; i++)
- {
- ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
- builder.Append(ch);
- }
- if (lowerCase)
- return builder.ToString().ToLower();
- return builder.ToString();
- }
- // validate phone number
- public static String validateMsisdn(String input)
- {
- String CountryCode = Constants.COUNTRY_CODE;
- if (input == null || input.Length == 0 || !long.TryParse(input, out long temp))
- {
- return "";
- }
- if (input.StartsWith("0"))
- {
- input = input.Substring(1);
- }
- if (input.StartsWith(CountryCode))
- {
- input = input.Substring(CountryCode.Length);
- }
- if (input.Length >= 7 && input.Length <= 8)
- {
- input = CountryCode + input;
- return input.Trim();
- }
- else
- {
- return "";
- }
- }
- public string ConvertToGameID(string termType, string ticketType)
- {
- if (termType == Constants.GameGroup.Singapore)
- {
- switch (ticketType)
- {
- case Constants.TicketType._4D:
- return Constants.GameId.Direct4D;
- case Constants.TicketType._3D:
- return Constants.GameId.Direct3D;
- default:
- return Constants.GameId.Direct2D;
- }
- }
- return Constants.GameId.Direct4D;
- }
- public string ConvertToListGameID(String gameIDCode)
- {
- switch (gameIDCode)
- {
- case Constants.GameId.Direct4D:
- return Constants.GameId.Direct4D + "," + Constants.GameId.Ibet4D;
- case Constants.GameId.Direct3D:
- return Constants.GameId.Direct3D + "," + Constants.GameId.Ibet3D;
- default:
- return Constants.GameId.Direct2D + "," + Constants.GameId.Ibet2D;
- }
- }
- public static string ConvertToWinType(String winType)
- {
- switch (winType)
- {
- case Constants.NOT_DRAW_CODE:
- return Lang.not_draw;
- case Constants.WIN_CODE:
- return Lang.win;
- default:
- return Lang.not_win;
- }
- }
- public static string ConvertGameIdToTerm(string gameId)
- {
- switch (gameId)
- {
- case Constants.GameId.Direct4D:
- return "Singapore";
- case Constants.GameId.Direct3D:
- return "Singapore";
- case Constants.GameId.Direct2D:
- return "Singapore";
- default:
- return "Singapore";
- }
- }
- public static string ConvertGameIdToPlayType(string gameId)
- {
- switch (gameId)
- {
- case Constants.GameId.Direct4D:
- return "Direct";
- case Constants.GameId.Direct3D:
- return "Direct";
- case Constants.GameId.Direct2D:
- return "Direct";
- default:
- return "IBet";
- }
- }
- public static string ConvertGameIdToName(string gameId)
- {
- switch (gameId)
- {
- case Constants.GameId.Direct4D:
- return "4D Direct";
- case Constants.GameId.Direct3D:
- return "3D Direct";
- case Constants.GameId.Direct2D:
- return "2D Direct";
- default:
- return "4D";
- }
- }
- public static string GetLangFromCode(string code)
- {
- switch (code)
- {
- case "1":
- return Lang.login_fail_wrong_pass;
- case "0":
- return Lang.success;
- case "-1":
- return Lang.error_happened;
- case "-2":
- return Lang.system_update;
- case "2":
- return Lang.term_timeout;
- case "3":
- return Lang.ticket_invalid;
- case "7":
- return "User was locked";
- case "9":
- return Lang.reset_after_1_minute;
- case "4":
- return Lang.params_invalid;
- case "20":
- return Lang.wallet_not_existed;
- case "21":
- return Lang.wallet_not_active;
- case "22":
- return Lang.younger_to_use;
- case "23":
- return Lang.account_not_existed;
- case "24":
- return Lang.internet_error;
- case "25":
- return Lang.pin_wrong;
- case "26":
- return Lang.in_blacklist;
- case "30":
- return Lang.otp_timeout;
- case "31":
- return Lang.otp_invalid;
- case "100":
- return Lang.no_permission;
- case "32":
- return Lang.not_enough_money_to_exchange;
- case "33":
- return Lang.over_each_exchange;
- case "34":
- return Lang.over_exchange_per_day;
- case "38":
- return Lang.promotion_code_invalid;
- case "39":
- return Lang.promotion_code_used;
- case "40":
- return Lang.promotion_code_inactive;
- case "41":
- return Lang.buying_code_not_existed;
- default:
- return code + " " + Lang.not_defined;
- }
- }
- public static string ConvertWalletTicket(string type)
- {
- switch (type)
- {
- case Constants.BASIC_WALLET_TICKET:
- return Lang.basic_account;
- default:
- return Lang.NatCash;
- }
- }
- // dateTime : MM/dd/yyyy
- public static long getCountTimeToTimestamp(string time)
- {
- // convert to Datetime
- DateTime endTime = DateTime.ParseExact(
- time,
- formats,
- new CultureInfo("en-US"),
- DateTimeStyles.None
- );
- TimeSpan elapsedTime = endTime - DateTime.Now;
- return (long)elapsedTime.TotalSeconds;
- }
- protected void CreateAuthToken()
- {
- // create session authen
- // Create the random value we will use to secure the session.
- string authId = GenerateAuthId();
- // Store the value in both our Session and a Cookie.
- HttpContext.Session.SetString("AuthorizationCookieId", authId);
- string sessionValue = HttpContext.Session.GetString("AuthorizationCookieId");
- //CookieOptions option = new CookieOptions
- //{
- // Expires = DateTime.Now.AddMinutes(1)
- //};
- //Response.Cookies.Append("Key Name", "Value", option);
- CookieOptions options = new CookieOptions()
- {
- //Path = "/",
- //HttpOnly = true,
- //Secure = false,
- //SameSite = SameSiteMode.None
- Expires = DateTime.Now.AddMinutes(60)
- };
- HttpContext.Response.Cookies.Append("AuthorizationCookie", authId, options);
- string cookieValue = HttpContext.Request.Cookies["AuthorizationCookie"];
- }
- protected bool CheckAuthToken()
- {
- //return true;
- string cookieValue = HttpContext.Request.Cookies["AuthorizationCookie"];
- string sessionValue = HttpContext.Session.GetString("AuthorizationCookieId");
- if (cookieValue == null || sessionValue == null || cookieValue != sessionValue)
- {
- // Invalidate the session and log out the current user.
- return false;
- //return true;
- }
- //if (sessionValue == null)
- //{
- // // Invalidate the session and log out the current user.
- // return false;
- //}
- else
- {
- return true;
- }
- }
- protected bool ClearCache()
- {
- HttpContext.Session.Clear();
- foreach (var cookieKey in HttpContext.Request.Cookies.Keys)
- {
- HttpContext.Response.Cookies.Delete(cookieKey);
- }
- return true;
- }
- private string GenerateAuthId()
- {
- using (RandomNumberGenerator rng = new RNGCryptoServiceProvider())
- {
- byte[] tokenData = new byte[32];
- rng.GetBytes(tokenData);
- return Convert.ToBase64String(tokenData);
- }
- }
- protected String DecryptRSA(IConfiguration _configuration, String data)
- {
- RSACryptoServiceProvider rsaPrivate = new RSACryptoServiceProvider();
- rsaPrivate.FromXmlFile(
- Path.Combine(
- Directory.GetCurrentDirectory(),
- "",
- _configuration["rsaPrivateKeyXml"]
- )
- );
- byte[] byteEntry = Convert.FromBase64String(data);
- byte[] byteText = rsaPrivate.Decrypt(byteEntry, false);
- return Encoding.UTF8.GetString(byteText);
- }
- protected async Task<string> CheckAutoLogin(ILog log, String uuid)
- {
- string res = null;
- try
- {
- HttpClient httpClient = new HttpClient();
- MultipartFormDataContent form = new MultipartFormDataContent();
- form.Add(new StringContent(uuid), "uuid");
- HttpResponseMessage response = await httpClient.PostAsync(
- Constants.URL_GET_MSISDN,
- form
- );
- response.EnsureSuccessStatusCode();
- httpClient.Dispose();
- res = response.Content.ReadAsStringAsync().Result;
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- log.Debug("Exp: " + ex);
- }
- return res;
- }
- public static string CreatePrivateURL(
- IConfiguration _configuration,
- string urlString,
- string durationUnits,
- string durationNumber,
- string startIntervalFromNow,
- string pathToPolicyStmnt
- )
- {
- TimeSpan timeSpanInterval = GetDuration(durationUnits, durationNumber);
- TimeSpan timeSpanToStart = GetDurationByUnits(durationUnits, startIntervalFromNow);
- if (null == timeSpanToStart)
- return "Invalid duration units. Valid options: seconds, minutes, hours, or days";
- string strPolicy = urlString;
- // Read the policy into a byte buffer.
- byte[] bufferPolicy = Encoding.ASCII.GetBytes(strPolicy);
- // Base64 encode URL-safe policy statement.
- //string urlSafePolicy = ToUrlSafeBase64String(bufferPolicy);
- // Initialize the SHA1CryptoServiceProvider object and hash the policy data.
- byte[] bufferPolicyHash;
- using (SHA1CryptoServiceProvider cryptoSHA1 = new SHA1CryptoServiceProvider())
- {
- bufferPolicyHash = cryptoSHA1.ComputeHash(bufferPolicy);
- // Initialize the RSACryptoServiceProvider object.
- RSACryptoServiceProvider providerRSA = new RSACryptoServiceProvider();
- XmlDocument xmlPrivateKey = new XmlDocument();
- // Load the PrivateKey.xml file generated by ConvertPEMtoXML.
- xmlPrivateKey.Load(_configuration["rsaPrivateKeyXml"]);
- // Format the RSACryptoServiceProvider providerRSA and create the signature.
- providerRSA.FromXmlString(xmlPrivateKey.InnerXml);
- RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(
- providerRSA
- );
- RSAFormatter.SetHashAlgorithm("SHA1");
- byte[] signedHash = RSAFormatter.CreateSignature(bufferPolicyHash);
- // Convert the signed policy to URL safe base 64 encoding.
- string strSignedPolicy = ToUrlSafeBase64String(signedHash);
- return urlString + "&signature=" + strSignedPolicy;
- }
- }
- public static string ToUrlSafeBase64String(byte[] bytes)
- {
- return System.Convert.ToBase64String(bytes);
- //.Replace('+', '-')
- //.Replace('=', '_')
- //.Replace('/', '~');
- }
- public static string CreatePolicyStatement(
- string policyStmnt,
- string resourceUrl,
- DateTime startTime,
- DateTime endTime
- )
- {
- // Create the policy statement.
- FileStream streamPolicy = new FileStream(policyStmnt, FileMode.Open, FileAccess.Read);
- using (StreamReader reader = new StreamReader(streamPolicy))
- {
- string strPolicy = reader.ReadToEnd();
- TimeSpan startTimeSpanFromNow = (startTime - DateTime.Now);
- TimeSpan endTimeSpanFromNow = (endTime - DateTime.Now);
- TimeSpan intervalStart =
- (DateTime.UtcNow.Add(startTimeSpanFromNow))
- - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
- TimeSpan intervalEnd =
- (DateTime.UtcNow.Add(endTimeSpanFromNow))
- - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
- int startTimestamp = (int)intervalStart.TotalSeconds; // START_TIME
- int endTimestamp = (int)intervalEnd.TotalSeconds; // END_TIME
- if (startTimestamp > endTimestamp)
- return "Error!";
- // Replace variables in the policy statement.
- strPolicy = strPolicy.Replace("RESOURCE", resourceUrl);
- //strPolicy = strPolicy.Replace("START_TIME", startTimestamp.ToString());
- //strPolicy = strPolicy.Replace("END_TIME", endTimestamp.ToString());
- //strPolicy = strPolicy.Replace("EXPIRES", endTimestamp.ToString());
- return resourceUrl;
- }
- }
- public static TimeSpan GetDuration(string units, string numUnits)
- {
- TimeSpan timeSpanInterval = new TimeSpan();
- switch (units)
- {
- case "seconds":
- timeSpanInterval = new TimeSpan(0, 0, 0, int.Parse(numUnits));
- break;
- case "minutes":
- timeSpanInterval = new TimeSpan(0, 0, int.Parse(numUnits), 0);
- break;
- case "hours":
- timeSpanInterval = new TimeSpan(0, int.Parse(numUnits), 0, 0);
- break;
- case "days":
- timeSpanInterval = new TimeSpan(int.Parse(numUnits), 0, 0, 0);
- break;
- default:
- Console.WriteLine("Invalid time units; use seconds, minutes, hours, or days");
- break;
- }
- return timeSpanInterval;
- }
- private static TimeSpan GetDurationByUnits(
- string durationUnits,
- string startIntervalFromNow
- )
- {
- TimeSpan timeSpanInterval = new TimeSpan();
- switch (durationUnits)
- {
- case "seconds":
- timeSpanInterval = new TimeSpan(0, 0, int.Parse(startIntervalFromNow));
- break;
- case "minutes":
- timeSpanInterval = new TimeSpan(0, int.Parse(startIntervalFromNow), 0);
- break;
- case "hours":
- timeSpanInterval = new TimeSpan(int.Parse(startIntervalFromNow), 0, 0);
- break;
- case "days":
- timeSpanInterval = new TimeSpan(int.Parse(startIntervalFromNow), 0, 0, 0);
- break;
- default:
- timeSpanInterval = new TimeSpan(0, 0, 0, 0);
- break;
- }
- return timeSpanInterval;
- }
- public static string ConvertDrawnTimeFromTerm(string type, TermObj termObj)
- {
- string drawnTime = DateTime
- .ParseExact(termObj.randomDate, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture)
- .ToString("HH:mm");
- string endTime = DateTime
- .ParseExact(termObj.endDate, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture)
- .ToString("HH:mm");
- return drawnTime;
- }
- public static string ConvertDrawnTimeFromTicket(string type, Ticket ticket)
- {
- string drawnTime = DateTime
- .ParseExact(
- ticket.termRandomDate,
- "dd/MM/yyyy HH:mm:ss",
- CultureInfo.InvariantCulture
- )
- .ToString("HH:mm");
- string endTime = DateTime
- .ParseExact(ticket.termEndDate, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture)
- .ToString("HH:mm");
- return drawnTime;
- }
- }
- }
|