using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Security.Cryptography; using System.ServiceModel; using System.Text; using log4net; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using WebPortal.Extensions; using WebPortal.Models; using WebService; namespace WebPortal.Controllers { public class BaseController : Controller { private readonly ILog log = LogManager.GetLogger(typeof(BaseController)); private readonly IWebHostEnvironment webHostEnvironment; protected IConfiguration configuration; public static String CountryCode = ""; public static int numWs = 0; //public static String FacebookAppId = ""; //public static String FacebookShareHref = ""; public static String channel = ""; public static String serviceId = ""; public static String RootHref = ""; public static String wsUser = ""; public static String wsPassword = ""; public static String wsUrl1 = ""; public static String wsLoginFail1 = ""; public static String wsSubUser = ""; public static String wsSubPassword = ""; public static int coin1Spin = 5; public static int testMode = 0; public static String wsLoad = ""; public static int enableCounter = 0; // Top no public static String TopNo0 = ""; public static String TopNo1 = ""; public static String TopNoUrl = ""; private Random ran = new Random(); private WsWebPortalClient wsClient = new WsWebPortalClient(); private static readonly object syncLock = new object(); private static readonly object syncCounter = new object(); public static List listMsisdn = new List(); public static DateTime? lastReload = null; public static int reloadPeriod = 120; //public static String CountryCode = ConfigurationManager.AppSettings["countryCode"]; //public static int numWs = int.Parse(ConfigurationManager.AppSettings["numWs"]); //public static String FacebookAppId = ConfigurationManager.AppSettings["FacebookAppId"]; //public static String channel = ConfigurationManager.AppSettings["channel"]; //public static String serviceId = ConfigurationManager.AppSettings["serviceId"]; public static String CaptchaSiteKey;// = ConfigurationManager.AppSettings["recaptchaPublicKey"]; public static String CaptchaSecretKey;// = ConfigurationManager.AppSettings["recaptchaPrivateKey"]; public BaseController() { } public BaseController(IConfiguration _configuration, IWebHostEnvironment hostEnvironment) { configuration = _configuration; webHostEnvironment = hostEnvironment; // load config CountryCode = configuration["countryCode"]; numWs = int.Parse(configuration["numWs"]); try { enableCounter = int.Parse(configuration["enableCounter"]); } catch { enableCounter = 0; } //FacebookAppId = configuration["FacebookAppId"]; //FacebookShareHref = configuration["FacebookShareHref"]; channel = configuration["channel"]; serviceId = configuration["serviceId"]; wsUser = configuration["wsUser"]; wsPassword = configuration["wsPassword"]; wsUrl1 = configuration["wsUrl1"]; wsLoginFail1 = configuration["wsLoginFail1"]; //RootHref = configuration["RootHref"]; //coin1Spin = int.Parse(configuration["coin1Spin"]); testMode = int.Parse(configuration["testMode"]); CaptchaSiteKey = configuration["recaptchaPublicKey"]; CaptchaSecretKey = configuration["recaptchaPrivateKey"]; wsSubUser = configuration["wsSubUser"]; wsSubPassword = configuration["wsSubPassword"]; wsLoad = configuration["wsUrl1"]; reloadPeriod = int.Parse(configuration["reloadPeriod"]); // TopNo0 = configuration["TopNo0"]; TopNo1 = configuration["TopNo1"]; TopNoUrl = configuration["TopNoUrl"]; } private static productObj[] hotPromotion; public static productObj[] GetHotPromotion() { if (hotPromotion != null) { return hotPromotion; } WsWebPortalClient wsClient = new WsWebPortalClient(); wsClient.Endpoint.Address = new EndpointAddress(wsLoad); string lang = CultureInfo.CurrentCulture.Name.ToUpper() == "EN" ? "1" : "0"; wsLoadProductRequest wsRequest = new wsLoadProductRequest( BaseController.wsUser, BaseController.wsPassword, null, null, "1", "3", "2", "1", null, lang); var wsResponse = wsClient.wsLoadProduct(wsRequest); hotPromotion = wsResponse.@return.listProduct; return hotPromotion; } protected void LoadBanner(WsWebPortalClient wsClient, String type, String status) { ViewBag.productType = type; // load banner SetWsClient(ref wsClient); wsLoadBannerByCodeRequest wsRequest = new wsLoadBannerByCodeRequest( BaseController.wsUser, BaseController.wsPassword, "BANNER_" + type, "1", "12", status, DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"), DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"), getCurrentLang()); var wsResponse = wsClient.wsLoadBannerByCode(wsRequest); if (wsResponse.@return.listBanner != null) { HttpContext.Session.SetComplexData("listBanner", wsResponse.@return.listBanner); } } public String GetParameter(String key) { return configuration.GetSection(key).Value; } public String GetParameter(String parentKey, String key) { var configs = configuration.GetSection(parentKey).GetChildren(); foreach (IConfiguration config in configs) { if (config[key] != null) { return config[key]; } } return ""; } public 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(); } protected string convertToDateTimeServer(String date) { // date: DateTime oDateFrom = DateTime.Parse(date); string hour = oDateFrom.Hour < 10 ? "0" + oDateFrom.Hour : oDateFrom.Hour.ToString(); string minute = oDateFrom.Minute < 10 ? "0" + oDateFrom.Minute : oDateFrom.Minute.ToString(); string second = oDateFrom.Second < 10 ? "0" + oDateFrom.Second : oDateFrom.Second.ToString(); string month = oDateFrom.Month < 10 ? "0" + oDateFrom.Month : oDateFrom.Month.ToString(); string day = oDateFrom.Day < 10 ? "0" + oDateFrom.Day : oDateFrom.Day.ToString(); string fromCheck = day + "/" + month + "/" + oDateFrom.Year + " " + hour + ":" + minute + ":" + second; return fromCheck; //MM/dd/yyyy HH24:mm:ss } protected void CreateAuthToken(String account, Object userObj) { // 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"]; HttpContext.Session.SetString("account", account); HttpContext.Session.SetComplexData("userInfo", userObj); } 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); } } public void SetWsClient(ref WsWebPortalClient wsClient, String sessionId) { int lastNum = sessionId[sessionId.Length - 1]; int wsId = lastNum % numWs + 1; wsClient.Endpoint.Address = new EndpointAddress(configuration["wsUrl" + wsId]); } public void SetWsClient(ref WsWebPortalClient wsClient) { int wsId = ran.Next(1, numWs); wsClient.Endpoint.Address = new EndpointAddress(configuration["wsUrl" + wsId]); } public String validateMsisdn(String input) { if (input == null || input.Length == 0) { return ""; } // check is number try { input = long.Parse(input) + ""; } catch { return ""; } // if (input.StartsWith("0")) { input = CountryCode + input.Substring(1); } else if (!input.StartsWith(CountryCode)) { input = CountryCode + input; } if (!input.StartsWith(CountryCode + "75") && !input.StartsWith(CountryCode + "76")) { return ""; } if (input.Length != 11) { return ""; } return input.Trim(); } public static String getCurrentLang() { if (CultureInfo.CurrentCulture.Name.ToUpper() == "EN") { return "1"; } return "0"; } public String getCurrentLangTxt() { if (CultureInfo.CurrentCulture.Name.ToUpper() == "EN") { return "en"; } return "te"; } public class WsType { //public const String MochaMsisdn = "urlMochaMsisdn"; //public const String LaoAppLogin = "laoAppUrlLogin"; //public const String LaoAppVerify = "laoAppUrlVerify"; //public const String LaoAppFind = "laoAppUrlFind"; public const String wsLoadVoucher = "wsLoadVoucher"; public const String wsGetLoyaltyInfo = "wsGetLoyaltyInfo"; } private String GetWsClient(String type) { return configuration[type]; } public String SendPost(log4net.ILog log, Object obj, String type) { StringBuilder sb = new StringBuilder(); sb.Append("Send post " + type + ": ").Append("\n"); sb.Append("\tRequest:" + JsonConvert.SerializeObject(obj)).Append("\n"); String result = SendPost(obj, type); sb.Append("\tResponse:" + result); log.Info(sb); return result; } public String SendPost(Object obj, String type) { var json = JsonConvert.SerializeObject(obj); var data = new StringContent(json, Encoding.UTF8, "application/json"); var url = GetWsClient(type); using (var client = new HttpClient()) { var response = client.PostAsync(url, data).Result; if (response.IsSuccessStatusCode) { var responseContent = response.Content; // by calling .Result you are synchronously reading the result string responseString = responseContent.ReadAsStringAsync().Result; return responseString; } else { try { var responseContent = response.Content; string responseString = responseContent.ReadAsStringAsync().Result; return responseString; } catch { return response.StatusCode.ToString(); } } } } public String SendPostParam(log4net.ILog log, Object obj, String type) { StringBuilder sb = new StringBuilder(); sb.Append("Send post param " + type + ": ").Append("\n"); sb.Append("\tRequest:" + JsonConvert.SerializeObject(obj)).Append("\n"); String result = SendPostParam(obj, type); sb.Append("\tResponse:" + result); log.Info(sb); return result; } public String SendPostParam(Object obj, String type) { //var json = JsonConvert.SerializeObject(obj); //var data = new StringContent(json, Encoding.UTF8, "application/json"); var url = GetWsClient(type) + AppendUrlParam(obj); using (var client = new HttpClient()) { var response = client.PostAsync(url, null).Result; if (response.IsSuccessStatusCode) { var responseContent = response.Content; // by calling .Result you are synchronously reading the result string responseString = responseContent.ReadAsStringAsync().Result; return responseString; } else { try { var responseContent = response.Content; string responseString = responseContent.ReadAsStringAsync().Result; return responseString; } catch { return response.StatusCode.ToString(); } } } } public String SendGetHeader(ILog log, Object obj, Dictionary headers, String type) { StringBuilder sb = new StringBuilder(); sb.Append("Send get " + type + ": ").Append("\n"); sb.Append("\tRequest:" + JsonConvert.SerializeObject(obj)).Append("\n"); sb.Append("\tHeaders:").Append("\n"); foreach (var key in headers.Keys) { sb.Append(key + "=" + headers[key] + "\n"); } String result = SendGetHeader(obj, headers, type); sb.Append("\tResponse:" + result); log.Info(sb); return result; } public String SendGetHeader(Object obj, Dictionary headers, String type) { //var json = JsonConvert.SerializeObject(obj); var url = GetWsClient(type) + AppendUrlParam(obj); using (var client = new HttpClient()) { if (headers != null) { foreach (String key in headers.Keys) { client.DefaultRequestHeaders.Add(key, headers[key]); } } var response = client.GetAsync(url).Result; if (response.IsSuccessStatusCode) { var responseContent = response.Content; // by calling .Result you are synchronously reading the result string responseString = responseContent.ReadAsStringAsync().Result; return responseString; } else { try { var responseContent = response.Content; string responseString = responseContent.ReadAsStringAsync().Result; return responseString; } catch { return response.StatusCode.ToString(); } } } } public String SendPostHeader(ILog log, Object obj, Dictionary headers, String type) { StringBuilder sb = new StringBuilder(); sb.Append("Send post header " + type + ": ").Append("\n"); sb.Append("\tRequest:" + JsonConvert.SerializeObject(obj)).Append("\n"); sb.Append("\tHeaders:").Append("\n"); foreach (var key in headers.Keys) { sb.Append(key + "=" + headers[key] + "\n"); } String result = SendPostHeader(obj, headers, type); sb.Append("\tResponse:" + result); log.Info(sb); return result; } public String SendPostHeader(Object obj, Dictionary headers, String type) { var json = JsonConvert.SerializeObject(obj); var data = new StringContent(json, Encoding.UTF8, "application/json"); var url = GetWsClient(type); using (var client = new HttpClient()) { foreach (String key in headers.Keys) { client.DefaultRequestHeaders.Add(key, headers[key]); } var response = client.PostAsync(url, data).Result; if (response.IsSuccessStatusCode) { var responseContent = response.Content; // by calling .Result you are synchronously reading the result string responseString = responseContent.ReadAsStringAsync().Result; return responseString; } else { try { var responseContent = response.Content; string responseString = responseContent.ReadAsStringAsync().Result; return responseString; } catch { return response.StatusCode.ToString(); } } } } public String AppendUrlParam(Object obj) { Type type = obj.GetType(); String append = "?"; foreach (var f in type.GetProperties()) { append += f.Name + "=" + f.GetValue(obj) + "&"; } return append.Substring(0, append.Length - 1); } public String DetectMsisdn() { string msisdn = null; // get header //foreach (var header in Request.Headers) //{ // if (header.Key.Trim().ToUpper() == "X-UP-CALLING-LINE-ID") // { // msisdn = header.Value; // log.Info("MSISDN: " + msisdn); // return msisdn; // } //} if (msisdn == null) { msisdn = Request.Query["isdn"]; } ViewBag.msisdn = msisdn; return msisdn; } public String DetectMsisdn(WsWebPortalClient wsClient) { string ipAddress = ""; string msisdn = null; // get header log.Info("Header:"); foreach (var header in Request.Headers) { log.Info(header.Key + "=" + header.Value); if (header.Key.Trim().ToUpper() == "X-FORWARDED-FOR") { //10.234.94.250 , 103.238.116.58 ipAddress = header.Value.ToString().Split(",", StringSplitOptions.RemoveEmptyEntries)[0].Trim(); log.Info("IPADDRESS: " + ipAddress); } if (header.Key.Trim().ToUpper() == "X-UP-CALLING-LINE-ID") { msisdn = header.Value; log.Info("MSISDN: " + msisdn); } } // detect msisdn if (ipAddress != "") { wsGetMsisdnFromIpRequest req = new wsGetMsisdnFromIpRequest(wsUser, wsPassword, ipAddress); string phoneNumber = wsClient.wsGetMsisdnFromIp(req).@return.content; if (phoneNumber != null && phoneNumber != "") { phoneNumber = validateMsisdn(phoneNumber); if (phoneNumber == msisdn) { CreateAuthToken(phoneNumber, null); return msisdn; } } } return null; } } }