NonInventPurchasingSystem/CPRNIMS.WebApi/Controllers/Base/BaseController.cs
2026-02-12 10:41:44 +08:00

133 lines
4.8 KiB
C#

using CPRNIMS.Domain.Services;
using CPRNIMS.Infrastructure.Entities.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace CPRNIMS.WebApi.Controllers.Base
{
[Route("api/[controller]")]
[ApiController]
public class BaseController : ControllerBase
{
public readonly IWebHostEnvironment _webHostEnvironment;
public readonly ErrorMessageService ErrorMessageService;
public IConfiguration _configuration;
public BaseController(ErrorMessageService errorMessageService,
IWebHostEnvironment webHostEnvironment, IConfiguration configuration)
{
ErrorMessageService = errorMessageService;
_webHostEnvironment = webHostEnvironment;
_configuration = configuration;
}
[NonAction]
[AllowAnonymous]
[HttpPost("{EMailTemplate}")]
public string EMailTemplate(string relativePath, string emailTemplate)
{
try
{
string templateFolderPath = Path.Combine(_webHostEnvironment.ContentRootPath, relativePath);
string templateFilePath = Path.Combine(templateFolderPath, emailTemplate);
if (System.IO.File.Exists(templateFilePath))
{
string body = System.IO.File.ReadAllText(templateFilePath);
return body;
}
else
{
Console.WriteLine($"File not found: {templateFilePath}");
return "Template file not found";
}
}
catch (Exception ex)
{
var errorMessage = ex.ToString() ?? ex.InnerException.ToString();
PostErrorMessage(errorMessage, "WebApi");
throw;
}
}
[NonAction]
[AllowAnonymous]
[HttpPost("{GetRelativePath}")]
public string GetRelativePath(string relativePath)
{
try
{
string templateFolderPath = Path.Combine(_webHostEnvironment.ContentRootPath, relativePath);
return templateFolderPath;
}
catch (Exception)
{
throw;
}
}
[NonAction]
[HttpPost("{ErrMessage}")]
public async Task PostErrorMessage(string errMessage, string appName)
{
var errorMessage = new ErrorMessage
{
CreatedDate = DateTime.Now,
Message = errMessage,
Application = appName,
CreatedBy = appName
};
await ErrorMessageService.PostErrorMessage(errorMessage);
}
[NonAction]
[HttpPost("{ErrorHandling}")]
protected async Task<IActionResult> ExecuteWithErrorHandling<T>(
Func<Task<T>> operation, string methodName,bool isPost)
{
try
{
var result = await operation();
if (isPost)
{
return Ok(new { success = true, messCode = 1, message = "Operation completed successfully", data = result });
}
return Ok(result);
}
catch (Exception ex)
{
var errorMessage = ex.InnerException?.ToString() ?? ex.Message.ToString();
await PostErrorMessage(errorMessage, $"WebApi {methodName}");
return BadRequest(new { success = false, messCode = 0, message = errorMessage });
}
}
[HttpPost("{GetToken}")]
[NonAction]
public JwtSecurityToken GetToken(List<Claim> authClaims)
{
var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"]));
// Specify the time zone you want to use (e.g., "Asia/Manila")
var localTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Asia/Manila");
// Calculate the expiration time in your local time zone
var localNow = TimeZoneInfo.ConvertTime(DateTime.Now, localTimeZone);
var localExpiration = localNow.AddHours(2);
// Convert the local expiration time to UTC
var utcExpiration = TimeZoneInfo.ConvertTimeToUtc(localExpiration, localTimeZone);
var token = new JwtSecurityToken(
issuer: _configuration["JWT:ValidIssuer"],
audience: _configuration["JWT:ValidAudience"],
expires: utcExpiration, // Use the UTC expiration time
claims: authClaims,
signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
);
return token;
}
}
}