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 = "509"; if (input == null || input.Length == 0 || !long.TryParse(input, out long temp)) { return ""; } else if ( ( ( input.StartsWith("32") || input.StartsWith("33") || input.StartsWith("35") || input.StartsWith("40") || input.StartsWith("41") || input.StartsWith("42") || input.StartsWith("55") || input.StartsWith("43") || input.StartsWith("44") || input.StartsWith("45") ) && input.Length == 8 ) ) { // 066200017 55797979 input = CountryCode + input; return input.Trim(); } else if (input.StartsWith(CountryCode) && input.Length == 11) { String removeCountry = input.Substring(3); if ((removeCountry.StartsWith("32") || removeCountry.StartsWith("33") || removeCountry.StartsWith("35") || removeCountry.StartsWith("40") || removeCountry.StartsWith("41") || removeCountry.StartsWith("55") || removeCountry.StartsWith("42") || removeCountry.StartsWith("43") || removeCountry.StartsWith("44") || removeCountry.StartsWith("45"))) { removeCountry = CountryCode + removeCountry; return input.Trim(); } else { return ""; } } else return ""; } public string ConvertToGameID(string termType, string ticketType) { if (termType == Constants.BOULCHANS_CODE) { return Constants.BOULCHANS_CODE; } else if ( termType == Constants.NEW_YORK_BOLET_CODE || termType == Constants.NEW_YORK_MAYRAJ_CODE || termType == Constants.NEW_YORK_LOTTO3_CODE ) { switch (ticketType) { case Constants.BOLET_CODE: return Constants.NEW_YORK_BOLET_CODE; case Constants.MAYRAJ_CODE: return Constants.NEW_YORK_MAYRAJ_CODE; default: return Constants.NEW_YORK_LOTTO3_CODE; } } else { switch (ticketType) { case Constants.BOLET_CODE: return Constants.FLORIDA_BOLET_CODE; case Constants.MAYRAJ_CODE: return Constants.FLORIDA_MAYRAJ_CODE; default: return Constants.FLORIDA_LOTTO3_CODE; } } } public string ConvertToListGameID(String gameIDCode) { switch (gameIDCode) { case Constants.NEW_YORK_BOLET_CODE: return Constants.NEW_YORK_BOLET_CODE + "," + Constants.FLORIDA_BOLET_CODE; case Constants.NEW_YORK_MAYRAJ_CODE: return Constants.NEW_YORK_MAYRAJ_CODE + "," + Constants.FLORIDA_MAYRAJ_CODE; case Constants.BOULCHANS_CODE: return Constants.BOULCHANS_CODE; default: return Constants.NEW_YORK_LOTTO3_CODE + "," + Constants.FLORIDA_LOTTO3_CODE; } } 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.drawn; } } public static string ConvertGameIdToTerm(string gameId) { switch (gameId) { case Constants.NEW_YORK_BOLET_CODE: return Lang.new_york_lottery; case Constants.NEW_YORK_MAYRAJ_CODE: return Lang.new_york_lottery; case Constants.NEW_YORK_LOTTO3_CODE: return Lang.new_york_lottery; case Constants.FLORIDA_BOLET_CODE: return Lang.florida_lottery; case Constants.FLORIDA_MAYRAJ_CODE: return Lang.florida_lottery; case Constants.FLORIDA_LOTTO3_CODE: return Lang.florida_lottery; case Constants.BOULCHANS_CODE: return "BOULCHANS"; default: return Lang.new_york_lottery; } } public static string ConvertGameIdToName(string gameId) { switch (gameId) { case Constants.NEW_YORK_BOLET_CODE: return Lang.bolet; case Constants.NEW_YORK_MAYRAJ_CODE: return Lang.maryaj; case Constants.NEW_YORK_LOTTO3_CODE: return Lang.lotto3; case Constants.FLORIDA_BOLET_CODE: return Lang.bolet; case Constants.FLORIDA_MAYRAJ_CODE: return Lang.maryaj; case Constants.FLORIDA_LOTTO3_CODE: return Lang.lotto3; case Constants.BOULCHANS_CODE: return "BOULCHANS"; default: return Lang.new_york_lottery; } } 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 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"); switch (type) { case Constants.NEW_YORK_BOLET_CODE: return drawnTime; case Constants.NEW_YORK_MAYRAJ_CODE: return drawnTime; case Constants.NEW_YORK_LOTTO3_CODE: return drawnTime; case Constants.FLORIDA_BOLET_CODE: return drawnTime; case Constants.FLORIDA_MAYRAJ_CODE: return drawnTime; case Constants.FLORIDA_LOTTO3_CODE: return drawnTime; case Constants.BOULCHANS_CODE: return endTime; default: return Lang.new_york_lottery; } } 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"); switch (type) { case Constants.NEW_YORK_BOLET_CODE: return drawnTime; case Constants.NEW_YORK_MAYRAJ_CODE: return drawnTime; case Constants.NEW_YORK_LOTTO3_CODE: return drawnTime; case Constants.FLORIDA_BOLET_CODE: return drawnTime; case Constants.FLORIDA_MAYRAJ_CODE: return drawnTime; case Constants.FLORIDA_LOTTO3_CODE: return drawnTime; case Constants.BOULCHANS_CODE: return endTime; default: return Lang.new_york_lottery; } } } }