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.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Newtonsoft.Json; using ReportWeb.Models; using SuperAdmin.Models.Http; using SuperAdmin.Models.Object; using SuperAdmin.Models.Vsa; using SuperAdmin.Source; using SuperCms.Extensions; namespace SuperAdmin.Controllers { public class BaseController : Controller { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program)); private readonly IWebHostEnvironment webHostEnvironment; protected IConfiguration configuration; protected static String VsaAppId = ""; protected static String VsaWsUrl = ""; public static String useVsa = "0"; public static String PARENT_ID = "100207"; public static String Channel = "APP"; public static String RoleAdminSale = "admin_sale_loto"; public static String RoleAdminCC = "admin_cc_loto"; public static String RoleStaffSale = "staff_sale_loto"; public static String NumberSeparated = "."; public static String CountryCode = ""; public static String subDomain = ""; public BaseController() { } public BaseController(IConfiguration _configuration, IWebHostEnvironment hostEnvironment) { configuration = _configuration; webHostEnvironment = hostEnvironment; CountryCode = configuration["countryCode"]; VsaAppId = configuration["vsaAppId"]; VsaWsUrl = configuration["vsaWsUrl"]; useVsa = configuration["useVsa"]; Channel = configuration["channel"]; NumberSeparated = configuration["numberSeparated"]; PARENT_ID = configuration["PARENT_ID"]; subDomain = configuration["subDomain"]; //RequestKey = configuration["requestKey"]; //CaptchaSiteKey = configuration["recaptchaPublicKey"]; //CaptchaSecretKey = configuration["recaptchaPrivateKey"]; //ExpirePrize = int.Parse(configuration["expirePrize"]); } public static String validateMsisdn(String input) { if (input == null || input.Length == 0) { return ""; } // check is number try { long.Parse(input); } catch { return ""; } // if (input.StartsWith("0")) { input = CountryCode + input.Substring(1); } else if (!input.StartsWith(CountryCode)) { input = CountryCode + input; } return input; } public Services GetServiceById(int serviceId) { List list = HttpContext.Session.GetComplexData>("listService"); foreach (Services sv in list) { if (sv.id == serviceId) { return sv; } } return null; } protected bool UseVsa() { if (useVsa == "0") { return false; } return true; } public static bool UsingVsa() { if (useVsa == "0") { return false; } return true; } private static Dictionary mapParam = null; private Dictionary MapParam() { if (mapParam == null) { mapParam = loadParam(); } return mapParam; } private Dictionary loadParam() { try { Dictionary mParam = new Dictionary(); GetParamsReq req = new GetParamsReq(); string result = SendPost(req, GetParameter(LumilotoUtils.WsType.Executes)); GetParamsRes res = GetParamsRes.Parse(result); if (res != null && res.paramList != null) { foreach (ParamObj param in res.paramList) { mParam.Add(param.code, param); } return mParam; } return null; } catch (Exception ex) { log.Error("Error load param: " + ex.Message, ex); return null; } } public ParamObj GetParam(string paramCode) { try { return MapParam()[paramCode]; } catch { return null; } } 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 async Task OnPostUploadAsync(List files) { long size = files.Sum(f => f.Length); foreach (var formFile in files) { if (formFile.Length > 0) { var filePath = Path.GetTempFileName(); log.Info("path " + filePath); using (var stream = System.IO.File.Create(filePath)) { await formFile.CopyToAsync(stream); } } } // Process uploaded files // Don't rely on or trust the FileName property without validation. return Ok(new { count = files.Count, size }); } 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 } public String SendPost(Posting obj, String url) { return SendPost(obj, null, url); } public String SendPost(Posting obj, String serviceId, String url) { obj.serviceId = serviceId; obj.SV_ID = serviceId; obj.service_id = serviceId; obj.key = GetParameter("keyPost"); var json = JsonConvert.SerializeObject(obj); var data = new StringContent(json, Encoding.UTF8, "application/json"); log.Debug(url); log.Debug("Request: " + json); 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; log.Debug("Response: " + responseString); return responseString; } else { log.Error("Response: " + response.StatusCode.ToString()); return response.StatusCode.ToString(); } } } 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("user", userObj); } protected bool CheckAuthToken() { 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; } if (sessionValue == null) { // Invalidate the session and log out the current user. return false; } // check vsaCheckRole if (useVsa == "1") { var path = HttpContext.Request.Path.Value; return CheckRole(path); } 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 UploadedFile(IFormFile image, String folder) { try { //string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "img"); string uploadsFolder = GetParameter(UtilsController.Constant.PATH_OUTSIDE); string uniqueFileName = Guid.NewGuid().ToString() + "_" + image.FileName; string filePath = Path.Combine(uploadsFolder, folder, uniqueFileName); using (var fileStream = new FileStream(filePath, FileMode.Create)) { image.CopyTo(fileStream); } return filePath; } catch (Exception ex) { log.Error("Exception: " + ex); return ""; } } protected bool CheckRole(String path) { // VsaValidateResult userInfo = HttpContext.Session.GetComplexData("userInfo"); if (userInfo == null || userInfo.ObjectAll == null || userInfo.ObjectAll.Row == null) { log.Info("Not found user VSA"); return false; } foreach (VsaObject obj in userInfo.ObjectAll.Row) { if (obj.OBJECTURL.ToUpper() == path.ToUpper()) { return true; } } log.Info("Not have privileges: " + userInfo.UserData.Row.USERNAME + ", executing path: " + path); return false; } public bool CheckHasRole(String role) { VsaValidateResult userInfo = HttpContext.Session.GetComplexData("userInfo"); if (userInfo == null || userInfo.ObjectAll == null || userInfo.ObjectAll.Row == null) { log.Info("Not found user VSA"); return false; } foreach (VsaRole obj in userInfo.Roles.Row) { if (obj.ROLENAME.ToUpper() == role.ToUpper()) { return true; } } log.Info("Not have privileges: " + userInfo.UserData.Row.USERNAME + ", executing role: " + role); return false; } public static String FormatNumber(float number) { var nfi = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone(); nfi.NumberGroupSeparator = NumberSeparated; return number.ToString("#,0", nfi); } public static String FormatNumber(String number) { var nfi = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone(); nfi.NumberGroupSeparator = NumberSeparated; return float.Parse(number).ToString("#,0", nfi); } protected VsaValidateResult GetUserInfo() { VsaValidateResult userInfo = HttpContext.Session.GetComplexData("userInfo"); return userInfo; } } }