NonInventPurchasingSystem/CPRNIMS.WebApps/Controllers/Base/BaseMethod.cs
2026-01-20 07:44:30 +08:00

243 lines
10 KiB
C#

using CPRNIMS.Core.Facades;
using CPRNIMS.Infrastructure.Constant;
using CPRNIMS.Infrastructure.Entities.Common;
using CPRNIMS.Infrastructure.Helper;
using CPRNIMS.Infrastructure.Security;
using CPRNIMS.Infrastructure.ViewModel;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace CPRNIMS.WebApps.Controllers.Base
{
public class BaseMethod : BaseProperties
{
private readonly HttpClient _httpClient;
public readonly ErrorLogHelper ErrorMessageService;
public readonly IConfiguration _configuration;
public readonly TokenHelper _tokenHelper;
public readonly IWebHostEnvironment _webHostEnvironment;
public BaseMethod(HttpClient httpClient, IConfiguration configuration)
{
_configuration = configuration;
_httpClient = httpClient;
}
public BaseMethod(TokenHelper tokenHelper, ErrorLogHelper errorMessageService,
IWebHostEnvironment webHostEnvironment)
{
_tokenHelper = tokenHelper;
ErrorMessageService = errorMessageService;
_webHostEnvironment = webHostEnvironment;
}
public AttachmentVM CreateUpdateAttachment(string contentValueBytes)
{
var base64Image = contentValueBytes.Split(',')[1];
byte[] contentBytes = Convert.FromBase64String(base64Image);
var facadeAttachment = new FacadeAttachment();
var (imageFormat, imageEncoder, imageResult) = facadeAttachment.GetImageFormatAndEncoder
(contentValueBytes);
if (imageResult != "Format is valid")
{
return new AttachmentVM { Result = imageResult };
}
var (isValid, isValidResult) = facadeAttachment.CheckFileSize(contentBytes, 2 * 1024 * 1024);
if (!isValid)
{
return new AttachmentVM { Result = isValidResult };
}
var fileName = $"{Guid.NewGuid()}.{imageFormat.Name.ToLower()}";
var filePath = Path.Combine(_webHostEnvironment.WebRootPath, FileExtensionPath.GetExtensionPath(imageFormat.Name.ToLower()), fileName);
// Remove the application's root path
var relativePath = Path.GetRelativePath(_webHostEnvironment.WebRootPath, filePath);
return facadeAttachment.
SaveAttachment(contentBytes, relativePath, imageEncoder,
fileName, imageFormat.Name.ToLower() == "png" ? FileExtension.Png : FileExtension.Jpeg);
}
public async Task PostErrorMessage(string errMessage, string appName)
{
var errorMessage = new ErrorMessage
{
CreatedDate = DateTime.Now,
Message = errMessage,
Application = appName,
CreatedBy = appName
};
await ErrorMessageService.ErrorLogs(errorMessage);
}
private class AttributeResponse
{
public string? Response { get; set; }
}
public void GetStoreAttachment(string urlContent, bool isNull)
{
if (!String.IsNullOrEmpty(urlContent) && isNull == true)
{
HttpContext.Session.SetString("URLAttachment", urlContent);
ViewBag.URLAttachment = urlContent;
TempData["URLAttachment"] = urlContent;
}
else
{
HttpContext.Session.SetString("URLAttachment", "Content\\Images\\UserProfile\\404userImage.jpg");
URLAttachment = HttpContext.Session.GetString("URLAttachment");
ViewBag.URLAttachment = HttpContext.Session.GetString("URLAttachment");
}
}
public async Task<(Infrastructure.Models.Account.User, bool)>
GetStoreCredAsync(Infrastructure.Models.Account.User user, string token)
{
var responseObj = new AttributeResponse();
UserRoles = await _tokenHelper.GetRoleAsync(user.UserName, user.Password, token);
var userClaimsResponse = JsonConvert.DeserializeObject<UserClaimsResponse>(UserRoles);
var userRoles = userClaimsResponse.UserRoles;
UserId = userClaimsResponse.UserId;
try
{
var myClaimsInfo = userClaimsResponse.OtherClaims.FirstOrDefault();
string myClaims = myClaimsInfo?.value ?? string.Empty;
string myCompany = myClaimsInfo?.company ?? string.Empty;
FullName = myClaimsInfo?.FullName ?? string.Empty;
UserCompany = myCompany;
MyAccess = myClaims;
UserRoles = string.Join(",", userRoles);
}
catch (Exception)
{
var credNull = new Infrastructure.Models.Account.User();
return (credNull, false);
throw;
}
HttpContext.Session.SetString("UserRoles", UserRoles);
HttpContext.Session.SetString("UserClaim", MyAccess);
HttpContext.Session.SetString("UserCompany", UserCompany);
HttpContext.Session.SetString("UserId", UserId);
HttpContext.Session.SetString("UserName", user.UserName);
HttpContext.Session.SetString("Password", user.Password);
HttpContext.Session.SetString("FullName", FullName);
HttpContext.Session.SetString("NewPassword", user.Password);
var cred = new Infrastructure.Models.Account.User
{
UserId = UserId,
Password = user.Password,
UserName = user.UserName,
FullName = FullName,
};
if (!String.IsNullOrEmpty(cred.UserId)
&& !String.IsNullOrEmpty(cred.UserName) && !String.IsNullOrEmpty(cred.Password))
{
ViewBag.UserName = cred.UserName;
ViewBag.Password = cred.Password;
ViewBag.FullName = cred.FullName;
ViewBag.UserId = cred.UserId;
}
ViewBag.UserRoles = MyAccess;
ViewBag.UserCompany = UserCompany;
if (!String.IsNullOrEmpty(user.URLAttachment))
{
ViewBag.URLAttachment = user.URLAttachment;
cred.URLAttachment = user.URLAttachment;
TempData["UserName"] = user.UserName; TempData["Password"] = user.Password;
HttpContext.Session.SetString("URLAttachment", user.URLAttachment);
TempData["URLAttachment"] = user.URLAttachment ?? HttpContext.Session.GetString("URLAttachment");
}
else
{
HttpContext.Session.SetString("URLAttachment", "Content/Images/UserProfile/404userImage.jpg");//Images\UserProfile\488e082d-3a89-4c2b-b51d-8cf62d22326b.jpg
ViewBag.URLAttachment = HttpContext.Session.GetString("URLAttachment");
URLAttachment = HttpContext.Session.GetString("URLAttachment");
}
if (String.IsNullOrEmpty(HttpContext.Session.GetString("UserRoles") ?? HttpContext.Session.GetString("UserName") ?? HttpContext.Session.GetString("Password") ?? HttpContext.Session.GetString("URLAttachment")))
{
return (null, false);
}
return (cred, true);
}
public async Task<Infrastructure.Models.Account.User>
StoredCred(Infrastructure.Models.Account.User user, bool isNull)
{
if (isNull == true && !String.IsNullOrEmpty(user.UserName) && !String.IsNullOrEmpty(user.Password))
{
TempData["UserName"] = user.UserName;
TempData["FullName"] = user.FullName;
TempData["Password"] = user.Password;
TempData["UserId"] = user.UserId ?? HttpContext.Session.GetString("UserId");
TempData["URLAttachment"] = user.URLAttachment ?? HttpContext.Session.GetString("URLAttachment");
return user;
}
else
{
var credPopulation = new Infrastructure.Models.Account.User
{
UserName = TempData?["UserName"]?.ToString(),
FullName = TempData?["FullName"]?.ToString(),
Password = TempData?["Password"]?.ToString(),
UserId = TempData?["UserId"]?.ToString(),
URLAttachment = TempData?["URLAttachment"]?.ToString()
};
if (credPopulation != null)
{
var (newCredPopulation, isValid) = await GetStoreCredAsync(credPopulation, await _tokenHelper.GetJwtTokenAsync(credPopulation));
return newCredPopulation;
}
return credPopulation;
}
}
public async Task<Infrastructure.Models.Account.User> GetUser()
{
var myCred = new Infrastructure.Models.Account.User
{
UserName = HttpContext.Session.GetString("UserName"),
FullName = HttpContext.Session.GetString("FullName"),
Password = HttpContext.Session.GetString("Password"),
UserId = HttpContext.Session.GetString("UserId"),
URLAttachment = HttpContext.Session.GetString("URLAttachment")
};
if (String.IsNullOrEmpty(myCred.UserName) && String.IsNullOrEmpty(myCred.Password) && String.IsNullOrEmpty(myCred.URLAttachment) && String.IsNullOrEmpty(myCred.UserId))
{
myCred = await StoredCred(myCred, true);
}
return myCred;
}
public IActionResult GetResponse<T>(T response)
{
if (response == null)
{
response = (T)Activator.CreateInstance(typeof(T));
ViewBag.UserRoles = UserRoles;
return Json(new { success = false, data = response });
}
ViewBag.UserRoles = UserRoles;
return Json(new { success = true, data = response });
}
public async Task<IActionResult> IsAuthenTicated()
{
if (GetUser() == null)
{
RedirectToAction("Logout", "Home");
}
await GetStoreCredAsync(await GetUser(),
await _tokenHelper.GetJwtTokenAsync(await GetUser()));
return View();
}
}
}