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; private readonly IDataPermissionService _dataPermissionService; private readonly LDAPAuthService _ldapAuthService; private readonly ISmsService _smsService; private readonly IMemoryCache _cache; private readonly IUserLogInInfoService _userLogInInfoService; private readonly IBadLoginAttemptInfoService _badLoginAttemptInfoService; public AuthController(IConfiguration config, IUserService userService, IOptions appSettings, IOptions jwtOptions, ISystemConfigaration sysconfig, IUserRoleService userRole, IRoleService rService, IPayrollTypeService pTypeService, IUserAccessTypeService uaccesstypesrv, IPasswordHistoryService passwordHistoryService, IOptions emailSettings, IBookmarkService bookmarkService, IDataPermissionService dataPermissionService, LDAPAuthService ldapAuthService, ISmsService smsService, IMemoryCache cache, IUserLogInInfoService userLogInInfoService, IBadLoginAttemptInfoService badLoginAttemptInfoService) { _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; _userLogInInfoService = userLogInInfoService; _badLoginAttemptInfoService = badLoginAttemptInfoService; } [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 items = new List(); 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(); } /// /// /// /// /// [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 payrollTypes = new List(); 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) { List payrollTypes = new List(); payrollTypes = this._payrollTypeService.GetPayrollTypes(userForLoginDto.Username.ToLower()); if (payrollTypes != null && payrollTypes.Count > 0) { userForLoginDto.nextPayProcessDate = payrollTypes[0].NextPayProcessDate; userForLoginDto.payrollTypeid = payrollTypes[0].ID; } } 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, }); } } } //userFromRepo = _userService.GetByLoginIDAndPassword(userForLoginDto.Username.ToLower(), userForLoginDto.Password); } if (!isADLogin && userFromRepo == null) { new BadLoginAttemptInfoService().SaveInThread(new BadLoginAttemptInfo { LoginID = userForLoginDto.Username, AttemptTime = DateTime.Now, }); 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"); } } //string userToken = this.CreateToten(userFromRepo, userForLoginDto.payrollTypeid, userForLoginDto.nextPayProcessDate); string userToken = this.CreateTokenNew(userFromRepo, userForLoginDto.payrollTypeid, userForLoginDto.nextPayProcessDate, mfaCode); return Ok(userToken); } 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 { 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()), }; claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role))); var key = Ease.Core.Utility.JwtSigningKey.FromSecret(this.Secret); var token = new JwtSecurityToken( issuer: _jwt.Issuer, audience: _jwt.Audience, claims: claims, expires: DateTime.UtcNow.AddMinutes(_jwt.TokenLifetimeMinutes), signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256) ); 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), signingCredentials: new SigningCredentials(new SymmetricSecurityKey(rtkey),SecurityAlgorithms.HmacSha256) ); string newuserToken = new JwtSecurityTokenHandler().WriteToken(rttoken); return newuserToken; } private List DefineRoles(User user) { var roles = new List(); 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.Email : ""; //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 = "

Your login verification code is: " + mfaCode + "

"; //otpBodyMail += "

This code is valid till " + time + ".

"; otpBodyMail += "

This code will expire in next 2 minutes.

"; 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 = "

Dear " + name + ",

"; mailSender.Body += otpBodyMail; mailSender.Body += "

Note: Do not share this code with anyone. If you did not request this code, please ignore this email.

"; mailSender.Body += "

For assistance, contact HR.

"; mailSender.Body += "

Regards.

