BaseController.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net.Http;
  8. using System.Security.Cryptography;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using Microsoft.AspNetCore.Hosting;
  12. using Microsoft.AspNetCore.Http;
  13. using Microsoft.AspNetCore.Mvc;
  14. using Microsoft.Extensions.Configuration;
  15. using Newtonsoft.Json;
  16. using ReportWeb.Models;
  17. using SuperAdmin.Models.Http;
  18. using SuperAdmin.Models.Object;
  19. using SuperAdmin.Models.Vsa;
  20. using SuperAdmin.Source;
  21. using SuperCms.Extensions;
  22. namespace SuperAdmin.Controllers
  23. {
  24. public class BaseController : Controller
  25. {
  26. private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
  27. private readonly IWebHostEnvironment webHostEnvironment;
  28. protected IConfiguration configuration;
  29. protected static String VsaAppId = "";
  30. protected static String VsaWsUrl = "";
  31. public static String useVsa = "0";
  32. public static String PARENT_ID = "100207";
  33. public static String Channel = "APP";
  34. public static String RoleAdminSale = "admin_sale_loto";
  35. public static String RoleAdminCC = "admin_cc_loto";
  36. public static String RoleStaffSale = "staff_sale_loto";
  37. public static String NumberSeparated = ".";
  38. public static String CountryCode = "";
  39. public static String subDomain = "";
  40. public BaseController() { }
  41. public BaseController(IConfiguration _configuration, IWebHostEnvironment hostEnvironment)
  42. {
  43. configuration = _configuration;
  44. webHostEnvironment = hostEnvironment;
  45. CountryCode = configuration["countryCode"];
  46. VsaAppId = configuration["vsaAppId"];
  47. VsaWsUrl = configuration["vsaWsUrl"];
  48. useVsa = configuration["useVsa"];
  49. Channel = configuration["channel"];
  50. NumberSeparated = configuration["numberSeparated"];
  51. PARENT_ID = configuration["PARENT_ID"];
  52. subDomain = configuration["subDomain"];
  53. //RequestKey = configuration["requestKey"];
  54. //CaptchaSiteKey = configuration["recaptchaPublicKey"];
  55. //CaptchaSecretKey = configuration["recaptchaPrivateKey"];
  56. //ExpirePrize = int.Parse(configuration["expirePrize"]);
  57. }
  58. public static String validateMsisdn(String input)
  59. {
  60. if (input == null || input.Length == 0)
  61. {
  62. return "";
  63. }
  64. // check is number
  65. try
  66. {
  67. long.Parse(input);
  68. }
  69. catch
  70. {
  71. return "";
  72. }
  73. //
  74. if (input.StartsWith("0"))
  75. {
  76. input = CountryCode + input.Substring(1);
  77. }
  78. else if (!input.StartsWith(CountryCode))
  79. {
  80. input = CountryCode + input;
  81. }
  82. return input;
  83. }
  84. public Services GetServiceById(int serviceId)
  85. {
  86. List<Services> list = HttpContext.Session.GetComplexData<List<Services>>("listService");
  87. foreach (Services sv in list)
  88. {
  89. if (sv.id == serviceId)
  90. {
  91. return sv;
  92. }
  93. }
  94. return null;
  95. }
  96. protected bool UseVsa()
  97. {
  98. if (useVsa == "0")
  99. {
  100. return false;
  101. }
  102. return true;
  103. }
  104. public static bool UsingVsa()
  105. {
  106. if (useVsa == "0")
  107. {
  108. return false;
  109. }
  110. return true;
  111. }
  112. private static Dictionary<string, ParamObj> mapParam = null;
  113. private Dictionary<string, ParamObj> MapParam()
  114. {
  115. if (mapParam == null)
  116. {
  117. mapParam = loadParam();
  118. }
  119. return mapParam;
  120. }
  121. private Dictionary<string, ParamObj> loadParam()
  122. {
  123. try
  124. {
  125. Dictionary<string, ParamObj> mParam = new Dictionary<string, ParamObj>();
  126. GetParamsReq req = new GetParamsReq();
  127. string result = SendPost(req, GetParameter(LumilotoUtils.WsType.Executes));
  128. GetParamsRes res = GetParamsRes.Parse(result);
  129. if (res != null && res.paramList != null)
  130. {
  131. foreach (ParamObj param in res.paramList)
  132. {
  133. mParam.Add(param.code, param);
  134. }
  135. return mParam;
  136. }
  137. return null;
  138. }
  139. catch (Exception ex)
  140. {
  141. log.Error("Error load param: " + ex.Message, ex);
  142. return null;
  143. }
  144. }
  145. public ParamObj GetParam(string paramCode)
  146. {
  147. try
  148. {
  149. return MapParam()[paramCode];
  150. }
  151. catch { return null; }
  152. }
  153. public String GetParameter(String key)
  154. {
  155. return configuration.GetSection(key).Value;
  156. }
  157. public String GetParameter(String parentKey, String key)
  158. {
  159. var configs = configuration.GetSection(parentKey).GetChildren();
  160. foreach (IConfiguration config in configs)
  161. {
  162. if (config[key] != null)
  163. {
  164. return config[key];
  165. }
  166. }
  167. return "";
  168. }
  169. public async Task<IActionResult> OnPostUploadAsync(List<IFormFile> files)
  170. {
  171. long size = files.Sum(f => f.Length);
  172. foreach (var formFile in files)
  173. {
  174. if (formFile.Length > 0)
  175. {
  176. var filePath = Path.GetTempFileName();
  177. log.Info("path " + filePath);
  178. using (var stream = System.IO.File.Create(filePath))
  179. {
  180. await formFile.CopyToAsync(stream);
  181. }
  182. }
  183. }
  184. // Process uploaded files
  185. // Don't rely on or trust the FileName property without validation.
  186. return Ok(new { count = files.Count, size });
  187. }
  188. public string RandomString(int size, bool lowerCase)
  189. {
  190. StringBuilder builder = new StringBuilder();
  191. Random random = new Random();
  192. char ch;
  193. for (int i = 0; i < size; i++)
  194. {
  195. ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
  196. builder.Append(ch);
  197. }
  198. if (lowerCase)
  199. return builder.ToString().ToLower();
  200. return builder.ToString();
  201. }
  202. protected string convertToDateTimeServer(String date)
  203. {
  204. // date:
  205. DateTime oDateFrom = DateTime.Parse(date);
  206. string hour = oDateFrom.Hour < 10 ? "0" + oDateFrom.Hour : oDateFrom.Hour.ToString();
  207. string minute = oDateFrom.Minute < 10 ? "0" + oDateFrom.Minute : oDateFrom.Minute.ToString();
  208. string second = oDateFrom.Second < 10 ? "0" + oDateFrom.Second : oDateFrom.Second.ToString();
  209. string month = oDateFrom.Month < 10 ? "0" + oDateFrom.Month : oDateFrom.Month.ToString();
  210. string day = oDateFrom.Day < 10 ? "0" + oDateFrom.Day : oDateFrom.Day.ToString();
  211. string fromCheck = day + "/" + month + "/" + oDateFrom.Year + " " + hour + ":" + minute + ":" + second;
  212. return fromCheck; //MM/dd/yyyy HH24:mm:ss
  213. }
  214. public String SendPost(Posting obj, String url)
  215. {
  216. return SendPost(obj, null, url);
  217. }
  218. public String SendPost(Posting obj, String serviceId, String url)
  219. {
  220. obj.serviceId = serviceId;
  221. obj.SV_ID = serviceId;
  222. obj.service_id = serviceId;
  223. obj.key = GetParameter("keyPost");
  224. var json = JsonConvert.SerializeObject(obj);
  225. var data = new StringContent(json, Encoding.UTF8, "application/json");
  226. log.Debug(url);
  227. log.Debug("Request: " + json);
  228. using (var client = new HttpClient())
  229. {
  230. var response = client.PostAsync(url, data).Result;
  231. if (response.IsSuccessStatusCode)
  232. {
  233. var responseContent = response.Content;
  234. // by calling .Result you are synchronously reading the result
  235. string responseString = responseContent.ReadAsStringAsync().Result;
  236. log.Debug("Response: " + responseString);
  237. return responseString;
  238. }
  239. else
  240. {
  241. log.Error("Response: " + response.StatusCode.ToString());
  242. return response.StatusCode.ToString();
  243. }
  244. }
  245. }
  246. protected void CreateAuthToken(String account, Object userObj)
  247. {
  248. // create session authen
  249. // Create the random value we will use to secure the session.
  250. string authId = GenerateAuthId();
  251. // Store the value in both our Session and a Cookie.
  252. HttpContext.Session.SetString("AuthorizationCookieId", authId);
  253. string sessionValue = HttpContext.Session.GetString("AuthorizationCookieId");
  254. //CookieOptions option = new CookieOptions
  255. //{
  256. // Expires = DateTime.Now.AddMinutes(1)
  257. //};
  258. //Response.Cookies.Append("Key Name", "Value", option);
  259. CookieOptions options = new CookieOptions()
  260. {
  261. //Path = "/",
  262. //HttpOnly = true,
  263. //Secure = false,
  264. //SameSite = SameSiteMode.None
  265. Expires = DateTime.Now.AddMinutes(60)
  266. };
  267. HttpContext.Response.Cookies.Append("AuthorizationCookie", authId, options);
  268. string cookieValue = HttpContext.Request.Cookies["AuthorizationCookie"];
  269. HttpContext.Session.SetString("account", account);
  270. HttpContext.Session.SetComplexData("user", userObj);
  271. }
  272. protected bool CheckAuthToken()
  273. {
  274. string cookieValue = HttpContext.Request.Cookies["AuthorizationCookie"];
  275. string sessionValue = HttpContext.Session.GetString("AuthorizationCookieId");
  276. if (cookieValue == null || sessionValue == null || cookieValue != sessionValue)
  277. {
  278. // Invalidate the session and log out the current user.
  279. return false;
  280. }
  281. if (sessionValue == null)
  282. {
  283. // Invalidate the session and log out the current user.
  284. return false;
  285. }
  286. // check vsaCheckRole
  287. if (useVsa == "1")
  288. {
  289. var path = HttpContext.Request.Path.Value;
  290. return CheckRole(path);
  291. }
  292. return true;
  293. }
  294. protected bool ClearCache()
  295. {
  296. HttpContext.Session.Clear();
  297. foreach (var cookieKey in HttpContext.Request.Cookies.Keys)
  298. {
  299. HttpContext.Response.Cookies.Delete(cookieKey);
  300. }
  301. return true;
  302. }
  303. private string GenerateAuthId()
  304. {
  305. using (RandomNumberGenerator rng = new RNGCryptoServiceProvider())
  306. {
  307. byte[] tokenData = new byte[32];
  308. rng.GetBytes(tokenData);
  309. return Convert.ToBase64String(tokenData);
  310. }
  311. }
  312. protected string UploadedFile(IFormFile image, String folder)
  313. {
  314. try
  315. {
  316. //string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "img");
  317. string uploadsFolder = GetParameter(UtilsController.Constant.PATH_OUTSIDE);
  318. string uniqueFileName = Guid.NewGuid().ToString() + "_" + image.FileName;
  319. string filePath = Path.Combine(uploadsFolder, folder, uniqueFileName);
  320. using (var fileStream = new FileStream(filePath, FileMode.Create))
  321. {
  322. image.CopyTo(fileStream);
  323. }
  324. return filePath;
  325. }
  326. catch (Exception ex)
  327. {
  328. log.Error("Exception: " + ex);
  329. return "";
  330. }
  331. }
  332. protected bool CheckRole(String path)
  333. {
  334. //
  335. VsaValidateResult userInfo = HttpContext.Session.GetComplexData<VsaValidateResult>("userInfo");
  336. if (userInfo == null || userInfo.ObjectAll == null || userInfo.ObjectAll.Row == null)
  337. {
  338. log.Info("Not found user VSA");
  339. return false;
  340. }
  341. foreach (VsaObject obj in userInfo.ObjectAll.Row)
  342. {
  343. if (obj.OBJECTURL.ToUpper() == path.ToUpper())
  344. {
  345. return true;
  346. }
  347. }
  348. log.Info("Not have privileges: " + userInfo.UserData.Row.USERNAME + ", executing path: " + path);
  349. return false;
  350. }
  351. public bool CheckHasRole(String role)
  352. {
  353. VsaValidateResult userInfo = HttpContext.Session.GetComplexData<VsaValidateResult>("userInfo");
  354. if (userInfo == null || userInfo.ObjectAll == null || userInfo.ObjectAll.Row == null)
  355. {
  356. log.Info("Not found user VSA");
  357. return false;
  358. }
  359. foreach (VsaRole obj in userInfo.Roles.Row)
  360. {
  361. if (obj.ROLENAME.ToUpper() == role.ToUpper())
  362. {
  363. return true;
  364. }
  365. }
  366. log.Info("Not have privileges: " + userInfo.UserData.Row.USERNAME + ", executing role: " + role);
  367. return false;
  368. }
  369. public static String FormatNumber(float number)
  370. {
  371. var nfi = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();
  372. nfi.NumberGroupSeparator = NumberSeparated;
  373. return number.ToString("#,0", nfi);
  374. }
  375. public static String FormatNumber(String number)
  376. {
  377. var nfi = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();
  378. nfi.NumberGroupSeparator = NumberSeparated;
  379. return float.Parse(number).ToString("#,0", nfi);
  380. }
  381. protected VsaValidateResult GetUserInfo()
  382. {
  383. VsaValidateResult userInfo = HttpContext.Session.GetComplexData<VsaValidateResult>("userInfo");
  384. return userInfo;
  385. }
  386. }
  387. }