EchoTex_Payroll/HRM.UI/Controllers/Auth/AuthController.cs

1362 lines
49 KiB
C#
Raw Normal View History

2024-10-14 10:01:49 +06:00
using AutoMapper;
using HRM.DA;
using HRM.UI.DTOs.Auth;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Threading.Tasks;
using HRM.BO;
using System.Net.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Options;
using HRM.UI.Api;
using System.Text;
using HRM.BO.Configuration;
using Newtonsoft.Json;
using System.Data;
using System.Net;
using System.Reflection;
using HRM.DA.Service;
using HRM.Service;
using HRM.DA;
using System.IO;
namespace HRM.UI.Controllers
{
[ApiController]
[Route("api/Authentication")]
[Authorize]
public class AuthController : ControllerBase
{
private readonly IConfiguration _config;
private readonly IMapper _mapper;
private readonly IUserService _userService;
private readonly IBookmarkService _bookmarkService;
private readonly ISystemConfigaration _systemConfig;
private readonly string Secret;
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;
public AuthController(IConfiguration config, IMapper mapper, IUserService userService,
IOptions<AppSettings> appSettings,
ISystemConfigaration sysconfig
, IUserRoleService userRole, IRoleService rService,
IPayrollTypeService pTypeService, IUserAccessTypeService uaccesstypesrv,
IPasswordHistoryService passwordHistoryService,
IOptions<EmailSettings> emailSettings,
IBookmarkService bookmarkService,
IDataPermissionService dataPermissionService)
{
_config = config;
_mapper = mapper;
_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;
}
[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")]
[AllowAnonymous]
public IActionResult Login(UserForLoginDto userForLoginDto)
{
User userFromRepo = null;
//var hostName = Dns.GetHostEntry(HttpContext.Connection.RemoteIpAddress).HostName;
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
{
userFromRepo = _userService.GetByLoginIDAndPassword(userForLoginDto.Username.ToLower(), userForLoginDto.Password);
}
if (userFromRepo == null)
return BadRequest("Login ID/Password is invalid");
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");
}
}
//var key = Encoding.ASCII.GetBytes(this.Secret);
//PayrollType payrollType = null;
//if (userForLoginDto.payrollTypeid != null)
//{
// payrollType = new PayrollTypeService().Get((int)userForLoginDto.payrollTypeid);
//}
//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",
// (userForLoginDto.payrollTypeid == null) ? "0" : ((int) userForLoginDto.payrollTypeid).ToString()),
// new Claim("taxParamId", (payrollType == null) ? "0" : payrollType.TaxParamID.ToString()),
// new Claim("nextPayProcessDate", (userForLoginDto.nextPayProcessDate == null) ? "null" : userForLoginDto.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);
//}
string userToken = this.CreateToten(userFromRepo, userForLoginDto.payrollTypeid, userForLoginDto.nextPayProcessDate);
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 = Encoding.ASCII.GetBytes(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;
}
[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>();
//if (ouser.UserType == EnumUserType.SuperUser)
//{
// return BadRequest("Login ID/Password is invalid");
//}
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(omp.EmployeeNo);
//if((oempUser.UserStatus != EnumAuthStatus.Approved || oempUser.UserStatus != EnumAuthStatus.Active) && oempUser.Status != EnumStatus.Active)
//{
// return BadRequest("Your user not is not active. contract to System Administrator.");
//}
if (omp.EndOfContractDate != null && omp.EndOfContractDate < DateTime.Today)
{
return BadRequest("Login ID/Password is invalid");
}
token = this.CreateToten(oempUser, omp.PayrollTypeID, 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<int>();
PayrollType optype = new PayrollTypeService().Get(payrollTypeId);
User guser = this._userService.Get((int) currentUser.EmployeeID, EnumUserType.User);
if(guser == null)
{
return BadRequest("Employee is not a Admin user.");
}
token = this.CreateToten(guser, optype.ID, optype.NextPayProcessDate);
}
else if (ouser.UserType == EnumUserType.SuperUser)
{
User guser = this._userService.Get((int)currentUser.EmployeeID, EnumUserType.SuperUser);
if (guser == null)
{
return BadRequest("Employee is not a Super-User.");
}
token = this.CreateToten(guser, null, null);
}
}
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);
}
}
[HttpGet]
[Route("getUserByEmail/{email}")]
[AllowAnonymous]
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<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
[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);
}
[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>();
// 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;
_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();
Configuration.GetSection("EmailSettings").Bind(emailSettings);
string isSSO = Configuration.GetSection("EmailSettings")["isSSO"];
string nmgtLink = Configuration.GetSection("EmailSettings")["nmgtLink"];
DataTable dt = new DataTable();
dt.Columns.Add("isSSO", typeof(bool));
dt.Columns.Add("nmgtLink", typeof(string));
dt.TableName = "SSO";
DataRow row = dt.NewRow();
row["isSSO"] = isSSO == "true" ? true : false;
row["nmgtLink"] = nmgtLink;
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 = new GlobalFunctionService().GetOperationDate();
return Ok(operationDate);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
}
}