| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617 |
- 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<string> listMsisdn = new List<string>();
- 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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;
- }
-
- }
- }
|