"; 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"); 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."); } #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}"); } } [HttpPost("verify-mfa")] [EnableRateLimiting("MfaPolicy")] [AllowAnonymous] public IActionResult VerifyMfa([FromBody] VerifyMfaDto dto) { var key = $"MFA_{dto.MfaSessionId}"; var challenge = _cache.Get(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 payrollTypes = new List(); 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 }); } [HttpPost("CipherMechanism")] public ActionResult CipherMechanism(dynamic data) { var item = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data)); string decryptedvalue = (string)item["decryptedvalue"].ToObject(); 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); } // 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(); } [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(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); } } [HttpPost("userPayrolltypeSwitch")] public ActionResult userPayrolltypeSwitch(dynamic data) { var item = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data)); User ouser = item["user"].ToObject(); int payrollTypeId = (int)item["payrollTypeId"].ToObject(); 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(); 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 //token = this.CreateToten(oempUser, omp.PayrollTypeID, null); token = this.CreateTokenNew(oempUser, omp.PayrollTypeID, null, null); } 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(); PayrollType optype = new PayrollTypeService().Get(payrollTypeId); 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); } 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); } #endregion //token = this.CreateToten(guser, optype.ID, optype.NextPayProcessDate); token = this.CreateTokenNew(guser, optype.ID, optype.NextPayProcessDate, null); } else if (ouser.UserType == EnumUserType.SuperUser) { if (item["payrollTypeId"] == null) { } payrollTypeId = (int)item["payrollTypeId"].ToObject(); 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); } 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 //token = this.CreateToten(guser, null, null); token = this.CreateTokenNew(guser, optype.ID, optype.NextPayProcessDate, null); } } catch (Exception e) { return StatusCode(StatusCodes.Status500InternalServerError, e.Message); } return Ok(token); } [HttpGet] [Route("GetPayrollTypesByLoginID/{LoginID}")] [AllowAnonymous] public ActionResult GetPayrollTypesByLoginID(string LoginID) { List payrollTypes = new List(); 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 payrollTypes = new List(); 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 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); } } [HttpGet] [Route("getUserByEmail/{email}")] public ActionResult GetUserByEmail(string email) { User user = null; try { user = _userService.GetByEmail(email); } catch (Exception ex) { //return ex; return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } return Ok(user); } [HttpGet] [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 loadMenu() //{ // SystemConfigarationService sysConfig = new SystemConfigarationService(); // return sysConfig.LoadMenu(); //} [HttpGet("getMenuesFromConfig")] public ActionResult getMenuesFromConfig() { List items = new List(); 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 items = new List(); 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); try { 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; 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; } id = this._roleService.Save(role); } catch (Exception e) { return StatusCode(StatusCodes.Status500InternalServerError, e.Message); } return Ok(id); } //[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 searchEmps) { List ouroles = new List(); 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 items = new List(); 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 newItems = new List(); //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 items = new List(); 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 items = new List(); try { items = this._payrollTypeService.Get(); } catch (Exception e) { return StatusCode(StatusCodes.Status500InternalServerError, e.Message); } return Ok(items); } [HttpPost("saveUserRole")] public ActionResult saveUserRole(List 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 items = new List(); try { items = this._userAccessTypeService.GetByUserID(userid); } catch (Exception e) { return StatusCode(StatusCodes.Status500InternalServerError, e.Message); } return Ok(items); } [HttpPost("SaveUserAccessType")] public ActionResult SaveUserAccessType(List 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 //[HttpGet] //[Route("getPasswordHistoryList")] //[AllowAnonymous] //public ActionResult GetPasswordHistoryList() //{ // List items = new List(); // 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); //} [HttpPost("changePasswordbyAdmin")] public ActionResult changePasswordbyAdmin(dynamic data) { List passwordHistories = new List(); 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(); User ou = this._userService.Get(userid); string newPassword = (string) item["newPassword"].ToObject(); string email = (string) item["empEmail"].ToObject(); string loginID = (string) item["loginid"].ToObject(); int employeeID = (int)item["employeeID"].ToObject(); // 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.

User Log-in ID : " + loginID + "

"; mailSender.Body += "

New Password : " + newPassword.Trim() + "

"; 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 passwordHistories = new List(); 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 newPassword = (string) item["newPassword"].ToObject(); string confirmPassword = (string) item["confirmedPassword"].ToObject(); 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 emailAddress = (string) item["emailAddress"].ToObject(); 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 = "

User Log-in ID : " + employeeId + "

"; mailSender.Body += "

Password : " + password + "

"; 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 items = new List(); 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 items = new List(); // 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(); dataPermission.PayrollTypeID = (int)item["payrollTypeID"].ToObject(); dataPermission.PermissionType = (EnumDataPermissionType)item["permissionTypeID"].ToObject(); dataPermission.ReferenceID = (int)item["refitemid"].ToObject(); dataPermission.PermissionStatus = EnumMenuPermissionStatus.Approved;// (EnumMenuPermissionStatus)item["permissionStatus"].ToObject(); 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 items = new List(); 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 olist = _userService.GetAll(); return Ok(olist); } catch (Exception ex) { //return ex; return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } } #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 items = new List(); 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 items = new List(); 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 [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(); //Configuration.GetSection("EmailSettings").Bind(emailSettings); string isSSO = Configuration.GetSection("EmailSettings")["isSSO"]; string isNewDashboard = Configuration.GetSection("EmailSettings")["isNewDashboard"]; string nmgtLink = Configuration.GetSection("EmailSettings")["nmgtLink"]; string isMFA = Configuration.GetSection("LDAPSettings")["isMFA"]; string mfaTimer = Configuration.GetSection("LDAPSettings")["MFATimer"]; DataTable dt = new DataTable(); dt.Columns.Add("isSSO", typeof(bool)); dt.Columns.Add("nmgtLink", typeof(string)); dt.Columns.Add("isNewDashboard", typeof(bool)); dt.Columns.Add("isMFA", typeof(bool)); dt.Columns.Add("mfaTimer", typeof(int)); dt.TableName = "SSO"; DataRow row = dt.NewRow(); row["isSSO"] = isSSO == "true" ? true : false; row["isNewDashboard"] = isNewDashboard == "false" ? false : true; row["nmgtLink"] = nmgtLink; row["isMFA"] = isMFA == "true" ? true : false; row["mfaTimer"] = int.Parse(mfaTimer); 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); } } } }