HRM-10/HRM.UI/Controllers/Auth/AuthController.cs

2542 lines
96 KiB
C#
Raw Normal View History

2026-11-03 13:06:00 +06:00
using HRM.BO;
using HRM.BO.Configuration;
using HRM.DA;
using HRM.DA;
using HRM.DA.Service;
using HRM.Service;
using HRM.UI.Api;
using HRM.UI.DTOs.Auth;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace HRM.UI.Controllers
{
[ApiController]
[Route("api/Authentication")]
[Authorize]
public class AuthController : ControllerBase
{
private readonly IConfiguration _config;
private readonly IUserService _userService;
private readonly IBookmarkService _bookmarkService;
private readonly ISystemConfigaration _systemConfig;
private readonly string Secret;
private readonly JwtSettings _jwt;
private readonly IUserRoleService _userRoleService;
private readonly IRoleService _roleService;
private readonly IPayrollTypeService _payrollTypeService;
private readonly IPasswordHistoryService _passwordHistoryService;
private readonly IUserAccessTypeService _userAccessTypeService;
private readonly IOptions<EmailSettings> _emailSettings;
private readonly IDataPermissionService _dataPermissionService;
private readonly LDAPAuthService _ldapAuthService;
private readonly ISmsService _smsService;
private readonly IMemoryCache _cache;
2026-11-12 14:58:04 +06:00
private readonly IUserLogInInfoService _userLogInInfoService;
private readonly IBadLoginAttemptInfoService _badLoginAttemptInfoService;
2026-11-03 13:06:00 +06:00
public AuthController(IConfiguration config,
IUserService userService,
IOptions<AppSettings> appSettings,
IOptions<JwtSettings> jwtOptions,
ISystemConfigaration sysconfig,
IUserRoleService userRole,
IRoleService rService,
IPayrollTypeService pTypeService,
IUserAccessTypeService uaccesstypesrv,
IPasswordHistoryService passwordHistoryService,
IOptions<EmailSettings> emailSettings,
IBookmarkService bookmarkService,
IDataPermissionService dataPermissionService,
LDAPAuthService ldapAuthService,
ISmsService smsService,
2026-11-12 14:58:04 +06:00
IMemoryCache cache,
IUserLogInInfoService userLogInInfoService,
IBadLoginAttemptInfoService badLoginAttemptInfoService)
2026-11-03 13:06:00 +06:00
{
_config = config;
_jwt = jwtOptions.Value;
_userService = userService;
this.Secret = appSettings.Value.Secret;
_userService = userService;
this._systemConfig = sysconfig;
this._userRoleService = userRole;
this._roleService = rService;
this._payrollTypeService = pTypeService;
this._userAccessTypeService = uaccesstypesrv;
this._passwordHistoryService = passwordHistoryService;
this._emailSettings = emailSettings;
this._bookmarkService = bookmarkService;
this._dataPermissionService = dataPermissionService;
this._ldapAuthService = ldapAuthService;
this._smsService = smsService;
_cache = cache;
2026-11-12 14:58:04 +06:00
_userLogInInfoService = userLogInInfoService;
_badLoginAttemptInfoService = badLoginAttemptInfoService;
2026-11-03 13:06:00 +06:00
}
[HttpPost]
[Route("SaveUser")]
public ActionResult SaveUser(User ouser)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
ouser.ChangePasswordAtNextLogon = true;
ouser.ApprovedBy = null;
ouser.ApprovedDate = null;
if (ouser.IsNew == true)
{
ouser.CreatedBy = currentUser.UserID;
ouser.CreatedDate = DateTime.Now;
ouser.ParentID = currentUser.UserID;
}
else
{
ouser.ModifiedBy = currentUser.UserID;
ouser.ModifiedDate = DateTime.Now;
ouser.AuthorizedBy = currentUser.UserID;
ouser.AuthorizedDate = DateTime.Now;
ouser.ResetPassword = true;
ouser.SISU = false;
ouser.LastPasswordChangedDate = ouser.ModifiedDate;
if(ouser.UserStatus == EnumAuthStatus.Approved)
{
ouser.ApprovedBy = currentUser.UserID;
ouser.ApprovedDate = DateTime.Now;
}
}
_userService.Save(ouser);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(ouser);
}
[HttpPost]
[Route("ApproveUser")]
public ActionResult ApproveUser(User ouser)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
ouser.ChangePasswordAtNextLogon = true;
ouser.ModifiedBy = currentUser.UserID;
ouser.ModifiedDate = DateTime.Now;
ouser.AuthorizedBy = currentUser.UserID;
ouser.AuthorizedDate = DateTime.Now;
ouser.ResetPassword = true;
ouser.ApprovedBy = currentUser.UserID;
ouser.ApprovedDate = DateTime.Now;
_userService.Approve(ouser);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(ouser);
}
[HttpPost]
[Route("DoActiveAndIntacive")]
public ActionResult DoActiveAndIntacive(User ouser)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
ouser.ModifiedBy = currentUser.UserID;
ouser.ModifiedDate = DateTime.Now;
ouser.AuthorizedBy = currentUser.UserID;
ouser.AuthorizedDate = DateTime.Now;
_userService.DoActiveAndIntacive(ouser);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(ouser.ID);
}
[HttpPost]
[Route("SaveBookmark")]
public ActionResult SaveBookmark(Bookmark obookmark)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
if (obookmark.IsNew == true)
{
obookmark.UserID = currentUser.UserID;
obookmark.EmployeeId = currentUser.EmployeeID;
obookmark.CreatedBy = currentUser.UserID;
obookmark.CreatedDate = DateTime.Now;
}
else
{
obookmark.ModifiedBy = currentUser.UserID;
obookmark.ModifiedDate = DateTime.Now;
}
_bookmarkService.Save(obookmark);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(obookmark);
}
[HttpGet("getBookmarks")]
public ActionResult getBookmarks()
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
List<Bookmark> items = new List<Bookmark>();
try
{
items = this._bookmarkService.Get(currentUser.UserID);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(items);
}
[HttpPost]
[Route("deleteBookmark")]
public ActionResult DeleteBookmark(Bookmark item)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
_bookmarkService.Delete(item.ID);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok();
}
[HttpPost]
[Route("deleteBookmarkByMenuKey")]
public ActionResult deleteBookmarkByMenuKey(Bookmark item)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
_bookmarkService.Delete(currentUser.UserID, item.MenuCode);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok();
}
/// <summary>
///
/// </summary>
/// <param name="userForLoginDto"></param>
/// <returns></returns>
[HttpPost("login")]
[EnableRateLimiting("LoginPolicy")]
[AllowAnonymous]
public IActionResult Login(UserForLoginDto userForLoginDto)
{
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
IConfiguration Configuration = builder.Build();
string ADLoginStatus = Configuration.GetSection("LDAPSettings")["isADLogin"];
string MFAStatus = Configuration.GetSection("LDAPSettings")["isMFA"];
decimal mFATimer = Convert.ToDecimal(Configuration.GetSection("LDAPSettings")["MFATimer"]);
bool isADLogin = Convert.ToBoolean(ADLoginStatus);
bool isMFA = Convert.ToBoolean(MFAStatus);
string time = DateTime.Now.AddMinutes((double)mFATimer).ToString("hh:mm tt");
string mfaCode = "";
User userFromRepo = null;
if (userForLoginDto.IsSSO)
{
userFromRepo = _userService.GetByEmail(userForLoginDto.Email);
2026-11-17 14:52:13 +06:00
// Same rule as the password sign-in (UserDA.GetByLoginIDAndPassword: Status 1 or 5): a login that
// is not switched on (waiting for approval, rejected, inactive, ...) cannot sign in by SSO either.
if (userFromRepo != null
&& userFromRepo.UserStatus != EnumAuthStatus.Active
&& userFromRepo.UserStatus != EnumAuthStatus.Approved)
{
userFromRepo = null;
}
2026-11-03 13:06:00 +06:00
if (userFromRepo != null && userForLoginDto.nextPayProcessDate == null)
{
List<PayrollType> payrollTypes = new List<PayrollType>();
payrollTypes = this._payrollTypeService.GetPayrollTypes(userFromRepo.LoginID);
if (payrollTypes != null && payrollTypes.Count > 0)
{
userForLoginDto.nextPayProcessDate = payrollTypes[0].NextPayProcessDate;
userForLoginDto.payrollTypeid = payrollTypes[0].ID;
}
}
}
else
{
if (isADLogin)
{
string adLoginID = _ldapAuthService.ValidateUserAndGetADLoginID(userForLoginDto.Username, userForLoginDto.Password);
if (!string.IsNullOrEmpty(adLoginID))
{
userFromRepo = _userService.GetByAdLoginID(adLoginID);
if (userFromRepo != null)
{
if (isMFA)
{
int ID = userFromRepo.ID;
mfaCode = this.processMFA();
var mfaSessionId = Guid.NewGuid().ToString();
decimal minutes = mFATimer > 0 ? mFATimer : 2.0m;
TimeSpan otpValidity = TimeSpan.FromSeconds((double)(minutes * 60));
_cache.Remove($"MFA_{mfaSessionId}");
var challenge = new MfaChallenge
{
UserId = ID,
OTP = mfaCode,
CreatedAt = DateTime.Now,
ExpiredAt = DateTime.Now.Add(otpValidity),
AttemptCount = 0
};
var cacheOptions = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = otpValidity,
Priority = CacheItemPriority.High
};
_cache.Set($"MFA_{mfaSessionId}", challenge, cacheOptions);
WriteToFile("Code ready");
this.SendMfaCode(mfaCode, time, userFromRepo);
return Ok(new
{
mfaRequired = true,
mfaSessionId = mfaSessionId,
});
}
}
else
{
return BadRequest("User not found in the application. Please contact system administrator.");
}
}
else
{
return BadRequest("Invalid username or password. Please try again.");
}
}
else
{
userFromRepo = _userService.GetByLoginIDAndPasswordNew(userForLoginDto.Username.ToLower(), userForLoginDto.Password);
if (userFromRepo != null)
{
if (userForLoginDto.nextPayProcessDate == null || userForLoginDto.payrollTypeid == 0)
2026-11-03 18:32:24 +06:00
{
2026-11-03 13:06:00 +06:00
List<PayrollType> payrollTypes = new List<PayrollType>();
payrollTypes = this._payrollTypeService.GetPayrollTypes(userForLoginDto.Username.ToLower());
if (payrollTypes != null && payrollTypes.Count > 0)
{
userForLoginDto.nextPayProcessDate = payrollTypes[0].NextPayProcessDate;
userForLoginDto.payrollTypeid = payrollTypes[0].ID;
}
}
2026-11-03 18:32:24 +06:00
if (isMFA)
{
int ID = userFromRepo.ID;
mfaCode = this.processMFA();
var mfaSessionId = Guid.NewGuid().ToString();
decimal minutes = mFATimer > 0 ? mFATimer : 2.0m;
TimeSpan otpValidity = TimeSpan.FromSeconds((double)(minutes * 60));
_cache.Remove($"MFA_{mfaSessionId}");
var challenge = new MfaChallenge
{
UserId = ID,
OTP = mfaCode,
CreatedAt = DateTime.Now,
ExpiredAt = DateTime.Now.Add(otpValidity),
AttemptCount = 0
};
var cacheOptions = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = otpValidity,
Priority = CacheItemPriority.High
};
_cache.Set($"MFA_{mfaSessionId}", challenge, cacheOptions);
WriteToFile("Code ready");
this.SendMfaCode(mfaCode, time, userFromRepo);
return Ok(new
{
mfaRequired = true,
mfaSessionId = mfaSessionId,
});
}
2026-11-03 13:06:00 +06:00
}
}
//userFromRepo = _userService.GetByLoginIDAndPassword(userForLoginDto.Username.ToLower(), userForLoginDto.Password);
}
2026-11-12 14:58:04 +06:00
if (!isADLogin && userFromRepo == null)
{
new BadLoginAttemptInfoService().SaveInThread(new BadLoginAttemptInfo
{
LoginID = userForLoginDto.Username,
AttemptTime = DateTime.Now,
});
return BadRequest("Login ID/Password is invalid");
2026-11-03 13:06:00 +06:00
2026-11-12 14:58:04 +06:00
}
2026-11-03 13:06:00 +06:00
if (userFromRepo.UserType == EnumUserType.SuperUser )
{
userForLoginDto.payrollTypeid = null;
}
else if (userFromRepo.UserType == EnumUserType.User && (userForLoginDto.nextPayProcessDate == null || userForLoginDto.payrollTypeid == null))
{
return BadRequest("Access Type and process date is not valid.");
}
2026-11-16 19:05:45 +06:00
else if (userFromRepo.UserType == EnumUserType.User
&& !this._payrollTypeService.GetPayrollTypes(userFromRepo.LoginID).Any(p => p.ID == userForLoginDto.payrollTypeid))
{
// Only an approved (live) access type may be used to sign in; a requested one is not live yet.
return BadRequest("You do not have approved access to the selected Access Type.");
}
2026-11-03 13:06:00 +06:00
else if (userFromRepo.UserType == EnumUserType.Employee)
{
DateTime eocd= _userService.GetEndofContractDate(userForLoginDto.Username);
if (eocd != DateTime.MinValue && eocd < DateTime.Today)
{
return BadRequest("Login ID/Password is invalid");
}
}
2026-11-03 15:54:54 +06:00
//string userToken = this.CreateToten(userFromRepo, userForLoginDto.payrollTypeid, userForLoginDto.nextPayProcessDate);
string userToken = this.CreateTokenNew(userFromRepo, userForLoginDto.payrollTypeid, userForLoginDto.nextPayProcessDate, mfaCode);
return Ok(userToken);
2026-11-03 13:06:00 +06:00
}
public string CreateToten(User userFromRepo, int? payrolltypeid, DateTime? nextPayProcessDate)
{
PayrollType payrollType=null;
bool hasDataPermission = false;
if (payrolltypeid != null)
{
payrollType = new PayrollTypeService().Get((int)payrolltypeid);
hasDataPermission = new DataPermissionService().hasDataPermission(userFromRepo.ID, payrollType.ID);
}
var key = Ease.Core.Utility.JwtSigningKey.FromSecret(this.Secret);
var claims = new[]
{
new Claim("UserID", userFromRepo.ID.ToString()),
new Claim("LoginID", userFromRepo.LoginID),
new Claim("UserName", userFromRepo.UserName),
new Claim("UserType", ((int) userFromRepo.UserType).ToString()),
new Claim("ChangePasswordAtNextLogon", userFromRepo.ChangePasswordAtNextLogon.ToString()),
new Claim("EmployeeID", (userFromRepo.EmployeeID == null) ? "0" : userFromRepo.EmployeeID.ToString()),
new Claim("PayrollTypeID",
(payrolltypeid == null) ? "0" : ((int) payrolltypeid).ToString()),
new Claim("taxParamId", (payrollType == null) ? "0" : payrollType.TaxParamID.ToString()),
new Claim("hasDataPermission", hasDataPermission.ToString()),
new Claim("nextPayProcessDate", (payrolltypeid == null) ? "null" : payrollType.NextPayProcessDate.ToString())
};
var creds = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.Now.AddDays(1),
SigningCredentials = creds
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
string userToken = tokenHandler.WriteToken(token);
if (userToken != null)
{
HttpContext.Session.SetString("JWToken", userToken);
}
return userToken;
}
public string CreateTokenNew(User userFromRepo, int? payrolltypeid, DateTime? nextPayProcessDate, string? mfaCode)
{
PayrollType payrollType = null;
bool hasDataPermission = false;
if (payrolltypeid.HasValue)
{
payrollType = new PayrollTypeService().Get(payrolltypeid.Value);
hasDataPermission = new DataPermissionService()
.hasDataPermission(userFromRepo.ID, payrollType.ID);
}
mfaCode ??= string.Empty;
var roles = DefineRoles(userFromRepo);
var claims = new List<Claim>
{
new Claim("UserID", userFromRepo.ID.ToString()),
new Claim("LoginID", userFromRepo.LoginID),
new Claim("UserName", userFromRepo.UserName),
new Claim("UserType", ((int)userFromRepo.UserType).ToString()),
new Claim("ChangePasswordAtNextLogon", userFromRepo.ChangePasswordAtNextLogon.ToString()),
new Claim("EmployeeID", userFromRepo.EmployeeID?.ToString() ?? "0"),
new Claim("PayrollTypeID", payrolltypeid?.ToString() ?? "0"),
new Claim("taxParamId", payrollType?.TaxParamID.ToString() ?? "0"),
new Claim("hasDataPermission", hasDataPermission.ToString()),
new Claim("nextPayProcessDate", (payrolltypeid == null) ? "null" : payrollType.NextPayProcessDate.ToString()),
};
2026-11-03 15:54:54 +06:00
claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));
2026-11-03 16:26:18 +06:00
var key = Ease.Core.Utility.JwtSigningKey.FromSecret(this.Secret);
2026-11-03 13:06:00 +06:00
var token = new JwtSecurityToken(
issuer: _jwt.Issuer,
audience: _jwt.Audience,
claims: claims,
expires: DateTime.UtcNow.AddMinutes(_jwt.TokenLifetimeMinutes),
2026-11-03 15:54:54 +06:00
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256)
2026-11-03 13:06:00 +06:00
);
string userToken = new JwtSecurityTokenHandler().WriteToken(token);
if (!string.IsNullOrEmpty(userToken))
{
HttpContext.Session.SetString("JWToken", userToken);
}
Response.Cookies.Append("JWToken", userToken, new CookieOptions
{
HttpOnly = true,
Secure = true,
SameSite = SameSiteMode.Strict,
Expires = DateTimeOffset.UtcNow.AddMinutes(_jwt.TokenLifetimeMinutes)
});
var rtkey = Encoding.ASCII.GetBytes("abc-dummy-token-secret-key-32ch-2026");
var rttoken = new JwtSecurityToken(
issuer: "abc",
audience: "abc",
claims: claims,
expires: DateTime.UtcNow.AddMinutes(_jwt.TokenLifetimeMinutes),
2026-11-03 16:26:18 +06:00
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(rtkey),SecurityAlgorithms.HmacSha256)
2026-11-03 13:06:00 +06:00
);
string newuserToken = new JwtSecurityTokenHandler().WriteToken(rttoken);
return newuserToken;
}
private List<string> DefineRoles(User user)
{
var roles = new List<string>();
var menuKeys = new RolePermissionService().GetMenuKeysByUserID(user.ID);
switch (user.UserType)
{
case EnumUserType.SuperUser:
roles.Add("SuperUser");
break;
case EnumUserType.User:
roles.Add("User");
foreach (DataRow row in menuKeys.Tables[0].Rows)
{
switch (row[0].ToString())
{
case "1": roles.Add("MD"); break;
case "2": roles.Add("EMP"); break;
case "4.3": roles.Add("OT"); break;
case "4.4": roles.Add("Bonus"); break;
case "30.2.3": roles.Add("Loan"); break;
case "4.6": roles.Add("Tax"); break;
case "4.8": roles.Add("Salary"); break;
case "4.9": roles.Add("FS"); break;
case "30":
case "31": roles.Add("Fund"); break;
}
}
break;
case EnumUserType.Employee:
roles.Add("Employee");
foreach (DataRow row in menuKeys.Tables[0].Rows)
{
switch (row[0].ToString())
{
case "23.1": roles.Add("EssApprove"); break;
case "28": roles.Add("EssUpload"); break;
}
}
break;
}
return roles.Distinct().ToList();
}
public string processMFA()
{
// create
int codeLength = new SystemConfigarationService().GetconfigIntValue(EnumConfigurationType.Logic, "mfa", "codelength");
string notificationType = new SystemConfigarationService().GetconfigStringValue(EnumConfigurationType.Logic, "mfa", "notificationtype");
int min = (int)Math.Pow(10, codeLength - 1);
int max = (int)Math.Pow(10, codeLength) - 1;
string mfaCode = (new Random().Next(min, max + 1)).ToString();
return mfaCode;
}
public async Task SendMfaCode(string mfaCode, string time, User userFromRepo)
{
WriteToFile("Inside Send MFA");
Employee oEmployee = new Employee();
User oUser = new User();
string email = "";
string name = "";
string mobile = "";
if (userFromRepo.UserType == EnumUserType.Employee)
{
if (userFromRepo.EmployeeID == null) throw new Exception("Employee ID not found.");
oEmployee = new EmployeeService().Get((int)userFromRepo.EmployeeID);
//email = oEmployee != null ? oEmployee.EmailAddress : "";
if (oEmployee.EmailAddress != null)
{
string username = oEmployee.EmailAddress.Split('@')[0];
string actualEmail = username + "@celimited.com";
email = actualEmail;
}
name = oEmployee != null ? oEmployee.Name : "";
mobile = oEmployee != null ? oEmployee.MobileNo : "";
WriteToFile($"Employee: {email}, {name}, {mobile}");
}
else
{
oUser = new UserService().Get(userFromRepo.ID);
2026-11-11 12:09:05 +06:00
email = oUser != null ? oUser.Email : "";
2026-11-03 13:06:00 +06:00
//if (oEmployee.EmailAddress != null)
//{
// string username = oEmployee.EmailAddress.Split('@')[0];
// string actualEmail = username + "@celimited.com";
// email = actualEmail;
//}
name = oUser != null ? oUser.UserName : "";
mobile = oUser != null ? oUser.MobileNo : "";
WriteToFile($"User: {email}, {name}, {mobile}");
}
#region OTP Body
string otpBodyMail, otpBodySMS = string.Empty;
otpBodyMail = "<p>Your login verification code is: <b>" + mfaCode + "</b></p>";
//otpBodyMail += "<p>This code is valid till " + time + ".</p>";
otpBodyMail += "<p>This code will expire in next 2 minutes.</p>";
otpBodySMS = "Your login verification code is: " + mfaCode + ". This code will expire in next 2 minutes.";
#endregion
#region Mail
string notificationtypeMail = new SystemConfigarationService().GetconfigStringValue(EnumConfigurationType.Logic, "mfa", "notificationtypeMail");
if (notificationtypeMail.ToLower() == "yes")
{
if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(name))
{
EmailSettings emailSettings = _emailSettings.Value;
MailSender mailSender = new MailSender();
mailSender.AddTo(email);
mailSender.Subject = "Login Verification Code";
mailSender.Body = "<p>Dear " + name + ",</p>";
mailSender.Body += otpBodyMail;
mailSender.Body += "<p style='color:red;'><b>Note: Do not share this code with anyone. If you did not request this code, please ignore this email.</b></p>";
mailSender.Body += "<p>For assistance, contact HR.</p>";
mailSender.Body += "<p>Regards.</p>";
WriteToFile($"Mail is sending: {email}, {name}, {mobile}");
mailSender.ThreadSendMail(emailSettings);
}
else throw new Exception("Mail Address not found.");
WriteToFile($"Mail has been sent: {email}, {name}, {mobile}");
}
#endregion
#region SMS
string notificationtypeSMS = new SystemConfigarationService().GetconfigStringValue(EnumConfigurationType.Logic, "mfa", "notificationtypeSMS");
2026-11-03 18:32:24 +06:00
if (notificationtypeSMS.ToLower() == "yes")
{
WriteToFile($"SMS init");
if (!string.IsNullOrEmpty(mobile))
{
string mobileNo = new string(mobile.Where(char.IsDigit).ToArray());
if (mobileNo.Length == 11) mobileNo = "880" + mobileNo;
WriteToFile($"SMS is sending: {email}, {name}, {mobile}");
await _smsService.SendLoginOtp(mobileNo, otpBodySMS);
WriteToFile($"SMS has been sent: {email}, {name}, {mobile}");
}
else throw new Exception("Mobile Number not found.");
2026-11-03 13:06:00 +06:00
}
#endregion
}
private void WriteToFile(string text)
{
string pathDate = DateTime.Today.ToString("dd-MM-yyyy");
string path = "C:\\Log\\OTP log " + pathDate + ".txt";
using (StreamWriter writer = new StreamWriter(path, true))
{
writer.WriteLine($"{DateTime.Now:dd/MM/yyyy hh:mm:ss tt} - {text}");
}
}
2026-11-03 15:54:54 +06:00
[HttpPost("verify-mfa")]
[EnableRateLimiting("MfaPolicy")]
[AllowAnonymous]
public IActionResult VerifyMfa([FromBody] VerifyMfaDto dto)
{
var key = $"MFA_{dto.MfaSessionId}";
var challenge = _cache.Get<MfaChallenge>(key);
if (challenge == null)
return Unauthorized("OTP expired or invalid");
if (challenge.ExpiredAt < DateTime.Now)
{
_cache.Remove(key);
return Unauthorized("OTP expired");
}
if (dto.mfaCode != challenge.OTP)
{
challenge.AttemptCount++;
_cache.Set(key, challenge, new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = challenge.ExpiredAt - DateTime.UtcNow
});
return Unauthorized("Invalid OTP");
}
_cache.Remove(key);
User userFromRepo = _userService.Get(challenge.UserId);
int payrolltypeID = 0;
DateTime nextProcessDate = DateTime.Now;
if (userFromRepo != null)
{
List<PayrollType> payrollTypes = new List<PayrollType>();
payrollTypes = this._payrollTypeService.GetPayrollTypes(userFromRepo.LoginID);
if (payrollTypes != null && payrollTypes.Count > 0)
{
nextProcessDate = payrollTypes[0].NextPayProcessDate;
payrolltypeID = payrollTypes[0].ID;
}
}
string userToken = this.CreateTokenNew(userFromRepo, payrolltypeID, nextProcessDate, "");
return Ok(new { userToken });
}
2026-11-16 15:20:15 +06:00
[HttpPost("CipherMechanism")]
public ActionResult CipherMechanism(dynamic data)
{
var item = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data));
string decryptedvalue = (string)item["decryptedvalue"].ToObject<string>();
var encryptedValue = "";
try
{
if (!string.IsNullOrEmpty(decryptedvalue))
{
encryptedValue = Ease.NetCore.Utility.Global.CipherFunctions.Encrypt("CeLiMiTeD.AdMIn", decryptedvalue.Trim());
}
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(encryptedValue);
}
2026-11-03 17:03:07 +06:00
// Clears the HttpOnly "JWToken" cookie the API authenticates from (see Startup), so the
// session really ends on logout. Anonymous so an invalid/expired cookie can still be removed.
[HttpPost("logOut")]
[AllowAnonymous]
public IActionResult logOut()
{
Response.Cookies.Delete("JWToken", new CookieOptions
{
HttpOnly = true,
Secure = true,
SameSite = SameSiteMode.Strict
});
return Ok();
}
2026-11-03 15:54:54 +06:00
[HttpPost("resend-otp")]
[EnableRateLimiting("ResendOtpPolicy")]
[AllowAnonymous]
public ActionResult GetOTP([FromBody] VerifyMfaDto dto)
{
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
IConfiguration Configuration = builder.Build();
decimal mFATimer = Convert.ToDecimal(Configuration.GetSection("LDAPSettings")["MFATimer"]);
string time = DateTime.Now.AddMinutes((double)mFATimer).ToString("hh:mm tt");
string mfaCode = null;
try
{
var key = $"MFA_{dto.MfaSessionId}";
var challenge = _cache.Get<MfaChallenge>(key);
if (challenge == null)
return Unauthorized("OTP expired or invalid");
_cache.Remove(key);
User userFromRepo = _userService.Get(challenge.UserId);
int ID = userFromRepo.ID;
mfaCode = this.processMFA();
var mfaSessionId = Guid.NewGuid().ToString();
decimal minutes = mFATimer > 0 ? mFATimer : 2.0m;
TimeSpan otpValidity = TimeSpan.FromSeconds((double)(minutes * 60));
_cache.Remove($"MFA_{mfaSessionId}");
var newChallenge = new MfaChallenge
{
UserId = ID,
OTP = mfaCode,
CreatedAt = DateTime.Now,
ExpiredAt = DateTime.Now.Add(otpValidity),
AttemptCount = 0
};
var cacheOptions = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = otpValidity,
Priority = CacheItemPriority.High
};
_cache.Set($"MFA_{mfaSessionId}", newChallenge, cacheOptions);
SendMfaCode(mfaCode, time, userFromRepo);
return Ok(new
{
mfaRequired = true,
mfaSessionId = mfaSessionId,
});
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
}
2026-11-03 13:06:00 +06:00
[HttpPost("userPayrolltypeSwitch")]
public ActionResult userPayrolltypeSwitch(dynamic data)
{
var item = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data));
User ouser = item["user"].ToObject<User>();
int payrollTypeId = (int)item["payrollTypeId"].ToObject<int>();
if (ouser.UserType == EnumUserType.SuperUser)
{
return BadRequest("Login ID/Password is invalid");
}
string token = "";
if (ouser.UserType != EnumUserType.User)
{
return BadRequest("select a valid user");
}
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
PayrollType optype = new PayrollTypeService().Get(payrollTypeId);
User oempUser = new UserService().Get(ouser.ID);
2026-11-16 19:05:45 +06:00
// Only an approved (live) access type may be switched to.
if (oempUser == null || !this._payrollTypeService.GetPayrollTypes(oempUser.LoginID).Any(p => p.ID == payrollTypeId))
{
return BadRequest("You do not have approved access to this Access Type.");
}
2026-11-03 13:06:00 +06:00
token = this.CreateToten(oempUser, optype.ID, optype.NextPayProcessDate);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(token);
}
[HttpPost("switchuser")]
public ActionResult switchuser(dynamic data)
{
var item = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data));
User ouser = item["user"].ToObject<User>();
int payrollTypeId = 0;
string token = "";
if (ouser.UserType == EnumUserType.User && ouser.EmployeeID == null)
{
return BadRequest("Employee not yet linked for this User.");
}
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
if (ouser.UserType == EnumUserType.Employee)
{
Employee omp = new EmployeeService().Get((int)ouser.EmployeeID);
User oempUser = new UserService().Get((int)ouser.EmployeeID, EnumUserType.Employee);
if (omp.EndOfContractDate != null && omp.EndOfContractDate < DateTime.Today)
{
return BadRequest("Login ID/Password is invalid");
}
#region Save User Login History
if (oempUser != null)
{
new UserService().SaveUserLoginHistory(oempUser.ID);
}
#endregion
2026-11-03 18:32:24 +06:00
//token = this.CreateToten(oempUser, omp.PayrollTypeID, null);
token = this.CreateTokenNew(oempUser, omp.PayrollTypeID, null, null);
2026-11-03 13:06:00 +06:00
}
else if (ouser.UserType == EnumUserType.User)
{
if (item["payrollTypeId"] == null)
{
Employee omp = new EmployeeService().Get((int)currentUser.EmployeeID);
payrollTypeId = omp.PayrollTypeID;
}
else payrollTypeId = (int)item["payrollTypeId"].ToObject<int>();
PayrollType optype = new PayrollTypeService().Get(payrollTypeId);
2026-11-03 18:32:24 +06:00
User guser = null;
if (currentUser.UserType == EnumUserType.SuperUser && (currentUser.EmployeeID == null || currentUser.EmployeeID == 0))
{
return BadRequest("Admin access is restricted.");
}
else
{
guser = this._userService.Get((int)currentUser.EmployeeID, EnumUserType.User);
}
2026-11-03 13:06:00 +06:00
if (guser == null)
{
return BadRequest("Employee is not a Admin user.");
}
if (guser.UserStatus == EnumAuthStatus.Locked)
{
return BadRequest("Your account is now locked. Please contact with your Line Manager.");
}
2026-11-16 19:05:45 +06:00
// Only an approved (live) access type may be switched to: the same list the ESS
// switch shows (getAdminPayrollTypes).
List<PayrollType> liveAccessTypes = this._payrollTypeService.GetUsersAdminPayrollTypes((int)currentUser.EmployeeID);
if (!liveAccessTypes.Any(p => p.ID == payrollTypeId))
{
if (item["payrollTypeId"] != null || liveAccessTypes.Count == 0)
{
return BadRequest("You do not have approved access to this Access Type.");
}
// No type was chosen and the employee's own one is not an approved access:
// use the first approved one instead.
payrollTypeId = liveAccessTypes[0].ID;
optype = new PayrollTypeService().Get(payrollTypeId);
}
2026-11-03 13:06:00 +06:00
#region Save User Login History
if (guser != null)
{
new UserService().SaveUserLoginHistory(guser.ID);
2026-11-03 18:32:24 +06:00
}
#endregion
2026-11-03 13:06:00 +06:00
2026-11-03 18:32:24 +06:00
//token = this.CreateToten(guser, optype.ID, optype.NextPayProcessDate);
token = this.CreateTokenNew(guser, optype.ID, optype.NextPayProcessDate, null);
2026-11-03 13:06:00 +06:00
}
2026-11-03 18:32:24 +06:00
else if (ouser.UserType == EnumUserType.SuperUser)
2026-11-03 13:06:00 +06:00
{
2026-11-03 18:32:24 +06:00
if (item["payrollTypeId"] == null)
{
}
payrollTypeId = (int)item["payrollTypeId"].ToObject<int>();
PayrollType optype = new PayrollTypeService().Get(payrollTypeId);
User guser = null;
if (currentUser.EmployeeID == null || currentUser.EmployeeID == 0)
{
return BadRequest("You do not have permission to access this feature.");
}
else
{
guser = this._userService.Get((int)currentUser.EmployeeID, EnumUserType.SuperUser);
}
2026-11-03 13:06:00 +06:00
if (guser == null)
{
return BadRequest("Employee is not a Super-User.");
}
if (guser.UserStatus == EnumAuthStatus.Locked)
{
return BadRequest("Your account is now locked. Please contact with your Line Manager.");
}
#region Save User Login History
if (guser != null)
{
new UserService().SaveUserLoginHistory(guser.ID);
}
#endregion
2026-11-03 18:32:24 +06:00
//token = this.CreateToten(guser, null, null);
token = this.CreateTokenNew(guser, optype.ID, optype.NextPayProcessDate, null);
2026-11-03 13:06:00 +06:00
}
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(token);
}
[HttpGet]
[Route("GetPayrollTypesByLoginID/{LoginID}")]
[AllowAnonymous]
public ActionResult GetPayrollTypesByLoginID(string LoginID)
{
List<PayrollType> payrollTypes = new List<PayrollType>();
try
{
payrollTypes = this._payrollTypeService.GetPayrollTypes(LoginID);
return Ok(payrollTypes);
}
catch (Exception ex)
{
//return ex;
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
[HttpGet]
[Route("GetBenifitsProcessStatus")]
public ActionResult GetBenifitsProcessStatus()
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
bool bProcessed = false;
try
{
bProcessed = this._payrollTypeService.GetBenifitsProcessStatus((int)currentUser.PayrollTypeID);
return Ok(bProcessed);
}
catch (Exception ex)
{
//return ex;
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
[HttpGet]
[Route("getAdminPayrollTypes")]
2026-11-08 10:49:54 +06:00
//[AllowAnonymous]
2026-11-03 13:06:00 +06:00
public ActionResult GetAdminPayrollTypes()
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
int employeeId = currentUser.EmployeeID.GetValueOrDefault();
List<PayrollType> payrollTypes = new List<PayrollType>();
try
{
payrollTypes = this._payrollTypeService.GetUsersAdminPayrollTypes(employeeId);
return Ok(payrollTypes);
}
catch (Exception ex)
{
//return ex;
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
/*[HttpGet]
[Route("getSwitchLoginId")]
[AllowAnonymous]
public ActionResult GetSwitchLoginId()
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
if(currentUser.EmployeeID ==null || currentUser.EmployeeID ==0)
{
return StatusCode(StatusCodes.Status500InternalServerError, "Linked employee not found;");
}
string loginId = this._userService.GetLoginId((int)currentUser.EmployeeID, currentUser.UserType);
return Ok(loginId);
}
catch (Exception ex)
{
//return ex;
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}*/
[HttpGet]
[Route("getSwitchUserId/{userType}")]
public ActionResult getSwitchUserId(string usertype)
{
int userId = 0;
try
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser.EmployeeID == null || currentUser.EmployeeID == 0)
{
return StatusCode(StatusCodes.Status500InternalServerError, "Linked employee not found;");
}
userId = this._userService.GetUserId((int)currentUser.EmployeeID, (EnumUserType)Convert.ToInt32( usertype));
if (userId == 0)
{
return StatusCode(StatusCodes.Status500InternalServerError, "Linked employee not found;");
}
return Ok(userId);
}
catch (Exception ex)
{
//return ex;
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
[HttpGet]
[Route("GetPayrollTypeByLoginID")]
public ActionResult GetPayrollTypeByLoginID()
{
PayrollType payrollType = null;
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
payrollType = this._payrollTypeService.Get((int)currentUser.PayrollTypeID);
return Ok(payrollType);
}
catch (Exception ex)
{
//return ex;
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
[HttpGet]
[Route("GetUsers/{userType}/{LogInID}/{Name}")]
public ActionResult GetUsers(EnumUserType userType, string LogInID, string Name)
{
LogInID = GlobalFunctions.GetApiDefaultData(LogInID);
Name = GlobalFunctions.GetApiDefaultData(Name);
try
{
List<User> olist = _userService.Get(LogInID, Name, userType);
return Ok(olist);
}
catch (Exception ex)
{
//return ex;
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
[HttpGet]
[Route("GetUserByID/{userid}")]
public ActionResult GetUserByID(int userid)
{
try
{
User ouser = _userService.Get(userid);
return Ok(ouser);
}
catch (Exception ex)
{
//return ex;
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
2026-11-04 19:03:36 +06:00
[HttpGet]
[Route("getUserByEmail/{email}")]
public ActionResult GetUserByEmail(string email)
{
User user = null;
2026-11-03 13:06:00 +06:00
2026-11-04 19:03:36 +06:00
try
{
user = _userService.GetByEmail(email);
}
catch (Exception ex)
{
//return ex;
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(user);
}
2026-11-03 13:06:00 +06:00
2026-11-04 19:03:36 +06:00
[HttpGet]
2026-11-03 13:06:00 +06:00
[Route("GetLogInUserType")]
public ActionResult GetLogInUserType()
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
return Ok(currentUser.UserType);
}
catch (Exception ex)
{
//return ex;
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
[HttpGet]
[Route("GetCurrentUser")]
public ActionResult GetCurrentUser()
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
return Ok(currentUser);
}
catch (Exception ex)
{
//return ex;
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
[HttpGet]
[Route("GetUserByLoingID/{loginid}/{systemType}")]
public ActionResult GetUserByLoingID(string loginid, EnumSystemType systemType)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
return Ok(this._userService.GetByLogINID(loginid, systemType));
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
//[HttpGet("loadMenu")]
//[IgnoreAntiforgeryToken]
//[ProducesErrorResponseType(typeof(Exception))]
//public List<TreeNode> loadMenu()
//{
// SystemConfigarationService sysConfig = new SystemConfigarationService();
// return sysConfig.LoadMenu();
//}
[HttpGet("getMenuesFromConfig")]
public ActionResult getMenuesFromConfig()
{
List<Role.RolePermission> items = new List<Role.RolePermission>();
try
{
items = this._systemConfig.getMenuesFromConfig();
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(items);
}
[HttpGet("getRole/{roleID}")]
public ActionResult getRole(int roleID)
{
Role items = null;
try
{
items = this._roleService.Get(roleID);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(items);
}
[HttpGet("getAllRoles")]
public ActionResult getAllRoles()
{
List<Role> items = new List<Role>();
try
{
items = this._roleService.GetAllRole();
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(items);
}
[HttpPost("saveRole")]
public ActionResult SaveRole(Role role)
{
int id = 0;
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
2026-11-16 17:55:51 +06:00
try
2026-11-03 13:06:00 +06:00
{
2026-11-16 17:55:51 +06:00
User actingUser = this._userService.Get(currentUser.UserID);
if (actingUser == null || (actingUser.UserType != EnumUserType.SuperUser && actingUser.SISU != true))
{
return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to create, edit or approve roles.");
}
if (role.IsNew == true)
{
role.CreatedBy = currentUser.UserID;
role.CreatedDate = DateTime.Now;
role.RoleStatus = EnumAuthStatus.NewNotYetApprove;
}
else
{
Role existingRole = this._roleService.Get(role.ID);
if (existingRole == null)
{
return BadRequest("Role not found.");
}
bool isPending = existingRole.RoleStatus == EnumAuthStatus.NewNotYetApprove
|| existingRole.RoleStatus == EnumAuthStatus.EditedNotYetApprove
|| existingRole.RoleStatus == EnumAuthStatus.DeletedNotYetApprove;
if (role.RoleStatus == EnumAuthStatus.Approved)
{
if (!isPending)
{
return BadRequest("This role has no pending change to approve.");
}
int makerID = (existingRole.ModifiedBy ?? 0) > 0 ? existingRole.ModifiedBy.Value : existingRole.CreatedBy;
if (makerID == currentUser.UserID)
{
return BadRequest("You cannot approve a change you made yourself. Another user must approve it.");
}
}
else
{
if (isPending)
{
return BadRequest("This role is waiting for approval and cannot be edited.");
}
role.RoleStatus = EnumAuthStatus.EditedNotYetApprove;
}
role.CreatedBy = existingRole.CreatedBy;
role.CreatedDate = existingRole.CreatedDate;
2026-11-16 18:27:28 +06:00
// The browser does not send Sequence either; keep the role's own value instead of 0.
role.Sequence = existingRole.Sequence;
2026-11-16 17:55:51 +06:00
role.ApproveDate = null;
role.ApproveBy = null;
if (role.RoleStatus == EnumAuthStatus.Approved)
{
role.ModifiedBy = existingRole.ModifiedBy;
role.ModifiedDate = existingRole.ModifiedDate;
}
else
{
role.ModifiedBy = currentUser.UserID;
role.ModifiedDate = DateTime.Now;
}
}
if (role.RoleStatus == EnumAuthStatus.Approved)
{
role.ApproveDate = DateTime.Today;
role.ApproveBy = currentUser.UserID;
}
2026-11-03 13:06:00 +06:00
id = this._roleService.Save(role);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(id);
}
2026-11-16 17:55:51 +06:00
//[HttpPost("saveRole")]
//public ActionResult SaveRole(Role role)
//{
// int id = 0;
// CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
// if (role.IsNew == true)
// {
// role.CreatedBy = currentUser.UserID;
// role.CreatedDate = DateTime.Now;
// role.RoleStatus = EnumAuthStatus.NewNotYetApprove;
// }
// else
// {
// role.ApproveDate = null;
// role.ApproveBy = null;
// role.ModifiedBy = currentUser.UserID;
// role.ModifiedDate = DateTime.Now;
// }
// if (role.RoleStatus == EnumAuthStatus.Approved)
// {
// role.ApproveDate = DateTime.Today;
// role.ApproveBy = currentUser.UserID;
// }
// try
// {
// id = this._roleService.Save(role);
// }
// catch (Exception e)
// {
// return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
// }
// return Ok(id);
//}
2026-11-03 13:06:00 +06:00
[HttpPost("GetEmpUserRole")]
public ActionResult GetEmpUserRole(List<SearchEmployee> searchEmps)
{
List<UserRole> ouroles = new List<UserRole>();
try
{
2026-11-17 14:52:13 +06:00
// Admin screens only (Employee Profile's access permission): a self-service login may not read roles.
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser.UserType == EnumUserType.Employee)
{
return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to see user roles.");
}
2026-11-03 13:06:00 +06:00
ouroles = this._userRoleService.Get(searchEmps);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(ouroles);
}
[HttpGet("getUserRoles/{roleType}/{userID}/{roleid}")]
public ActionResult getUserRoles(EnumRoleType roletype, string userID, string roleid)
{
List<UserRole> items = new List<UserRole>();
int? nuserid = GlobalFunctions.GetApiDefaultIntData(userID);
int? nroleid = GlobalFunctions.GetApiDefaultIntData(roleid);
try
{
2026-11-17 14:52:13 +06:00
// Only the User Role Permission page reads this list (super users only, like its other endpoints).
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (!CanManageUserRole(currentUser))
{
return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to see user roles.");
}
2026-11-03 13:06:00 +06:00
items = this._userRoleService.Get(roletype, nuserid, nroleid);
// employee Name, Login-Status, status1, statu2, statu3
// employee group
// status group
//var results = items.GroupBy(n => new { n.UserID }).Select(g => new { g.Key.UserID });
//List<UserRole> newItems = new List<UserRole>();
//foreach (var item in results)
//{
// var uItems = items.FindAll(x => x.UserID == item.UserID);
// UserRole newItem = new UserRole();
// newItem.UserID = item.UserID;
// newItem.userNameView = uItems[0].userNameView;
// newItem.loginIDView = uItems[0].loginIDView;
// string roles = "";
// uItems.ForEach(x => { roles = roles + x.roleNameView + ", "; });
// roles.Substring(0, roles.Length - 2);
// newItem.roleNameView = roles;
// newItems.Add(newItem);
//}
//items = newItems;
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(items);
}
[HttpGet("GetRolePermissionbyUserID")]
public ActionResult GetRolePermissionbyUserID()
{
List<WebMenuHead> items = new List<WebMenuHead>();
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
items = this._roleService.GetRolePermissionbyUserID(currentUser.UserID);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(items);
}
[HttpGet("GetAllPayrollTypes")]
public ActionResult GetAllPayrollTypes()
{
List<PayrollType> items = new List<PayrollType>();
try
{
items = this._payrollTypeService.Get();
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(items);
}
[HttpPost("saveUserRole")]
public ActionResult saveUserRole(List<UserRole> userRoles)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
userRoles.ForEach(x =>
{
if (x.payrollTypeID == 0 || x.payrollTypeID == null)
{
x.payrollTypeID = currentUser.PayrollTypeID;
}
});
userRoles.ForEach(userRole =>
{
if (userRole.IsNew == true)
{
userRole.CreatedBy = currentUser.UserID;
userRole.CreatedDate = DateTime.Now;
}
else
{
userRole.ModifiedBy = currentUser.UserID;
userRole.ModifiedDate = DateTime.Now;
userRole.UserRoleStatus = EnumAuthStatus.Approved;
}
userRole.AuthorizedDate = DateTime.Today;
userRole.AuthorizedBy = currentUser.UserID;
});
try
{
this._userRoleService.Save(userRoles, currentUser.UserID);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok();
}
2026-11-17 12:32:27 +06:00
#region User Role Permission maker-checker
// Only super users manage role assignments (the page is in WebMenu.AdminMenus only), the same
// rule as User Access Type.
private bool CanManageUserRole(CurrentUser currentUser)
{
return CanManageUserAccessType(currentUser);
}
// Admin requests are about a User-type login; Self Service requests about an employee + payroll type.
private static string CheckUserRoleSubject(UserRoleSubject subject)
{
if (subject == null)
return "Select a user or an employee.";
if (subject.RoleType == EnumRoleType.Admin)
return (subject.UserID ?? 0) > 0 ? null : "Select a user.";
if (subject.RoleType == EnumRoleType.Self_Service)
return (subject.EmployeeID ?? 0) > 0 || (subject.UserID ?? 0) > 0 ? null : "Select an employee.";
return "Select Admin or Self Service.";
}
// Who made the pending change (the same maker for every request of one change).
private static bool IsUserRoleMaker(UserRoleState state, int userID)
{
return state.Pending.Any(p => p.CreatedBy == userID);
}
// The person's live roles of one role type, and any change waiting for approval.
[HttpGet("GetUserRoleState/{roleType}/{userID}/{employeeID}")]
public ActionResult GetUserRoleState(EnumRoleType roleType, int userID, int employeeID)
{
try
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (!CanManageUserRole(currentUser))
{
return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to manage user roles.");
}
UserRoleSubject subject = new UserRoleSubject
{
RoleType = roleType,
UserID = userID > 0 ? userID : (int?)null,
EmployeeID = employeeID > 0 ? employeeID : (int?)null,
};
string problem = CheckUserRoleSubject(subject);
if (problem != null)
{
return BadRequest(problem);
}
return Ok(this._userRoleService.GetRoleState(subject));
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
}
// Maker: the ticked roles become pending requests; nothing is live until approved.
[HttpPost("SaveUserRoleRequest")]
public ActionResult SaveUserRoleRequest(UserRoleChangeRequest request)
{
try
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (!CanManageUserRole(currentUser))
{
return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to change user roles.");
}
string problem = CheckUserRoleSubject(request);
if (problem != null)
{
return BadRequest(problem);
}
if (request.RoleType == EnumRoleType.Admin)
{
User target = this._userService.Get(request.UserID.Value);
if (target == null || target.UserType != EnumUserType.User)
{
return BadRequest("Select a valid admin user.");
}
}
UserRoleState state = this._userRoleService.GetRoleState(request);
if (state.Pending.Count > 0)
{
return BadRequest("This person already has a role change waiting for approval. Approve or reject it first.");
}
// A Self Service employee with no login gets one with this change: it needs the payroll type.
if (request.RoleType == EnumRoleType.Self_Service && !state.HasLogin && (request.PayrollTypeID ?? 0) <= 0)
{
return BadRequest("Select a payroll type.");
}
// Every wanted role must be of this role type; a role the person does not have yet must
// also be approved (a role still waiting for its own approval cannot be given).
List<int> wanted = (request.RoleIDs ?? new List<int>()).Distinct().ToList();
List<Role> allRoles = this._roleService.GetAllRole();
foreach (int roleID in wanted)
{
Role role = allRoles.FirstOrDefault(r => r.ID == roleID);
if (role == null || role.RoleType != request.RoleType)
{
return BadRequest("Invalid role for this role type.");
}
bool live = state.LiveRoleIDs.Contains(roleID);
bool approved = role.RoleStatus == EnumAuthStatus.Approved || role.RoleStatus == EnumAuthStatus.Active;
if (!live && !approved)
{
return BadRequest("Role '" + role.Name + "' is not approved yet, so it cannot be given.");
}
}
request.RoleIDs = wanted;
int changed = this._userRoleService.RequestChange(request, currentUser.UserID);
if (changed == 0)
{
return BadRequest("Nothing changed.");
}
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(true);
}
// Checker: makes the person's pending role change live. The maker cannot approve.
[HttpPost("ApproveUserRole")]
public ActionResult ApproveUserRole(UserRoleSubject subject)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
string problem;
try
{
if (!CanManageUserRole(currentUser))
{
return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to approve user roles.");
}
problem = DecideUserRole(subject, true, currentUser);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return problem == null ? Ok(true) : BadRequest(problem);
}
// Checker: drops the person's pending role change; live roles stay as they were. The maker cannot reject.
[HttpPost("RejectUserRole")]
public ActionResult RejectUserRole(UserRoleSubject subject)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
string problem;
try
{
if (!CanManageUserRole(currentUser))
{
return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to reject user roles.");
}
problem = DecideUserRole(subject, false, currentUser);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return problem == null ? Ok(true) : BadRequest(problem);
}
// Checker, many people at once: each one is decided on its own, with the same checks, so one
// that cannot be decided does not stop the rest. Returns { done, failed: [{ index, message }] }.
[HttpPost("ApproveUserRoles")]
public ActionResult ApproveUserRoles(List<UserRoleSubject> subjects)
{
return DecideUserRoles(subjects, true);
}
[HttpPost("RejectUserRoles")]
public ActionResult RejectUserRoles(List<UserRoleSubject> subjects)
{
return DecideUserRoles(subjects, false);
}
// Every role change waiting for approval, of everyone (Pending approvals list).
[HttpGet("GetPendingUserRoles")]
public ActionResult GetPendingUserRoles()
{
try
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (!CanManageUserRole(currentUser))
{
return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to see user role approvals.");
}
return Ok(this._userRoleService.GetPending());
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
}
private ActionResult DecideUserRoles(List<UserRoleSubject> subjects, bool approve)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
if (!CanManageUserRole(currentUser))
{
return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to approve or reject user roles.");
}
if (subjects == null || subjects.Count == 0)
{
return BadRequest("Select at least one person.");
}
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
int done = 0;
var failed = new List<object>();
for (int i = 0; i < subjects.Count; i++)
{
try
{
string problem = DecideUserRole(subjects[i], approve, currentUser);
if (problem == null)
done++;
else
failed.Add(new { index = i, message = problem });
}
catch (Exception e)
{
failed.Add(new { index = i, message = e.Message });
}
}
return Ok(new { done, failed });
}
// Returns null when decided, or why it could not be.
private string DecideUserRole(UserRoleSubject subject, bool approve, CurrentUser currentUser)
{
string problem = CheckUserRoleSubject(subject);
if (problem != null)
return problem;
UserRoleState state = this._userRoleService.GetRoleState(subject);
if (state.Pending.Count == 0)
return "No role change is waiting for approval.";
if (IsUserRoleMaker(state, currentUser.UserID))
return approve
? "You cannot approve a change you made yourself. Another user must approve it."
: "You cannot reject a change you made yourself. Another user must reject it.";
2026-11-17 14:52:13 +06:00
if (approve)
{
// A role given in this change must still be approved now: it may have been edited (and be
// waiting for its own approval) on the Role page since the change was sent.
List<int> giving = state.Pending
.Where(p => p.RequestType == EnumUserRoleRequestType.Add)
.Select(p => p.RoleID).Distinct().ToList();
if (giving.Count > 0)
{
List<Role> allRoles = this._roleService.GetAllRole();
foreach (int roleID in giving)
{
Role role = allRoles.FirstOrDefault(r => r.ID == roleID);
if (role == null)
return "A role in this change no longer exists. Reject the change and send it again.";
if (role.RoleStatus != EnumAuthStatus.Approved && role.RoleStatus != EnumAuthStatus.Active)
return "Role '" + role.Name + "' is not approved now (it may be waiting for its own approval on the Role page), so it cannot be given yet. Approve the role first, or reject this change.";
}
}
}
2026-11-17 12:32:27 +06:00
if (approve)
this._userRoleService.Approve(subject, currentUser.UserID);
else
this._userRoleService.Reject(subject, currentUser.UserID);
return null;
}
#endregion
2026-11-03 13:06:00 +06:00
[HttpGet("GetUserAccessType/{userid}")]
public ActionResult GetUserAccessType(int userid)
{
List<UserAccessType> items = new List<UserAccessType>();
try
{
items = this._userAccessTypeService.GetByUserID(userid);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(items);
}
2026-11-16 19:05:45 +06:00
// Maker-checker for User Access Type. The page is in the super-user menu only
// (WebMenu.AdminMenus, given to SuperUser / SISU users), so only they may request or decide.
private bool CanManageUserAccessType(CurrentUser currentUser)
{
User actingUser = this._userService.Get(currentUser.UserID);
return actingUser != null && (actingUser.UserType == EnumUserType.SuperUser || actingUser.SISU == true);
}
private static bool IsPendingAccess(UserAccessType x)
{
return x.AccessTypeStatus == EnumAuthStatus.NewNotYetApprove
|| x.AccessTypeStatus == EnumAuthStatus.DeletedNotYetApprove;
}
// Who made a pending row: the requester of a new access, or of a removal.
private static int AccessMakerID(UserAccessType x)
{
return x.AccessTypeStatus == EnumAuthStatus.DeletedNotYetApprove ? (x.ModifiedBy ?? 0) : x.CreatedBy;
}
// Maker: the ticked payroll types become pending changes; nothing is live until approved.
2026-11-03 13:06:00 +06:00
[HttpPost("SaveUserAccessType")]
public ActionResult SaveUserAccessType(List<UserAccessType> userAccessTypes)
{
try
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
2026-11-16 19:05:45 +06:00
if (!CanManageUserAccessType(currentUser))
2026-11-03 13:06:00 +06:00
{
2026-11-16 19:05:45 +06:00
return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to change user access types.");
}
if (userAccessTypes == null || userAccessTypes.Count == 0)
{
return BadRequest("Select at least one payroll type.");
}
int userID = userAccessTypes[0].UserID;
if (userID <= 0 || userAccessTypes.Any(x => x.UserID != userID))
{
return BadRequest("Select a user.");
}
List<int> payrollTypeIDs = userAccessTypes.Select(x => x.PayrollTypeID).Distinct().ToList();
List<PayrollType> allPayrollTypes = this._payrollTypeService.Get();
if (payrollTypeIDs.Any(id => !allPayrollTypes.Any(p => p.ID == id)))
{
return BadRequest("Invalid payroll type.");
}
if (this._userAccessTypeService.GetByUserID(userID).Any(IsPendingAccess))
{
return BadRequest("This user already has an access change waiting for approval. Approve or reject it first.");
}
int changed = this._userAccessTypeService.RequestChange(userID, payrollTypeIDs, currentUser.UserID);
if (changed == 0)
{
return BadRequest("Nothing changed.");
}
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(true);
}
// Checker: makes the user's pending access changes live. The maker cannot approve.
[HttpPost("ApproveUserAccessType/{userID}")]
public ActionResult ApproveUserAccessType(int userID)
{
try
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (!CanManageUserAccessType(currentUser))
{
return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to approve user access types.");
}
List<UserAccessType> pending = this._userAccessTypeService.GetByUserID(userID).Where(IsPendingAccess).ToList();
if (pending.Count == 0)
{
return BadRequest("This user has no access change waiting for approval.");
}
if (pending.Any(x => AccessMakerID(x) == currentUser.UserID))
{
return BadRequest("You cannot approve a change you made yourself. Another user must approve it.");
}
this._userAccessTypeService.Approve(userID, currentUser.UserID);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(true);
}
// Checker: drops the user's pending access changes; access stays as it was. The maker cannot reject.
[HttpPost("RejectUserAccessType/{userID}")]
public ActionResult RejectUserAccessType(int userID)
{
try
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (!CanManageUserAccessType(currentUser))
{
return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to reject user access types.");
}
List<UserAccessType> pending = this._userAccessTypeService.GetByUserID(userID).Where(IsPendingAccess).ToList();
if (pending.Count == 0)
{
return BadRequest("This user has no access change waiting for approval.");
}
if (pending.Any(x => AccessMakerID(x) == currentUser.UserID))
{
return BadRequest("You cannot reject a change you made yourself. Another user must reject it.");
}
this._userAccessTypeService.Reject(userID);
2026-11-03 13:06:00 +06:00
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(true);
}
2026-11-16 19:28:49 +06:00
// Pending approvals list: every user access change waiting for approval, one row per payroll type.
[HttpGet("GetPendingUserAccessTypes")]
public ActionResult GetPendingUserAccessTypes()
{
try
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (!CanManageUserAccessType(currentUser))
{
return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to see user access type approvals.");
}
return Ok(this._userAccessTypeService.GetPending());
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
}
// Checker, many users at once: approves each user's pending change on its own, with the same
// checks as ApproveUserAccessType, so one user that cannot be approved does not stop the rest.
[HttpPost("ApproveUserAccessTypes")]
public ActionResult ApproveUserAccessTypes(List<int> userIDs)
{
return DecideUserAccessTypes(userIDs, true);
}
// Checker, many users at once: rejects each user's pending change on its own (see ApproveUserAccessTypes).
[HttpPost("RejectUserAccessTypes")]
public ActionResult RejectUserAccessTypes(List<int> userIDs)
{
return DecideUserAccessTypes(userIDs, false);
}
private ActionResult DecideUserAccessTypes(List<int> userIDs, bool approve)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
if (!CanManageUserAccessType(currentUser))
{
return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to approve or reject user access types.");
}
if (userIDs == null || userIDs.Count == 0)
{
return BadRequest("Select at least one user.");
}
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
int done = 0;
var failed = new List<object>();
foreach (int userID in userIDs.Distinct())
{
try
{
List<UserAccessType> pending = this._userAccessTypeService.GetByUserID(userID).Where(IsPendingAccess).ToList();
if (pending.Count == 0)
{
failed.Add(new { userID, message = "No access change waiting for approval." });
continue;
}
if (pending.Any(x => AccessMakerID(x) == currentUser.UserID))
{
failed.Add(new { userID, message = "You made this change yourself; another user must decide it." });
continue;
}
if (approve)
this._userAccessTypeService.Approve(userID, currentUser.UserID);
else
this._userAccessTypeService.Reject(userID);
done++;
}
catch (Exception e)
{
failed.Add(new { userID, message = e.Message });
}
}
return Ok(new { done, failed });
}
2026-11-03 13:06:00 +06:00
// password history
2026-11-04 19:03:36 +06:00
//[HttpGet]
//[Route("getPasswordHistoryList")]
//[AllowAnonymous]
//public ActionResult GetPasswordHistoryList()
//{
// List<PasswordHistory> items = new List<PasswordHistory>();
// CurrentUser user = CurrentUser.GetCurrentUser(HttpContext.User);
// int userId = user.UserID;
// try
// {
// items = _passwordHistoryService.Get(userId);
// }
// catch (Exception ex)
// {
// //return ex;
// return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
// }
// return Ok(items);
//}
2026-11-03 13:06:00 +06:00
[HttpPost("changePasswordbyAdmin")]
public ActionResult changePasswordbyAdmin(dynamic data)
{
List<PasswordHistory> passwordHistories = new List<PasswordHistory>();
User user = new User();
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
user = new User();
try
{
var item = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data));
int userid = (int) item["userid"].ToObject<int>();
User ou = this._userService.Get(userid);
string newPassword = (string) item["newPassword"].ToObject<string>();
string email = (string) item["empEmail"].ToObject<string>();
string loginID = (string) item["loginid"].ToObject<string>();
int employeeID = (int)item["employeeID"].ToObject<int>();
// populate user
string tempPass = ou.Password;
user.ID = userid;
user.Password =
Ease.NetCore.Utility.Global.CipherFunctions.Encrypt("CeLiMiTeD.AdMIn", newPassword.Trim());
user.PasswordHints = newPassword;
user.LastPasswordChangedDate = DateTime.Today;
user.ChangePasswordAtNextLogon = true;
user.LoginID = loginID;
if (employeeID != null && employeeID > 0)
{
user.EmployeeID = employeeID;
user.PasswordChangedBy = (int)currentUser.UserID;
}
_userService.ChangePasswordAdmin(user);
PasswordHistory history = new PasswordHistory();
history.UserID = user.ID;
history.UserPassword =
ou.Password; // Ease.NetCore.Utility.Global.CipherFunctions.Encrypt("CeLiMiTeD.AdMIn", tempPass.Trim());
history.CreatedBy = user.ID;
history.CreatedDate = DateTime.Today;
_passwordHistoryService.Save(history);
if (email != "")
{
EmailSettings emailSettings = _emailSettings.Value;
string password = newPassword.Trim();
MailSender mailSender = new MailSender();
mailSender.AddTo(email);
mailSender.Subject = "Your HR software Login Password has changed by Admin";
mailSender.Body = @"Your HR software Login Password has changed by Admin.
<p> <b>User Log-in ID : </b> " + loginID + "</p>";
mailSender.Body += "<p> <b>New Password : </b> " + newPassword.Trim() + "</p>";
mailSender.ThreadSendMail(emailSettings);
}
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(true);
}
// password change
[HttpPost("changePassword")]
public ActionResult ChangePassword(dynamic data)
{
List<PasswordHistory> passwordHistories = new List<PasswordHistory>();
bool temp = false;
User user = new User();
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
string loginID = currentUser.LoginID;
int userId = currentUser.UserID;
user = _userService.Get(userId);
try
{
passwordHistories = _passwordHistoryService.Get(userId);
var item = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data));
string oldPassword = (string) item["oldPassword"].ToObject<string>();
string newPassword = (string) item["newPassword"].ToObject<string>();
string confirmPassword = (string) item["confirmedPassword"].ToObject<string>();
if (user.Password !=
Ease.NetCore.Utility.Global.CipherFunctions.Encrypt("CeLiMiTeD.AdMIn", oldPassword.Trim()))
{
throw new Exception("Current/existing Password is not valid");
}
// populate user
string tempPass = user.Password;
user.Password =
Ease.NetCore.Utility.Global.CipherFunctions.Encrypt("CeLiMiTeD.AdMIn", newPassword.Trim());
user.UserName = currentUser.UserName;
user.PasswordHints = newPassword;
user.LastPasswordChangedDate = DateTime.Today;
user.ChangePasswordAtNextLogon = false;
user.LoginID = loginID;
//if (passwordHistories != null && passwordHistories.Count > 0 &&
// confirmPassword.Trim() == user.Password.Trim())
//{
// PasswordHistory passwordHistory = passwordHistories.Find(x =>
// x.UserPassword ==
// Ease.NetCore.Utility.Global.CipherFunctions.Encrypt("CeLiMiTeD.AdMIn", oldPassword.Trim()));
// temp = passwordHistory != null;
//}
//else
//{
// temp = false;
//}
//if (temp)
//{
// return Ok("Error Happened");
//}
_userService.ChangePasswordEss(user);
PasswordHistory history = new PasswordHistory();
history.UserID = user.ID;
history.UserPassword =
Ease.NetCore.Utility.Global.CipherFunctions.Encrypt("CeLiMiTeD.AdMIn", tempPass.Trim());
history.CreatedBy = user.ID;
history.CreatedDate = DateTime.Today;
_passwordHistoryService.Save(history);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(true);
}
[HttpPost("forgotPassword")]
[AllowAnonymous]
public ActionResult ForgotPassword(dynamic data)
{
try
{
EmailSettings emailSettings = _emailSettings.Value;
var item = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data));
string employeeId = (string) item["employeeId"].ToObject<string>();
string emailAddress = (string) item["emailAddress"].ToObject<string>();
User user = _userService.GetByLogINID(employeeId, EnumSystemType.Self_Service);
if (user == null)
{
// error message
return StatusCode(StatusCodes.Status500InternalServerError, "Employee-ID not found in the system.");
}
Employee oemp = new EmployeeService().GetByEmail(emailAddress);
if(oemp ==null)
{
return StatusCode(StatusCodes.Status500InternalServerError, "Invalid Email Address");
}
if(oemp.EmployeeNo.ToLower() != employeeId.ToLower())
{
return StatusCode(StatusCodes.Status500InternalServerError, "Invalid Email Address");
}
if(oemp.Status != EnumEmployeeStatus.Live)
{
return StatusCode(StatusCodes.Status500InternalServerError, "Invalid Email Address");
}
string password = Ease.NetCore.Utility.Global.CipherFunctions.Decrypt("CeLiMiTeD.AdMIn", user.Password);
MailSender mailSender = new MailSender();
mailSender.AddTo(emailAddress);
mailSender.Subject = "Your HR software Login Password (Do not replay this mail)";
mailSender.Body = "<p> <b>User Log-in ID : </b> " + employeeId + "</p>";
mailSender.Body += "<p> <b>Password : </b> " + password + "</p>";
mailSender.SendMail(emailSettings);
System.Threading.Thread.Sleep(500);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(true);
}
[HttpGet]
[Route("getVersionNumber")]
public ActionResult getVersionNumber()
{
string connectionString = _config.GetSection("VersionNumber").Value;
return Ok(connectionString);
}
[HttpGet("getUserByUserType/{userType}")]
public ActionResult getUserByUserType(EnumUserType userType)
{
List<DataPermission> items = new List<DataPermission>();
try
{
items = this._dataPermissionService.getUsersByUserType(userType);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(items);
}
//[HttpGet]
//[Route("addPermission/{data}")]
//public ActionResult addPermission(EnumUserType userType)
//{
// List<DataPermission> items = new List<DataPermission>();
// try
// {
// items = this._dataPermissionService.getUsersByUserType(userType);
// }
// catch (Exception e)
// {
// return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
// }
// return Ok(items);
//}
//deletePermission
[HttpPost("deletePermission")]
public ActionResult deletePermission(DataPermission data)
{
try
{
_dataPermissionService.Delete(data.ID);
}
catch (Exception ex)
{
StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok();
}
[HttpPost("addPermission")]
public ActionResult addPermission(dynamic data)
{
var item = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data));
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
DataPermission dataPermission = new DataPermission();
dataPermission.UserID = (int)item["userID"].ToObject<int>();
dataPermission.PayrollTypeID = (int)item["payrollTypeID"].ToObject<int>();
dataPermission.PermissionType = (EnumDataPermissionType)item["permissionTypeID"].ToObject<EnumDataPermissionType>();
dataPermission.ReferenceID = (int)item["refitemid"].ToObject<int>();
dataPermission.PermissionStatus = EnumMenuPermissionStatus.Approved;// (EnumMenuPermissionStatus)item["permissionStatus"].ToObject<EnumMenuPermissionStatus>();
dataPermission.CreatedBy = currentUser.UserID;
dataPermission.CreatedDate = DateTime.Now;
try
{
_dataPermissionService.Save(dataPermission);
}
catch (Exception ex)
{
StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(dataPermission.ID);
}
[HttpGet("loadDataPermission/{userid}/{payrolltypeid}")]
public ActionResult loadDataPermission(int userid, int payrolltypeid)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
List<DataPermission> items = new List<DataPermission>();
try
{
items = this._dataPermissionService.Get(userid, payrolltypeid);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
return Ok(items);
}
[HttpGet]
[Route("getAllUsers")]
public ActionResult GetAllUsers()
{
try
{
List<User> olist = _userService.GetAll();
return Ok(olist);
}
catch (Exception ex)
{
//return ex;
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
2026-11-12 14:58:04 +06:00
#region System Audit Trail
// Login history in a date range (both days inclusive). Dates come as dd-MMM-yyyy
// (ApiService.getApiDateString). Self-service (Employee) logins are refused:
// the menu is not a security boundary.
[HttpGet]
[Route("getUserAuditTrail/{fromDate}/{toDate}")]
public ActionResult GetUserAuditTrail(string fromDate, string toDate)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser.UserType == EnumUserType.Employee)
return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to view the audit trail.");
List<UserLogInInfo> items = new List<UserLogInInfo>();
try
{
DateTime dFromDate = GlobalFunctions.GetApiDefaultDateData(fromDate);
DateTime dToDate = GlobalFunctions.GetApiDefaultDateData(toDate);
if (dFromDate == DateTime.MinValue || dToDate == DateTime.MinValue)
return StatusCode(StatusCodes.Status400BadRequest, "From date and To date are required.");
if (dFromDate.Date > dToDate.Date)
return StatusCode(StatusCodes.Status400BadRequest, "From date can not be after To date.");
items = _userLogInInfoService.GetAuditTrail(dFromDate, dToDate);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(items);
}
[HttpGet]
[Route("getBadLoginAuditTrail/{fromDate}/{toDate}")]
public ActionResult GetBadLoginAuditTrail(string fromDate, string toDate)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser.UserType == EnumUserType.Employee)
return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to view the audit trail.");
List<BadLoginAttemptInfo> items = new List<BadLoginAttemptInfo>();
try
{
DateTime dFromDate = GlobalFunctions.GetApiDefaultDateData(fromDate);
DateTime dToDate = GlobalFunctions.GetApiDefaultDateData(toDate);
if (dFromDate == DateTime.MinValue || dToDate == DateTime.MinValue)
return StatusCode(StatusCodes.Status400BadRequest, "From date and To date are required.");
if (dFromDate.Date > dToDate.Date)
return StatusCode(StatusCodes.Status400BadRequest, "From date can not be after To date.");
items = _badLoginAttemptInfoService.GetAuditTrail(dFromDate, dToDate);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(items);
}
#endregion
2026-11-03 13:06:00 +06:00
[HttpGet]
[Route("getSSOStatus")]
[AllowAnonymous]
public ActionResult getSSOStatus()
{
int userId = 0;
try
{
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
EmailSettings emailSettings = new EmailSettings();
IConfiguration Configuration = builder.Build();
2026-11-03 15:54:54 +06:00
//Configuration.GetSection("EmailSettings").Bind(emailSettings);
2026-11-03 13:06:00 +06:00
string isSSO = Configuration.GetSection("EmailSettings")["isSSO"];
string isNewDashboard = Configuration.GetSection("EmailSettings")["isNewDashboard"];
string nmgtLink = Configuration.GetSection("EmailSettings")["nmgtLink"];
2026-11-03 15:54:54 +06:00
string isMFA = Configuration.GetSection("LDAPSettings")["isMFA"];
string mfaTimer = Configuration.GetSection("LDAPSettings")["MFATimer"];
2026-11-03 13:06:00 +06:00
2026-11-03 15:54:54 +06:00
DataTable dt = new DataTable();
2026-11-03 13:06:00 +06:00
dt.Columns.Add("isSSO", typeof(bool));
dt.Columns.Add("nmgtLink", typeof(string));
dt.Columns.Add("isNewDashboard", typeof(bool));
2026-11-03 15:54:54 +06:00
dt.Columns.Add("isMFA", typeof(bool));
dt.Columns.Add("mfaTimer", typeof(int));
2026-11-03 13:06:00 +06:00
dt.TableName = "SSO";
DataRow row = dt.NewRow();
row["isSSO"] = isSSO == "true" ? true : false;
row["isNewDashboard"] = isNewDashboard == "false" ? false : true;
row["nmgtLink"] = nmgtLink;
2026-11-03 15:54:54 +06:00
row["isMFA"] = isMFA == "true" ? true : false;
row["mfaTimer"] = int.Parse(mfaTimer);
2026-11-03 13:06:00 +06:00
dt.Rows.Add(row);
return Ok(dt);
}
catch (Exception ex)
{
//return ex;
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
[HttpGet]
[Route("getOperationDate")]
public ActionResult GetOperationDate()
{
try
{
DateTime operationDate = DateTime.Today; //new GlobalFunctionService().GetOperationDate();
return Ok(operationDate);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
[HttpGet]
[Route("SetExpectedSalaryandApprovalDate/{expSalaryDate}/{expApprovalDate}")]
public ActionResult SetExpectedSalaryandApprovalDate(string expSalaryDate, string expApprovalDate)
{
try
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser == null || currentUser.PayrollTypeID == null)
{
return Unauthorized();
}
DateTime expectedSalaryDate = DateTime.Parse(expSalaryDate, System.Globalization.CultureInfo.InvariantCulture);
DateTime expectedApprovalDate = DateTime.Parse(expApprovalDate, System.Globalization.CultureInfo.InvariantCulture);
_payrollTypeService.UpdateExpectedSalaryandApprovalDate(expectedSalaryDate, expectedApprovalDate, (int)currentUser.PayrollTypeID);
return Ok();
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
}
}