Claims refactor both apps and api working well
This commit is contained in:
parent
1390642e0a
commit
eb7223d47e
@ -14,6 +14,7 @@ namespace CPRNIMS.Domain.Contracts.Account
|
||||
Task<List<UserRights>> GetUserRights(AccountDto accountDto);
|
||||
Task<List<ControllerAccess>> GetControllerAccessByUserId(string userId);
|
||||
Task<List<Departments>> GetDepartment();
|
||||
Task<string> CreateToken(ApplicationUser user);
|
||||
Task<UserRights> PutPostUserAccess(AccountDto itemDto);
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,12 +2,16 @@
|
||||
using CPRNIMS.Infrastructure.Database;
|
||||
using CPRNIMS.Infrastructure.Dto.Account;
|
||||
using CPRNIMS.Infrastructure.Entities.Account;
|
||||
using Google;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
@ -16,12 +20,49 @@ namespace CPRNIMS.Domain.Services.Account
|
||||
public class Account : IAccount
|
||||
{
|
||||
private readonly NonInventoryDbContext _accountDbContext;
|
||||
|
||||
public Account(NonInventoryDbContext applicationDbContext)
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly IConfiguration _configuration;
|
||||
public Account(NonInventoryDbContext applicationDbContext,
|
||||
UserManager<ApplicationUser> userManager,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
_accountDbContext = applicationDbContext;
|
||||
_userManager = userManager;
|
||||
_configuration = configuration;
|
||||
}
|
||||
public async Task<string> CreateToken(ApplicationUser user)
|
||||
{
|
||||
var authClaims = await BuildClaims(user);
|
||||
|
||||
var authSigningKey = new SymmetricSecurityKey(
|
||||
Encoding.UTF8.GetBytes(_configuration["JWT:Secret"]));
|
||||
|
||||
var token = new JwtSecurityToken(
|
||||
issuer: _configuration["JWT:ValidIssuer"],
|
||||
audience: _configuration["JWT:ValidAudience"],
|
||||
expires: DateTime.UtcNow.AddMinutes(30),
|
||||
claims: authClaims,
|
||||
signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
|
||||
);
|
||||
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
}
|
||||
private async Task<List<Claim>> BuildClaims(ApplicationUser user)
|
||||
{
|
||||
var roles = await _userManager.GetRolesAsync(user);
|
||||
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new Claim(ClaimTypes.Name, user.UserName),
|
||||
new Claim(ClaimTypes.NameIdentifier, user.Id),
|
||||
new Claim("FullName", user.FullName ?? ""),
|
||||
new Claim("Company", user.Company ?? ""),
|
||||
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
|
||||
};
|
||||
|
||||
claims.AddRange(roles.Select(r => new Claim(ClaimTypes.Role, r)));
|
||||
return claims;
|
||||
}
|
||||
public async Task<List<Infrastructure.Entities.Account.ControllerAccess>> GetControllerAccessByUserId(string userId)
|
||||
{
|
||||
try
|
||||
|
||||
177
CPRNIMS.Domain/Services/Account/RoleAuthorizationCache.cs
Normal file
177
CPRNIMS.Domain/Services/Account/RoleAuthorizationCache.cs
Normal file
@ -0,0 +1,177 @@
|
||||
using CPRNIMS.Infrastructure.Database;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace CPRNIMS.Domain.Services.Account
|
||||
{
|
||||
public interface IRoleAuthorizationCache
|
||||
{
|
||||
Task<List<string>> GetAllowedRoleIdsAsync(string controller);
|
||||
Task<bool> UserHasAccessAsync(string userId, string controller);
|
||||
Task<List<string>> GetUserRoleIdsAsync(string userId);
|
||||
void InvalidateCache(string controller);
|
||||
void InvalidateUserCache(string userId);
|
||||
void InvalidateAllCache();
|
||||
}
|
||||
|
||||
public class RoleAuthorizationCache : IRoleAuthorizationCache
|
||||
{
|
||||
private readonly IMemoryCache _cache;
|
||||
private readonly NonInventoryDbContext _dbContext;
|
||||
private readonly ILogger<RoleAuthorizationCache> _logger;
|
||||
|
||||
private const string CONTROLLER_ROLES_PREFIX = "controller_roles_";
|
||||
private const string USER_ROLES_PREFIX = "user_roles_";
|
||||
private const int CACHE_DURATION_MINUTES = 30;
|
||||
|
||||
public RoleAuthorizationCache(
|
||||
IMemoryCache cache,
|
||||
NonInventoryDbContext dbContext,
|
||||
ILogger<RoleAuthorizationCache> logger)
|
||||
{
|
||||
_cache = cache ?? throw new ArgumentNullException(nameof(cache));
|
||||
_dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get all role IDs that have access to a specific controller (CACHED)
|
||||
/// </summary>
|
||||
public async Task<List<string>> GetAllowedRoleIdsAsync(string controller)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(controller))
|
||||
throw new ArgumentException("Controller name cannot be null or empty", nameof(controller));
|
||||
|
||||
var cacheKey = $"{CONTROLLER_ROLES_PREFIX}{controller}";
|
||||
|
||||
return await _cache.GetOrCreateAsync(cacheKey, async entry =>
|
||||
{
|
||||
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(CACHE_DURATION_MINUTES);
|
||||
entry.SetPriority(CacheItemPriority.High);
|
||||
|
||||
_logger.LogInformation("Cache MISS: Loading role permissions for controller: {Controller}", controller);
|
||||
|
||||
var roleIds = await _dbContext.AuthorizeRoles
|
||||
.Where(ar => ar.IsActive && ar.Controller == controller)
|
||||
.Select(ar => ar.RoleId)
|
||||
.Distinct()
|
||||
.ToListAsync();
|
||||
|
||||
_logger.LogInformation("Cached {Count} roles for controller: {Controller}", roleIds.Count, controller);
|
||||
|
||||
return roleIds ?? new List<string>();
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get all role IDs for a specific user (CACHED)
|
||||
/// </summary>
|
||||
public async Task<List<string>> GetUserRoleIdsAsync(string userId)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(userId))
|
||||
throw new ArgumentException("User ID cannot be null or empty", nameof(userId));
|
||||
|
||||
var cacheKey = $"{USER_ROLES_PREFIX}{userId}";
|
||||
|
||||
return await _cache.GetOrCreateAsync(cacheKey, async entry =>
|
||||
{
|
||||
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(CACHE_DURATION_MINUTES);
|
||||
entry.SetPriority(CacheItemPriority.High);
|
||||
|
||||
_logger.LogInformation("Cache MISS: Loading roles for user: {UserId}", userId);
|
||||
|
||||
var userRoleIds = await _dbContext.UserRoles
|
||||
.Where(ur => ur.UserId == userId)
|
||||
.Select(ur => ur.RoleId)
|
||||
.ToListAsync();
|
||||
|
||||
_logger.LogInformation("Cached {Count} roles for user: {UserId}", userRoleIds.Count, userId);
|
||||
|
||||
return userRoleIds ?? new List<string>();
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Check if a specific user has access to a controller (FULLY CACHED)
|
||||
/// </summary>
|
||||
public async Task<bool> UserHasAccessAsync(string userId, string controller)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(userId))
|
||||
throw new ArgumentException("User ID cannot be null or empty", nameof(userId));
|
||||
|
||||
if (string.IsNullOrWhiteSpace(controller))
|
||||
throw new ArgumentException("Controller name cannot be null or empty", nameof(controller));
|
||||
|
||||
try
|
||||
{
|
||||
// Get allowed role IDs from cache (or database if cache miss)
|
||||
var allowedRoleIds = await GetAllowedRoleIdsAsync(controller);
|
||||
|
||||
if (!allowedRoleIds.Any())
|
||||
{
|
||||
_logger.LogWarning("No roles configured for controller: {Controller}", controller);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Get user's role IDs from cache (or database if cache miss)
|
||||
var userRoleIds = await GetUserRoleIdsAsync(userId);
|
||||
|
||||
if (!userRoleIds.Any())
|
||||
{
|
||||
_logger.LogWarning("User {UserId} has no roles assigned", userId);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if user has any of the required roles (IN-MEMORY operation, no database!)
|
||||
var hasAccess = userRoleIds.Any(userRole => allowedRoleIds.Contains(userRole));
|
||||
|
||||
_logger.LogDebug("User {UserId} access to {Controller}: {HasAccess}", userId, controller, hasAccess);
|
||||
|
||||
return hasAccess;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error checking access for user {UserId} on controller {Controller}",
|
||||
userId, controller);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invalidate cache for a specific controller
|
||||
/// </summary>
|
||||
public void InvalidateCache(string controller)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(controller))
|
||||
return;
|
||||
|
||||
var cacheKey = $"{CONTROLLER_ROLES_PREFIX}{controller}";
|
||||
_cache.Remove(cacheKey);
|
||||
|
||||
_logger.LogInformation("Cache invalidated for controller: {Controller}", controller);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invalidate cache for a specific user (call this when user roles change)
|
||||
/// </summary>
|
||||
public void InvalidateUserCache(string userId)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(userId))
|
||||
return;
|
||||
|
||||
var cacheKey = $"{USER_ROLES_PREFIX}{userId}";
|
||||
_cache.Remove(cacheKey);
|
||||
|
||||
_logger.LogInformation("Cache invalidated for user: {UserId}", userId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invalidate all controller role caches
|
||||
/// </summary>
|
||||
public void InvalidateAllCache()
|
||||
{
|
||||
_logger.LogWarning("All cache invalidation requested - consider implementing a cache key tracking system");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -16,7 +16,7 @@ namespace CPRNIMS.Domain.UIContracts.Account
|
||||
Task<UpdateUserVM> UpdateUserProfile(UpdateUserVM viewModel, User user);
|
||||
Task<RegisterVM> DisableUserAsync(RegisterVM registerModel);
|
||||
Task<List<RegisterVM>> GetAllUserAsync(User user);
|
||||
Task<List<UserRoleVM>> GetAllRoleAsync(User user);//
|
||||
Task<List<UserRoleVM>> GetAllRoleAsync(User user);
|
||||
Task<List<ControllerAccessVM>> GetLandingPageByUserId(User user);
|
||||
Task<List<string>> GetRoles(User user);
|
||||
Task<List<RegisterVM>> GetUserProfileById(User user);
|
||||
|
||||
@ -32,7 +32,7 @@ namespace CPRNIMS.Domain.UIServices.Account
|
||||
public async Task<UserRightsVM> SendPostApiRequest(User user,
|
||||
UserRightsVM viewModel, string apiEndpoint)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
try
|
||||
{
|
||||
@ -77,7 +77,7 @@ namespace CPRNIMS.Domain.UIServices.Account
|
||||
UserRightsVM viewModel,
|
||||
string apiEndpoint)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
try
|
||||
{
|
||||
@ -211,7 +211,7 @@ namespace CPRNIMS.Domain.UIServices.Account
|
||||
}
|
||||
public async Task<List<RegisterVM>> GetUserProfileById(User user)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
if (!string.IsNullOrEmpty(token))
|
||||
{
|
||||
@ -241,7 +241,7 @@ namespace CPRNIMS.Domain.UIServices.Account
|
||||
}
|
||||
async Task<RegisterVM> IAccount.CreateUserAsync(RegisterVM registerModel, User user)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
if (!string.IsNullOrEmpty(token))
|
||||
{
|
||||
registerModel.Id = registerModel.NewUserId;
|
||||
@ -281,7 +281,7 @@ namespace CPRNIMS.Domain.UIServices.Account
|
||||
}
|
||||
async Task<List<RegisterVM>> IAccount.GetAllUserAsync(User user)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
if (!string.IsNullOrEmpty(token))
|
||||
{
|
||||
@ -350,7 +350,7 @@ namespace CPRNIMS.Domain.UIServices.Account
|
||||
}
|
||||
public async Task<List<string>> GetRoles(User user)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
if (!string.IsNullOrEmpty(token))
|
||||
{
|
||||
@ -381,7 +381,7 @@ namespace CPRNIMS.Domain.UIServices.Account
|
||||
}
|
||||
public async Task<UserRoleVM> CreateUpdateRole(UserRoleVM UserRoleVM, User user)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
if (!string.IsNullOrEmpty(token))
|
||||
{
|
||||
// Serialize the RegisterVM to JSON
|
||||
@ -410,7 +410,7 @@ namespace CPRNIMS.Domain.UIServices.Account
|
||||
}
|
||||
public async Task<List<UserRoleVM>> GetAllRoleAsync(User user)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
if (!string.IsNullOrEmpty(token))
|
||||
{
|
||||
@ -441,9 +441,10 @@ namespace CPRNIMS.Domain.UIServices.Account
|
||||
}
|
||||
public async Task<List<ControllerAccessVM>> GetLandingPageByUserId(User user)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
try
|
||||
{
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
if (!string.IsNullOrEmpty(token))
|
||||
{
|
||||
var jsonContent = JsonSerializer.Serialize(user);
|
||||
@ -472,6 +473,7 @@ namespace CPRNIMS.Domain.UIServices.Account
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle token retrieval failure
|
||||
return null;
|
||||
}
|
||||
@ -483,7 +485,7 @@ namespace CPRNIMS.Domain.UIServices.Account
|
||||
}
|
||||
public async Task<List<DepartmentVM>> GetDepartment(User user)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
if (string.IsNullOrEmpty(token))
|
||||
{
|
||||
@ -527,7 +529,7 @@ namespace CPRNIMS.Domain.UIServices.Account
|
||||
|
||||
public async Task<UpdateUserVM> UpdateUserProfile(UpdateUserVM viewModel, User user)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
if (!string.IsNullOrEmpty(token))
|
||||
{
|
||||
|
||||
@ -28,7 +28,7 @@ namespace CPRNIMS.Domain.UIServices.Attachment
|
||||
{
|
||||
try
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
if (!string.IsNullOrEmpty(token))
|
||||
{
|
||||
@ -62,7 +62,7 @@ namespace CPRNIMS.Domain.UIServices.Attachment
|
||||
}
|
||||
public async Task<string> GetAllAttachment(User user)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
if (!string.IsNullOrEmpty(token))
|
||||
{
|
||||
@ -98,7 +98,7 @@ namespace CPRNIMS.Domain.UIServices.Attachment
|
||||
}
|
||||
public async Task<string> GetAttachmentById(User user)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
if (!string.IsNullOrEmpty(token))
|
||||
{
|
||||
|
||||
@ -31,7 +31,7 @@ namespace CPRNIMS.Domain.UIServices.Canvass
|
||||
public async Task<CanvassVM> SendPostApiRequest(User user,
|
||||
CanvassVM viewModel, string apiEndpoint)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
try
|
||||
{
|
||||
@ -76,7 +76,7 @@ namespace CPRNIMS.Domain.UIServices.Canvass
|
||||
CanvassVM viewModel,
|
||||
string apiEndpoint)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
@ -4,14 +4,9 @@ using CPRNIMS.Infrastructure.Helper;
|
||||
using CPRNIMS.Infrastructure.Models.Account;
|
||||
using CPRNIMS.Infrastructure.Models.Common;
|
||||
using CPRNIMS.Infrastructure.ViewModel.Finance;
|
||||
using CPRNIMS.Infrastructure.ViewModel.PR;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace CPRNIMS.Domain.UIServices.Finance
|
||||
{
|
||||
@ -31,7 +26,7 @@ namespace CPRNIMS.Domain.UIServices.Finance
|
||||
public async Task<RRVM> SendPostApiRequest(User user,
|
||||
RRVM viewModel, string apiEndpoint)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
try
|
||||
{
|
||||
@ -76,7 +71,7 @@ namespace CPRNIMS.Domain.UIServices.Finance
|
||||
RRVM viewModel,
|
||||
string apiEndpoint)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
@ -31,7 +31,7 @@ namespace CPRNIMS.Domain.UIServices.Inventory
|
||||
public async Task<InventoryVM> SendPostApiRequest(User user,
|
||||
InventoryVM viewModel, string apiEndpoint)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
try
|
||||
{
|
||||
@ -76,7 +76,7 @@ namespace CPRNIMS.Domain.UIServices.Inventory
|
||||
InventoryVM viewModel,
|
||||
string apiEndpoint)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
@ -35,7 +35,7 @@ namespace CPRNIMS.Domain.UIServices.Items
|
||||
public async Task<ItemVM> SendPostApiRequest(Infrastructure.Models.Account.User user,
|
||||
ItemVM viewModel, string apiEndpoint)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
try
|
||||
{
|
||||
@ -81,7 +81,7 @@ namespace CPRNIMS.Domain.UIServices.Items
|
||||
ItemVM viewModel,
|
||||
string apiEndpoint)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
@ -30,7 +30,7 @@ namespace CPRNIMS.Domain.UIServices.PO
|
||||
public async Task<POVM> SendPostApiRequest(User user,
|
||||
POVM viewModel, string apiEndpoint)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
var responseObject = new ResponseObject();
|
||||
try
|
||||
{
|
||||
@ -76,7 +76,7 @@ namespace CPRNIMS.Domain.UIServices.PO
|
||||
POVM viewModel,
|
||||
string apiEndpoint)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
@ -3,12 +3,8 @@ using CPRNIMS.Domain.UIContracts.PR;
|
||||
using CPRNIMS.Infrastructure.Helper;
|
||||
using CPRNIMS.Infrastructure.Models.Account;
|
||||
using CPRNIMS.Infrastructure.Models.Common;
|
||||
using CPRNIMS.Infrastructure.ViewModel.Items;
|
||||
using CPRNIMS.Infrastructure.ViewModel.PR;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
@ -31,7 +27,7 @@ namespace CPRNIMS.Domain.UIServices.PR
|
||||
public async Task<PRVM> SendPostApiRequest(User user,
|
||||
PRVM viewModel, string apiEndpoint)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
try
|
||||
{
|
||||
@ -74,17 +70,11 @@ namespace CPRNIMS.Domain.UIServices.PR
|
||||
}
|
||||
}
|
||||
public async Task<List<PRVM>> SendGetApiRequest(User user,
|
||||
PRVM viewModel,
|
||||
string apiEndpoint)
|
||||
PRVM viewModel,string apiEndpoint)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(token))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
viewModel.UserId = user.UserId;
|
||||
var jsonContent = JsonSerializer.Serialize(viewModel);
|
||||
|
||||
@ -30,7 +30,7 @@ namespace CPRNIMS.Domain.UIServices.Receiving
|
||||
public async Task<ReceivingVM> SendPostApiRequest(User user,
|
||||
ReceivingVM viewModel, string apiEndpoint)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
try
|
||||
{
|
||||
@ -77,7 +77,7 @@ namespace CPRNIMS.Domain.UIServices.Receiving
|
||||
ReceivingVM viewModel,
|
||||
string apiEndpoint)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
@ -31,7 +31,7 @@ namespace CPRNIMS.Domain.UIServices.SMTP
|
||||
public async Task<SMTPCredentialVM> SendPostApiRequest(User user,
|
||||
SMTPCredentialVM viewModel, string apiEndpoint)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
try
|
||||
{
|
||||
@ -76,7 +76,7 @@ namespace CPRNIMS.Domain.UIServices.SMTP
|
||||
SMTPCredentialVM viewModel,
|
||||
string apiEndpoint)
|
||||
{
|
||||
var token = await _tokenHelper.GetJwtTokenAsync(user);
|
||||
var token = await _tokenHelper.GetValidTokenAsync();
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
@ -7,6 +7,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.3.9" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
@ -18,6 +19,7 @@
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.Extensions.Features" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@ -1,26 +0,0 @@
|
||||
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using CPRNIMS.Infrastructure.Entities.Account;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace CPRNIMS.Infrastructure.Database
|
||||
{
|
||||
public class AuhorizationDbContext : IdentityDbContext<IdentityUser>
|
||||
{
|
||||
public AuhorizationDbContext(DbContextOptions<AuhorizationDbContext> options) : base(options) { }
|
||||
public DbSet<AuthorizeRoles> AuthorizeRoles { get; set; }
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
base.OnModelCreating(modelBuilder);
|
||||
modelBuilder.Entity<IdentityRole>(entity =>
|
||||
{
|
||||
entity.ToTable("Roles"); // Specify the table name for roles
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -26,6 +26,7 @@ namespace CPRNIMS.Infrastructure.Database
|
||||
public virtual DbSet<Item> Items { get; set; }
|
||||
public DbSet<Departments> Departments { get; set; }
|
||||
public DbSet<IdentityRole> IdentityRoles { get; set; }
|
||||
public DbSet<AuthorizeRoles> AuthorizeRoles { get; set; }
|
||||
public DbSet<UserRights> UserRights { get; set; }
|
||||
public DbSet<IdentityUserRole<string>> IdentityUserRoles { get; set; }
|
||||
public DbSet<ForgotPassword> ForgotPasswords { get; set; }
|
||||
|
||||
14
CPRNIMS.Infrastructure/Dto/Account/LoginRequest.cs
Normal file
14
CPRNIMS.Infrastructure/Dto/Account/LoginRequest.cs
Normal file
@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace CPRNIMS.Infrastructure.Dto.Account
|
||||
{
|
||||
public class LoginRequest
|
||||
{
|
||||
public string? UserName { get; set; }
|
||||
public string? Password { get; set; }
|
||||
}
|
||||
}
|
||||
27
CPRNIMS.Infrastructure/Dto/Account/LoginResponse.cs
Normal file
27
CPRNIMS.Infrastructure/Dto/Account/LoginResponse.cs
Normal file
@ -0,0 +1,27 @@
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace CPRNIMS.Infrastructure.Dto.Account
|
||||
{
|
||||
public class LoginResponse
|
||||
{
|
||||
public object? data { get; set; }
|
||||
public bool success { get; set; }
|
||||
public string? message { get; set; }
|
||||
public byte messCode { get; set; }
|
||||
public string? userName { get; set; }
|
||||
public string? fullName { get; set; }
|
||||
public string userId { get; set; } = string.Empty;
|
||||
public string URLAttachment { get; set; } = string.Empty;
|
||||
public string? token { get; set; }
|
||||
public string? company { get; set; }
|
||||
public string? refreshToken { get; set; }
|
||||
public DateTime expiresAt { get; set; }
|
||||
public int expiresInSeconds { get; set; }
|
||||
}
|
||||
}
|
||||
16
CPRNIMS.Infrastructure/Dto/Account/Response.cs
Normal file
16
CPRNIMS.Infrastructure/Dto/Account/Response.cs
Normal file
@ -0,0 +1,16 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace CPRNIMS.Infrastructure.Dto.Account
|
||||
{
|
||||
public class Response
|
||||
{
|
||||
public object? Data { get; set; }
|
||||
public bool Success { get; set; }
|
||||
public string? Message { get; set; }
|
||||
public byte MessCode { get; set; }
|
||||
}
|
||||
}
|
||||
17
CPRNIMS.Infrastructure/Dto/Account/UserClaimsDto.cs
Normal file
17
CPRNIMS.Infrastructure/Dto/Account/UserClaimsDto.cs
Normal file
@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace CPRNIMS.Infrastructure.Dto.Account
|
||||
{
|
||||
public class UserClaimsDto
|
||||
{
|
||||
public string UserId { get; init; } = default!;
|
||||
public string UserName { get; init; } = default!;
|
||||
public string FullName { get; init; } = default!;
|
||||
public string Company { get; init; } = default!;
|
||||
public IReadOnlyList<string> Roles { get; init; } = [];
|
||||
}
|
||||
}
|
||||
@ -1,147 +1,317 @@
|
||||
using CPRNIMS.Infrastructure.Models.Account;
|
||||
using CPRNIMS.Infrastructure.Models.Common;
|
||||
using CPRNIMS.Infrastructure.Dto.Account;
|
||||
using CPRNIMS.Infrastructure.Models.Account;
|
||||
using CPRNIMS.Infrastructure.ViewModel.Account;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Security.Claims;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace CPRNIMS.Infrastructure.Helper
|
||||
{
|
||||
public class TokenHelper
|
||||
{
|
||||
private readonly HttpClient _httpClient;
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
private readonly IConfiguration _configuration;
|
||||
public TokenHelper(HttpClient httpClient, IConfiguration configuration)
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
|
||||
public TokenHelper(
|
||||
IHttpClientFactory httpClientFactory,
|
||||
IConfiguration configuration,
|
||||
IHttpContextAccessor httpContextAccessor)
|
||||
{
|
||||
_httpClient = httpClient;
|
||||
_httpClientFactory = httpClientFactory;
|
||||
_configuration = configuration;
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
}
|
||||
public async Task<string> GetRoleAsync(string username, string password, string token)
|
||||
|
||||
public async Task<LoginResponse> LoginAsync(LoginVM loginModel)
|
||||
{
|
||||
var loginModel = new LoginModel
|
||||
{
|
||||
Username = username,
|
||||
Password = password
|
||||
};
|
||||
var loginResponse = new LoginResponse();
|
||||
try
|
||||
{
|
||||
var httpClient = new HttpClient(new HttpClientHandler
|
||||
{
|
||||
ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true
|
||||
})
|
||||
{
|
||||
BaseAddress = new Uri(_configuration["CommonEndpoints:ApiDefaultHeaders:BaseUrl"]),
|
||||
DefaultRequestHeaders = {
|
||||
Authorization = new AuthenticationHeaderValue("Bearer", token)}
|
||||
};
|
||||
var response = await httpClient.PostAsJsonAsync(_configuration["Account:Claims"], loginModel);
|
||||
var httpClient = _httpClientFactory.CreateClient("AuthApi");
|
||||
var response = await httpClient.PostAsJsonAsync(
|
||||
_configuration["Account:Login"],
|
||||
loginModel);
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
var tokenResponse = await response.Content.ReadAsStringAsync();
|
||||
loginResponse = JsonSerializer.Deserialize<LoginResponse>(
|
||||
await response.Content.ReadAsStringAsync());
|
||||
|
||||
return tokenResponse;
|
||||
if (response.IsSuccessStatusCode && loginResponse != null)
|
||||
{
|
||||
return loginResponse;
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return null;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<LoginVM> LoginAsync(LoginVM loginModel)
|
||||
{
|
||||
var loginResponse = new ResponseObject();
|
||||
try
|
||||
{
|
||||
var httpClient = new HttpClient(new HttpClientHandler
|
||||
{
|
||||
ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true
|
||||
})
|
||||
{
|
||||
BaseAddress = new Uri(_configuration["CommonEndpoints:ApiDefaultHeaders:BaseUrl"]),
|
||||
};
|
||||
|
||||
// Send a POST request to the /login endpoint
|
||||
var response = await httpClient.PostAsJsonAsync(_configuration["Account:Login"], loginModel);
|
||||
|
||||
// Deserialize the JSON response
|
||||
loginResponse = JsonSerializer.Deserialize<ResponseObject>(await response.Content.ReadAsStringAsync());
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
|
||||
// Access the message property
|
||||
loginModel.Message = loginResponse.message;
|
||||
loginModel.Status = loginResponse.statusResponse;
|
||||
return loginModel;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Access the message property
|
||||
loginModel.Message = loginResponse.message;
|
||||
loginModel.Status = loginResponse.statusResponse;
|
||||
return loginModel;
|
||||
var errorContent = await response.Content.ReadAsStringAsync();
|
||||
loginResponse.message = errorContent;
|
||||
return loginResponse;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
loginModel.Message = ex.ToString();
|
||||
loginModel.Status = "Invalid";
|
||||
return loginModel;
|
||||
throw;
|
||||
loginResponse.message = ex.Message;
|
||||
return loginResponse;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<string> GetJwtTokenAsync(User loginModel)
|
||||
public async Task<string> GetValidTokenAsync()
|
||||
{
|
||||
var httpClient = new HttpClient(new HttpClientHandler
|
||||
{
|
||||
ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true
|
||||
})
|
||||
{
|
||||
BaseAddress = new Uri(_configuration["CommonEndpoints:ApiDefaultHeaders:BaseUrl"]),
|
||||
};
|
||||
var httpContext = _httpContextAccessor.HttpContext;
|
||||
|
||||
var response = await httpClient.PostAsJsonAsync(_configuration["Account:Auth"], loginModel);
|
||||
if (httpContext?.User?.Identity?.IsAuthenticated != true)
|
||||
return null;
|
||||
|
||||
// Get token from claims
|
||||
var tokenClaim = httpContext.User.FindFirst("Token");
|
||||
var expiryStr = httpContext.User.FindFirst("TokenExpiry")?.Value;
|
||||
var refreshTokenClaim = httpContext.User.FindFirst("RefreshToken");
|
||||
|
||||
if (tokenClaim == null || string.IsNullOrEmpty(tokenClaim.Value))
|
||||
return null;
|
||||
|
||||
// Check if token is expiring soon
|
||||
if (!string.IsNullOrEmpty(expiryStr) &&
|
||||
DateTime.TryParse(expiryStr, out DateTime expiry))
|
||||
{
|
||||
// If token expires in less than 5 minutes, refresh it
|
||||
if (DateTime.UtcNow.AddMinutes(5) >= expiry)
|
||||
{
|
||||
if (refreshTokenClaim != null &&
|
||||
!string.IsNullOrEmpty(refreshTokenClaim.Value))
|
||||
{
|
||||
var newTokenInfo = await RefreshTokenAsync(refreshTokenClaim.Value);
|
||||
|
||||
if (newTokenInfo != null)
|
||||
{
|
||||
// Update claims with new token
|
||||
await UpdateTokenInClaims(newTokenInfo);
|
||||
return newTokenInfo.AccessToken;
|
||||
}
|
||||
|
||||
return null; // Refresh failed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return tokenClaim.Value;
|
||||
}
|
||||
|
||||
private async Task UpdateTokenInClaims(TokenInfo tokenInfo)
|
||||
{
|
||||
var httpContext = _httpContextAccessor.HttpContext;
|
||||
var currentPrincipal = httpContext.User;
|
||||
|
||||
// Create new claims list with updated token
|
||||
var claims = currentPrincipal.Claims.Where(c =>
|
||||
c.Type != "Token" &&
|
||||
c.Type != "TokenExpiry" &&
|
||||
c.Type != "RefreshToken").ToList();
|
||||
|
||||
claims.Add(new Claim("Token", tokenInfo.AccessToken));
|
||||
claims.Add(new Claim("TokenExpiry", tokenInfo.ExpiresAt.ToString("O")));
|
||||
|
||||
if (!string.IsNullOrEmpty(tokenInfo.RefreshToken))
|
||||
claims.Add(new Claim("RefreshToken", tokenInfo.RefreshToken));
|
||||
|
||||
var identity = new ClaimsIdentity(claims,
|
||||
CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
|
||||
await httpContext.SignInAsync(
|
||||
CookieAuthenticationDefaults.AuthenticationScheme,
|
||||
new ClaimsPrincipal(identity),
|
||||
new AuthenticationProperties
|
||||
{
|
||||
IsPersistent = true,
|
||||
ExpiresUtc = DateTimeOffset.UtcNow.AddHours(2),
|
||||
AllowRefresh = true
|
||||
});
|
||||
}
|
||||
|
||||
private async Task<TokenInfo> RefreshTokenAsync(string refreshToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var httpClient = _httpClientFactory.CreateClient("AuthApi");
|
||||
var response = await httpClient.PostAsJsonAsync(
|
||||
_configuration["Account:Refresh"],
|
||||
new { refreshToken });
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
var tokenResponse = await response.Content.ReadAsStringAsync();
|
||||
var loginResponse = JsonSerializer.Deserialize<LoginResponse>(
|
||||
await response.Content.ReadAsStringAsync());
|
||||
|
||||
var tokenObj = JsonSerializer.Deserialize<Dictionary<string, string>>(tokenResponse);
|
||||
var expiresAt = CalculateExpiration(loginResponse);
|
||||
|
||||
if (tokenObj.TryGetValue("token", out var token))
|
||||
return new TokenInfo
|
||||
{
|
||||
return token;
|
||||
}
|
||||
|
||||
return tokenResponse;
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
AccessToken = loginResponse.token,
|
||||
RefreshToken = loginResponse.refreshToken,
|
||||
ExpiresAt = expiresAt,
|
||||
IssuedAt = DateTime.UtcNow,
|
||||
Claims = ExtractClaimsFromToken(loginResponse.token)
|
||||
};
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return null;
|
||||
throw;
|
||||
// Refresh failed
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private DateTime CalculateExpiration(LoginResponse response)
|
||||
{
|
||||
// Try multiple sources for expiration
|
||||
if (response.expiresInSeconds > 0)
|
||||
{
|
||||
return DateTime.UtcNow.AddSeconds(response.expiresInSeconds);
|
||||
}
|
||||
else if (response.expiresAt > DateTime.MinValue && response.expiresAt.Year > 1)
|
||||
{
|
||||
return response.expiresAt;
|
||||
}
|
||||
else if (!string.IsNullOrEmpty(response.token))
|
||||
{
|
||||
var expiry = ExtractExpirationFromToken(response.token);
|
||||
if (expiry > DateTime.MinValue)
|
||||
return expiry;
|
||||
}
|
||||
|
||||
// Default: 2 hours
|
||||
return DateTime.UtcNow.AddHours(2);
|
||||
}
|
||||
|
||||
private DateTime ExtractExpirationFromToken(string token)
|
||||
{
|
||||
try
|
||||
{
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
var jwtToken = handler.ReadJwtToken(token);
|
||||
|
||||
if (jwtToken.ValidTo != DateTime.MinValue && jwtToken.ValidTo.Year > 1)
|
||||
{
|
||||
return jwtToken.ValidTo;
|
||||
}
|
||||
|
||||
// Check exp claim
|
||||
var expClaim = jwtToken.Claims.FirstOrDefault(c => c.Type == "exp");
|
||||
if (expClaim != null && long.TryParse(expClaim.Value, out long exp))
|
||||
{
|
||||
return DateTimeOffset.FromUnixTimeSeconds(exp).UtcDateTime;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Token parsing failed
|
||||
}
|
||||
|
||||
return DateTime.MinValue;
|
||||
}
|
||||
|
||||
private Dictionary<string, string> ExtractClaimsFromToken(string token)
|
||||
{
|
||||
var claims = new Dictionary<string, string>();
|
||||
|
||||
try
|
||||
{
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
var jwtToken = handler.ReadJwtToken(token);
|
||||
|
||||
foreach (var claim in jwtToken.Claims)
|
||||
{
|
||||
if (!claims.ContainsKey(claim.Type))
|
||||
{
|
||||
claims[claim.Type] = claim.Value;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Token parsing failed
|
||||
}
|
||||
|
||||
return claims;
|
||||
}
|
||||
|
||||
public Dictionary<string, string> GetStoredClaims()
|
||||
{
|
||||
var httpContext = _httpContextAccessor.HttpContext;
|
||||
|
||||
if (httpContext?.User?.Identity?.IsAuthenticated != true)
|
||||
return new Dictionary<string, string>();
|
||||
|
||||
var tokenClaim = httpContext.User.FindFirst("Token");
|
||||
|
||||
if (tokenClaim == null || string.IsNullOrEmpty(tokenClaim.Value))
|
||||
return new Dictionary<string, string>();
|
||||
|
||||
return ExtractClaimsFromToken(tokenClaim.Value);
|
||||
}
|
||||
|
||||
// Rest of your existing methods...
|
||||
public HttpClient CreateHttpClientWithDefaultHeaders(string token)
|
||||
{
|
||||
string BaseUrl = _configuration["CommonEndpoints:ApiDefaultHeaders:BaseUrl"];
|
||||
|
||||
var httpClient = new HttpClient(new HttpClientHandler
|
||||
{
|
||||
ServerCertificateCustomValidationCallback =
|
||||
(sender, cert, chain, sslPolicyErrors) => true
|
||||
})
|
||||
{
|
||||
BaseAddress = new Uri(BaseUrl)
|
||||
};
|
||||
|
||||
httpClient.DefaultRequestHeaders.Authorization =
|
||||
new AuthenticationHeaderValue("Bearer", token);
|
||||
|
||||
var customHeaders = CustomHeaders;
|
||||
foreach (var header in customHeaders)
|
||||
{
|
||||
httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
|
||||
}
|
||||
|
||||
return httpClient;
|
||||
}
|
||||
|
||||
public Dictionary<string, string> DefaultHeaders
|
||||
{
|
||||
get
|
||||
{
|
||||
var headersSection = _configuration.GetSection(
|
||||
"CommonEndpoints:ApiDefaultHeaders");
|
||||
var headers = new Dictionary<string, string>();
|
||||
|
||||
foreach (var childSection in headersSection.GetChildren())
|
||||
{
|
||||
headers[childSection.Key] = childSection.Value;
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
}
|
||||
|
||||
public Dictionary<string, string> CustomHeaders
|
||||
{
|
||||
get
|
||||
{
|
||||
var headersSection = _configuration.GetSection(
|
||||
"CommonEndpoints:CustomApiHeaders");
|
||||
var headers = new Dictionary<string, string>();
|
||||
|
||||
foreach (var childSection in headersSection.GetChildren())
|
||||
{
|
||||
headers[childSection.Key] = childSection.Value;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
27
CPRNIMS.Infrastructure/Models/Account/TokenInfo.cs
Normal file
27
CPRNIMS.Infrastructure/Models/Account/TokenInfo.cs
Normal file
@ -0,0 +1,27 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace CPRNIMS.Infrastructure.Models.Account
|
||||
{
|
||||
public class TokenInfo
|
||||
{
|
||||
public string? AccessToken { get; set; }
|
||||
public string? RefreshToken { get; set; }
|
||||
public DateTime ExpiresAt { get; set; }
|
||||
public DateTime IssuedAt { get; set; }
|
||||
public Dictionary<string, string>? Claims { get; set; }
|
||||
|
||||
public bool IsExpiringSoon(int minutesThreshold = 5)
|
||||
{
|
||||
return DateTime.UtcNow.AddMinutes(minutesThreshold) >= ExpiresAt;
|
||||
}
|
||||
|
||||
public bool IsExpired()
|
||||
{
|
||||
return DateTime.UtcNow >= ExpiresAt;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -20,5 +20,8 @@ namespace CPRNIMS.Infrastructure.Models.Account
|
||||
public bool ErrMessage { get; set; } = false;
|
||||
public string UserId { get; set; } = string.Empty;
|
||||
public string URLAttachment { get; set; } = string.Empty;
|
||||
public string? Token { get; set; }
|
||||
public string? Company { get; set; }
|
||||
public string? MyAccess { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@ -15,6 +15,7 @@ namespace CPRNIMS.Infrastructure.Models.Common
|
||||
public string statusResponse { get; set; } = string.Empty;
|
||||
public string NewUserId { get; set; } = string.Empty;
|
||||
public string? message { get; set; }
|
||||
public string? token { get; set; }
|
||||
public long itemCode { get; set; } = 0;
|
||||
public byte messCode { get; set; }
|
||||
public bool IsValid { get; set; }
|
||||
|
||||
@ -13,8 +13,7 @@ namespace CPRNIMS.Infrastructure.ViewModel.Account
|
||||
public int Id { get; set; }
|
||||
public string? Message { get; set; }
|
||||
public string? Status { get; set; }
|
||||
public string? Token { get; internal set; }
|
||||
|
||||
//[Required(ErrorMessage = "Password is required")]
|
||||
//public string? Password { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@ -4,7 +4,7 @@
|
||||
<ActiveDebugProfile>https</ActiveDebugProfile>
|
||||
<Controller_SelectedScaffolderID>MvcControllerEmptyScaffolder</Controller_SelectedScaffolderID>
|
||||
<Controller_SelectedScaffolderCategoryPath>root/Common/MVC/Controller</Controller_SelectedScaffolderCategoryPath>
|
||||
<NameOfLastUsedPublishProfile>D:\sourcecode\CPRNIMS\CPRNIMS.WebApi\Properties\PublishProfiles\FolderProfile.pubxml</NameOfLastUsedPublishProfile>
|
||||
<NameOfLastUsedPublishProfile>D:\sourcecode\NonInventPurchasing\CPRNIMS.WebApi\Properties\PublishProfiles\FolderProfile1.pubxml</NameOfLastUsedPublishProfile>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
|
||||
|
||||
@ -95,13 +95,6 @@ namespace CPRNIMS.WebApi.Common
|
||||
sql.EnableRetryOnFailure(5, TimeSpan.FromHours(2), null);
|
||||
sql.CommandTimeout(20);
|
||||
}));
|
||||
|
||||
services.AddDbContext<AuhorizationDbContext>(options =>
|
||||
options.UseSqlServer(defaultConn, sql =>
|
||||
{
|
||||
sql.EnableRetryOnFailure(5, TimeSpan.FromHours(2), null);
|
||||
sql.CommandTimeout(20);
|
||||
}));
|
||||
}
|
||||
|
||||
private static void AddMvcServices(IServiceCollection services)
|
||||
@ -130,7 +123,7 @@ namespace CPRNIMS.WebApi.Common
|
||||
ValidateAudience = true,
|
||||
ValidAudience = builder.Configuration["JWT:ValidAudience"],
|
||||
ValidIssuer = builder.Configuration["JWT:ValidIssuer"],
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JWT:Secret"]))
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JWT:Secret"] ?? "N/A"))
|
||||
};
|
||||
});
|
||||
}
|
||||
@ -151,6 +144,8 @@ namespace CPRNIMS.WebApi.Common
|
||||
|
||||
private static void AddOtherServices(IServiceCollection services)
|
||||
{
|
||||
services.AddMemoryCache();
|
||||
services.AddScoped<IRoleAuthorizationCache, RoleAuthorizationCache>();
|
||||
services.AddScoped<IDepartment, Department>();
|
||||
services.AddScoped<IAttachment, Domain.Services.Account.Attachment>();
|
||||
services.AddScoped<IItem, Domain.Services.Items.Item>();
|
||||
|
||||
@ -1,43 +1,70 @@
|
||||
using CPRNIMS.Domain.Contracts.Account;
|
||||
using CPRNIMS.Domain.Services.Account;
|
||||
using CPRNIMS.Domain.Services;
|
||||
using CPRNIMS.Domain.Services.Account;
|
||||
using CPRNIMS.Infrastructure.Dto.Account;
|
||||
using CPRNIMS.Infrastructure.Entities.Account;
|
||||
using CPRNIMS.Infrastructure.Entities.Common;
|
||||
using CPRNIMS.Infrastructure.Helper;
|
||||
using CPRNIMS.Infrastructure.Models;
|
||||
using CPRNIMS.Infrastructure.Models.Account;
|
||||
using CPRNIMS.Infrastructure.Models.Common;
|
||||
using CPRNIMS.Infrastructure.Models;
|
||||
using CPRNIMS.Infrastructure.Security;
|
||||
using CPRNIMS.Infrastructure.ViewModel.Account;
|
||||
using CPRNIMS.WebApi.Security;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Security.Claims;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using CPRNIMS.Infrastructure.Helper;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using CPRNIMS.Infrastructure.Dto.Account;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace CPRNIMS.WebApi.Controllers.Account
|
||||
{
|
||||
[Security.AuthorizeRoles("Account")]
|
||||
public class AccountController : AnonController
|
||||
public class AccountController : Base.BaseController
|
||||
{
|
||||
private readonly ErrorMessageService _errorMessageService;
|
||||
private readonly IAttachment _attachment;
|
||||
|
||||
private readonly IAccount _account;
|
||||
private readonly IDepartment _department;
|
||||
private readonly IControllerAccess _controllerAccess;
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly UserClaimsManager _userClaimsManager;
|
||||
private readonly RoleManager<IdentityRole> _roleManager;
|
||||
public AccountController(ErrorMessageService errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment,
|
||||
SMTPHelper sMTPHelper,
|
||||
IForgotPassword forgotPassword,
|
||||
UserManager<ApplicationUser> userManager,
|
||||
SignInManager<ApplicationUser> signInManager, IConfiguration configuration,
|
||||
UserClaimsManager userClaimsManager, RoleManager<IdentityRole> roleManager,
|
||||
IControllerAccess controllerAccess, IDepartment department,
|
||||
IAccount account)
|
||||
: base(errorMessageService, webHostEnvironment,
|
||||
sMTPHelper,forgotPassword,
|
||||
userManager, signInManager, configuration, userClaimsManager, roleManager, controllerAccess, department,account)
|
||||
IWebHostEnvironment webHostEnvironment, SMTPHelper sMTPHelper,
|
||||
IConfiguration configuration,
|
||||
IAttachment attachment, IAccount account, IDepartment department, IControllerAccess controllerAccess,
|
||||
UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager,
|
||||
UserClaimsManager userClaimsManager, RoleManager<IdentityRole> roleManager
|
||||
) :
|
||||
base(errorMessageService, webHostEnvironment, sMTPHelper, configuration)
|
||||
{
|
||||
_errorMessageService = errorMessageService;
|
||||
_attachment = attachment;
|
||||
_department = department;
|
||||
_controllerAccess = controllerAccess;
|
||||
_userManager = userManager;
|
||||
_userClaimsManager = userClaimsManager;
|
||||
_roleManager = roleManager;
|
||||
_account= account;
|
||||
}
|
||||
[HttpPost("RefreshToken")]
|
||||
public async Task<IActionResult> RefreshToken()
|
||||
{
|
||||
var currentUser = User.ToUserClaims();
|
||||
if (currentUser == null)
|
||||
return Unauthorized();
|
||||
var user = new ApplicationUser
|
||||
{
|
||||
UserName = currentUser.UserName,
|
||||
};
|
||||
var token = await _account.CreateToken(user);
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
token,
|
||||
expiresAt = DateTime.UtcNow.AddMinutes(30)
|
||||
});
|
||||
}
|
||||
[HttpPut("UpdateUser")]
|
||||
public async Task<IActionResult> UpdateUserProfile([FromBody] RegisterModel model)
|
||||
|
||||
@ -1,178 +1,132 @@
|
||||
using CPRNIMS.Domain.Contracts.Account;
|
||||
using CPRNIMS.Domain.Services.Account;
|
||||
using CPRNIMS.Domain.Services;
|
||||
using CPRNIMS.Infrastructure.Entities.Account;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using CPRNIMS.Infrastructure.Models.Common;
|
||||
using CPRNIMS.Infrastructure.Models.Account;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using CPRNIMS.Infrastructure.Helper;
|
||||
using CPRNIMS.Infrastructure.Entities.Common;
|
||||
using CPRNIMS.Infrastructure.ViewModel.Common;
|
||||
using CPRNIMS.Infrastructure.Dto.Account;
|
||||
|
||||
namespace CPRNIMS.WebApi.Controllers.Account
|
||||
{
|
||||
public class AnonController : Base.BaseController
|
||||
{
|
||||
private readonly SMTPHelper _smtpHelper;
|
||||
public readonly IForgotPassword _forgotPassword;
|
||||
public readonly UserManager<ApplicationUser> _userManager;
|
||||
public readonly SignInManager<ApplicationUser> _signInManager;
|
||||
public readonly UserClaimsManager _userClaimsManager;
|
||||
public readonly RoleManager<IdentityRole> _roleManager;
|
||||
public readonly IControllerAccess _controllerAccess;
|
||||
public readonly IDepartment _department;
|
||||
public readonly IConfiguration _config;
|
||||
public readonly IAccount _account;
|
||||
private readonly IForgotPassword _forgotPassword;
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly SignInManager<ApplicationUser> _signInManager;
|
||||
private readonly IConfiguration _config;
|
||||
|
||||
public AnonController(ErrorMessageService errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment
|
||||
, SMTPHelper sMTPHelper, IForgotPassword forgotPassword
|
||||
, UserManager<ApplicationUser> userManager
|
||||
, SignInManager<ApplicationUser> signInManager
|
||||
, IConfiguration configuration
|
||||
, UserClaimsManager userClaimsManager, RoleManager<IdentityRole> roleManager
|
||||
, IControllerAccess controllerAccess, IDepartment department
|
||||
, IAccount account) :
|
||||
base(errorMessageService, webHostEnvironment, configuration)
|
||||
IWebHostEnvironment webHostEnvironment,
|
||||
SMTPHelper sMTPHelper, IConfiguration configuration,
|
||||
IForgotPassword forgotPassword,
|
||||
IDepartment department ,
|
||||
SignInManager<ApplicationUser> signInManager,
|
||||
UserManager<ApplicationUser> userManager
|
||||
)
|
||||
: base(errorMessageService, webHostEnvironment, sMTPHelper, configuration)
|
||||
{
|
||||
_config = configuration;
|
||||
_smtpHelper = sMTPHelper;
|
||||
_forgotPassword = forgotPassword;
|
||||
_userManager = userManager;
|
||||
_signInManager = signInManager;
|
||||
_userClaimsManager = userClaimsManager;
|
||||
_roleManager = roleManager;
|
||||
_controllerAccess = controllerAccess;
|
||||
_department = department;
|
||||
_config = configuration;
|
||||
_account = account;
|
||||
}
|
||||
|
||||
[AllowAnonymous]
|
||||
[HttpPost("GetToken")]
|
||||
public async Task<IActionResult> GetToken([FromBody] User model)
|
||||
[HttpPost("Login")]
|
||||
public async Task<IActionResult> Login([FromBody] LoginRequest model,
|
||||
[FromServices] IAccount tokenService)
|
||||
{
|
||||
try
|
||||
{
|
||||
{
|
||||
var user = await _userManager.FindByNameAsync(model.UserName.ToLower());
|
||||
var userRoles = await _userManager.GetRolesAsync(user);
|
||||
var signInResult = await _signInManager.CheckPasswordSignInAsync(user, model.Password, lockoutOnFailure: false);
|
||||
if (user == null)
|
||||
return BadRequest(new ResponseObject
|
||||
{
|
||||
success = false,
|
||||
messCode = 0,
|
||||
message = "Invalid username or password."
|
||||
});
|
||||
|
||||
var signInResult = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);
|
||||
|
||||
if (signInResult.Succeeded)
|
||||
{
|
||||
var authClaims = new List<Claim>
|
||||
{ new Claim(ClaimTypes.Name, user.UserName),
|
||||
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
|
||||
};
|
||||
|
||||
foreach (var userRole in userRoles)
|
||||
{
|
||||
authClaims.Add(new Claim(ClaimTypes.Role, userRole));
|
||||
}
|
||||
|
||||
var token = GetToken(authClaims);
|
||||
await HandleSuccessfulLogin(user);
|
||||
|
||||
var token = await tokenService.CreateToken(user);
|
||||
return Ok(new
|
||||
{
|
||||
token = new JwtSecurityTokenHandler().WriteToken(token),
|
||||
expiration = token.ValidTo
|
||||
token,
|
||||
expiresAt= DateTime.UtcNow.AddMinutes(30),
|
||||
userId = user.Id,
|
||||
userName = user.UserName,
|
||||
fullName = user.FullName,
|
||||
email = user.Email,
|
||||
phoneNumber = user.PhoneNumber,
|
||||
company = user.Company,
|
||||
success = true,
|
||||
messCode = 1,
|
||||
message = "Yehey!"
|
||||
});
|
||||
}
|
||||
return BadRequest();
|
||||
|
||||
return await HandleFailedLogin(user, signInResult);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, " WebApi");
|
||||
throw;
|
||||
var message = ex.InnerException?.Message ?? ex.Message;
|
||||
return BadRequest(new ResponseObject
|
||||
{
|
||||
success = false,
|
||||
messCode = 0,
|
||||
message = message
|
||||
});
|
||||
}
|
||||
}
|
||||
[AllowAnonymous]
|
||||
[HttpPost("login")]
|
||||
public async Task<IActionResult> Login([FromBody] User model)
|
||||
protected async Task HandleSuccessfulLogin(ApplicationUser user)
|
||||
{
|
||||
try
|
||||
// Unlock if necessary
|
||||
if (user.LockoutEnabled || user.LockoutEnd != null)
|
||||
{
|
||||
var user = await _userManager.FindByNameAsync(model.UserName.ToLower());
|
||||
await _userManager.SetLockoutEnabledAsync(user, false);
|
||||
user.LockoutEnd = null;
|
||||
await _userManager.UpdateAsync(user);
|
||||
}
|
||||
|
||||
if (user != null)
|
||||
// Reset failed attempts
|
||||
await _userManager.ResetAccessFailedCountAsync(user);
|
||||
}
|
||||
protected async Task<IActionResult> HandleFailedLogin(ApplicationUser user,
|
||||
Microsoft.AspNetCore.Identity.SignInResult signInResult)
|
||||
{
|
||||
// Increment failed attempts
|
||||
await _userManager.AccessFailedAsync(user);
|
||||
|
||||
if (user.AccessFailedCount > 3 || signInResult.IsLockedOut)
|
||||
{
|
||||
await _userManager.SetLockoutEnabledAsync(user, true);
|
||||
await _userManager.SetLockoutEndDateAsync(user, DateTime.Now.AddMinutes(30));
|
||||
|
||||
return BadRequest(new ResponseObject
|
||||
{
|
||||
var signInResult = await _signInManager.CheckPasswordSignInAsync(user, model.Password, lockoutOnFailure: false);
|
||||
|
||||
if (signInResult.Succeeded)
|
||||
{
|
||||
if (user.LockoutEnabled == true || user.LockoutEnd != null)
|
||||
{
|
||||
await _userManager.SetLockoutEnabledAsync(user, false);
|
||||
user.LockoutEnd = null;
|
||||
await _userManager.UpdateAsync(user);
|
||||
}
|
||||
|
||||
// Reset access failed count upon successful login
|
||||
await _userManager.ResetAccessFailedCountAsync(user);
|
||||
|
||||
var userRoles = await _userManager.GetRolesAsync(user);
|
||||
|
||||
try
|
||||
{
|
||||
var authClaims = new List<Claim> { new Claim(ClaimTypes.Name, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), };
|
||||
|
||||
foreach (var userRole in userRoles)
|
||||
{
|
||||
authClaims.Add(new Claim(ClaimTypes.Role, userRole));
|
||||
}
|
||||
|
||||
var token = GetToken(authClaims);
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
token = new JwtSecurityTokenHandler().WriteToken(token),
|
||||
expiration = token.ValidTo
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, " WebApi");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Increment access failed count
|
||||
await _userManager.AccessFailedAsync(user);
|
||||
|
||||
// Check if the access failed count reaches a threshold
|
||||
if (user.AccessFailedCount > 3)
|
||||
{
|
||||
await _userManager.SetLockoutEnabledAsync(user, true);
|
||||
await _userManager.SetLockoutEndDateAsync(user, DateTime.Now.AddMinutes(30)); // Lock the account for 30 minutes (you can adjust as needed)
|
||||
return BadRequest(new ResponseObject { success = false, statusResponse = "Failed", message = "Account is locked. Please try again after 30 minutes or contact support." });
|
||||
}
|
||||
else if (signInResult.IsLockedOut)
|
||||
{
|
||||
// Increment access failed count
|
||||
await _userManager.AccessFailedAsync(user);
|
||||
return BadRequest(new ResponseObject { success = false,statusResponse = "Failed", message = "Account is locked. Please try again after 30 minutes or contact support." });
|
||||
}
|
||||
//If the
|
||||
else
|
||||
{
|
||||
return BadRequest(new ResponseObject { success = false, statusResponse = "Failed", message = "Invalid UserName or Password, please double check!" });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return BadRequest(new ResponseObject { success = false, statusResponse = "Failed", message = "Invalid UserName or Password, please double check!" });
|
||||
success = false,
|
||||
messCode = 0,
|
||||
message = "Account is locked. Please try again after 30 minutes or contact support."
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
return BadRequest(new ResponseObject
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, " WebApi");
|
||||
return BadRequest(new ResponseObject { success = false, statusResponse = "Failed", message = message });
|
||||
}
|
||||
success = false,
|
||||
messCode = 0,
|
||||
message = "Invalid username or password, please double check!"
|
||||
});
|
||||
}
|
||||
[AllowAnonymous]
|
||||
[HttpPost("ValidateOTP")]
|
||||
|
||||
@ -17,7 +17,7 @@ namespace CPRNIMS.WebApi.Controllers.Base
|
||||
public readonly ErrorMessageService ErrorMessageService;
|
||||
public IConfiguration _configuration;
|
||||
public BaseController(ErrorMessageService errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment, IConfiguration configuration)
|
||||
IWebHostEnvironment webHostEnvironment, Infrastructure.Helper.SMTPHelper sMTPHelper, IConfiguration configuration)
|
||||
{
|
||||
ErrorMessageService = errorMessageService;
|
||||
_webHostEnvironment = webHostEnvironment;
|
||||
|
||||
@ -6,29 +6,28 @@ using CPRNIMS.Infrastructure.Entities.Canvass;
|
||||
using CPRNIMS.Infrastructure.Helper;
|
||||
using CPRNIMS.Infrastructure.ViewModel.Canvass;
|
||||
using CPRNIMS.Infrastructure.ViewModel.Common;
|
||||
using CPRNIMS.WebApi.Controllers.Base;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Text;
|
||||
|
||||
namespace CPRNIMS.WebApi.Controllers.Canvass
|
||||
{
|
||||
[Security.AuthorizeRoles("CanvassMgmt")]
|
||||
public class CanvassMgmtController : BaseController
|
||||
public class CanvassMgmtController : Base.BaseController
|
||||
{
|
||||
private readonly ISMTP _sMTP;
|
||||
private readonly SMTPHelper _smtpHelper;
|
||||
private readonly ICanvass _canvass;
|
||||
private readonly IConfiguration _config;
|
||||
|
||||
public CanvassMgmtController(ErrorMessageService errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment, IConfiguration configuration
|
||||
, ICanvass canvass, SMTPHelper sMTPHelper, ISMTP sMTP)
|
||||
: base(errorMessageService, webHostEnvironment, configuration)
|
||||
IWebHostEnvironment webHostEnvironment, SMTPHelper sMTPHelper,
|
||||
IConfiguration configuration, ICanvass canvass) :
|
||||
base(errorMessageService, webHostEnvironment, sMTPHelper, configuration)
|
||||
{
|
||||
_canvass = canvass;
|
||||
_smtpHelper = sMTPHelper;
|
||||
_sMTP = sMTP;
|
||||
_config = configuration;
|
||||
_smtpHelper = sMTPHelper;
|
||||
}
|
||||
|
||||
#region Get
|
||||
[HttpPost("GetSupplierItemWOEmail")]
|
||||
public async Task<IActionResult> GetSupplierItemWOEmail(CanvassDto viewModel)
|
||||
|
||||
@ -14,18 +14,16 @@ namespace CPRNIMS.WebApi.Controllers.Finance
|
||||
{
|
||||
public class RRMgmtController : BaseController
|
||||
{
|
||||
// private readonly ISMTP _sMTP;
|
||||
private readonly SMTPHelper _smptHelper;
|
||||
private readonly IRR _rr;
|
||||
|
||||
public RRMgmtController(ErrorMessageService errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment, IConfiguration configuration
|
||||
, IRR rr, SMTPHelper sMTPHelper)
|
||||
: base(errorMessageService, webHostEnvironment, configuration)
|
||||
IWebHostEnvironment webHostEnvironment, SMTPHelper sMTPHelper,
|
||||
IConfiguration configuration, SMTPHelper smptHelper, IRR rr) :
|
||||
base(errorMessageService, webHostEnvironment, sMTPHelper, configuration)
|
||||
{
|
||||
_rr = rr;
|
||||
_smptHelper = sMTPHelper;
|
||||
//_sMTP = sMTP;
|
||||
}
|
||||
|
||||
#region Get
|
||||
[HttpPost("GetAllClosedPO")]
|
||||
public async Task<IActionResult> GetAllClosedPO(RRDetailsDto itemCodeDto)
|
||||
|
||||
@ -11,23 +11,19 @@ using System.Text;
|
||||
|
||||
namespace CPRNIMS.WebApi.Controllers.Inventory
|
||||
{
|
||||
// [Security.AuthorizeRoles("InventoryMgmt")]
|
||||
[Security.AuthorizeRoles("InventoryMgmt")]
|
||||
public class InventoryMgmtController : BaseController
|
||||
{
|
||||
//private readonly ISMTP _sMTP;
|
||||
private readonly SMTPHelper _smptHelper;
|
||||
private readonly IInventory _inventory;
|
||||
|
||||
public InventoryMgmtController(ErrorMessageService errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment, IConfiguration configuration
|
||||
, IInventory inventory, SMTPHelper sMTPHelper
|
||||
// ISMTP sMTP
|
||||
)
|
||||
: base(errorMessageService, webHostEnvironment, configuration)
|
||||
IWebHostEnvironment webHostEnvironment, SMTPHelper sMTPHelper, IConfiguration configuration,
|
||||
IInventory inventory) :
|
||||
base(errorMessageService, webHostEnvironment, sMTPHelper, configuration)
|
||||
{
|
||||
_inventory = inventory;
|
||||
_smptHelper = sMTPHelper;
|
||||
// _sMTP = sMTP;
|
||||
}
|
||||
|
||||
#region Get
|
||||
[HttpPost("GetInventoryByUserId")]
|
||||
public async Task<IActionResult> GetInventoryByUserId(InventoryDto itemCodeDto)
|
||||
|
||||
@ -17,66 +17,39 @@ namespace CPRNIMS.WebApi.Controllers.Items
|
||||
{
|
||||
private readonly IItem _item;
|
||||
private readonly IConfiguration _config;
|
||||
private readonly SMTPHelper _smptHelper;
|
||||
private readonly ISMTP _sMTP;
|
||||
public ItemMgmtController(ErrorMessageService errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment, IConfiguration configuration,
|
||||
IItem item, SMTPHelper sMTPHelper, ISMTP sMTP)
|
||||
: base(errorMessageService, webHostEnvironment, configuration)
|
||||
IWebHostEnvironment webHostEnvironment, SMTPHelper sMTPHelper,
|
||||
IConfiguration configuration, IItem item) :
|
||||
base(errorMessageService, webHostEnvironment, sMTPHelper, configuration)
|
||||
{
|
||||
_item = item;
|
||||
_config = configuration;
|
||||
_smptHelper = sMTPHelper;
|
||||
_sMTP = sMTP;
|
||||
_item= item;
|
||||
}
|
||||
|
||||
[HttpPost("PostPutItemPath")]
|
||||
public async Task<IActionResult> PostPutItemPath(ItemDto itemDto)
|
||||
{
|
||||
try
|
||||
{
|
||||
var itemCart = await _item.PostPutItemCart(itemDto);
|
||||
|
||||
return Ok(itemCart);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApi");
|
||||
throw;
|
||||
}
|
||||
return await ExecuteWithErrorHandling(
|
||||
() => _item.PostPutItemCart(itemDto),
|
||||
nameof(PostPutItemPath), true
|
||||
);
|
||||
}
|
||||
[HttpPost("PutItemDetail")]
|
||||
public async Task<IActionResult> PutItemDetail(ItemDto itemDto)
|
||||
{
|
||||
try
|
||||
{
|
||||
var approveartWork = await _item.PutItemDetail(itemDto);
|
||||
|
||||
return Ok( new { success = true ,data = approveartWork });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApi");
|
||||
throw;
|
||||
}
|
||||
return await ExecuteWithErrorHandling(
|
||||
() => _item.PutItemDetail(itemDto),
|
||||
nameof(PutItemDetail), true
|
||||
);
|
||||
}
|
||||
|
||||
[HttpPost("PostPutItemCart")]
|
||||
public async Task<IActionResult> PostPutItemCart(ItemDto itemDto)
|
||||
{
|
||||
try
|
||||
{
|
||||
var itemCart = await _item.PostPutItemCart(itemDto);
|
||||
|
||||
return Ok(itemCart);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApi");
|
||||
throw;
|
||||
}
|
||||
return await ExecuteWithErrorHandling(
|
||||
() => _item.PostPutItemCart(itemDto),
|
||||
nameof(PostPutItemCart), true
|
||||
);
|
||||
}
|
||||
[HttpPost("PostPurchRequest")]
|
||||
public async Task<IActionResult> PostPurchRequest([FromBody] ItemVM viewModel)
|
||||
|
||||
@ -20,15 +20,16 @@ namespace CPRNIMS.WebApi.Controllers.PO
|
||||
private readonly SMTPHelper _smtpHelper;
|
||||
private readonly IPurchaseOrder _purchaseOrder;
|
||||
private readonly IConfiguration _config;
|
||||
|
||||
public POMgmtController(ErrorMessageService errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment, IConfiguration configuration
|
||||
, IPurchaseOrder purchaseOrder, SMTPHelper sMTPHelper, ISMTP sMTP)
|
||||
: base(errorMessageService, webHostEnvironment, configuration)
|
||||
IWebHostEnvironment webHostEnvironment, SMTPHelper sMTPHelper,
|
||||
IConfiguration configuration, ISMTP sMTP, IPurchaseOrder purchaseOrder) :
|
||||
base(errorMessageService, webHostEnvironment, sMTPHelper, configuration)
|
||||
{
|
||||
_purchaseOrder=purchaseOrder;
|
||||
_smtpHelper = sMTPHelper;
|
||||
_sMTP = sMTP;
|
||||
_sMTP= sMTP;
|
||||
_config = configuration;
|
||||
_purchaseOrder= purchaseOrder;
|
||||
}
|
||||
#region Post Put
|
||||
[HttpPost("PostIncShipFollowUp")]
|
||||
|
||||
@ -1,11 +1,6 @@
|
||||
using CPRNIMS.Domain.Contracts.Items;
|
||||
using CPRNIMS.Domain.Contracts.PR;
|
||||
using CPRNIMS.Domain.Contracts.SMTP;
|
||||
using CPRNIMS.Domain.Contracts.PR;
|
||||
using CPRNIMS.Domain.Services;
|
||||
using CPRNIMS.Infrastructure.Dto.PO;
|
||||
using CPRNIMS.Infrastructure.Dto.PR;
|
||||
using CPRNIMS.Infrastructure.Dto.SMTP;
|
||||
using CPRNIMS.Infrastructure.Entities.Purchasing;
|
||||
using CPRNIMS.Infrastructure.Helper;
|
||||
using CPRNIMS.Infrastructure.ViewModel.Common;
|
||||
using CPRNIMS.Infrastructure.ViewModel.PR;
|
||||
@ -21,19 +16,16 @@ namespace CPRNIMS.WebApi.Controllers.PR
|
||||
{
|
||||
private readonly IPRequest _pRequest;
|
||||
private readonly SMTPHelper _smptHelper;
|
||||
private readonly ISMTP _sMTP;
|
||||
private readonly IItem _item;
|
||||
private readonly IConfiguration _config;
|
||||
|
||||
public PRMgmtController(ErrorMessageService errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment, IConfiguration configuration
|
||||
, IPRequest pRequest, IItem item, SMTPHelper sMTPHelper, ISMTP sMTP)
|
||||
: base(errorMessageService, webHostEnvironment, configuration)
|
||||
IWebHostEnvironment webHostEnvironment, SMTPHelper sMTPHelper,
|
||||
IConfiguration configuration, IPRequest pRequest) :
|
||||
base(errorMessageService, webHostEnvironment, sMTPHelper, configuration)
|
||||
{
|
||||
_pRequest = pRequest;
|
||||
_item = item;
|
||||
_smptHelper = sMTPHelper;
|
||||
_sMTP = sMTP;
|
||||
_config = configuration;
|
||||
_smptHelper = sMTPHelper;
|
||||
_pRequest = pRequest;
|
||||
}
|
||||
#region POST PUT
|
||||
[HttpPost("PostPutDeniedItem")]
|
||||
|
||||
@ -15,21 +15,17 @@ namespace CPRNIMS.WebApi.Controllers.Receiving
|
||||
public class ReceivingController : BaseController
|
||||
{
|
||||
private readonly IReceiving _receiving;
|
||||
private readonly SMTPHelper _smptHelper;
|
||||
private readonly ISMTP _sMTP;
|
||||
private readonly IItem _item;
|
||||
private readonly IConfiguration _config;
|
||||
|
||||
public ReceivingController(ErrorMessageService errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment, IConfiguration configuration
|
||||
, IReceiving receiving, IItem item, SMTPHelper sMTPHelper, ISMTP sMTP)
|
||||
: base(errorMessageService, webHostEnvironment, configuration)
|
||||
IWebHostEnvironment webHostEnvironment, SMTPHelper sMTPHelper,
|
||||
IConfiguration configuration, IReceiving receiving, IItem item) :
|
||||
base(errorMessageService, webHostEnvironment, sMTPHelper, configuration)
|
||||
{
|
||||
_receiving = receiving;
|
||||
_item = item;
|
||||
_smptHelper = sMTPHelper;
|
||||
_sMTP = sMTP;
|
||||
_config = configuration;
|
||||
_item= item;
|
||||
}
|
||||
|
||||
#region POST PUT
|
||||
[HttpPost("PostPutReceiving")]
|
||||
public async Task<IActionResult> PostPutReceiving([FromBody] ReceivingVM viewModel)
|
||||
|
||||
@ -1,19 +1,22 @@
|
||||
using CPRNIMS.Domain.Contracts.SMTP;
|
||||
using CPRNIMS.Domain.Services;
|
||||
using CPRNIMS.Infrastructure.Dto.SMTP;
|
||||
using CPRNIMS.Infrastructure.Helper;
|
||||
using CPRNIMS.WebApi.Controllers.Base;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace CPRNIMS.WebApi.Controllers.SMTP
|
||||
{
|
||||
[Security.AuthorizeRoles("SMTPMgmt")]
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
public class SMTPMgmtController : BaseController
|
||||
{
|
||||
private readonly ISMTP _sMTP;
|
||||
public SMTPMgmtController(ErrorMessageService errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment, IConfiguration configuration
|
||||
, ISMTP sMTP)
|
||||
: base(errorMessageService, webHostEnvironment, configuration)
|
||||
IWebHostEnvironment webHostEnvironment, SMTPHelper sMTPHelper,
|
||||
IConfiguration configuration, ISMTP sMTP) :
|
||||
base(errorMessageService, webHostEnvironment, sMTPHelper, configuration)
|
||||
{
|
||||
_sMTP = sMTP;
|
||||
}
|
||||
|
||||
@ -1,13 +1,15 @@
|
||||
using CPRNIMS.Infrastructure.Database;
|
||||
using CPRNIMS.Domain.Services.Account;
|
||||
using CPRNIMS.Infrastructure.Database;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace CPRNIMS.WebApi.Security
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
|
||||
public class AuthorizeRolesAttribute : AuthorizeAttribute, IAuthorizationFilter
|
||||
public class AuthorizeRolesAttribute : AuthorizeAttribute, IAsyncAuthorizationFilter
|
||||
{
|
||||
private readonly string _controllerName;
|
||||
|
||||
@ -16,27 +18,85 @@ namespace CPRNIMS.WebApi.Security
|
||||
_controllerName = controllerName;
|
||||
}
|
||||
|
||||
public async void OnAuthorization(AuthorizationFilterContext context)
|
||||
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
var user = context.HttpContext.User;
|
||||
|
||||
if (!user.Identity?.IsAuthenticated ?? true)
|
||||
{
|
||||
context.Result = new JsonResult(new
|
||||
{
|
||||
Success = false,
|
||||
MessCode = 0,
|
||||
Message = "You must be logged in to access this resource."
|
||||
})
|
||||
{
|
||||
StatusCode = StatusCodes.Status401Unauthorized
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
var userId = user.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
|
||||
if (string.IsNullOrEmpty(userId))
|
||||
{
|
||||
context.Result = new UnauthorizedResult();
|
||||
return;
|
||||
}
|
||||
|
||||
var serviceProvider = context.HttpContext.RequestServices;
|
||||
var dbContext = serviceProvider.GetRequiredService<AuhorizationDbContext>();
|
||||
|
||||
var roles = await (from ar in dbContext.AuthorizeRoles
|
||||
join r in dbContext.Roles on ar.RoleId equals r.Id into roleJoin
|
||||
from r in roleJoin.DefaultIfEmpty()
|
||||
where ar.IsActive && ar.Controller == _controllerName
|
||||
select r.Name).ToListAsync();
|
||||
var authCache = serviceProvider.GetService<IRoleAuthorizationCache>();
|
||||
|
||||
Roles = string.Join(",", roles);
|
||||
bool hasAccess;
|
||||
|
||||
if (authCache != null)
|
||||
{
|
||||
// Use cached authorization check
|
||||
hasAccess = await authCache.UserHasAccessAsync(userId, _controllerName);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Fallback to direct database query
|
||||
var dbContext = serviceProvider.GetRequiredService<NonInventoryDbContext>();
|
||||
|
||||
hasAccess = await (
|
||||
from ar in dbContext.AuthorizeRoles
|
||||
join ur in dbContext.UserRoles on ar.RoleId equals ur.RoleId
|
||||
where ar.IsActive
|
||||
&& ar.Controller == _controllerName
|
||||
&& ur.UserId == userId
|
||||
select ar.AuthorizeRoleId
|
||||
).AnyAsync();
|
||||
}
|
||||
|
||||
if (!hasAccess)
|
||||
{
|
||||
context.Result = new JsonResult(new
|
||||
{
|
||||
Success = false,
|
||||
MessCode = 0,
|
||||
Message = "You don't have permission to access this page. Please contact your administrator."
|
||||
})
|
||||
{
|
||||
StatusCode = StatusCodes.Status403Forbidden
|
||||
};
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
catch (Exception ex)
|
||||
{
|
||||
//ex.ToString();
|
||||
//var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
//await PostErrorMessage(message, ApplicationName.Name.WebApi);
|
||||
context.Result = new StatusCodeResult(StatusCodes.Status500InternalServerError);
|
||||
context.Result = new JsonResult(new
|
||||
{
|
||||
Success = false,
|
||||
MessCode = 0,
|
||||
Message = "An error occurred while checking permissions."
|
||||
})
|
||||
{
|
||||
StatusCode = StatusCodes.Status500InternalServerError
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
25
CPRNIMS.WebApi/Security/ClaimsPrincipalExtensions.cs
Normal file
25
CPRNIMS.WebApi/Security/ClaimsPrincipalExtensions.cs
Normal file
@ -0,0 +1,25 @@
|
||||
using CPRNIMS.Infrastructure.Dto.Account;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace CPRNIMS.WebApi.Security
|
||||
{
|
||||
public static class ClaimsPrincipalExtensions
|
||||
{
|
||||
public static UserClaimsDto? ToUserClaims(this ClaimsPrincipal user)
|
||||
{
|
||||
if (user?.Identity?.IsAuthenticated != true)
|
||||
return null;
|
||||
|
||||
return new UserClaimsDto
|
||||
{
|
||||
UserId = user.FindFirstValue(ClaimTypes.NameIdentifier) ?? "",
|
||||
UserName = user.FindFirstValue(ClaimTypes.Name) ?? "",
|
||||
FullName = user.FindFirstValue("fullName") ?? "",
|
||||
Company = user.FindFirstValue("company") ?? "",
|
||||
Roles = user.FindAll(ClaimTypes.Role)
|
||||
.Select(r => r.Value)
|
||||
.ToList()
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -57,6 +57,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Common\Helper\" />
|
||||
<Folder Include="Properties\NewFolder\" />
|
||||
<Folder Include="Views\Components\CanvassMgmt\" />
|
||||
</ItemGroup>
|
||||
|
||||
62
CPRNIMS.WebApps/Common/Middleware/TokenRefreshMiddleware.cs
Normal file
62
CPRNIMS.WebApps/Common/Middleware/TokenRefreshMiddleware.cs
Normal file
@ -0,0 +1,62 @@
|
||||
using CPRNIMS.Infrastructure.Helper;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Newtonsoft.Json;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
|
||||
namespace CPRNIMS.WebApps.Common.Middleware
|
||||
{
|
||||
public class TokenRefreshMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
|
||||
public TokenRefreshMiddleware(RequestDelegate next)
|
||||
{
|
||||
_next = next;
|
||||
}
|
||||
|
||||
public async Task InvokeAsync(
|
||||
HttpContext context,
|
||||
IHttpClientFactory httpClientFactory)
|
||||
{
|
||||
var accessToken = context.Session.GetString("AccessToken");
|
||||
|
||||
if (!string.IsNullOrEmpty(accessToken) &&
|
||||
IsTokenExpiringSoon(accessToken))
|
||||
{
|
||||
var client = httpClientFactory.CreateClient($"AuthApi{"Account/RefreshToken"}");
|
||||
|
||||
var response = await client.PostAsync("RefreshToken", null);
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
var json = await response.Content.ReadAsStringAsync();
|
||||
var tokenResult = JsonConvert.DeserializeObject<TokenResult>(json);
|
||||
|
||||
context.Session.SetString("AccessToken", tokenResult.AccessToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
// refresh token invalid → force logout
|
||||
context.Session.Clear();
|
||||
context.Response.Redirect("/Home/Logout");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await _next(context);
|
||||
}
|
||||
|
||||
private static bool IsTokenExpiringSoon(string token, int thresholdMinutes = 2)
|
||||
{
|
||||
var jwt = new JwtSecurityTokenHandler().ReadJwtToken(token);
|
||||
return DateTime.UtcNow >= jwt.ValidTo.AddMinutes(-thresholdMinutes);
|
||||
}
|
||||
public class TokenResult
|
||||
{
|
||||
public string? AccessToken { get; set; }
|
||||
public DateTime Expiration { get; set; }
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@ -22,10 +22,10 @@ using CPRNIMS.Domain.UIServices.Receiving;
|
||||
using CPRNIMS.Domain.UIServices.SMTP;
|
||||
using CPRNIMS.Infrastructure.Database;
|
||||
using CPRNIMS.Infrastructure.Helper;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace CPRNIMS.WebApps.Common
|
||||
{
|
||||
@ -59,7 +59,7 @@ namespace CPRNIMS.WebApps.Common
|
||||
|
||||
private static void ConfigureHttpClient(WebApplicationBuilder builder)
|
||||
{
|
||||
builder.Services.AddHttpClient<TokenHelper>(client =>
|
||||
builder.Services.AddHttpClient("AuthApi", client =>
|
||||
{
|
||||
client.BaseAddress = new Uri(builder.Configuration["CommonEndpoints:ApiDefaultHeaders:BaseUrl"]);
|
||||
//This code block should be removed once deployed in production
|
||||
@ -71,7 +71,8 @@ namespace CPRNIMS.WebApps.Common
|
||||
|
||||
private static void AddScopedServices(WebApplicationBuilder builder)
|
||||
{
|
||||
builder.Services.AddTransient<IApiConfigurationService, ApiConfigurationService>();
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
builder.Services.AddTransient<IApiConfigurationService, ApiConfigurationService>();
|
||||
builder.Services.AddScoped<TokenHelper>();
|
||||
builder.Services.AddTransient<IItem, Item>();
|
||||
builder.Services.AddTransient<IPRequest, PRequest>();
|
||||
@ -89,16 +90,20 @@ namespace CPRNIMS.WebApps.Common
|
||||
|
||||
private static void AddSessionAndAuthentication(WebApplicationBuilder builder)
|
||||
{
|
||||
// Configure Session with sliding expiration
|
||||
builder.Services.AddDistributedMemoryCache();
|
||||
|
||||
// Configure Session with proper settings
|
||||
builder.Services.AddSession(options =>
|
||||
{
|
||||
options.IdleTimeout = TimeSpan.FromHours(2);
|
||||
options.Cookie.Name = ".CPRNIMS.Session";
|
||||
options.Cookie.HttpOnly = true;
|
||||
options.Cookie.IsEssential = true;
|
||||
options.Cookie.SameSite = SameSiteMode.Lax; // or Strict for better security
|
||||
options.Cookie.SameSite = SameSiteMode.Lax;
|
||||
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
|
||||
});
|
||||
|
||||
// Configure Authentication with sliding expiration
|
||||
// Configure Authentication
|
||||
builder.Services.AddAuthentication(options =>
|
||||
{
|
||||
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
|
||||
@ -110,46 +115,52 @@ namespace CPRNIMS.WebApps.Common
|
||||
options.LoginPath = "/Home/Index";
|
||||
options.LogoutPath = "/Home/Logout";
|
||||
options.AccessDeniedPath = "/Home/AccessDenied";
|
||||
options.Cookie.Name = ".CPRNIMS.Auth";
|
||||
|
||||
// CRITICAL: Enable sliding expiration
|
||||
options.SlidingExpiration = true;
|
||||
|
||||
// Set expiration time to match your session timeout
|
||||
options.ExpireTimeSpan = TimeSpan.FromHours(2);
|
||||
|
||||
// Cookie configuration for security
|
||||
options.Cookie.HttpOnly = true;
|
||||
//options.Cookie.SecurePolicy = CookieSecurePolicy.Always; // Requires HTTPS
|
||||
options.Cookie.SameSite = SameSiteMode.Lax;
|
||||
options.Cookie.IsEssential = true;
|
||||
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
|
||||
|
||||
// Optional: Cookie name customization
|
||||
// options.Cookie.Name = ".MyApp.Auth";
|
||||
|
||||
// Optional: Handle cookie expiration events
|
||||
options.Events = new CookieAuthenticationEvents
|
||||
{
|
||||
OnValidatePrincipal = async context =>
|
||||
{
|
||||
// Log when cookie is validated (useful for debugging)
|
||||
var lastChanged = context.Properties.IssuedUtc;
|
||||
var currentUtc = DateTimeOffset.UtcNow;
|
||||
var timeElapsed = currentUtc.Subtract(lastChanged.Value);
|
||||
var tokenExpiryClaim = context.Principal?.FindFirst("TokenExpiry");
|
||||
if (tokenExpiryClaim != null)
|
||||
{
|
||||
if (DateTime.TryParse(tokenExpiryClaim.Value, out DateTime expiry))
|
||||
{
|
||||
if (DateTime.UtcNow.AddMinutes(5) >= expiry)
|
||||
{
|
||||
// Token is expiring soon - trigger refresh
|
||||
var tokenHelper = context.HttpContext.RequestServices
|
||||
.GetRequiredService<Infrastructure.Helper.TokenHelper>();
|
||||
|
||||
await Task.CompletedTask;
|
||||
var newToken = await tokenHelper.GetValidTokenAsync();
|
||||
|
||||
if (string.IsNullOrEmpty(newToken))
|
||||
{
|
||||
context.RejectPrincipal();
|
||||
await context.HttpContext.SignOutAsync(
|
||||
CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
OnRedirectToLogin = context =>
|
||||
{
|
||||
// Handle session timeout redirect
|
||||
if (context.Request.Path.StartsWithSegments("/api"))
|
||||
{
|
||||
// For API calls, return 401 instead of redirect
|
||||
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||
}
|
||||
else
|
||||
{
|
||||
// For regular pages, redirect to login
|
||||
context.Response.Redirect(context.RedirectUri);
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
|
||||
@ -1,9 +1,7 @@
|
||||
using Azure;
|
||||
using CPRNIMS.Domain.UIContracts.Account;
|
||||
using CPRNIMS.Domain.UIContracts.Account;
|
||||
using CPRNIMS.Infrastructure.Helper;
|
||||
using CPRNIMS.Infrastructure.ViewModel.Account;
|
||||
using CPRNIMS.Infrastructure.ViewModel.Common;
|
||||
using CPRNIMS.Infrastructure.ViewModel.Finance;
|
||||
using CPRNIMS.WebApps.Controllers.Base;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
@ -13,10 +11,9 @@ namespace CPRNIMS.WebApps.Controllers.Account
|
||||
{
|
||||
private readonly IAccount _account;
|
||||
List<UserRightsVM>? response;
|
||||
List<RegisterVM>? userResponse;
|
||||
public AccountController(IWebHostEnvironment webHostEnvironment,
|
||||
IAccount account, TokenHelper tokenHelper, ErrorLogHelper errorMessageService
|
||||
) : base(tokenHelper, errorMessageService, webHostEnvironment)
|
||||
IAccount account,ErrorLogHelper errorMessageService,TokenHelper tokenHelper
|
||||
) : base(errorMessageService, webHostEnvironment,tokenHelper)
|
||||
{
|
||||
_account = account;
|
||||
}
|
||||
@ -38,7 +35,6 @@ namespace CPRNIMS.WebApps.Controllers.Account
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "AccWebApps");
|
||||
return BadRequest();
|
||||
}
|
||||
}
|
||||
@ -59,7 +55,6 @@ namespace CPRNIMS.WebApps.Controllers.Account
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "AccWebApps");
|
||||
return Json(new { data = "No Data" });
|
||||
}
|
||||
|
||||
@ -82,7 +77,6 @@ namespace CPRNIMS.WebApps.Controllers.Account
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "AccWebApps");
|
||||
return Json(new { data = "No Data" });
|
||||
}
|
||||
}
|
||||
@ -102,7 +96,7 @@ namespace CPRNIMS.WebApps.Controllers.Account
|
||||
AccessTypeId = userRightsList.SelectMany(ic => ic.AccessTypeId).ToList(),
|
||||
IsActive = userRightsList.SelectMany(ic => ic.IsActive).ToList()
|
||||
};
|
||||
var cred = await GetUser();
|
||||
var cred = GetUser();
|
||||
viewModel.AdminUserId = cred.UserId;
|
||||
postPutItem = await _account.PutPostUserAccess(cred, viewModel);
|
||||
if (postPutItem.messCode != 0)
|
||||
@ -119,7 +113,6 @@ namespace CPRNIMS.WebApps.Controllers.Account
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
return Json(new { success = false, response = postPutItem.errMessage });
|
||||
}
|
||||
}
|
||||
@ -146,12 +139,10 @@ namespace CPRNIMS.WebApps.Controllers.Account
|
||||
|
||||
viewModel.Attachment = attachment;
|
||||
}
|
||||
var cred = await GetUser();
|
||||
var (newCred, isValid) = await GetStoreCredAsync(cred, await _tokenHelper.GetJwtTokenAsync(cred));
|
||||
|
||||
viewModel.Password = viewModel.NewPassword;
|
||||
// var registerResponse = await _account.UpdateUserProfile(viewModel, newCred);
|
||||
var registerResponse = await _account.CreateUserAsync(viewModel, await GetUser());
|
||||
var registerResponse = await _account.CreateUserAsync(viewModel, GetUser());
|
||||
if (registerResponse.statusResponse != "Error")
|
||||
{
|
||||
return Json(new { success = true });
|
||||
@ -162,7 +153,7 @@ namespace CPRNIMS.WebApps.Controllers.Account
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -170,10 +161,9 @@ namespace CPRNIMS.WebApps.Controllers.Account
|
||||
{
|
||||
try
|
||||
{
|
||||
var cred = await GetUser();
|
||||
var (myCred, isValid) = await GetStoreCredAsync(cred, await _tokenHelper.GetJwtTokenAsync(cred));
|
||||
var cred = GetUser();
|
||||
|
||||
var response = await _account.GetUserProfileById(myCred);
|
||||
var response = await _account.GetUserProfileById(cred);
|
||||
|
||||
if (response != null)
|
||||
{
|
||||
@ -187,7 +177,6 @@ namespace CPRNIMS.WebApps.Controllers.Account
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
return BadRequest();
|
||||
}
|
||||
}
|
||||
@ -195,7 +184,7 @@ namespace CPRNIMS.WebApps.Controllers.Account
|
||||
{
|
||||
try
|
||||
{
|
||||
var registerResponse = await _account.CreateUserAsync(register, await GetUser());
|
||||
var registerResponse = await _account.CreateUserAsync(register, GetUser());
|
||||
if (registerResponse.statusResponse != "Error")
|
||||
{
|
||||
return Json(new { success = true });
|
||||
@ -205,7 +194,7 @@ namespace CPRNIMS.WebApps.Controllers.Account
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -213,36 +202,27 @@ namespace CPRNIMS.WebApps.Controllers.Account
|
||||
{
|
||||
try
|
||||
{
|
||||
var userResponse = await _account.GetAllUserAsync(await GetUser());
|
||||
var userResponse = await _account.GetAllUserAsync(GetUser());
|
||||
return Json(new { data = userResponse });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
|
||||
return Json(new { data = "No Data" }); // Return empty array instead of "No Data" string
|
||||
}
|
||||
}
|
||||
public async Task<IActionResult> GetDepartment()
|
||||
{
|
||||
try
|
||||
{
|
||||
var viewModels = new UserRightsVM();
|
||||
response = await _account.GetDepartment(await GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage("GetDepartment:" + message, "WebApps");
|
||||
throw;
|
||||
}
|
||||
var viewModels = new UserRightsVM();
|
||||
response = await _account.GetDepartment(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetRoles()
|
||||
{
|
||||
try
|
||||
{
|
||||
var response = await _account.GetRoles(await GetUser());
|
||||
var response = await _account.GetRoles(GetUser());
|
||||
|
||||
if (response != null)
|
||||
{
|
||||
@ -258,7 +238,7 @@ namespace CPRNIMS.WebApps.Controllers.Account
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
|
||||
return Json(new { data = "No Data" });
|
||||
}
|
||||
}
|
||||
@ -266,13 +246,13 @@ namespace CPRNIMS.WebApps.Controllers.Account
|
||||
{
|
||||
try
|
||||
{
|
||||
response = await _account.GetUserRights(await GetUser(), viewModels);
|
||||
response = await _account.GetUserRights(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
|
||||
return Json(new { data = "No Data" });
|
||||
}
|
||||
}
|
||||
@ -280,11 +260,7 @@ namespace CPRNIMS.WebApps.Controllers.Account
|
||||
#region Views
|
||||
public async Task<IActionResult> Index()
|
||||
{
|
||||
if (GetUser() == null)
|
||||
{
|
||||
RedirectToAction("Logout", "Home");
|
||||
}
|
||||
await GetStoreCredAsync(await GetUser(), await _tokenHelper.GetJwtTokenAsync(await GetUser()));
|
||||
await IsAuthenTicated();
|
||||
return View();
|
||||
}
|
||||
#endregion
|
||||
|
||||
@ -1,82 +1,113 @@
|
||||
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.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Newtonsoft.Json;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace CPRNIMS.WebApps.Controllers.Base
|
||||
{
|
||||
public class BaseMethod : BaseProperties
|
||||
public abstract 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)
|
||||
protected readonly ErrorLogHelper ErrorMessageService;
|
||||
protected readonly IWebHostEnvironment WebHostEnvironment;
|
||||
protected readonly Infrastructure.Helper.TokenHelper TokenHelper;
|
||||
|
||||
protected BaseMethod(
|
||||
ErrorLogHelper errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment,
|
||||
Infrastructure.Helper.TokenHelper tokenHelper)
|
||||
{
|
||||
_configuration = configuration;
|
||||
_httpClient = httpClient;
|
||||
}
|
||||
public BaseMethod(TokenHelper tokenHelper, ErrorLogHelper errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment)
|
||||
{
|
||||
_tokenHelper = tokenHelper;
|
||||
ErrorMessageService = errorMessageService;
|
||||
_webHostEnvironment = webHostEnvironment;
|
||||
WebHostEnvironment = webHostEnvironment;
|
||||
TokenHelper = tokenHelper;
|
||||
}
|
||||
public AttachmentVM CreateUpdateAttachment(string contentValueBytes)
|
||||
|
||||
protected Infrastructure.Models.Account.User GetUser()
|
||||
{
|
||||
var base64Image = contentValueBytes.Split(',')[1];
|
||||
byte[] contentBytes = Convert.FromBase64String(base64Image);
|
||||
if (!User.Identity?.IsAuthenticated ?? true)
|
||||
return null;
|
||||
|
||||
var facadeAttachment = new FacadeAttachment();
|
||||
var roles = User.FindAll(ClaimTypes.Role).Select(r => r.Value).ToList();
|
||||
|
||||
var (imageFormat, imageEncoder, imageResult) = facadeAttachment.GetImageFormatAndEncoder
|
||||
(contentValueBytes);
|
||||
if (imageResult != "Format is valid")
|
||||
UserRoles = roles.Any() ? string.Join(",", roles) : null;
|
||||
|
||||
return new Infrastructure.Models.Account.User
|
||||
{
|
||||
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
|
||||
|
||||
UserId = User.FindFirstValue(ClaimTypes.NameIdentifier),
|
||||
UserName = User.Identity?.Name,
|
||||
FullName = User.FindFirst("FullName")?.Value,
|
||||
Company = User.FindFirst("Company")?.Value,
|
||||
MyAccess = UserRoles,
|
||||
URLAttachment = User.FindFirst("URLAttachment")?.Value
|
||||
};
|
||||
await ErrorMessageService.ErrorLogs(errorMessage);
|
||||
}
|
||||
private class AttributeResponse
|
||||
protected async Task<string> GetValidTokenAsync()
|
||||
{
|
||||
public string? Response { get; set; }
|
||||
var token = await TokenHelper.GetValidTokenAsync();
|
||||
|
||||
if (string.IsNullOrEmpty(token))
|
||||
{
|
||||
// Token refresh failed, user needs to re-login
|
||||
await HttpContext.SignOutAsync(
|
||||
CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
return null;
|
||||
}
|
||||
|
||||
return token;
|
||||
}
|
||||
protected Dictionary<string, string> GetTokenClaims()
|
||||
{
|
||||
return TokenHelper.GetStoredClaims();
|
||||
}
|
||||
|
||||
protected async Task<IActionResult> IsAuthenTicated()
|
||||
{
|
||||
if (!User.Identity.IsAuthenticated)
|
||||
return RedirectToAction("Index", "Home");
|
||||
|
||||
// Ensure token is still valid
|
||||
var token = await GetValidTokenAsync();
|
||||
if (string.IsNullOrEmpty(token))
|
||||
return RedirectToAction("Index", "Home");
|
||||
|
||||
PopulateViewBagFromClaims();
|
||||
return View();
|
||||
}
|
||||
|
||||
protected void PopulateViewBagFromClaims()
|
||||
{
|
||||
if (!User.Identity?.IsAuthenticated ?? true)
|
||||
return;
|
||||
|
||||
ViewBag.UserId = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
ViewBag.UserName = User.Identity?.Name;
|
||||
ViewBag.FullName = User.FindFirst("FullName")?.Value;
|
||||
ViewBag.UserCompany = User.FindFirst("Company")?.Value;
|
||||
ViewBag.UserRoles = string.Join(",",
|
||||
User.FindAll(ClaimTypes.Role).Select(c => c.Value));
|
||||
ViewBag.URLAttachment = User.FindFirst("URLAttachment")?.Value;
|
||||
}
|
||||
|
||||
protected IActionResult GetResponse<T>(T response)
|
||||
{
|
||||
return Json(new
|
||||
{
|
||||
success = response != null,
|
||||
data = response ?? Activator.CreateInstance<T>()
|
||||
});
|
||||
}
|
||||
|
||||
protected string ResolveProfileImage(string urlAttachment)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(urlAttachment)
|
||||
? "Content/Images/UserProfile/404userImage.jpg"
|
||||
: urlAttachment;
|
||||
}
|
||||
public void GetStoreAttachment(string urlContent, bool isNull)
|
||||
{
|
||||
|
||||
if (!String.IsNullOrEmpty(urlContent) && isNull == true)
|
||||
{
|
||||
HttpContext.Session.SetString("URLAttachment", urlContent);
|
||||
@ -90,153 +121,42 @@ namespace CPRNIMS.WebApps.Controllers.Base
|
||||
ViewBag.URLAttachment = HttpContext.Session.GetString("URLAttachment");
|
||||
}
|
||||
}
|
||||
public async Task<(Infrastructure.Models.Account.User, bool)>
|
||||
GetStoreCredAsync(Infrastructure.Models.Account.User user, string token)
|
||||
protected AttachmentVM CreateUpdateAttachment(string contentValueBytes)
|
||||
{
|
||||
var responseObj = new AttributeResponse();
|
||||
UserRoles = await _tokenHelper.GetRoleAsync(user.UserName, user.Password, token);
|
||||
var base64Image = contentValueBytes.Split(',')[1];
|
||||
byte[] contentBytes = Convert.FromBase64String(base64Image);
|
||||
|
||||
var userClaimsResponse = JsonConvert.DeserializeObject<UserClaimsResponse>(UserRoles);
|
||||
var facadeAttachment = new FacadeAttachment();
|
||||
|
||||
var userRoles = userClaimsResponse.UserRoles;
|
||||
var (imageFormat, imageEncoder, imageResult) =
|
||||
facadeAttachment.GetImageFormatAndEncoder(contentValueBytes);
|
||||
|
||||
UserId = userClaimsResponse.UserId;
|
||||
if (imageResult != "Format is valid")
|
||||
return new AttachmentVM { Result = imageResult };
|
||||
|
||||
try
|
||||
{
|
||||
var myClaimsInfo = userClaimsResponse.OtherClaims.FirstOrDefault();
|
||||
var (isValid, isValidResult) =
|
||||
facadeAttachment.CheckFileSize(contentBytes, 2 * 1024 * 1024);
|
||||
|
||||
string myClaims = myClaimsInfo?.value ?? string.Empty;
|
||||
string myCompany = myClaimsInfo?.company ?? string.Empty;
|
||||
FullName = myClaimsInfo?.FullName ?? string.Empty;
|
||||
if (!isValid)
|
||||
return new AttachmentVM { Result = isValidResult };
|
||||
|
||||
UserCompany = myCompany;
|
||||
MyAccess = myClaims;
|
||||
var fileName = $"{Guid.NewGuid()}.{imageFormat.Name.ToLower()}";
|
||||
var filePath = Path.Combine(
|
||||
WebHostEnvironment.WebRootPath,
|
||||
FileExtensionPath.GetExtensionPath(imageFormat.Name.ToLower()),
|
||||
fileName);
|
||||
|
||||
UserRoles = string.Join(",", userRoles);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
var credNull = new Infrastructure.Models.Account.User();
|
||||
var relativePath =
|
||||
Path.GetRelativePath(WebHostEnvironment.WebRootPath, filePath);
|
||||
|
||||
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();
|
||||
return facadeAttachment.SaveAttachment(
|
||||
contentBytes,
|
||||
relativePath,
|
||||
imageEncoder,
|
||||
fileName,
|
||||
imageFormat.Name.ToLower() == "png"
|
||||
? FileExtension.Png
|
||||
: FileExtension.Jpeg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -14,7 +14,7 @@ namespace CPRNIMS.WebApps.Controllers.Canvass
|
||||
IWebHostEnvironment webHostEnvironment
|
||||
, ICanvass canvass
|
||||
)
|
||||
: base(tokenHelper, errorMessageService, webHostEnvironment)
|
||||
: base(errorMessageService, webHostEnvironment, tokenHelper)
|
||||
{
|
||||
_canvass = canvass;
|
||||
}
|
||||
@ -29,7 +29,7 @@ namespace CPRNIMS.WebApps.Controllers.Canvass
|
||||
ItemNo = CanvassList.SelectMany(ic => ic.ItemNo).ToList(),
|
||||
PRNo = CanvassList.SelectMany(ic => ic.PRNo).ToList(),
|
||||
};
|
||||
var postPutItem = await _canvass.PostCanvass(await GetUser(), viewModel);
|
||||
var postPutItem = await _canvass.PostCanvass(GetUser(), viewModel);
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
return Json(new { success = true });
|
||||
@ -43,7 +43,7 @@ namespace CPRNIMS.WebApps.Controllers.Canvass
|
||||
}
|
||||
public async Task<IActionResult> PostPutSupplier(CanvassVM viewModel)
|
||||
{
|
||||
var postPutItem = await _canvass.PostPutSupplier(await GetUser(), viewModel);
|
||||
var postPutItem = await _canvass.PostPutSupplier(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
@ -63,7 +63,7 @@ namespace CPRNIMS.WebApps.Controllers.Canvass
|
||||
{
|
||||
SupplierId = SupplierList.SelectMany(ic => ic.SupplierId).ToList(),
|
||||
};
|
||||
postPutItem = await _canvass.PostTaggingSupplier(await GetUser(), viewModel);
|
||||
postPutItem = await _canvass.PostTaggingSupplier(GetUser(), viewModel);
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
return Json(new { success = true });
|
||||
@ -78,7 +78,7 @@ namespace CPRNIMS.WebApps.Controllers.Canvass
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
|
||||
return Json(new { success = false, response = postPutItem.errMessage });
|
||||
}
|
||||
}
|
||||
@ -94,7 +94,7 @@ namespace CPRNIMS.WebApps.Controllers.Canvass
|
||||
{
|
||||
ItemNo = ItemList.SelectMany(ic => ic.ItemNo).ToList(),
|
||||
};
|
||||
postPutItem = await _canvass.PostPutItemTagging(await GetUser(), viewModel);
|
||||
postPutItem = await _canvass.PostPutItemTagging(GetUser(), viewModel);
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
return Json(new { success = true });
|
||||
@ -109,13 +109,13 @@ namespace CPRNIMS.WebApps.Controllers.Canvass
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
|
||||
return Json(new { success = false, response = postPutItem.errMessage });
|
||||
}
|
||||
}
|
||||
public async Task<IActionResult> PostApprovedSupp(CanvassVM viewModel)
|
||||
{
|
||||
var postPutItem = await _canvass.PostApprovedSupp(await GetUser(), viewModel);
|
||||
var postPutItem = await _canvass.PostApprovedSupp(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
@ -126,7 +126,7 @@ namespace CPRNIMS.WebApps.Controllers.Canvass
|
||||
}
|
||||
public async Task<IActionResult> PostSuggestedSupp(CanvassVM viewModel)
|
||||
{
|
||||
var postPutItem = await _canvass.PostSuggestedSupp(await GetUser(), viewModel);
|
||||
var postPutItem = await _canvass.PostSuggestedSupp(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
@ -137,7 +137,7 @@ namespace CPRNIMS.WebApps.Controllers.Canvass
|
||||
}
|
||||
public async Task<IActionResult> PutSuppUnitPrice(CanvassVM viewModel)
|
||||
{
|
||||
var postPutItem = await _canvass.PutSuppUnitPrice(await GetUser(), viewModel);
|
||||
var postPutItem = await _canvass.PutSuppUnitPrice(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
@ -148,7 +148,7 @@ namespace CPRNIMS.WebApps.Controllers.Canvass
|
||||
}
|
||||
public async Task<IActionResult> PutSuppBidDetails(CanvassVM viewModel)
|
||||
{
|
||||
var postPutItem = await _canvass.PutSuppBidDetails(await GetUser(), viewModel);
|
||||
var postPutItem = await _canvass.PutSuppBidDetails(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
@ -159,7 +159,7 @@ namespace CPRNIMS.WebApps.Controllers.Canvass
|
||||
}
|
||||
public async Task<IActionResult> PostPutMySupplier(CanvassVM viewModel)
|
||||
{
|
||||
var postPutItem = await _canvass.PostPutMySupplier(await GetUser(), viewModel);
|
||||
var postPutItem = await _canvass.PostPutMySupplier(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
@ -170,7 +170,7 @@ namespace CPRNIMS.WebApps.Controllers.Canvass
|
||||
}
|
||||
public async Task<IActionResult> UnlockFormLink(CanvassVM viewModel)
|
||||
{
|
||||
var postPutItem = await _canvass.UnlockFormLink(await GetUser(), viewModel);
|
||||
var postPutItem = await _canvass.UnlockFormLink(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
@ -185,122 +185,122 @@ namespace CPRNIMS.WebApps.Controllers.Canvass
|
||||
{
|
||||
var viewModels = new CanvassVM();
|
||||
viewModels.PRNo = PRNo;
|
||||
response = await _canvass.GetItemSupplierWOEmail(await GetUser(), viewModels);
|
||||
response = await _canvass.GetItemSupplierWOEmail(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetSupplierById(CanvassVM viewModel)
|
||||
{
|
||||
response = await _canvass.GetSupplierById(await GetUser(), viewModel);
|
||||
response = await _canvass.GetSupplierById(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetSupplierItemWOEmail(long ItemNo)
|
||||
{
|
||||
var viewModels = new CanvassVM();
|
||||
viewModels.ItemNo = ItemNo;
|
||||
response = await _canvass.GetSupplierItemWOEmail(await GetUser(), viewModels);
|
||||
response = await _canvass.GetSupplierItemWOEmail(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetCanvassPerSupplier()
|
||||
{
|
||||
var viewModels = new CanvassVM();
|
||||
response = await _canvass.GetCanvassPerSupplier(await GetUser(), viewModels);
|
||||
response = await _canvass.GetCanvassPerSupplier(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetCanvassPerSupplierEmail(CanvassVM viewModel)
|
||||
{
|
||||
response = await _canvass.GetCanvassPerSupplierEmail(await GetUser(), viewModel);
|
||||
response = await _canvass.GetCanvassPerSupplierEmail(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetCanvassPerSupplierId(CanvassVM viewModel)
|
||||
{
|
||||
response = await _canvass.GetCanvassPerSupplierId(await GetUser(), viewModel);
|
||||
response = await _canvass.GetCanvassPerSupplierId(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetSupplierBid(CanvassVM viewModels)
|
||||
{
|
||||
response = await _canvass.GetSupplierBid(await GetUser(), viewModels);
|
||||
response = await _canvass.GetSupplierBid(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetAlternativeOfferByPRDetailId(CanvassVM viewModels)
|
||||
{
|
||||
response = await _canvass.GetAlternativeOfferByPRDetailId(await GetUser(), viewModels);
|
||||
response = await _canvass.GetAlternativeOfferByPRDetailId(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetSupplierBidByItem(CanvassVM viewModel)
|
||||
{
|
||||
response = await _canvass.GetSupplierBidByItem(await GetUser(), viewModel);
|
||||
response = await _canvass.GetSupplierBidByItem(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetSupplierBidById(CanvassVM viewModel)
|
||||
{
|
||||
response = await _canvass.GetSupplierBidById(await GetUser(), viewModel);
|
||||
response = await _canvass.GetSupplierBidById(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetCanvassByPRNo(long PRNo)
|
||||
{
|
||||
var viewModels = new CanvassVM();
|
||||
viewModels.PRNo = PRNo;
|
||||
response = await _canvass.GetCanvassByPRNo(await GetUser(), viewModels);
|
||||
response = await _canvass.GetCanvassByPRNo(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetCanvassById()
|
||||
{
|
||||
var viewModels = new CanvassVM();
|
||||
response = await _canvass.GetCanvassById(await GetUser(), viewModels);
|
||||
response = await _canvass.GetCanvassById(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetPRItemList()
|
||||
{
|
||||
var viewModels = new CanvassVM();
|
||||
response = await _canvass.GetPRItemList(await GetUser(), viewModels);
|
||||
response = await _canvass.GetPRItemList(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetPRItem(long ItemNo)
|
||||
{
|
||||
var viewModels = new CanvassVM();
|
||||
viewModels.ItemNo = ItemNo;
|
||||
response = await _canvass.GetPRItem(await GetUser(), viewModels);
|
||||
response = await _canvass.GetPRItem(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetCanvassWOResponse()
|
||||
{
|
||||
var viewModels = new CanvassVM();
|
||||
response = await _canvass.GetCanvassWOResponse(await GetUser(), viewModels);
|
||||
response = await _canvass.GetCanvassWOResponse(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetWOResponseBySuppId(CanvassVM viewModels)
|
||||
{
|
||||
response = await _canvass.GetWOResponseBySuppId(await GetUser(), viewModels);
|
||||
response = await _canvass.GetWOResponseBySuppId(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetForCanvassPerItem()
|
||||
{
|
||||
var viewModels = new CanvassVM();
|
||||
response = await _canvass.GetForCanvassPerItem(await GetUser(), viewModels);
|
||||
response = await _canvass.GetForCanvassPerItem(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetPRListByPRNo(CanvassVM viewModel)
|
||||
{
|
||||
response = await _canvass.
|
||||
GetPRListByPRNo(await GetUser(), viewModel);
|
||||
GetPRListByPRNo(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetMySuppliers(CanvassVM viewModel)
|
||||
{
|
||||
response = await _canvass.
|
||||
GetMySuppliers(await GetUser(), viewModel);
|
||||
GetMySuppliers(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetMyPRWOCanvass(CanvassVM viewModel)
|
||||
{
|
||||
response = await _canvass.
|
||||
GetMyPRWOCanvass(await GetUser(), viewModel);
|
||||
GetMyPRWOCanvass(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetCanvassGroupByPRNo(CanvassVM viewModel)
|
||||
{
|
||||
response = await _canvass.
|
||||
GetCanvassGroupByPRNo(await GetUser(), viewModel);
|
||||
GetCanvassGroupByPRNo(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
#endregion
|
||||
|
||||
@ -11,10 +11,10 @@ namespace CPRNIMS.WebApps.Controllers.Finance
|
||||
{
|
||||
List<RRVM>? response;
|
||||
private readonly IRR _rr;
|
||||
public RRMgmtController(TokenHelper tokenHelper, ErrorLogHelper errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment
|
||||
public RRMgmtController(ErrorLogHelper errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment, TokenHelper tokenHelper
|
||||
, IRR pRequest)
|
||||
: base(tokenHelper, errorMessageService, webHostEnvironment)
|
||||
: base(errorMessageService, webHostEnvironment, tokenHelper)
|
||||
{
|
||||
_rr = pRequest;
|
||||
}
|
||||
@ -24,13 +24,13 @@ namespace CPRNIMS.WebApps.Controllers.Finance
|
||||
try
|
||||
{
|
||||
var viewModels = new RRVM();
|
||||
response = await _rr.GetAllClosedPO(await GetUser(), viewModels);
|
||||
response = await _rr.GetAllClosedPO(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -38,13 +38,13 @@ namespace CPRNIMS.WebApps.Controllers.Finance
|
||||
{
|
||||
try
|
||||
{
|
||||
response = await _rr.GetRRDetailByPO(await GetUser(), viewModels);
|
||||
response = await _rr.GetRRDetailByPO(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -60,7 +60,7 @@ namespace CPRNIMS.WebApps.Controllers.Finance
|
||||
{
|
||||
PRDetailsId = ItemList.SelectMany(ic => ic.PRDetailsId).ToList()
|
||||
};
|
||||
var postPutItem = await _rr.PostPutPayment(await GetUser(), viewModel);
|
||||
var postPutItem = await _rr.PostPutPayment(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.StatusResponse != "Error")
|
||||
{
|
||||
@ -74,7 +74,7 @@ namespace CPRNIMS.WebApps.Controllers.Finance
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -82,11 +82,7 @@ namespace CPRNIMS.WebApps.Controllers.Finance
|
||||
#region Views
|
||||
public async Task<IActionResult> Index()
|
||||
{
|
||||
if (GetUser() == null)
|
||||
{
|
||||
RedirectToAction("Logout", "Home");
|
||||
}
|
||||
await GetStoreCredAsync(await GetUser(), await _tokenHelper.GetJwtTokenAsync(await GetUser()));
|
||||
await IsAuthenTicated();
|
||||
return View();
|
||||
}
|
||||
#endregion
|
||||
|
||||
@ -1,16 +1,19 @@
|
||||
using CPRNIMS.Domain.Services;
|
||||
using CPRNIMS.Domain.Services;
|
||||
using CPRNIMS.Domain.UIContracts.Account;
|
||||
using CPRNIMS.Domain.UIContracts.Attachment;
|
||||
using CPRNIMS.Domain.UIContracts.CaptCha;
|
||||
using CPRNIMS.Infrastructure.Helper;
|
||||
using CPRNIMS.Infrastructure.Models.Account;
|
||||
using CPRNIMS.Infrastructure.ViewModel.Account;
|
||||
using CPRNIMS.WebApps.Controllers.Base;
|
||||
using CPRNIMS.WebApps.Models;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Diagnostics;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Web;
|
||||
using System.Drawing.Imaging;
|
||||
using System.Drawing;
|
||||
|
||||
namespace CPRNIMS.WebApps.Controllers
|
||||
{
|
||||
@ -20,16 +23,18 @@ namespace CPRNIMS.WebApps.Controllers
|
||||
private readonly IAccount _account;
|
||||
private readonly IAttachment _attachment;
|
||||
private readonly ICaptchaService _captchaService;
|
||||
private readonly TokenHelper _tokenHelper;
|
||||
public HomeController(TokenHelper tokenHelper,
|
||||
ErrorLogHelper errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment,
|
||||
IAttachment attachment, IAccount account,
|
||||
ICaptchaService captchaService) :
|
||||
base(tokenHelper, errorMessageService, webHostEnvironment)
|
||||
base(errorMessageService, webHostEnvironment,tokenHelper)
|
||||
{
|
||||
_account = account;
|
||||
_attachment = attachment;
|
||||
_captchaService = captchaService;
|
||||
_tokenHelper = tokenHelper;
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult GetCaptcha()
|
||||
@ -117,74 +122,131 @@ namespace CPRNIMS.WebApps.Controllers
|
||||
var cred = new Infrastructure.Models.Account.User { ErrMessage = false };
|
||||
return View(cred);
|
||||
}
|
||||
public async Task<IActionResult> RouteController(Infrastructure.Models.Account.User user)
|
||||
public async Task<IActionResult> RouteController(User user)
|
||||
{
|
||||
try
|
||||
{
|
||||
var storedCaptchaCode = HttpContext.Session.GetString("CaptchaCode");
|
||||
|
||||
if (string.IsNullOrEmpty(storedCaptchaCode))
|
||||
{
|
||||
return Json(new { success = false, ResponseMessage = "CAPTCHA validation is required." });
|
||||
return Json(new
|
||||
{
|
||||
success = false,
|
||||
ResponseMessage = "CAPTCHA validation is required."
|
||||
});
|
||||
}
|
||||
|
||||
var cred = new LoginVM
|
||||
{
|
||||
UserName = user.UserName,
|
||||
Password = user.Password,
|
||||
Password = user.Password
|
||||
};
|
||||
|
||||
var login = await _tokenHelper.LoginAsync(cred);
|
||||
|
||||
if (login.Status == "Failed")
|
||||
if (login == null || login.messCode == 0)
|
||||
{
|
||||
return Json(new { success = false, Response = login.Status, ResponseMessage = login.Message });
|
||||
}
|
||||
else if (login.Status == "Invalid")
|
||||
{
|
||||
await PostErrorMessage(login.Message, "WebApps");
|
||||
return Json(new { success = false, responseStatus = login.Status, ResponseMessage = login.Message });
|
||||
}
|
||||
else
|
||||
{
|
||||
var (newCred, isValid) = await GetStoreCredAsync(user, await _tokenHelper.GetJwtTokenAsync(user));
|
||||
if (isValid == true)
|
||||
return Json(new
|
||||
{
|
||||
var userAccess = await _account.GetLandingPageByUserId(newCred);
|
||||
|
||||
var landingAction = userAccess.Where(u => u.AccessTypeId == 1).ToList();
|
||||
if (landingAction.Count != 0)
|
||||
{
|
||||
return Json(new
|
||||
{
|
||||
success = true,
|
||||
Response = true,
|
||||
responseAction = landingAction.Select(u => u.Action).FirstOrDefault(),
|
||||
responseController = landingAction.Select(u => u.Controller).FirstOrDefault()
|
||||
});
|
||||
}
|
||||
return Json(new { success = false, ResponseMessage = "NoAcces" });
|
||||
}
|
||||
return Json(new { success = false, ResponseMessage = "NoAcces" });
|
||||
success = false,
|
||||
responseStatus = login?.messCode ?? 0,
|
||||
ResponseMessage = login?.message ?? "Invalid login"
|
||||
});
|
||||
}
|
||||
|
||||
DateTime expirationTime = DateTime.UtcNow.AddHours(2);
|
||||
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
var jwtToken = handler.ReadJwtToken(login.token);
|
||||
if (login.expiresInSeconds > 0)
|
||||
{
|
||||
expirationTime = DateTime.UtcNow.AddSeconds(login.expiresInSeconds);
|
||||
}
|
||||
else if (!string.IsNullOrEmpty(login.token))
|
||||
{
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
if (jwtToken.ValidTo > DateTime.MinValue)
|
||||
{
|
||||
expirationTime = jwtToken.ValidTo;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new Claim(ClaimTypes.NameIdentifier, login.userId),
|
||||
new Claim(ClaimTypes.Name, login.userName),
|
||||
new Claim("FullName", login.fullName),
|
||||
new Claim("Company", login.company),
|
||||
new Claim("Token", login.token),
|
||||
new Claim("TokenExpiry", expirationTime.ToString("O"))
|
||||
};
|
||||
foreach (var roleClaim in jwtToken.Claims
|
||||
.Where(c => c.Type == ClaimTypes.Role))
|
||||
{
|
||||
claims.Add(new Claim(ClaimTypes.Role, roleClaim.Value));
|
||||
}
|
||||
if (!string.IsNullOrEmpty(login.refreshToken))
|
||||
{
|
||||
claims.Add(new Claim("RefreshToken", login.refreshToken));
|
||||
}
|
||||
|
||||
var identity = new ClaimsIdentity(
|
||||
claims,
|
||||
CookieAuthenticationDefaults.AuthenticationScheme
|
||||
);
|
||||
|
||||
var authProperties = new AuthenticationProperties
|
||||
{
|
||||
IsPersistent = true,
|
||||
ExpiresUtc = DateTimeOffset.UtcNow.AddHours(2),
|
||||
AllowRefresh = true
|
||||
};
|
||||
|
||||
await HttpContext.SignInAsync(
|
||||
CookieAuthenticationDefaults.AuthenticationScheme,
|
||||
new ClaimsPrincipal(identity),
|
||||
authProperties
|
||||
);
|
||||
|
||||
var userAccess = await _account.GetLandingPageByUserId(GetUser());
|
||||
|
||||
var landingAction = userAccess?.FirstOrDefault(u => u.AccessTypeId == 1);
|
||||
|
||||
if (landingAction != null)
|
||||
{
|
||||
return Json(new
|
||||
{
|
||||
success = true,
|
||||
Response = true,
|
||||
responseAction = landingAction.Action,
|
||||
responseController = landingAction.Controller
|
||||
});
|
||||
}
|
||||
|
||||
return Json(new { success = false, ResponseMessage = "No Access" });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message,"WebApps");
|
||||
return Json(new { success = false, ResponseMessage = "NoAcces" });
|
||||
return Json(new
|
||||
{
|
||||
success = false,
|
||||
ResponseMessage = ex.InnerException?.Message ?? ex.Message
|
||||
});
|
||||
}
|
||||
}
|
||||
public async Task<bool> GetUserAttribute(Infrastructure.Models.Account.User user, string token)
|
||||
{
|
||||
if (user.Password != null && user.UserName != null)
|
||||
{
|
||||
|
||||
var (cred, isValid) = await GetStoreCredAsync(user, token);
|
||||
|
||||
IsValid = isValid;
|
||||
if (isValid)
|
||||
if (token !=null)
|
||||
{
|
||||
//Getting the URL
|
||||
var URLAttachment = await _attachment.GetAttachmentById(cred);
|
||||
var URLAttachment = await _attachment.GetAttachmentById(user);
|
||||
if (URLAttachment != null)
|
||||
{
|
||||
GetStoreAttachment(URLAttachment, true);
|
||||
@ -200,6 +262,7 @@ namespace CPRNIMS.WebApps.Controllers
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public IActionResult Privacy()
|
||||
{
|
||||
return View();
|
||||
|
||||
@ -14,10 +14,10 @@ namespace CPRNIMS.WebApps.Controllers.Inventory
|
||||
{
|
||||
List<InventoryVM>? response;
|
||||
private readonly IInventory _inventory;
|
||||
public InventoryMgmtController(TokenHelper tokenHelper, ErrorLogHelper errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment
|
||||
public InventoryMgmtController(ErrorLogHelper errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment, TokenHelper tokenHelper
|
||||
, IInventory inventory)
|
||||
: base(tokenHelper, errorMessageService, webHostEnvironment)
|
||||
: base(errorMessageService, webHostEnvironment, tokenHelper)
|
||||
{
|
||||
_inventory = inventory;
|
||||
}
|
||||
@ -26,13 +26,13 @@ namespace CPRNIMS.WebApps.Controllers.Inventory
|
||||
{
|
||||
try
|
||||
{
|
||||
response = await _inventory.GetLotQtyByItem(await GetUser(), viewModels);
|
||||
response = await _inventory.GetLotQtyByItem(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -40,13 +40,13 @@ namespace CPRNIMS.WebApps.Controllers.Inventory
|
||||
{
|
||||
try
|
||||
{
|
||||
response = await _inventory.GetLotNo(await GetUser(), viewModels);
|
||||
response = await _inventory.GetLotNo(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -54,13 +54,13 @@ namespace CPRNIMS.WebApps.Controllers.Inventory
|
||||
{
|
||||
try
|
||||
{
|
||||
response = await _inventory.GetLotNoById(await GetUser(), viewModels);
|
||||
response = await _inventory.GetLotNoById(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -68,13 +68,13 @@ namespace CPRNIMS.WebApps.Controllers.Inventory
|
||||
{
|
||||
try
|
||||
{
|
||||
response = await _inventory.GetInventoryById(await GetUser(), viewModels);
|
||||
response = await _inventory.GetInventoryById(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -82,13 +82,12 @@ namespace CPRNIMS.WebApps.Controllers.Inventory
|
||||
{
|
||||
try
|
||||
{
|
||||
response = await _inventory.GetInventoryByUserId(await GetUser(), viewModels);
|
||||
response = await _inventory.GetInventoryByUserId(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -96,13 +95,13 @@ namespace CPRNIMS.WebApps.Controllers.Inventory
|
||||
{
|
||||
try
|
||||
{
|
||||
response = await _inventory.GetRequestedItemByUserId(await GetUser(), viewModels);
|
||||
response = await _inventory.GetRequestedItemByUserId(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -112,7 +111,7 @@ namespace CPRNIMS.WebApps.Controllers.Inventory
|
||||
{
|
||||
try
|
||||
{
|
||||
var postPutItem = await _inventory.PostPutLotNo(await GetUser(), viewModel);
|
||||
var postPutItem = await _inventory.PostPutLotNo(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.StatusResponse != "Error")
|
||||
{
|
||||
@ -124,7 +123,6 @@ namespace CPRNIMS.WebApps.Controllers.Inventory
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -132,7 +130,7 @@ namespace CPRNIMS.WebApps.Controllers.Inventory
|
||||
{
|
||||
try
|
||||
{
|
||||
var postPutItem = await _inventory.PostPutLotBin(await GetUser(), viewModel);
|
||||
var postPutItem = await _inventory.PostPutLotBin(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.StatusResponse != "Error")
|
||||
{
|
||||
@ -144,7 +142,7 @@ namespace CPRNIMS.WebApps.Controllers.Inventory
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -152,7 +150,7 @@ namespace CPRNIMS.WebApps.Controllers.Inventory
|
||||
{
|
||||
try
|
||||
{
|
||||
var postPutItem = await _inventory.PostPutReqApproval(await GetUser(), viewModel);
|
||||
var postPutItem = await _inventory.PostPutReqApproval(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.StatusResponse != "Error")
|
||||
{
|
||||
@ -164,7 +162,6 @@ namespace CPRNIMS.WebApps.Controllers.Inventory
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -172,7 +169,7 @@ namespace CPRNIMS.WebApps.Controllers.Inventory
|
||||
{
|
||||
try
|
||||
{
|
||||
var postPutItem = await _inventory.PostPutReqItems(await GetUser(), viewModel);
|
||||
var postPutItem = await _inventory.PostPutReqItems(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.StatusResponse != "Error")
|
||||
{
|
||||
@ -184,7 +181,6 @@ namespace CPRNIMS.WebApps.Controllers.Inventory
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -192,29 +188,17 @@ namespace CPRNIMS.WebApps.Controllers.Inventory
|
||||
#region Views
|
||||
public async Task<IActionResult> Inventory()
|
||||
{
|
||||
if (GetUser() == null)
|
||||
{
|
||||
RedirectToAction("Logout", "Home");
|
||||
}
|
||||
await GetStoreCredAsync(await GetUser(), await _tokenHelper.GetJwtTokenAsync(await GetUser()));
|
||||
await IsAuthenTicated();
|
||||
return View();
|
||||
}
|
||||
public async Task<IActionResult> Lot()
|
||||
{
|
||||
if (GetUser() == null)
|
||||
{
|
||||
RedirectToAction("Logout", "Home");
|
||||
}
|
||||
await GetStoreCredAsync(await GetUser(), await _tokenHelper.GetJwtTokenAsync(await GetUser()));
|
||||
await IsAuthenTicated();
|
||||
return View();
|
||||
}
|
||||
public async Task<IActionResult> RequestItem()
|
||||
{
|
||||
if (GetUser() == null)
|
||||
{
|
||||
RedirectToAction("Logout", "Home");
|
||||
}
|
||||
await GetStoreCredAsync(await GetUser(), await _tokenHelper.GetJwtTokenAsync(await GetUser()));
|
||||
await IsAuthenTicated();
|
||||
return View();
|
||||
}
|
||||
#endregion
|
||||
|
||||
@ -26,10 +26,10 @@ namespace CPRNIMS.WebApps.Controllers.Items
|
||||
ItemVM? postPutItem;
|
||||
private readonly IConfiguration _config;
|
||||
private readonly IHubContext<CartHub> _hubContext;
|
||||
public ItemMgmtController(TokenHelper tokenHelper, ErrorLogHelper errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment, IConfiguration config,
|
||||
public ItemMgmtController(ErrorLogHelper errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment, IConfiguration config, TokenHelper tokenHelper,
|
||||
IItem item, IHubContext<CartHub> hubContext)
|
||||
: base(tokenHelper, errorMessageService, webHostEnvironment)
|
||||
: base(errorMessageService, webHostEnvironment,tokenHelper)
|
||||
{
|
||||
_item = item;
|
||||
_config = config;
|
||||
@ -40,7 +40,7 @@ namespace CPRNIMS.WebApps.Controllers.Items
|
||||
{
|
||||
try
|
||||
{
|
||||
var postPutItem = await _item.PostPutItemCart(await GetUser(), viewModel);
|
||||
var postPutItem = await _item.PostPutItemCart(GetUser(), viewModel);
|
||||
int count = await UpdateCart(viewModel);
|
||||
await _hubContext.Clients.User(viewModel.UserId).SendAsync("ReceiveCartUpdate", count);
|
||||
|
||||
@ -53,7 +53,7 @@ namespace CPRNIMS.WebApps.Controllers.Items
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -61,7 +61,7 @@ namespace CPRNIMS.WebApps.Controllers.Items
|
||||
{
|
||||
viewModel.IsCount = true;
|
||||
int count=0;
|
||||
var itemCartResp = await _item.GetItemCart(await GetUser(), viewModel);
|
||||
var itemCartResp = await _item.GetItemCart(GetUser(), viewModel);
|
||||
if (itemCartResp.Count <= 0)
|
||||
{
|
||||
ViewBag.CartItemCount = 0;
|
||||
@ -94,7 +94,7 @@ namespace CPRNIMS.WebApps.Controllers.Items
|
||||
if (isSuccess) {
|
||||
viewModel.ItemAttachPath = uploadResult;
|
||||
|
||||
postPutItem = await _item.PutItemDetail(await GetUser(), viewModel);
|
||||
postPutItem = await _item.PutItemDetail(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
@ -114,7 +114,7 @@ namespace CPRNIMS.WebApps.Controllers.Items
|
||||
{
|
||||
try
|
||||
{
|
||||
var postPutItem = await _item.PostPutItem(await GetUser(), viewModel);
|
||||
var postPutItem = await _item.PostPutItem(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
@ -131,7 +131,6 @@ namespace CPRNIMS.WebApps.Controllers.Items
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -147,7 +146,7 @@ namespace CPRNIMS.WebApps.Controllers.Items
|
||||
Qty = ItemCartIds.SelectMany(ic => ic.Qty).ToList(),
|
||||
ItemNo = ItemCartIds.SelectMany(ic => ic.ItemNo).ToList()
|
||||
};
|
||||
var postPutItem = await _item.PostPurchRequest(await GetUser(), viewModel);
|
||||
var postPutItem = await _item.PostPurchRequest(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.statusResponse != "Error")
|
||||
{
|
||||
@ -159,7 +158,7 @@ namespace CPRNIMS.WebApps.Controllers.Items
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -191,14 +190,14 @@ namespace CPRNIMS.WebApps.Controllers.Items
|
||||
{
|
||||
try
|
||||
{
|
||||
response = await _item.GetItemDetail(await GetUser(), viewModels);
|
||||
response = await _item.GetItemDetail(GetUser(), viewModels);
|
||||
response[0].URL = _config["CommonEndpoints:ApiDefaultHeaders:ItemImages"];
|
||||
return GetResponse(response);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -206,20 +205,20 @@ namespace CPRNIMS.WebApps.Controllers.Items
|
||||
{
|
||||
try
|
||||
{
|
||||
response = await _item.GetItemCart(await GetUser(), viewModels);
|
||||
response = await _item.GetItemCart(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
public async Task<IActionResult> GetItemList()
|
||||
{
|
||||
var viewModels = new ItemVM();
|
||||
response = await _item.GetItemList(await GetUser(), viewModels);
|
||||
response = await _item.GetItemList(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetItemCateg(ItemVM viewModels)
|
||||
@ -227,7 +226,7 @@ namespace CPRNIMS.WebApps.Controllers.Items
|
||||
|
||||
try
|
||||
{
|
||||
var responseQuery = await _item.GetItemCateg(await GetUser(), viewModels);
|
||||
var responseQuery = await _item.GetItemCateg(GetUser(), viewModels);
|
||||
|
||||
if (responseQuery == null)
|
||||
{
|
||||
@ -239,7 +238,6 @@ namespace CPRNIMS.WebApps.Controllers.Items
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage("GetItemCateg:" + message, "WebApps");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -249,7 +247,7 @@ namespace CPRNIMS.WebApps.Controllers.Items
|
||||
{
|
||||
var viewModels = new ItemVM();
|
||||
viewModels.ItemColorName = query;
|
||||
var responseQuery = await _item.GetItemColor(await GetUser(), viewModels);
|
||||
var responseQuery = await _item.GetItemColor(GetUser(), viewModels);
|
||||
|
||||
if (responseQuery == null)
|
||||
{
|
||||
@ -268,7 +266,6 @@ namespace CPRNIMS.WebApps.Controllers.Items
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage("GetItemColor:" + message, "WebApps");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -278,7 +275,7 @@ namespace CPRNIMS.WebApps.Controllers.Items
|
||||
{
|
||||
var viewModels = new ItemVM();
|
||||
viewModels.ItemLocalName = query;
|
||||
var responseQuery = await _item.GetItemLocalization(await GetUser(), viewModels);
|
||||
var responseQuery = await _item.GetItemLocalization(GetUser(), viewModels);
|
||||
|
||||
if (responseQuery == null)
|
||||
{
|
||||
@ -297,7 +294,6 @@ namespace CPRNIMS.WebApps.Controllers.Items
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage("GetItemLocalization:" + message, "WebApps");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -307,7 +303,7 @@ namespace CPRNIMS.WebApps.Controllers.Items
|
||||
{
|
||||
var viewModels = new ItemVM();
|
||||
viewModels.UOMName = query;
|
||||
var responseQuery = await _item.GetItemUOM(await GetUser(), viewModels);
|
||||
var responseQuery = await _item.GetItemUOM(GetUser(), viewModels);
|
||||
|
||||
if (responseQuery == null)
|
||||
{
|
||||
@ -325,7 +321,6 @@ namespace CPRNIMS.WebApps.Controllers.Items
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage("GetItemUOM:" + message, "WebApps");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -334,7 +329,7 @@ namespace CPRNIMS.WebApps.Controllers.Items
|
||||
try
|
||||
{
|
||||
var viewModels = new ItemVM();
|
||||
var responseQuery = await _item.GetDepartment(await GetUser(), viewModels);
|
||||
var responseQuery = await _item.GetDepartment(GetUser(), viewModels);
|
||||
|
||||
if (responseQuery == null)
|
||||
{
|
||||
@ -346,7 +341,6 @@ namespace CPRNIMS.WebApps.Controllers.Items
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage("GetDepartment:" + message, "WebApps");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -453,7 +447,6 @@ namespace CPRNIMS.WebApps.Controllers.Items
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
return Json(new { success = false, Response ="There is something wrong, please ask administrator!" });
|
||||
}
|
||||
}
|
||||
|
||||
@ -14,10 +14,10 @@ namespace CPRNIMS.WebApps.Controllers.PO
|
||||
POVM postPutItem;
|
||||
|
||||
private readonly IPurchaseOrder _purchaseOrder;
|
||||
public POMgmtController(TokenHelper tokenHelper,
|
||||
public POMgmtController(
|
||||
ErrorLogHelper errorMessageService, IWebHostEnvironment webHostEnvironment
|
||||
, IPurchaseOrder purchaseOrder
|
||||
) : base(tokenHelper, errorMessageService, webHostEnvironment)
|
||||
, IPurchaseOrder purchaseOrder, TokenHelper tokenHelper
|
||||
) : base(errorMessageService, webHostEnvironment, tokenHelper)
|
||||
{
|
||||
_purchaseOrder = purchaseOrder;
|
||||
}
|
||||
@ -26,7 +26,7 @@ namespace CPRNIMS.WebApps.Controllers.PO
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> DeleteIncShip(POVM viewModel)
|
||||
{
|
||||
var postPutItem = await _purchaseOrder.DeleteIncShip(await GetUser(), viewModel);
|
||||
var postPutItem = await _purchaseOrder.DeleteIncShip(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
@ -37,7 +37,7 @@ namespace CPRNIMS.WebApps.Controllers.PO
|
||||
}
|
||||
public async Task<IActionResult> PostPutIncoterms(POVM viewModel)
|
||||
{
|
||||
postPutItem = await _purchaseOrder.PostPutIncoterms(await GetUser(), viewModel);
|
||||
postPutItem = await _purchaseOrder.PostPutIncoterms(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
@ -47,7 +47,7 @@ namespace CPRNIMS.WebApps.Controllers.PO
|
||||
}
|
||||
public async Task<IActionResult> PostPutOtherCharges(POVM viewModel)
|
||||
{
|
||||
postPutItem = await _purchaseOrder.PostPutOtherCharges(await GetUser(), viewModel);
|
||||
postPutItem = await _purchaseOrder.PostPutOtherCharges(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
@ -58,7 +58,7 @@ namespace CPRNIMS.WebApps.Controllers.PO
|
||||
}
|
||||
public async Task<IActionResult> PostPutDocRequired(POVM viewModel)
|
||||
{
|
||||
postPutItem = await _purchaseOrder.PostPutDocRequired(await GetUser(), viewModel);
|
||||
postPutItem = await _purchaseOrder.PostPutDocRequired(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode !=0)
|
||||
{
|
||||
@ -69,7 +69,7 @@ namespace CPRNIMS.WebApps.Controllers.PO
|
||||
}
|
||||
public async Task<IActionResult> PostPOToSupplier(POVM viewModel)
|
||||
{
|
||||
postPutItem = await _purchaseOrder.PostPOToSupplier(await GetUser(), viewModel);
|
||||
postPutItem = await _purchaseOrder.PostPOToSupplier(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
@ -81,7 +81,7 @@ namespace CPRNIMS.WebApps.Controllers.PO
|
||||
public async Task<IActionResult> PostPutPO(POVM viewModel, List<DocRequirementList> DocRequiredList)
|
||||
{
|
||||
viewModel.DocRequiredList = MapToDocReqList(DocRequiredList);
|
||||
postPutItem = await _purchaseOrder.PostPutPO(await GetUser(), viewModel);
|
||||
postPutItem = await _purchaseOrder.PostPutPO(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
@ -99,7 +99,7 @@ namespace CPRNIMS.WebApps.Controllers.PO
|
||||
viewModel.OtherChargesList = MapToPOChargesList(OtherChargesList);
|
||||
viewModel.PRItemList = MapToPRItemList(PRItemList);
|
||||
|
||||
postPutItem = await _purchaseOrder.PostPutCustomPO(await GetUser(), viewModel);
|
||||
postPutItem = await _purchaseOrder.PostPutCustomPO(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
@ -109,7 +109,7 @@ namespace CPRNIMS.WebApps.Controllers.PO
|
||||
}
|
||||
public async Task<IActionResult> PutPOCancel(POVM viewModel)
|
||||
{
|
||||
postPutItem = await _purchaseOrder.PutPOCancel(await GetUser(), viewModel);
|
||||
postPutItem = await _purchaseOrder.PutPOCancel(GetUser(), viewModel);
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
return Json(new { success = true, Response = postPutItem.Message,
|
||||
@ -124,7 +124,7 @@ namespace CPRNIMS.WebApps.Controllers.PO
|
||||
{
|
||||
viewModel.POList = MapToPONoList(POList);
|
||||
|
||||
postPutItem = await _purchaseOrder.ApprovedSelectedPO(await GetUser(), viewModel);
|
||||
postPutItem = await _purchaseOrder.ApprovedSelectedPO(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
@ -135,14 +135,13 @@ namespace CPRNIMS.WebApps.Controllers.PO
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
return Json(new { success = false, Response = postPutItem.Message });
|
||||
throw;
|
||||
}
|
||||
}
|
||||
public async Task<IActionResult> PostApprovedSuggested(POVM viewModel)
|
||||
{
|
||||
postPutItem = await _purchaseOrder.PostApprovedSuggested(await GetUser(), viewModel);
|
||||
postPutItem = await _purchaseOrder.PostApprovedSuggested(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.StatusResponse != "Error")
|
||||
{
|
||||
@ -153,7 +152,7 @@ namespace CPRNIMS.WebApps.Controllers.PO
|
||||
}
|
||||
public async Task<IActionResult> PostApprovedPO(POVM viewModel)
|
||||
{
|
||||
postPutItem = await _purchaseOrder.PostApprovedPO(await GetUser(), viewModel);
|
||||
postPutItem = await _purchaseOrder.PostApprovedPO(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.StatusResponse != "Error")
|
||||
{
|
||||
@ -164,7 +163,7 @@ namespace CPRNIMS.WebApps.Controllers.PO
|
||||
}
|
||||
public async Task<IActionResult> PostApprovedSupplier(POVM viewModel)
|
||||
{
|
||||
postPutItem = await _purchaseOrder.PostApprovedSupplier(await GetUser(), viewModel);
|
||||
postPutItem = await _purchaseOrder.PostApprovedSupplier(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.StatusResponse != "Error")
|
||||
{
|
||||
@ -175,7 +174,7 @@ namespace CPRNIMS.WebApps.Controllers.PO
|
||||
}
|
||||
public async Task<IActionResult> PutPRItemDetails(POVM viewModel)
|
||||
{
|
||||
postPutItem = await _purchaseOrder.PutPRItemDetails(await GetUser(), viewModel);
|
||||
postPutItem = await _purchaseOrder.PutPRItemDetails(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
@ -186,7 +185,7 @@ namespace CPRNIMS.WebApps.Controllers.PO
|
||||
}
|
||||
public async Task<IActionResult> PutPOItemDetail(POVM viewModel)
|
||||
{
|
||||
postPutItem = await _purchaseOrder.PutPOItemDetail(await GetUser(), viewModel);
|
||||
postPutItem = await _purchaseOrder.PutPOItemDetail(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
@ -197,7 +196,7 @@ namespace CPRNIMS.WebApps.Controllers.PO
|
||||
}
|
||||
public async Task<IActionResult> PutMyPONo(POVM viewModel)
|
||||
{
|
||||
postPutItem = await _purchaseOrder.PutMyPONo(await GetUser(), viewModel);
|
||||
postPutItem = await _purchaseOrder.PutMyPONo(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
@ -269,77 +268,77 @@ namespace CPRNIMS.WebApps.Controllers.PO
|
||||
}
|
||||
public async Task<IActionResult> GetIncomingShipment(POVM viewModels)
|
||||
{
|
||||
response = await _purchaseOrder.GetIncomingShipment(await GetUser(), viewModels);
|
||||
response = await _purchaseOrder.GetIncomingShipment(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetSupplierBid()
|
||||
{
|
||||
var viewModels = new POVM();
|
||||
response = await _purchaseOrder.GetSupplierBid(await GetUser(), viewModels);
|
||||
response = await _purchaseOrder.GetSupplierBid(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetSupplierBidById(POVM viewModel)
|
||||
{
|
||||
response = await _purchaseOrder.GetSupplierBidById(await GetUser(), viewModel);
|
||||
response = await _purchaseOrder.GetSupplierBidById(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetSupplierBidByItem(POVM viewModel)
|
||||
{
|
||||
response = await _purchaseOrder.GetSupplierBidByItem(await GetUser(), viewModel);
|
||||
response = await _purchaseOrder.GetSupplierBidByItem(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetForPOApprovalByPRNo(POVM viewModel)
|
||||
{
|
||||
response = await _purchaseOrder.GetForPOApprovalByPRNo(await GetUser(), viewModel);
|
||||
response = await _purchaseOrder.GetForPOApprovalByPRNo(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetForBiddingApproval()
|
||||
{
|
||||
var viewModels = new POVM();
|
||||
response = await _purchaseOrder.GetForBiddingApproval(await GetUser(), viewModels);
|
||||
response = await _purchaseOrder.GetForBiddingApproval(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetForPO()
|
||||
{
|
||||
var viewModels = new POVM();
|
||||
response = await _purchaseOrder.GetForPO(await GetUser(), viewModels);
|
||||
response = await _purchaseOrder.GetForPO(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetForPOPerSuppEmail(POVM viewModels)
|
||||
{
|
||||
response = await _purchaseOrder.GetForPOPerSuppEmail(await GetUser(), viewModels);
|
||||
response = await _purchaseOrder.GetForPOPerSuppEmail(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetApprovedPO(POVM viewModels)
|
||||
{
|
||||
response = await _purchaseOrder.GetApprovedPO(await GetUser(), viewModels);
|
||||
response = await _purchaseOrder.GetApprovedPO(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetCreatedPO(POVM viewModels)
|
||||
{
|
||||
response = await _purchaseOrder.GetCreatedPO(await GetUser(), viewModels);
|
||||
response = await _purchaseOrder.GetCreatedPO(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetMyCreatedPO(POVM viewModels)
|
||||
{
|
||||
response = await _purchaseOrder.GetMyCreatedPO(await GetUser(), viewModels);
|
||||
response = await _purchaseOrder.GetMyCreatedPO(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetApprovedPOPerEmail(POVM viewModels)
|
||||
{
|
||||
response = await _purchaseOrder.GetApprovedPOPerEmail(await GetUser(), viewModels);
|
||||
response = await _purchaseOrder.GetApprovedPOPerEmail(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetCreatedPOPerSupId(POVM viewModels)
|
||||
{
|
||||
response = await _purchaseOrder.GetCreatedPOPerSupId(await GetUser(), viewModels);
|
||||
response = await _purchaseOrder.GetCreatedPOPerSupId(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetPortOfDischarge(string query)
|
||||
{
|
||||
var viewModels = new POVM();
|
||||
viewModels.PortOfDischarge = query;
|
||||
response = await _purchaseOrder.GetPortOfDischarge(await GetUser(), viewModels);
|
||||
response = await _purchaseOrder.GetPortOfDischarge(GetUser(), viewModels);
|
||||
if (response == null)
|
||||
{
|
||||
response = new List<POVM>();
|
||||
@ -356,7 +355,7 @@ namespace CPRNIMS.WebApps.Controllers.PO
|
||||
{
|
||||
var viewModels = new POVM();
|
||||
viewModels.PaymentTerms = query;
|
||||
response = await _purchaseOrder.GetPaymentTerms(await GetUser(), viewModels);
|
||||
response = await _purchaseOrder.GetPaymentTerms(GetUser(), viewModels);
|
||||
if (response == null)
|
||||
{
|
||||
response = new List<POVM>();
|
||||
@ -371,29 +370,29 @@ namespace CPRNIMS.WebApps.Controllers.PO
|
||||
}
|
||||
public async Task<IActionResult> GetLatestPO(POVM viewModels)
|
||||
{
|
||||
response = await _purchaseOrder.GetLatestPO(await GetUser(), viewModels);
|
||||
response = await _purchaseOrder.GetLatestPO(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetLatestPO2(POVM viewModels)
|
||||
{
|
||||
response = await _purchaseOrder.GetLatestPO2(await GetUser(), viewModels);
|
||||
response = await _purchaseOrder.GetLatestPO2(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetDocRequired(POVM viewModels)
|
||||
{
|
||||
response = await _purchaseOrder.GetDocRequired(await GetUser(), viewModels);
|
||||
response = await _purchaseOrder.GetDocRequired(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetOtherCharges(POVM viewModels)
|
||||
{
|
||||
response = await _purchaseOrder.GetOtherCharges(await GetUser(), viewModels);
|
||||
response = await _purchaseOrder.GetOtherCharges(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetSuppliers(string query)
|
||||
{
|
||||
var viewModels = new POVM();
|
||||
viewModels.SupplierName = query;
|
||||
var responseQuery = await _purchaseOrder.GetSuppliers(await GetUser(), viewModels);
|
||||
var responseQuery = await _purchaseOrder.GetSuppliers(GetUser(), viewModels);
|
||||
|
||||
if (responseQuery == null)
|
||||
{
|
||||
@ -412,33 +411,33 @@ namespace CPRNIMS.WebApps.Controllers.PO
|
||||
}
|
||||
public async Task<IActionResult> GetPRWOCanvass(POVM viewModels)
|
||||
{
|
||||
response = await _purchaseOrder.GetPRWOCanvass(await GetUser(), viewModels);
|
||||
response = await _purchaseOrder.GetPRWOCanvass(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetPOItemDetail(POVM viewModels)
|
||||
{
|
||||
response = await _purchaseOrder.GetPOItemDetail(await GetUser(), viewModels);
|
||||
response = await _purchaseOrder.GetPOItemDetail(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetIncoterms(POVM viewModels)
|
||||
{
|
||||
response = await _purchaseOrder.GetIncoterms(await GetUser(), viewModels);
|
||||
response = await _purchaseOrder.GetIncoterms(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetPRPOSummaryReport(POVM viewModels)
|
||||
{
|
||||
response = await _purchaseOrder.GetPRPOSummaryReport(await GetUser(), viewModels);
|
||||
response = await _purchaseOrder.GetPRPOSummaryReport(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetPRPOSummaryItem(POVM viewModels)
|
||||
{
|
||||
response = await _purchaseOrder.GetPRPOSummaryItem(await GetUser(), viewModels);
|
||||
response = await _purchaseOrder.GetPRPOSummaryItem(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetIndexCard(POVM viewModel)
|
||||
{
|
||||
response = await _purchaseOrder.
|
||||
GetIndexCard(await GetUser(), viewModel);
|
||||
GetIndexCard(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
#endregion
|
||||
|
||||
@ -13,86 +13,88 @@ namespace CPRNIMS.WebApps.Controllers.PR
|
||||
public PRMgmtController(TokenHelper tokenHelper, ErrorLogHelper errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment
|
||||
, IPRequest pRequest, IConfiguration configuration)
|
||||
: base(tokenHelper, errorMessageService, webHostEnvironment)
|
||||
: base(errorMessageService, webHostEnvironment, tokenHelper)
|
||||
{
|
||||
_pRequest = pRequest;
|
||||
}
|
||||
#region Get
|
||||
public async Task<IActionResult> GetApproverName(PRVM viewModels)
|
||||
{
|
||||
response = await _pRequest.GetApproverName(await GetUser(), viewModels);
|
||||
response = await _pRequest.GetApproverName(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetAllPR(PRVM viewModels)
|
||||
{
|
||||
response = await _pRequest.GetAllPR(await GetUser(), viewModels);
|
||||
response = await _pRequest.GetAllPR(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetPRDetailByPRNo(PRVM viewModels)
|
||||
{
|
||||
response = await _pRequest.GetPRDetailByPRNo(await GetUser(), viewModels);
|
||||
response = await _pRequest.GetPRDetailByPRNo(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetPRListByPRNo(PRVM viewModels)
|
||||
{
|
||||
response = await _pRequest.GetPRListByPRNo(await GetUser(), viewModels);
|
||||
response = await _pRequest.GetPRListByPRNo(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetMyPR(PRVM viewModels)
|
||||
{
|
||||
response = await _pRequest.GetMyPR(await GetUser(), viewModels);
|
||||
response = await _pRequest.GetMyPR(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetForReceiving()
|
||||
{
|
||||
var viewModels = new PRVM();
|
||||
response = await _pRequest.GetForReceiving(await GetUser(), viewModels);
|
||||
response = await _pRequest.GetForReceiving(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetDeniedItem(PRVM viewModels)
|
||||
{
|
||||
response = await _pRequest.GetForReceiving(await GetUser(), viewModels);
|
||||
response = await _pRequest.GetForReceiving(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetPRByRRId(PRVM viewModel)
|
||||
{
|
||||
response = await _pRequest.GetPRByRRId(await GetUser(), viewModel);
|
||||
response = await _pRequest.GetPRByRRId(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetRRDetailByPO(PRVM viewModel)
|
||||
{
|
||||
response = await _pRequest.GetRRDetailByPO(await GetUser(), viewModel);
|
||||
response = await _pRequest.GetRRDetailByPO(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetPRStatusById(PRVM viewModel)
|
||||
{
|
||||
response = await _pRequest.GetPRStatusById(await GetUser(), viewModel);
|
||||
response = await _pRequest.GetPRStatusById(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetItemDetailForReceiving(PRVM viewModel)
|
||||
{
|
||||
response = await _pRequest.GetItemDetailForReceiving(await GetUser(), viewModel);
|
||||
response = await _pRequest.GetItemDetailForReceiving(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetDetailedPRTracking(PRVM viewModel)
|
||||
{
|
||||
response = await _pRequest.GetDetailedPRTracking(await GetUser(), viewModel);
|
||||
response = await _pRequest.GetDetailedPRTracking(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetSupplierAlternativeOffer(PRVM viewModel)
|
||||
{
|
||||
response = await _pRequest.GetSupplierAlternativeOffer(await GetUser(), viewModel);
|
||||
response = await _pRequest.GetSupplierAlternativeOffer(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetSupplierAlterOfferDetails(PRVM viewModel)
|
||||
{
|
||||
response = await _pRequest.GetSupplierAlterOfferDetails(await GetUser(), viewModel);
|
||||
response = await _pRequest.GetSupplierAlterOfferDetails(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetDashBoard()
|
||||
{
|
||||
var viewModel = new PRVM();
|
||||
response = await _pRequest.GetDashBoard(await GetUser(), viewModel);
|
||||
|
||||
response = await _pRequest.GetDashBoard(GetUser(), viewModel);
|
||||
|
||||
return GetResponse(response);
|
||||
}
|
||||
#endregion
|
||||
@ -107,7 +109,7 @@ namespace CPRNIMS.WebApps.Controllers.PR
|
||||
PRNo = ItemList.SelectMany(ic => ic.PRNo).ToList(),
|
||||
ItemNo = ItemList.SelectMany(ic => ic.ItemNo).ToList(),
|
||||
};
|
||||
var postPutItem = await _pRequest.PostPutDeniedItem(await GetUser(), viewModel);
|
||||
var postPutItem = await _pRequest.PostPutDeniedItem(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
@ -120,7 +122,7 @@ namespace CPRNIMS.WebApps.Controllers.PR
|
||||
}
|
||||
public async Task<IActionResult> PutItemDetail(PRVM viewModel)
|
||||
{
|
||||
var postPutItem = await _pRequest.PutItemDetail(await GetUser(), viewModel);
|
||||
var postPutItem = await _pRequest.PutItemDetail(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
@ -131,7 +133,7 @@ namespace CPRNIMS.WebApps.Controllers.PR
|
||||
}
|
||||
public async Task<IActionResult> PostPRApproveReject(PRVM viewModel)
|
||||
{
|
||||
var postPutItem = await _pRequest.PostPRApproveReject(await GetUser(), viewModel);
|
||||
var postPutItem = await _pRequest.PostPRApproveReject(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
@ -142,7 +144,7 @@ namespace CPRNIMS.WebApps.Controllers.PR
|
||||
}
|
||||
public async Task<IActionResult> PutSupplierAlterOffer(PRVM viewModel)
|
||||
{
|
||||
var postPutItem = await _pRequest.PutSupplierAlterOffer(await GetUser(), viewModel);
|
||||
var postPutItem = await _pRequest.PutSupplierAlterOffer(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
@ -152,7 +154,7 @@ namespace CPRNIMS.WebApps.Controllers.PR
|
||||
}
|
||||
public async Task<IActionResult> PRItemRemoval(PRVM viewModel)
|
||||
{
|
||||
var postPutItem = await _pRequest.PRItemRemoval(await GetUser(), viewModel);
|
||||
var postPutItem = await _pRequest.PRItemRemoval(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode != 0)
|
||||
{
|
||||
|
||||
@ -12,10 +12,10 @@ namespace CPRNIMS.WebApps.Controllers.Receiving
|
||||
List<ReceivingVM>? response;
|
||||
private readonly IReceiving _receiving;
|
||||
private readonly IConfiguration _configuration;
|
||||
public ReceivingController(TokenHelper tokenHelper, ErrorLogHelper errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment
|
||||
public ReceivingController(ErrorLogHelper errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment,TokenHelper tokenHelper
|
||||
, IReceiving receiving, IConfiguration configuration)
|
||||
: base(tokenHelper, errorMessageService, webHostEnvironment)
|
||||
: base(errorMessageService, webHostEnvironment,tokenHelper)
|
||||
{
|
||||
_receiving = receiving;
|
||||
_configuration = configuration;
|
||||
@ -23,45 +23,45 @@ namespace CPRNIMS.WebApps.Controllers.Receiving
|
||||
#region Get
|
||||
public async Task<IActionResult> GetRRReport(ReceivingVM viewModels)
|
||||
{
|
||||
response = await _receiving.GetRRReport(await GetUser(), viewModels);
|
||||
response = await _receiving.GetRRReport(GetUser(), viewModels);
|
||||
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetPRDetailByPRNo(ReceivingVM viewModels)
|
||||
{
|
||||
response = await _receiving.GetPRDetailByPRNo(await GetUser(), viewModels);
|
||||
response = await _receiving.GetPRDetailByPRNo(GetUser(), viewModels);
|
||||
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetForReceiving()
|
||||
{
|
||||
var viewModels = new ReceivingVM();
|
||||
response = await _receiving.GetForReceiving(await GetUser(), viewModels);
|
||||
response = await _receiving.GetForReceiving(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetDeniedItem(ReceivingVM viewModels)
|
||||
{
|
||||
response = await _receiving.GetForReceiving(await GetUser(), viewModels);
|
||||
response = await _receiving.GetForReceiving(GetUser(), viewModels);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetRRDetailByPO(ReceivingVM viewModel)
|
||||
{
|
||||
response = await _receiving.GetRRDetailByPO(await GetUser(), viewModel);
|
||||
response = await _receiving.GetRRDetailByPO(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetRR(ReceivingVM viewModel)
|
||||
{
|
||||
response = await _receiving.GetRR(await GetUser(), viewModel);
|
||||
response = await _receiving.GetRR(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetLatestRRNo(ReceivingVM viewModel)
|
||||
{
|
||||
response = await _receiving.GetLatestRRNo(await GetUser(), viewModel);
|
||||
response = await _receiving.GetLatestRRNo(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
public async Task<IActionResult> GetRRDetail(ReceivingVM viewModel)
|
||||
{
|
||||
response = await _receiving.GetRRDetail(await GetUser(), viewModel);
|
||||
response = await _receiving.GetRRDetail(GetUser(), viewModel);
|
||||
return GetResponse(response);
|
||||
}
|
||||
#endregion
|
||||
@ -76,7 +76,7 @@ namespace CPRNIMS.WebApps.Controllers.Receiving
|
||||
{
|
||||
PRDetailsId = ItemList.SelectMany(ic => ic.PRDetailsId).ToList(),
|
||||
};
|
||||
var postPutItem = await _receiving.PutPOClose(await GetUser(), viewModel);
|
||||
var postPutItem = await _receiving.PutPOClose(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.messCode !=0)
|
||||
{
|
||||
@ -90,7 +90,6 @@ namespace CPRNIMS.WebApps.Controllers.Receiving
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -105,7 +104,7 @@ namespace CPRNIMS.WebApps.Controllers.Receiving
|
||||
PRDetailsId = ItemList.SelectMany(ic => ic.PRDetailsId).ToList(),
|
||||
QuantityReceived = ItemList.SelectMany(ic => ic.QuantityReceived).ToList(),
|
||||
};
|
||||
var postPutItem = await _receiving.PostPutReceiving(await GetUser(), viewModel);
|
||||
var postPutItem = await _receiving.PostPutReceiving(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.ErrCode != 0)
|
||||
{
|
||||
@ -119,7 +118,6 @@ namespace CPRNIMS.WebApps.Controllers.Receiving
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -135,7 +133,7 @@ namespace CPRNIMS.WebApps.Controllers.Receiving
|
||||
PRNo = ItemList.SelectMany(ic => ic.PRNo).ToList(),
|
||||
ItemNo = ItemList.SelectMany(ic => ic.ItemNo).ToList(),
|
||||
};
|
||||
var postPutItem = await _receiving.PostPutDeniedItem(await GetUser(), viewModel);
|
||||
var postPutItem = await _receiving.PostPutDeniedItem(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.StatusResponse != "Error")
|
||||
{
|
||||
@ -149,7 +147,6 @@ namespace CPRNIMS.WebApps.Controllers.Receiving
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -157,7 +154,7 @@ namespace CPRNIMS.WebApps.Controllers.Receiving
|
||||
{
|
||||
try
|
||||
{
|
||||
var postPutItem = await _receiving.PutRRNoSeries(await GetUser(), viewModel);
|
||||
var postPutItem = await _receiving.PutRRNoSeries(GetUser(), viewModel);
|
||||
|
||||
if (postPutItem.StatusResponse != "Error")
|
||||
{
|
||||
@ -169,7 +166,6 @@ namespace CPRNIMS.WebApps.Controllers.Receiving
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
@ -15,21 +15,17 @@ namespace CPRNIMS.WebApps.Controllers.SMTP
|
||||
{
|
||||
List<SMTPCredentialVM>? response;
|
||||
private readonly ISMTP _sMTP;
|
||||
public SMTPMgmtController(TokenHelper tokenHelper, ErrorLogHelper errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment
|
||||
public SMTPMgmtController(ErrorLogHelper errorMessageService,
|
||||
IWebHostEnvironment webHostEnvironment, TokenHelper tokenHelper
|
||||
, ISMTP sMTP
|
||||
)
|
||||
: base(tokenHelper, errorMessageService, webHostEnvironment)
|
||||
: base(errorMessageService, webHostEnvironment,tokenHelper)
|
||||
{
|
||||
_sMTP = sMTP;
|
||||
}
|
||||
public async Task<IActionResult> Index()
|
||||
{
|
||||
if (GetUser() == null)
|
||||
{
|
||||
RedirectToAction("Logout", "Home");
|
||||
}
|
||||
await GetStoreCredAsync(await GetUser(), await _tokenHelper.GetJwtTokenAsync(await GetUser()));
|
||||
await IsAuthenTicated();
|
||||
return View();
|
||||
}
|
||||
#region Get
|
||||
@ -38,7 +34,7 @@ namespace CPRNIMS.WebApps.Controllers.SMTP
|
||||
try
|
||||
{
|
||||
var viewModels = new SMTPCredentialVM();
|
||||
response = await _sMTP.GetAllSmtp(await GetUser(), viewModels);
|
||||
response = await _sMTP.GetAllSmtp(GetUser(), viewModels);
|
||||
if (response == null)
|
||||
{
|
||||
response = new List<SMTPCredentialVM>();
|
||||
@ -51,7 +47,6 @@ namespace CPRNIMS.WebApps.Controllers.SMTP
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -60,7 +55,7 @@ namespace CPRNIMS.WebApps.Controllers.SMTP
|
||||
{
|
||||
try
|
||||
{
|
||||
response = await _sMTP.GetMySmtp(await GetUser(), viewModels);
|
||||
response = await _sMTP.GetMySmtp(GetUser(), viewModels);
|
||||
if (response == null)
|
||||
{
|
||||
|
||||
@ -74,7 +69,6 @@ namespace CPRNIMS.WebApps.Controllers.SMTP
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -84,7 +78,7 @@ namespace CPRNIMS.WebApps.Controllers.SMTP
|
||||
{
|
||||
try
|
||||
{
|
||||
var postPutSmtp = await _sMTP.PostPutSmtp(await GetUser(), viewModel);
|
||||
var postPutSmtp = await _sMTP.PostPutSmtp(GetUser(), viewModel);
|
||||
|
||||
if (postPutSmtp.StatusResponse != "Error")
|
||||
{
|
||||
@ -96,7 +90,7 @@ namespace CPRNIMS.WebApps.Controllers.SMTP
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex.InnerException?.ToString() ?? ex.Message.ToString();
|
||||
await PostErrorMessage(message, "WebApps");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
@ -13,7 +13,6 @@ var app = builder.Build();
|
||||
if (!app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseExceptionHandler("/Home/Error");
|
||||
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
|
||||
app.UseHsts();
|
||||
}
|
||||
//app.UseRewriter(options);
|
||||
@ -22,10 +21,11 @@ app.UseStaticFiles();
|
||||
app.UseCors("AllowAll");
|
||||
|
||||
app.UseRouting();
|
||||
app.UseSession();
|
||||
|
||||
app.MapHub<CartHub>("/cartHub");
|
||||
app.UseSession();
|
||||
//app.UseAuthentication();
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapControllerRoute(
|
||||
|
||||
@ -12,7 +12,6 @@
|
||||
string allowedRoles = ViewBag.UserRoles;
|
||||
var userCred = new CPRNIMS.Infrastructure.Models.Account.User();
|
||||
userCred.UserName = ViewBag.UserName;
|
||||
userCred.Password = ViewBag.Password;
|
||||
userCred.UserId = ViewBag.UserId;
|
||||
|
||||
var myControllerAccess = await _account.GetLandingPageByUserId(userCred);
|
||||
|
||||
@ -11,8 +11,8 @@
|
||||
},
|
||||
"Account": {
|
||||
"BaseUrl": "https://localhost:7107/",
|
||||
"Auth": "api/Account/GetToken/",
|
||||
"Login": "api/Account/Login/",
|
||||
"Auth": "api/Account/RefreshToken/",
|
||||
"Login": "api/Anon/Login/",
|
||||
"GetAllUsers": "api/Account/GetAllUser/",
|
||||
"GetRoles": "api/Account/GetRoles/",
|
||||
"GetAllRoles": "api/Account/GetAllRoles/",
|
||||
|
||||
Loading…
Reference in New Issue
Block a user