| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643 |
- using System.Data;
- using System.Globalization;
- using System.IdentityModel.Tokens.Jwt;
- using System.Net;
- using System.Net.Http.Headers;
- using System.Net.Http.Json;
- using System.Security.Claims;
- using System.Security.Cryptography;
- using System.Text;
- using Database;
- using Database.Database;
- using log4net;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Server.Kestrel.Core;
- using Microsoft.Extensions.Configuration;
- using Microsoft.IdentityModel.Tokens;
- using Newtonsoft.Json;
- using static Common.Request;
- namespace Common;
- public static class CommonLogic
- {
- private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(CommonLogic));
- public static List<List<DateTime>> GetTimeWeekly(int numOfWeek)
- {
- List<List<DateTime>> timeWeek = new List<List<DateTime>>();
- DateTime timeNow = DateTime.Now;
- var day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(timeNow);
- //int end = DayOfWeek.Saturday - day;
- //int start = day - DayOfWeek.Sunday;
- DateTime timeStart =
- day == 0
- ? timeNow.AddDays(-(7 - day - DayOfWeek.Sunday) + 1)
- : timeNow.AddDays(-(day - DayOfWeek.Sunday) + 1);
- DateTime timeEnd =
- day == 0 ? timeNow.AddDays(0) : timeNow.AddDays(DayOfWeek.Saturday - day + 1);
- // add for 4 weeks
- for (int i = 0; i <= numOfWeek; i++)
- {
- List<DateTime> time = new List<DateTime>();
- DateTime start = timeStart.AddDays(-7 * i);
- DateTime end = timeEnd.AddDays(-7 * i + 1);
- time.Add(new DateTime(start.Year, start.Month, start.Day, 0, 0, 0));
- time.Add(new DateTime(end.Year, end.Month, end.Day, 0, 0, 0));
- timeWeek.Add(time);
- }
- return timeWeek;
- }
- public static List<List<DateTime>> GetTimeMonthly(int numOfMonth)
- {
- List<List<DateTime>> timeMonth = new List<List<DateTime>>();
- DateTime timeNow = DateTime.Now;
- // add for 4 weeks
- for (int i = 0; i <= numOfMonth; i++)
- {
- List<DateTime> time = new List<DateTime>();
- DateTime start = timeNow.AddMonths(-i);
- DateTime end = timeNow.AddMonths(-i + 1);
- time.Add(new DateTime(start.Year, start.Month, 1, 0, 0, 0));
- time.Add(new DateTime(end.Year, end.Month, 1, 0, 0, 0));
- timeMonth.Add(time);
- }
- return timeMonth;
- }
- public static string? SendPost(ILog log, string Url, dynamic data)
- {
- var json = JsonConvert.SerializeObject(data);
- log.Info("request: " + Url + " data: " + json);
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
- request.Method = "POST";
- request.ContentType = "application/json";
- request.ContentLength = json.Length;
- // CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
- // log.Debug("Lang: " + currentCulture.Name);
- // request.Headers.Add("Lang", currentCulture.Name);
- using (Stream webStream = request.GetRequestStream())
- using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
- {
- requestWriter.Write(json);
- }
- try
- {
- WebResponse webResponse = request.GetResponse();
- using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
- using (StreamReader responseReader = new StreamReader(webStream))
- {
- string response = responseReader.ReadToEnd();
- log.Info("request: " + Url + " /nData: " + json + " /n response: " + response);
- return response;
- }
- }
- catch (Exception e)
- {
- log.Error("Exception: ", e);
- }
- return null;
- }
- public static async Task<ReturnDataPost?>? SendPostWithAuthen(
- string? url,
- Object? data,
- string? token,
- string? refreshToken,
- string? signature,
- string? lang
- )
- {
- ReturnDataPost returnDataPost = new ReturnDataPost
- {
- token = token,
- refreshToken = refreshToken
- };
- var json = JsonConvert.SerializeObject(data);
- try
- {
- var client = new HttpClient();
- log.Debug("token: " + token);
- log.Info(
- Thread.CurrentThread.ManagedThreadId
- + " | "
- + "Request: "
- + url
- + " /nData: "
- + json
- );
- client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
- client.DefaultRequestHeaders.Add("Signature", signature);
- client.DefaultRequestHeaders.Add("Accept-Language", lang == "en-US" ? "en" : "my");
- client.DefaultRequestHeaders.Add("Language", lang == "en-US" ? "en" : "my");
- var result = await client.PostAsJsonAsync(url, data!);
- if (result.IsSuccessStatusCode)
- {
- var response = await result.Content.ReadAsStringAsync();
- log.Info(
- Thread.CurrentThread.ManagedThreadId
- + " | "
- + "Request: "
- + url
- + " /nData: "
- + json
- + " /n Response: "
- + response
- );
- returnDataPost.data = response;
- return returnDataPost;
- }
- else if (result.StatusCode == HttpStatusCode.Unauthorized)
- {
- log.Error(Thread.CurrentThread.ManagedThreadId + " | " + "401");
- returnDataPost.needToLogin = true;
- return returnDataPost;
- }
- else if (result.StatusCode == HttpStatusCode.BadRequest)
- {
- var response = await result.Content.ReadAsStringAsync();
- log.Info(
- Thread.CurrentThread.ManagedThreadId
- + " | "
- + "Request: "
- + url
- + " /nData: "
- + json
- + " /n Response: "
- + response
- );
- returnDataPost.data = response;
- return returnDataPost;
- }
- else
- {
- log.Info(
- Thread.CurrentThread.ManagedThreadId
- + " | "
- + "Request: "
- + url
- + " /nData: "
- + json
- + " /n Response: "
- + result
- );
- }
- }
- catch (Exception e)
- {
- log.Info(Thread.CurrentThread.ManagedThreadId + " | " + "-----------------");
- log.Error(Thread.CurrentThread.ManagedThreadId + " | " + e.Message);
- if (e is Microsoft.AspNetCore.Http.BadHttpRequestException)
- {
- //400 exception.
- }
- if (e is UnauthorizedAccessException) { }
- }
- return null;
- }
- public static async Task<string?> SendPostWithSignatureAsync(
- ILog log,
- string url,
- dynamic data,
- string? signature,
- string? username,
- string? password
- )
- {
- // var json = JsonConvert.SerializeObject(data);
- // HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
- // request.Method = "POST";
- // request.ContentType = "application/json";
- // request.ContentLength = json.Length;
- // request.Headers.Add("signature", signature);
- // request.Headers.Add("Username", username);
- // request.Headers.Add("Password", password);
- // using (Stream webStream = request.GetRequestStream())
- // using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
- // {
- // requestWriter.Write(json);
- // }
- // try
- // {
- // WebResponse webResponse = request.GetResponse();
- // using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
- // using (StreamReader responseReader = new StreamReader(webStream))
- // {
- // string response = responseReader.ReadToEnd();
- // log.Info("request: " + url + " /nData: " + json + " /n response: " + response);
- // return response;
- // }
- // }
- // catch (Exception e)
- // {
- // log.Info("-----------------");
- // log.Info(e.Message);
- // }
- // return null;
- var json = JsonConvert.SerializeObject(data);
- var body = new StringContent(json, Encoding.UTF8, "application/json");
- try
- {
- log.Debug("url: " + url);
- log.Debug("Request: " + json);
- string svcCredentials = Convert.ToBase64String(
- ASCIIEncoding.ASCII.GetBytes(username + ":" + password)
- );
- // request.Headers.Add("Authorization", "Basic " + svcCredentials);
- using (var client = new HttpClient())
- {
- client.DefaultRequestHeaders.Add("signature", signature);
- client.DefaultRequestHeaders.Add("Authorization", "Basic " + svcCredentials);
- // client.DefaultRequestHeaders.Add("Password", password);
- var response = client.PostAsync(url, body).Result;
- // log.Debug("Error req: " + client);
- 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;
- }
- log.Debug("Error res: " + response);
- return null;
- // return response.StatusCode.ToString();
- }
- }
- catch (Exception e)
- {
- log.Error("Exception: ", e);
- }
- return null;
- }
- public static DateTime? ParseToDateTime(string input)
- {
- if (string.IsNullOrWhiteSpace(input))
- return null;
- if (DateTime.TryParseExact(
- input,
- CommonConstants.ListDateTimeFormat,
- CultureInfo.InvariantCulture,
- DateTimeStyles.None,
- out DateTime result))
- {
- return result;
- }
- return null;
- }
- public static string SendGetWithAuthen(ILog log, string url, string token)
- {
- log.Debug("GET url: " + url);
- using (var client = new HttpClient())
- {
- client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
- 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;
- log.Debug("Response: " + responseString);
- return responseString;
- }
- log.Debug("Error res: " + response);
- return response.StatusCode.ToString();
- }
- }
- public static string? ValidateMsisdn(string countryCode, string? input)
- {
- if (input == null || input.Length == 0 || !long.TryParse(input, out long temp))
- {
- return null;
- }
- else if (input.Length == 9)
- {
- return countryCode + input.Trim();
- }
- else
- {
- return input.Trim();
- }
- }
- public static DateTime ConvertStringToDateTime(string time)
- {
- return DateTime.ParseExact(
- time,
- "dd/MM/yyyy HH:mm:ss",
- System.Globalization.CultureInfo.InvariantCulture
- );
- }
- public static string GenerateUniqueNumber()
- {
- var bytes = new byte[4];
- var rng = RandomNumberGenerator.Create();
- rng.GetBytes(bytes);
- uint random = BitConverter.ToUInt32(bytes, 0) % 10;
- return String.Format("{0:D8}", random);
- }
- public static string GetTimeStampMiliSecond()
- {
- // Get the offset from current time in UTC time
- DateTimeOffset dto = new DateTimeOffset(DateTime.UtcNow);
- // Get the unix timestamp in seconds
- string unixTime = dto.ToUnixTimeMilliseconds().ToString();
- return unixTime.Substring(2, 8);
- }
- public static string GenerateUUID()
- {
- Guid myuuid = Guid.NewGuid();
- return myuuid.ToString();
- }
- public static string? CreateSignature(ILog log, Object data, string key)
- {
- string bodyString = JsonConvert.SerializeObject(data);
- log.Debug("body to signature: " + bodyString + key);
- return ComputeSHA256Hash(bodyString + key);
- }
- public static string ComputeSHA256Hash(string text)
- {
- using (var sha256 = new SHA256Managed())
- {
- return Convert
- .ToHexString(sha256.ComputeHash(Encoding.UTF8.GetBytes(text)))
- .Replace("-", "")
- .ToLower();
- }
- }
- private static byte[] HashHMAC(byte[] key, byte[] message)
- {
- var hash = new HMACSHA256(key);
- return hash.ComputeHash(message);
- }
- public static string HashHMACHex(string key, string message)
- {
- byte[] ba = Encoding.Default.GetBytes(key);
- var keyHexConvert = BitConverter.ToString(ba).Replace("-", "");
- var keyHex = Convert.FromHexString(keyHexConvert);
- byte[] baMes = Encoding.Default.GetBytes(message);
- var mesHexConvert = BitConverter.ToString(baMes).Replace("-", "");
- var messageHex = Convert.FromHexString(mesHexConvert);
- var hash = new HMACSHA256(keyHex);
- var compute = hash.ComputeHash(messageHex);
- return Convert.ToHexString(compute).ToLower();
- }
- public static bool CheckTime(string time)
- {
- try
- {
- DateTime dateTime = DateTime.ParseExact(time, "HH:mm:ss", CultureInfo.InvariantCulture);
- return true;
- }
- catch (Exception)
- {
- return false;
- }
- }
- public static bool CheckPermission(
- ModelContext dbContext,
- IConfiguration configuration,
- HttpRequest httpRequest
- )
- {
- return true;
- try
- {
- string realToken = "";
- var token = httpRequest.Headers["Authorization"];
- if (token.Count == 0)
- {
- return false;
- }
- realToken = token[0];
- // Trim 'Bearer ' from the start since its just a prefix for the token
- var jwtEncodedString = realToken.Substring(7);
- string? pathsString = GetPath(configuration, jwtEncodedString, "Paths");
- if (pathsString == null)
- {
- return false;
- }
- string url = httpRequest.Path;
- // log.Info("url: " + url + " || paths: " + pathsString);
- // convert string to list
- List<string>? paths = JsonConvert.DeserializeObject<List<string>>(pathsString);
- if (paths == null || paths.Count == 0)
- {
- return false;
- }
- if (!paths.Contains(url))
- {
- return false;
- }
- else
- {
- return true;
- }
- }
- catch (Exception e)
- {
- // log.Error("Exception: " + e);
- }
- return false;
- }
- public static String GenToken(IConfiguration configuration, String user, List<String> paths)
- {
- var issuer = configuration["Jwt:Issuer"];
- var audience = configuration["Jwt:Audience"];
- var key = Encoding.ASCII.GetBytes(configuration["Jwt:Key"]);
- string pathsJson = JsonConvert.SerializeObject(paths);
- var tokenDescriptor = new SecurityTokenDescriptor
- {
- Subject = new ClaimsIdentity(
- new[]
- {
- new Claim("Id", Guid.NewGuid().ToString()),
- new Claim("Role", user),
- new Claim("Paths", pathsJson),
- new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
- }
- ),
- Expires = DateTime.UtcNow.AddMinutes(5),
- Issuer = issuer,
- Audience = audience,
- SigningCredentials = new SigningCredentials(
- new SymmetricSecurityKey(key),
- SecurityAlgorithms.HmacSha512Signature
- )
- };
- var tokenHandler = new JwtSecurityTokenHandler();
- var token = tokenHandler.CreateToken(tokenDescriptor);
- var jwtToken = tokenHandler.WriteToken(token);
- var stringToken = tokenHandler.WriteToken(token);
- return stringToken;
- }
- public static String GenRefreshToken(IConfiguration configuration, String user)
- {
- var issuer = configuration["Jwt:Issuer"];
- var audience = configuration["Jwt:Audience"];
- var key = Encoding.ASCII.GetBytes(configuration["Jwt:Key"]);
- var tokenDescriptor = new SecurityTokenDescriptor
- {
- Subject = new ClaimsIdentity(
- new[]
- {
- new Claim("Id", Guid.NewGuid().ToString()),
- new Claim("Role", user),
- new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
- }
- ),
- Expires = DateTime.UtcNow.AddMinutes(2 * 24 * 60),
- Issuer = issuer,
- Audience = audience,
- SigningCredentials = new SigningCredentials(
- new SymmetricSecurityKey(key),
- SecurityAlgorithms.HmacSha512Signature
- )
- };
- var tokenHandler = new JwtSecurityTokenHandler();
- var token = tokenHandler.CreateToken(tokenDescriptor);
- var jwtToken = tokenHandler.WriteToken(token);
- var stringToken = tokenHandler.WriteToken(token);
- return stringToken;
- }
- public static String GenRequestId(String msisdn)
- {
- // get time in tik tac
- long epochTime = (DateTime.UtcNow.Ticks - 621355968000000000);
- return msisdn + "-" + epochTime.ToString();
- }
- public static string? GetPath(IConfiguration configuration, string token, string nameKey)
- {
- var key = Encoding.ASCII.GetBytes(configuration["Jwt:Key"] ?? "");
- var handler = new JwtSecurityTokenHandler();
- var validations = new TokenValidationParameters
- {
- ValidateIssuerSigningKey = true,
- IssuerSigningKey = new SymmetricSecurityKey(key),
- ValidateIssuer = false,
- ValidateAudience = false
- };
- var claims = handler.ValidateToken(token, validations, out var tokenSecure);
- var data = claims.Claims.First(x => x.Type == nameKey).Value;
- return data;
- }
- public static string GetLanguage(HttpRequest httpRequest)
- {
- var language = httpRequest.Headers["Language"];
- if (!language.IsNullOrEmpty())
- {
- return language.ToString();
- ;
- }
- return "en";
- }
- public static string GetLocalizedValue(string json, string language = "en")
- {
- try
- {
- var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
- if (dict != null && dict.ContainsKey(language))
- {
- return dict[language];
- }
- }
- catch (Exception e)
- {
- log.Error("Exception: ", e);
- }
- return "Unknown";
- }
- public static async Task<bool> SendMtToUserAsync(
- ModelContext dbContext,
- string msisdn,
- string? message
- )
- {
- if (message == null)
- {
- return true;
- }
- // send mt to user
- decimal seq = (decimal)await Database.DbLogic.GenIdAsync(dbContext, "mt_seq");
- Mt mt = new Mt();
- mt.MtId = seq;
- mt.MoHisId = (int)seq;
- mt.ReceiveTime = DateTime.Now;
- mt.Channel = CommonConstants.Channel;
- mt.Message = message;
- mt.Msisdn = msisdn;
- dbContext.Mts.Add(mt);
- await dbContext.SaveChangesAsync();
- return true;
- }
- public static string GetShortDecadeFromYear(int year)
- {
- if (year < 0)
- {
- throw new ArgumentException("Year cannot be negative.");
- }
- // Tìm năm bắt đầu của thập niên
- var decadeStart = (year / 10) * 10;
- // Trả về dạng đầy đủ
- return $"{decadeStart}s";
- }
- }
|