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 ;
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 ,
IMemoryCache cache )
{
_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 ;
}
[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 ) ;
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.0 m ;
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.0 m ;
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);
}
if ( ! isADLogin & & userFromRepo = = null )
return BadRequest ( "Login ID/Password is invalid" ) ;
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." ) ;
}
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 ) ;
email = oUser ! = null ? oUser . EmailAddress : "" ;
//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-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.0 m ;
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 ) ;
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." ) ;
}
#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")]
[AllowAnonymous]
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 ) ;
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 ) ;
}
[HttpPost("GetEmpUserRole")]
public ActionResult GetEmpUserRole ( List < SearchEmployee > searchEmps )
{
List < UserRole > ouroles = new List < UserRole > ( ) ;
try
{
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
{
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 ( ) ;
}
[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 ) ;
}
[HttpPost("SaveUserAccessType")]
public ActionResult SaveUserAccessType ( List < UserAccessType > userAccessTypes )
{
try
{
CurrentUser currentUser = CurrentUser . GetCurrentUser ( HttpContext . User ) ;
userAccessTypes . ForEach ( x = >
{
x . CreatedBy = currentUser . UserID ;
x . CreatedDate = DateTime . Today ;
x . ApprovedBy = currentUser . UserID ;
x . ApprovedDate = DateTime . Today ;
} ) ;
this . _userAccessTypeService . Save ( userAccessTypes ) ;
}
catch ( Exception e )
{
return StatusCode ( StatusCodes . Status500InternalServerError , e . Message ) ;
}
return Ok ( true ) ;
}
// 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 ) ;
}
}
[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 ) ;
}
}
}
}