public virtual IActionResult UsersIdPermissionsGet([FromRoute] int id) { bool exists = _context.HetUser.Any(x => x.UserId == id); // not found if (!exists) { return(new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)))); } // get record HetUser user = UserHelper.GetRecord(id, _context); List <HetPermission> permissions = new List <HetPermission>(); foreach (HetUserRole item in user.HetUserRole) { if (item.Role?.HetRolePermission != null) { foreach (HetRolePermission permission in item.Role.HetRolePermission) { permissions.Add(permission.Permission); } } } return(new ObjectResult(new HetsResponse(permissions))); }
public virtual IActionResult UsersIdDeletePost([FromRoute] int id) { bool exists = _context.HetUser.Any(x => x.UserId == id); // not found if (!exists) { return(new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)))); } // get record HetUser user = _context.HetUser.AsNoTracking() .Include(x => x.HetUserRole) .Include(x => x.HetUserDistrict) .First(x => x.UserId == id); // delete user roles foreach (HetUserRole item in user.HetUserRole) { _context.HetUserRole.Remove(item); } // delete user districts foreach (HetUserDistrict item in user.HetUserDistrict) { _context.HetUserDistrict.Remove(item); } // delete user _context.HetUser.Remove(user); _context.SaveChanges(); return(new ObjectResult(new HetsResponse(user))); }
/// <summary> /// Add a user with smUserId as systemId if not in the database /// </summary> /// <param name="dbContext"></param> /// <param name="systemId"></param> public static void InsertSystemUser(DbAppContext dbContext, string systemId) { try { HetUser sysUser = dbContext.HetUser.FirstOrDefault(x => x.SmUserId == systemId); if (sysUser == null) { sysUser = new HetUser { SmUserId = systemId, Surname = "System", GivenName = "HETS", Initials = "SH", Active = true, AppCreateTimestamp = DateTime.UtcNow, AppLastUpdateTimestamp = DateTime.UtcNow, AppCreateUserid = systemId, AppLastUpdateUserid = systemId }; dbContext.HetUser.Add(sysUser); dbContext.SaveChangesForImport(); } } catch { // do nothing } }
public virtual IActionResult UserDistrictsIdSwitchPost([FromRoute] int id) { bool exists = _context.HetUserDistrict.Any(a => a.UserDistrictId == id); // not found if (!exists) { return(new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)))); } // get record HetUserDistrict userDistrict = _context.HetUserDistrict.First(a => a.UserDistrictId == id); string userId = UserAccountHelper.GetUserId(_httpContext); HetUser user = _context.HetUser.First(a => a.SmUserId == userId); user.DistrictId = userDistrict.DistrictId; _context.SaveChanges(); // create new district switch cookie _httpContext.Response.Cookies.Append( "HETSDistrict", userDistrict.DistrictId.ToString(), new CookieOptions { Path = "/", SameSite = SameSiteMode.None } ); return(new ObjectResult(new HetsResponse(user))); }
public virtual IActionResult UsersPost([FromBody] HetUser item) { // not found if (item == null) { return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)))); } HetUser user = new HetUser { Active = item.Active, Email = item.Email, GivenName = item.GivenName, Surname = item.Surname, SmUserId = item.SmUserId, DistrictId = item.District.DistrictId, AgreementCity = item.AgreementCity }; HetUserDistrict newUserDistrict = new HetUserDistrict { DistrictId = item.District.DistrictId, IsPrimary = true }; user.HetUserDistrict.Add(newUserDistrict); _context.HetUser.Add(user); _context.SaveChanges(); int id = user.UserId; // get updated user record and return to UI return(new ObjectResult(new HetsResponse(UserHelper.GetRecord(id, _context)))); }
public virtual IActionResult UsersCurrentLogoffPost() { // get the current user id string userId = _context.SmUserId; // not found if (userId == null) { return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)))); } // get user district HetUserDistrict userDistrict = _context.HetUserDistrict.AsNoTracking() .Include(x => x.User) .Include(x => x.District) .FirstOrDefault(x => x.User.SmUserId == userId && x.IsPrimary); // if we don't find a primary - look for the first one in the list if (userDistrict == null) { userDistrict = _context.HetUserDistrict.AsNoTracking() .Include(x => x.User) .Include(x => x.District) .FirstOrDefault(x => x.User.SmUserId == userId); } // update the current district for the user if (userDistrict != null) { HetUser user = _context.HetUser.First(a => a.SmUserId == userId); user.DistrictId = userDistrict.District.DistrictId; _context.SaveChanges(); } // get the correct logoff url and return string logoffUrl = _configuration.GetSection("Constants:LogoffUrl-Development").Value; if (_env.IsProduction()) { logoffUrl = _configuration.GetSection("Constants:LogoffUrl-Production").Value; } else if (_env.IsStaging()) { logoffUrl = _configuration.GetSection("Constants:LogoffUrl-Test").Value; } LogoffModel response = new LogoffModel { LogoffUrl = logoffUrl }; return(new ObjectResult(new HetsResponse(response))); }
/// <summary> /// Get user record using the user id from the http context /// </summary> /// <param name="context"></param> /// <param name="httpContext"></param> /// <returns></returns> public static User GetUser(DbAppContext context, HttpContext httpContext) { User user = new User(); // is this a business? bool isBusinessUser = IsBusiness(httpContext); string userId = GetUserId(httpContext); if (!isBusinessUser) { HetUser tmpUser = context.HetUser.AsNoTracking() .FirstOrDefault(x => x.SmUserId.ToLower().Equals(userId.ToLower())); if (tmpUser != null) { user.Id = tmpUser.UserId; user.SmUserId = tmpUser.SmUserId; user.GivenName = tmpUser.GivenName; user.Surname = tmpUser.Surname; user.DisplayName = tmpUser.GivenName + " " + tmpUser.Surname; user.UserGuid = tmpUser.Guid; user.BusinessUser = false; user.SmAuthorizationDirectory = tmpUser.SmAuthorizationDirectory; user.AgreementCity = tmpUser.AgreementCity; } } else { HetBusinessUser tmpUser = context.HetBusinessUser.AsNoTracking() .FirstOrDefault(x => x.BceidUserId.ToLower().Equals(userId.ToLower())); if (tmpUser != null) { // get business HetBusiness business = context.HetBusiness.AsNoTracking() .First(x => x.BusinessId == tmpUser.BusinessId); user.Id = tmpUser.BusinessUserId; user.SmUserId = tmpUser.BceidUserId; user.GivenName = tmpUser.BceidFirstName; user.Surname = tmpUser.BceidLastName; user.DisplayName = tmpUser.BceidDisplayName; user.UserGuid = tmpUser.BceidGuid; user.BusinessUser = true; user.BusinessId = tmpUser.BusinessId; user.BusinessGuid = business.BceidBusinessGuid; user.SmAuthorizationDirectory = "BCeID"; } } return(user); }
/// <summary> /// Returns a user based on the guid /// </summary> /// <param name="guid"></param> /// <param name="context"></param> /// <returns></returns> public static HetUser GetUserByGuid(string guid, DbAppContext context) { HetUser user = context.HetUser.AsNoTracking() .Where(x => x.Guid != null && x.Guid.Equals(guid)) .Include(u => u.HetUserRole) .ThenInclude(r => r.Role) .ThenInclude(rp => rp.HetRolePermission) .ThenInclude(p => p.Permission) .FirstOrDefault(); return(user); }
/// <summary> /// Returns a user based on the account name /// </summary> /// <param name="smUserId"></param> /// <param name="context"></param> /// <returns></returns> public static HetUser GetUserBySmUserId(string smUserId, DbAppContext context) { HetUser user = context.HetUser.AsNoTracking() .Where(x => x.SmUserId != null && x.SmUserId.ToLower().Equals(smUserId.ToLower())) .Include(u => u.HetUserRole) .ThenInclude(r => r.Role) .ThenInclude(rp => rp.HetRolePermission) .ThenInclude(p => p.Permission) .FirstOrDefault(); return(user); }
public virtual IActionResult UsersIdRolesPost([FromRoute] int id, [FromBody] HetUserRole item) { bool exists = _context.HetUser.Any(x => x.UserId == id); // not found if (!exists) { return(new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)))); } // check the role id bool roleExists = _context.HetRole.Any(x => x.RoleId == item.RoleId); // record not found if (!roleExists) { return(new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)))); } // check the user exists HetUser user = UserHelper.GetRecord(id, _context); if (user == null) { return(new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)))); } // check if the user has this role - then add if (user.HetUserRole.All(x => x.RoleId != item.RoleId)) { // create a new UserRole record HetUserRole userRole = new HetUserRole { RoleId = item.RoleId, UserId = id, EffectiveDate = item.EffectiveDate, ExpiryDate = item.ExpiryDate }; _context.HetUserRole.Add(userRole); _context.SaveChanges(); } // return updated roles user = UserHelper.GetRecord(id, _context); // return user roles return(new ObjectResult(new HetsResponse(user.HetUserRole))); }
public virtual IActionResult UsersPost([FromBody] HetUser item) { // not found if (item == null) { return(new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)))); } // validate that user id is unique // HETS-1033 - Post Live: Add validation on User ID while adding a new user item.SmUserId = item.SmUserId?.Trim().ToLower(); HetUser existingUser = _context.HetUser.AsNoTracking() .FirstOrDefault(x => x.SmUserId.ToLower() == item.SmUserId); if (existingUser != null) { return(new BadRequestObjectResult(new HetsResponse("HETS-38", ErrorViewModel.GetDescription("HETS-38", _configuration)))); } // add new user HetUser user = new HetUser { Active = item.Active, Email = item.Email?.Trim(), GivenName = item.GivenName?.Trim(), Surname = item.Surname?.Trim(), SmUserId = item.SmUserId, DistrictId = item.District.DistrictId, AgreementCity = item.AgreementCity }; HetUserDistrict newUserDistrict = new HetUserDistrict { DistrictId = item.District.DistrictId, IsPrimary = true }; user.HetUserDistrict.Add(newUserDistrict); _context.HetUser.Add(user); _context.SaveChanges(); int id = user.UserId; // get updated user record and return to UI return(new ObjectResult(new HetsResponse(UserHelper.GetRecord(id, _context)))); }
public virtual IActionResult UsersIdRolesGet([FromRoute] int id) { bool exists = _context.HetUser.Any(x => x.UserId == id); // not found if (!exists) { return(new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)))); } // get record HetUser user = UserHelper.GetRecord(id, _context); // return user roles return(new ObjectResult(new HetsResponse(user.HetUserRole))); }
public virtual IActionResult UsersIdRolesPut([FromRoute] int id, [FromBody] HetUserRole[] items) { bool exists = _context.HetUser.Any(x => x.UserId == id); // not found if (!exists || items == null) { return(new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)))); } // get record HetUser user = UserHelper.GetRecord(id, _context); if (user.HetUserRole == null) { return(new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)))); } // iterate the roles and update effective date foreach (HetUserRole item in items) { // check the role id bool roleExists = _context.HetUserRole.Any(x => x.RoleId == item.RoleId && x.UserId == id); if (roleExists) { // check if we need to modify the effective date HetUserRole role = _context.HetUserRole.First(x => x.RoleId == item.RoleId && x.UserId == id); if (role.ExpiryDate != item.ExpiryDate) { role.ExpiryDate = item.ExpiryDate; _context.SaveChanges(); } } } // return updated roles user = UserHelper.GetRecord(id, _context); // return user roles return(new ObjectResult(new HetsResponse(user.HetUserRole))); }
/// <summary> /// Get a User record /// </summary> /// <param name="id"></param> /// <param name="context"></param> /// <returns></returns> public static HetUser GetRecord(int id, DbAppContext context) { HetUser user = context.HetUser.AsNoTracking() .Include(x => x.District) .Include(x => x.HetUserDistrict) .Include(x => x.HetUserRole) .ThenInclude(y => y.Role) .ThenInclude(z => z.HetRolePermission) .ThenInclude(z => z.Permission) .FirstOrDefault(x => x.UserId == id); if (user != null) { // remove inactive roles user.HetUserRole = user.HetUserRole .Where(x => x.Role != null && x.EffectiveDate <= DateTime.UtcNow && (x.ExpiryDate == null || x.ExpiryDate > DateTime.UtcNow)) .ToList(); } return(user); }
/// <summary> /// Process Authentication Request /// </summary> /// <returns></returns> protected override Task <AuthenticateResult> HandleAuthenticateAsync() { // get SiteMinder headers _logger.LogDebug("Parsing the HTTP headers for SiteMinder authentication credential"); SiteMinderAuthOptions options = new SiteMinderAuthOptions(); try { HttpContext context = Request.HttpContext; DbAppContext dbAppContext = (DbAppContext)context.RequestServices.GetService(typeof(DbAppContext)); IHostingEnvironment hostingEnv = (IHostingEnvironment)context.RequestServices.GetService(typeof(IHostingEnvironment)); UserSettings userSettings = new UserSettings(); string userId = ""; string siteMinderGuid = ""; string businessGuid = ""; string url = context.Request.GetDisplayUrl().ToLower(); _logger.LogWarning("Timestamp: {0:dd-MM-yyyy HH:mm:ss.FFFF} | Url: {1} | Remote Ip: {0}", DateTime.Now, url, context.Connection.RemoteIpAddress.ToString()); // ******************************************************** // if this is an Error or Authentication API - Ignore // ******************************************************** if (url.Contains("/authentication/dev") || url.Contains("/error") || url.Contains("/hangfire") || url.Contains("/swagger")) { _logger.LogInformation("Bypassing authentication process ({0})", url); return(Task.FromResult(AuthenticateResult.NoResult())); } // ************************************************** // check if we have a Dev Environment Cookie // ************************************************** string tempToken = context.Request.Cookies[options.DevAuthenticationTokenKey]; if (hostingEnv.IsDevelopment() && !string.IsNullOrEmpty(tempToken)) { _logger.LogInformation("Dev Authentication token found ({0})", tempToken); userId = tempToken; } else if ((context.Connection.RemoteIpAddress.ToString().StartsWith("::1") || context.Connection.RemoteIpAddress.ToString().StartsWith("::ffff:127.0.0.1")) && url.StartsWith("http://*****:*****@"LOCK TABLE ""HET_USER"" IN EXCLUSIVE MODE;"); HetUser user = dbAppContext.HetUser.First(x => x.UserId == updUserId); user.DistrictId = districtId; dbAppContext.HetUser.Update(user); // update user record dbAppContext.SaveChanges(); // commit transaction.Commit(); } } } userSettings.SiteMinderGuid = siteMinderGuid; userSettings.UserAuthenticated = true; userSettings.BusinessUser = false; } // ************************************************** // validate / check user permissions // ************************************************** _logger.LogInformation("Validating user permissions"); ClaimsPrincipal userPrincipal; if (userSettings.BusinessUser && userSettings.UserAuthenticated && userSettings.HetsBusinessUser != null) { userPrincipal = userSettings.HetsBusinessUser.ToClaimsPrincipal(options.Scheme); if (!userPrincipal.HasClaim(HetUser.PermissionClaim, HetPermission.BusinessLogin)) { _logger.LogWarning(options.MissingDbUserIdError + " (" + userId + ")"); return(Task.FromResult(AuthenticateResult.Fail(options.InvalidPermissions))); } } else { userPrincipal = userSettings.HetsUser.ToClaimsPrincipal(options.Scheme); if (!userPrincipal.HasClaim(HetUser.PermissionClaim, HetPermission.Login) && !userPrincipal.HasClaim(HetUser.PermissionClaim, HetPermission.BusinessLogin)) { _logger.LogWarning(options.MissingDbUserIdError + " (" + userId + ")"); return(Task.FromResult(AuthenticateResult.Fail(options.InvalidPermissions))); } } // ************************************************** // create authenticated user // ************************************************** _logger.LogInformation("Authentication successful: " + userId); _logger.LogInformation("Setting identity and creating session for: " + userId); // ************************************************** // done! // ************************************************** ClaimsPrincipal principal = userPrincipal; return(Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principal, null, Options.Scheme)))); } catch (Exception exception) { _logger.LogError(exception.Message); Console.WriteLine(exception); throw; } }
public virtual IActionResult UsersIdPut([FromRoute] int id, [FromBody] HetUser item) { if (item == null || id != item.UserId) { // not found return(new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)))); } bool exists = _context.HetUser.Any(x => x.UserId == id); // not found if (!exists) { return(new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)))); } // get record HetUser user = _context.HetUser .Include(x => x.District) .Include(x => x.HetUserDistrict) .First(x => x.UserId == id); // validate that user id is unique // HETS-1033 - Post Live: Add validation on User ID while editing a user string smUserId = item.SmUserId?.Trim().ToLower(); HetUser existingUser = _context.HetUser.AsNoTracking() .FirstOrDefault(x => x.SmUserId.ToLower() == smUserId && x.UserId != user.UserId); if (existingUser != null) { return(new BadRequestObjectResult(new HetsResponse("HETS-38", ErrorViewModel.GetDescription("HETS-38", _configuration)))); } user.ConcurrencyControlNumber = item.ConcurrencyControlNumber; user.Active = item.Active; user.Email = item.Email; user.GivenName = item.GivenName; user.Surname = item.Surname; user.SmUserId = item.SmUserId; user.AgreementCity = item.AgreementCity; if (item.District != null) { bool districtExists = _context.HetDistrict.Any(x => x.DistrictId == item.District.DistrictId); if (districtExists) { HetDistrict district = _context.HetDistrict .Include(x => x.Region) .First(x => x.DistrictId == item.District.DistrictId); user.DistrictId = district.DistrictId; // check if we need to add this to the User District List too bool userDistrictExists = false; foreach (HetUserDistrict userDistrict in user.HetUserDistrict) { if (userDistrict.DistrictId == item.District.DistrictId) { userDistrictExists = true; break; } } // if not found - then add it! if (!userDistrictExists) { HetUserDistrict newUserDistrict = new HetUserDistrict { UserId = item.UserId, DistrictId = district.DistrictId }; if (user.HetUserDistrict == null) { user.HetUserDistrict = new List <HetUserDistrict>(); newUserDistrict.IsPrimary = true; } user.HetUserDistrict.Add(newUserDistrict); } } } // save changes _context.SaveChanges(); // get updated user record and return to UI return(new ObjectResult(new HetsResponse(UserHelper.GetRecord(id, _context)))); }
/// <summary> /// Get user record /// </summary> /// <param name="context"></param> /// <param name="userId"></param> /// <param name="guid"></param> /// <returns></returns> public static HetUser GetUser(DbAppContext context, string userId, string guid = null) { HetUser user = null; if (!string.IsNullOrEmpty(guid)) { user = GetUserByGuid(guid, context); } if (user == null) { user = GetUserBySmUserId(userId, context); } if (user == null) { return(null); } if (!string.IsNullOrEmpty(guid) && string.IsNullOrEmpty(user.Guid)) { // self register (write the users Guid to the db) int updUserId = user.UserId; using (IDbContextTransaction transaction = context.Database.BeginTransaction()) { // lock the table during this transaction context.Database.ExecuteSqlCommand(@"LOCK TABLE ""HET_USER"" IN EXCLUSIVE MODE;"); HetUser updUser = context.HetUser.First(x => x.UserId == updUserId); updUser.Guid = guid; updUser.AppLastUpdateUserDirectory = user.SmAuthorizationDirectory; updUser.AppLastUpdateUserGuid = guid; updUser.AppLastUpdateUserid = userId; updUser.AppLastUpdateTimestamp = DateTime.UtcNow; context.HetUser.Update(updUser); // update user record context.SaveChanges(); // commit transaction.Commit(); } // update the user object for the current session user.Guid = guid; user.AppLastUpdateUserDirectory = user.SmAuthorizationDirectory; user.AppLastUpdateUserGuid = guid; user.AppLastUpdateUserid = userId; user.AppLastUpdateTimestamp = DateTime.UtcNow; } else if (!string.IsNullOrEmpty(user.Guid) && !string.IsNullOrEmpty(guid) && !user.Guid.Equals(guid, StringComparison.OrdinalIgnoreCase)) { // invalid account - guid doesn't match user credential return(null); } // detach user and return context.Entry(user).State = EntityState.Detached; return(user); }
/// <summary> /// Map data /// </summary> /// <param name="dbContext"></param> /// <param name="oldObject"></param> /// <param name="user"></param> /// <param name="systemId"></param> /// <param name="smUserId"></param> /// <param name="firstName"></param> /// <param name="lastName"></param> /// <param name="maxUserIndex"></param> private static void CopyToInstance(DbAppContext dbContext, ImportModels.UserHets oldObject, ref HetUser user, string systemId, string smUserId, string firstName, string lastName, ref int maxUserIndex) { try { // file contains multiple records per user (1 for each district they can access) // we are currently importing 1 only -> where Default_Service_Area = Y if (oldObject.Default_Service_Area != "Y") { return; } // check if this user already exists in the db bool userExists = dbContext.HetUser.Any(x => x.SmUserId == smUserId); if (userExists) { user = dbContext.HetUser.First(x => x.SmUserId == smUserId); // ******************************************************************* // check if this is a different district // ******************************************************************* int serviceAreaId; try { serviceAreaId = int.Parse(oldObject.Service_Area_Id); } catch { // not mapped correctly throw new ArgumentException(string.Format("User Error - Invalid Service Area (userId: {0}", user.SmUserId)); } HetServiceArea serviceArea = dbContext.HetServiceArea.AsNoTracking() .FirstOrDefault(x => x.MinistryServiceAreaId == serviceAreaId); if (serviceArea == null) { // not mapped correctly throw new ArgumentException(string.Format("User Error - Invalid Service Area (userId: {0}", user.SmUserId)); } int tempUserId = user.UserId; int?tempDistrictId = serviceArea.DistrictId; if (tempDistrictId != null) { HetUserDistrict userDistrict = dbContext.HetUserDistrict.AsNoTracking() .FirstOrDefault(x => x.User.UserId == tempUserId && x.District.DistrictId == tempDistrictId); // *********************************************** // create user district record // *********************************************** if (userDistrict == null) { userDistrict = new HetUserDistrict { UserId = tempUserId, DistrictId = tempDistrictId, AppCreateTimestamp = DateTime.UtcNow, AppCreateUserid = systemId, AppLastUpdateUserid = systemId, AppLastUpdateTimestamp = DateTime.UtcNow }; dbContext.HetUserDistrict.Add(userDistrict); dbContext.SaveChangesForImport(); } } } else { user = new HetUser { UserId = ++maxUserIndex, Active = true, SmUserId = smUserId, SmAuthorizationDirectory = "IDIR" }; if (!string.IsNullOrEmpty(firstName)) { user.GivenName = firstName; } if (!string.IsNullOrEmpty(lastName)) { user.Surname = lastName; } // ******************************************************************* // create initials // ******************************************************************* string temp = ""; if (!string.IsNullOrEmpty(lastName) && lastName.Length > 0) { temp = lastName.Substring(0, 1).ToUpper(); } if (!string.IsNullOrEmpty(firstName) && firstName.Length > 0) { temp = temp + firstName.Substring(0, 1).ToUpper(); } if (!string.IsNullOrEmpty(temp)) { user.Initials = temp; } // ******************************************************************* // map user to the correct service area // ******************************************************************* int serviceAreaId; try { serviceAreaId = int.Parse(oldObject.Service_Area_Id); } catch { // not mapped correctly throw new ArgumentException(string.Format("User Error - Invalid Service Area (userId: {0}", user.SmUserId)); } HetServiceArea serviceArea = dbContext.HetServiceArea.AsNoTracking() .FirstOrDefault(x => x.MinistryServiceAreaId == serviceAreaId); if (serviceArea == null) { // not mapped correctly throw new ArgumentException(string.Format("User Error - Invalid Service Area (userId: {0}", user.SmUserId)); } user.DistrictId = serviceArea.DistrictId; // ******************************************************************* // set the user's role // ** all new users will be added with basic access only // ******************************************************************* HetUserRole userRole = new HetUserRole(); HetRole role = dbContext.HetRole.FirstOrDefault(x => x.Name == "HETS District User"); int roleId = -1; if (role != null) { roleId = role.RoleId; } // *********************************************** // create user // *********************************************** user.AppCreateTimestamp = DateTime.UtcNow; user.AppCreateUserid = systemId; user.AppLastUpdateUserid = systemId; user.AppLastUpdateTimestamp = DateTime.UtcNow; userRole.Role = dbContext.HetRole.First(x => x.RoleId == roleId); userRole.EffectiveDate = DateTime.UtcNow.AddDays(-1); userRole.AppCreateTimestamp = DateTime.UtcNow; userRole.AppCreateUserid = systemId; userRole.AppLastUpdateUserid = systemId; userRole.AppLastUpdateTimestamp = DateTime.UtcNow; user.HetUserRole = new List <HetUserRole> { userRole }; dbContext.HetUser.Add(user); dbContext.SaveChangesForImport(); // *********************************************** // create user district record // *********************************************** HetUserDistrict userDistrict = new HetUserDistrict { UserId = user.UserId, DistrictId = user.DistrictId, IsPrimary = true, AppCreateTimestamp = DateTime.UtcNow, AppCreateUserid = systemId, AppLastUpdateUserid = systemId, AppLastUpdateTimestamp = DateTime.UtcNow }; dbContext.HetUserDistrict.Add(userDistrict); dbContext.SaveChangesForImport(); } } catch (Exception ex) { Debug.WriteLine("***Error*** - Employee Id: " + oldObject.Popt_Id); Debug.WriteLine("***Error*** - Master User Index: " + maxUserIndex); Debug.WriteLine(ex.Message); throw; } }
/// <summary> /// Import Users /// </summary> /// <param name="performContext"></param> /// <param name="dbContext"></param> /// <param name="fileLocation"></param> /// <param name="systemId"></param> public static void Import(PerformContext performContext, DbAppContext dbContext, string fileLocation, string systemId) { // check the start point. If startPoint == sigId then it is already completed int startPoint = ImportUtility.CheckInterMapForStartPoint(dbContext, OldTableProgress, BcBidImport.SigId, NewTable); if (startPoint == BcBidImport.SigId) // this means the import job it has done today is complete for all the records in the xml file. { performContext.WriteLine("*** Importing " + XmlFileName + " is complete from the former process ***"); return; } // manage the id value for new user records int maxUserIndex = 0; if (dbContext.HetUser.Any()) { maxUserIndex = dbContext.HetUser.Max(x => x.UserId); maxUserIndex = maxUserIndex + 1; } try { string rootAttr = "ArrayOf" + OldTable; // create progress indicator performContext.WriteLine("Processing " + OldTable); IProgressBar progress = performContext.WriteProgressBar(); progress.SetValue(0); // create serializer and serialize xml file XmlSerializer ser = new XmlSerializer(typeof(ImportModels.UserHets[]), new XmlRootAttribute(rootAttr)); MemoryStream memoryStream = ImportUtility.MemoryStreamGenerator(XmlFileName, OldTable, fileLocation, rootAttr); ImportModels.UserHets[] legacyItems = (ImportModels.UserHets[])ser.Deserialize(memoryStream); int ii = startPoint; // skip the portion already processed if (startPoint > 0) { legacyItems = legacyItems.Skip(ii).ToArray(); } // create an array of names using the created by and modified by values in the data performContext.WriteLine("Extracting first and last names"); progress.SetValue(0); Dictionary <string, string> firstNames = new Dictionary <string, string>(); Dictionary <string, string> lastNames = new Dictionary <string, string>(); foreach (ImportModels.UserHets item in legacyItems.WithProgress(progress)) { string name = item.Created_By; GetNameParts(name, ref firstNames, ref lastNames); name = item.Modified_By; GetNameParts(name, ref firstNames, ref lastNames); } // import the data performContext.WriteLine("Importing User Data"); progress.SetValue(0); foreach (ImportModels.UserHets item in legacyItems.WithProgress(progress)) { string tempId = item.Popt_Id + "-" + item.Service_Area_Id; HetImportMap importMap = dbContext.HetImportMap.AsNoTracking() .FirstOrDefault(x => x.OldTable == OldTable && x.OldKey == tempId); if (importMap == null) { string username = NormalizeUserCode(item.User_Cd).ToUpper(); string firstName = GetNamePart(username, firstNames); string lastName = GetNamePart(username, lastNames); HetUser user = null; username = username.ToLower(); CopyToInstance(dbContext, item, ref user, systemId, username, firstName, lastName, ref maxUserIndex); if (user != null) { ImportUtility.AddImportMap(dbContext, OldTable, tempId, NewTable, user.UserId); dbContext.SaveChangesForImport(); } } } try { performContext.WriteLine("*** Importing " + XmlFileName + " is Done ***"); ImportUtility.AddImportMapForProgress(dbContext, OldTableProgress, BcBidImport.SigId.ToString(), BcBidImport.SigId, NewTable); dbContext.SaveChangesForImport(); } catch (Exception e) { string temp = string.Format("Error saving data (UserIndex: {0}): {1}", maxUserIndex, e.Message); performContext.WriteLine(temp); throw new DataException(temp); } } catch (Exception e) { performContext.WriteLine("*** ERROR ***"); performContext.WriteLine(e.ToString()); throw; } }
private IActionResult UpdateFavourite(HetUserFavourite item) { item.User = null; // get the current user id string userId = _context.SmUserId; // not found if (userId == null) { return(new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)))); } // get initial results - must be limited to user's district int?districtId = UserAccountHelper.GetUsersDistrictId(_context, _httpContext); // get user record bool userExists = _context.HetUser.Any(a => a.SmUserId == userId); if (!userExists) { return(new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)))); } HetUser user = _context.HetUser.AsNoTracking() .First(a => a.SmUserId == userId); // get favourites bool exists = _context.HetUserFavourite.Any(a => a.UserFavouriteId == item.UserFavouriteId); HetUserFavourite favourite; if (exists) { favourite = _context.HetUserFavourite .First(a => a.UserFavouriteId == item.UserFavouriteId); favourite.ConcurrencyControlNumber = item.ConcurrencyControlNumber; favourite.Value = item.Value; favourite.Name = item.Name; favourite.IsDefault = item.IsDefault; _context.HetUserFavourite.Update(favourite); } else { favourite = new HetUserFavourite { UserId = user.UserId, DistrictId = districtId, Type = item.Type, Value = item.Value, Name = item.Name, IsDefault = item.IsDefault }; _context.HetUserFavourite.Add(favourite); } // save the changes _context.SaveChanges(); int favouriteId = favourite.UserFavouriteId; // get record and return favourite = _context.HetUserFavourite.AsNoTracking() .First(x => x.UserFavouriteId == favouriteId); return(new ObjectResult(new HetsResponse(favourite))); }
public virtual IActionResult UsersCurrentGet() { _logger.LogDebug("Get Current User"); // get the current user id string businessGuid = _context.SmBusinessGuid; string userId = _context.SmUserId; _logger.LogDebug("User Id: {0}", userId); _logger.LogDebug("Business Guid: {0}", businessGuid); // not found - return an HTTP 401 error response if (string.IsNullOrEmpty(userId)) { return(StatusCode(401)); } User user = new User(); if (string.IsNullOrEmpty(businessGuid)) { HetUser currentUser = _context.HetUser .Include(x => x.District) .Include(x => x.HetUserRole) .ThenInclude(y => y.Role) .ThenInclude(z => z.HetRolePermission) .ThenInclude(z => z.Permission) .First(x => x.SmUserId == userId); // remove inactive roles for (int i = currentUser.HetUserRole.Count - 1; i >= 0; i--) { if (currentUser.HetUserRole.ElementAt(i).EffectiveDate > DateTime.UtcNow || (currentUser.HetUserRole.ElementAt(i).ExpiryDate != null && currentUser.HetUserRole.ElementAt(i).ExpiryDate < DateTime.UtcNow)) { currentUser.HetUserRole.Remove(currentUser.HetUserRole.ElementAt(i)); } } user.Id = currentUser.UserId; user.SmUserId = currentUser.SmUserId; user.GivenName = currentUser.GivenName; user.Surname = currentUser.Surname; user.DisplayName = currentUser.GivenName + " " + currentUser.Surname; user.UserGuid = currentUser.Guid; user.BusinessUser = false; user.District = currentUser.District; user.HetUserDistrict = currentUser.HetUserDistrict; user.HetUserRole = currentUser.HetUserRole; user.SmAuthorizationDirectory = currentUser.SmAuthorizationDirectory; // set environment user.Environment = "Development"; if (_env.IsProduction()) { user.Environment = "Production"; } else if (_env.IsStaging()) { user.Environment = "Test"; } else if (_env.IsEnvironment("Training")) { user.Environment = "Training"; } else if (_env.IsEnvironment("UAT")) { user.Environment = "UAT"; } } else { HetBusinessUser tmpUser = _context.HetBusinessUser.AsNoTracking() .Include(x => x.HetBusinessUserRole) .ThenInclude(y => y.Role) .ThenInclude(z => z.HetRolePermission) .ThenInclude(z => z.Permission) .FirstOrDefault(x => x.BceidUserId.Equals(userId, StringComparison.InvariantCultureIgnoreCase)); if (tmpUser != null) { // get business HetBusiness business = _context.HetBusiness.AsNoTracking() .First(x => x.BusinessId == tmpUser.BusinessId); user.Id = tmpUser.BusinessUserId; user.SmUserId = tmpUser.BceidUserId; user.GivenName = tmpUser.BceidFirstName; user.Surname = tmpUser.BceidLastName; user.DisplayName = tmpUser.BceidDisplayName; user.UserGuid = tmpUser.BceidGuid; user.BusinessUser = true; user.BusinessId = tmpUser.BusinessId; user.BusinessGuid = business.BceidBusinessGuid; user.SmAuthorizationDirectory = "BCeID"; int id = 0; foreach (HetBusinessUserRole role in tmpUser.HetBusinessUserRole) { id++; HetUserRole userRole = new HetUserRole { UserRoleId = id, UserId = role.BusinessUserId, RoleId = role.RoleId, Role = role.Role }; if (user.HetUserRole == null) { user.HetUserRole = new List <HetUserRole>(); } user.HetUserRole.Add(userRole); } } } return(new ObjectResult(new HetsResponse(user))); }
public virtual IActionResult RentalRequestsHiresGet([FromQuery] string localAreas, [FromQuery] string projects, [FromQuery] string owners, [FromQuery] string equipment) { int?[] localAreasArray = ArrayHelper.ParseIntArray(localAreas); int?[] projectArray = ArrayHelper.ParseIntArray(projects); int?[] ownerArray = ArrayHelper.ParseIntArray(owners); int?[] equipmentArray = ArrayHelper.ParseIntArray(equipment); // get initial results - must be limited to user's district int?districtId = UserAccountHelper.GetUsersDistrictId(_context, _httpContext); // get fiscal year HetDistrictStatus district = _context.HetDistrictStatus.AsNoTracking() .FirstOrDefault(x => x.DistrictId == districtId); if (district?.CurrentFiscalYear == null) { return(new BadRequestObjectResult(new HetsResponse("HETS-30", ErrorViewModel.GetDescription("HETS-30", _configuration)))); } int fiscalYear = (int)district.CurrentFiscalYear; // status table uses the start of the year DateTime fiscalStart = new DateTime(fiscalYear, 3, 31); // look for all records AFTER the 31st IQueryable <HetRentalRequestRotationList> data = _context.HetRentalRequestRotationList.AsNoTracking() .Include(x => x.RentalRequest) .ThenInclude(y => y.LocalArea) .ThenInclude(z => z.ServiceArea) .Include(x => x.RentalRequest) .ThenInclude(y => y.Project) .Include(x => x.Equipment) .ThenInclude(y => y.Owner) .Where(x => x.RentalRequest.LocalArea.ServiceArea.DistrictId.Equals(districtId) && x.AskedDateTime > fiscalStart && (x.IsForceHire == true || x.OfferResponse.ToLower() == "no")); if (localAreasArray != null && localAreasArray.Length > 0) { data = data.Where(x => localAreasArray.Contains(x.RentalRequest.LocalAreaId)); } if (projectArray != null && projectArray.Length > 0) { data = data.Where(x => projectArray.Contains(x.RentalRequest.ProjectId)); } if (ownerArray != null && ownerArray.Length > 0) { data = data.Where(x => ownerArray.Contains(x.Equipment.OwnerId)); } if (equipmentArray != null && equipmentArray.Length > 0) { data = data.Where(x => equipmentArray.Contains(x.EquipmentId)); } // convert Rental Request Model to the "RentalRequestHires" Model List <RentalRequestHires> result = new List <RentalRequestHires>(); foreach (HetRentalRequestRotationList item in data) { HetUser user = _context.HetUser.AsNoTracking() .FirstOrDefault(x => x.SmUserId == item.AppCreateUserid); result.Add(RentalRequestHelper.ToHiresModel(item, user)); } // return to the client return(new ObjectResult(new HetsResponse(result))); }