| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429 |
- 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<Services> list = HttpContext.Session.GetComplexData<List<Services>>("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<string, ParamObj> mapParam = null;
- private Dictionary<string, ParamObj> MapParam()
- {
- if (mapParam == null)
- {
- mapParam = loadParam();
- }
- return mapParam;
- }
- private Dictionary<string, ParamObj> loadParam()
- {
- try
- {
- Dictionary<string, ParamObj> mParam = new Dictionary<string, ParamObj>();
- 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<IActionResult> OnPostUploadAsync(List<IFormFile> 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<VsaValidateResult>("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<VsaValidateResult>("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<VsaValidateResult>("userInfo");
- return userInfo;
- }
- }
- }
|