private static EditUserModel GetEditModel(int?userId) { // If no user ID provided, return logged in user. if (!userId.HasValue) { return(new EditUserModel(Membership.GetUser().GetUserEntity())); } var user = new UserEntity(userId.Value); if (user.IsNew) { throw new HttpException(404, SharedRes.Error.NotFound_User); } // Service admin can edit all users. if (RoleUtils.IsUserServiceAdmin()) { return(new EditUserModel(user)); } // Org admin can edit all user in his/her organization. if (RoleUtils.IsUserOrgAdmin() && user.OrganizationId == Membership.GetUser().GetUserId().OrganizationId) { return(new EditUserModel(user)); } throw new HttpException(401, SharedRes.Error.Unauthorized_User); }
public static IQueryable <PurchaseHistoryEntity> WithPermissions(this IQueryable <PurchaseHistoryEntity> purchases) { var user = Membership.GetUser().GetUserEntity(); if (RoleUtils.IsUserServiceAdmin()) { return(purchases); } if (RoleUtils.IsUserOrgAdmin()) { return(purchases.Where(x => x.Location.OrganizationId == user.OrganizationId)); } return(purchases.Where(x => x.Location.UserAssignedLocations.Any(y => y.UserId == user.UserId))); }
public static IQueryable <TreatmentEntity> WithPermissions(this IQueryable <TreatmentEntity> treatments) { var user = Membership.GetUser().GetUserEntity(); if (RoleUtils.IsUserServiceAdmin()) { return(treatments); } if (RoleUtils.IsUserOrgAdmin()) { return(treatments.Where(x => x.Patient.Location.OrganizationId == user.OrganizationId)); } return(treatments.Where(x => x.Patient.Location.UserAssignedLocations.Any(y => y.UserId == user.UserId))); }
public static IQueryable <LocationEntity> WithPermissions(this IQueryable <LocationEntity> locations, int?organizationId = null) { var user = Membership.GetUser().GetUserEntity(); if (RoleUtils.IsUserServiceAdmin()) { return(organizationId.HasValue ? locations.Where(x => x.OrganizationId == organizationId.Value) : locations); } if (RoleUtils.IsUserOrgAdmin()) { return(locations.Where(x => x.OrganizationId == user.OrganizationId)); } return(locations.Where(x => x.UserAssignedLocations.Any(y => y.UserId == user.UserId))); }
/// <summary> /// Called by the Edit function this performs all of the proper permissions checks. /// </summary> /// <param name="locationId"></param> /// <param name="organizationId"></param> /// <returns>The LocationEntity for the specified locationId or a new entity if locationId is not specified and the current user has permission to add locations.</returns> private static LocationEntity GetLocation(int?locationId, int?organizationId) { LocationEntity location; if (locationId.HasValue) { location = new LocationEntity(locationId.Value); if (location.IsNew) { throw new HttpException(404, SharedRes.Error.NotFound_Location); } if (!Permissions.UserHasPermission("Edit", location)) { throw new HttpException(401, SharedRes.Error.Unauthorized_Location); } } else { location = new LocationEntity { IsActive = true, OrganizationId = Membership.GetUser().GetUserId().OrganizationId }; if (RoleUtils.IsUserServiceAdmin()) { if (organizationId.HasValue) { location.OrganizationId = organizationId.Value; } } else if (!RoleUtils.IsUserOrgAdmin()) { throw new HttpException(401, SharedRes.Error.Unauthorized_Location); } } return(location); }
public ActionResult Edit(int?organizationId, OrganizationEntity organizationModel) { OrganizationEntity organization; var user = Membership.GetUser().GetUserEntity(); if (!organizationId.HasValue) { if (!RoleUtils.IsUserServiceAdmin()) { throw new HttpException(401, Error.Unauthorized_OrganizationAdd); } organization = new OrganizationEntity(); } else { if (RoleUtils.IsUserServiceAdmin() || (RoleUtils.IsUserOrgAdmin() && organizationId.Value == user.OrganizationId)) { organization = new OrganizationEntity(organizationId.Value); if (organization.IsNew) { throw new HttpException(404, Error.NotFound_Organization); } } else { throw new HttpException(401, Error.Unauthorized_OrganizationEdit); } } if (ModelState.IsValid) { // Organization admin can edit name. organization.Name = organizationModel.Name; if (RoleUtils.IsUserServiceAdmin()) { // Only service admin can change other properties. // NOTE! For now disallowing setting type to "Host". There can be only // one "Host". if (organizationModel.OrganizationType == OrganizationType.Host) { throw new HttpException(401, Error.Unauthorized_OrganizationHost); } organization.OrganizationType = organizationModel.OrganizationType; organization.IsActive = organizationModel.IsActive; if (!organizationId.HasValue) { organization.UniqueIdentifier = OrganizationUtils.CreateUid(); } } organization.Save(); } return((Request.IsAjaxRequest() || ControllerContext.IsChildAction) ? (ActionResult) new EmptyResult() : RedirectToAction("View")); }
private IQueryable <UserEntity> GetListModel(int?locationId, int?organizationId) { LinqMetaData m = new LinqMetaData(); var user = Membership.GetUser().GetUserEntity(); if (!organizationId.HasValue) { if (RoleUtils.IsUserServiceAdmin()) { if (!locationId.HasValue) { // Service admin gets all users. return(m.User); } // Location specified, so just users assigned to that location. return(m.User .Where( x => x.UserAssignedLocations.Any( y => y.LocationId == locationId.Value))); } // Other users assume their organization ID. organizationId = user.OrganizationId; } // View needs this for building URLs. ViewData.Add("organizationId", organizationId.Value); var organization = new OrganizationEntity(organizationId.Value); if (organization.IsNew) { throw new HttpException(404, SharedRes.Error.NotFound_Organization); } ViewData.Add("organization", organization); if (!locationId.HasValue) { if (RoleUtils.IsUserServiceAdmin() || RoleUtils.IsUserOrgAdmin()) { // All users for the specified organization. return(new LinqMetaData().User.Where(u => u.OrganizationId == organizationId.Value)); } // Other users only see unrestricted users at their assigned locations. // TODO: Decide if we even want to allow this. var query = from ual1 in m.UserAssignedLocation join ual2 in m.UserAssignedLocation on ual1.LocationId equals ual2.LocationId join usr in m.User on ual2.UserId equals usr.UserId where ual1.UserId == user.UserId && !usr.UserAccountRestrictions.Any() select usr; return(query); } var location = new LocationEntity(locationId.Value); if (location.IsNew || location.OrganizationId != organizationId.Value) { throw new HttpException(404, SharedRes.Error.NotFound_Location); } ViewData.Add("location", location); // View needs this for building URLs. ViewData.Add("locationId", locationId.Value); var users = m.User .Where( x => x.UserAssignedLocations.Any( y => y.LocationId == locationId.Value)); // Service admin can see all users for any organization. if (RoleUtils.IsUserServiceAdmin()) { return(users); } // Other users must be from the organization. if (organizationId.Value != user.OrganizationId) { throw new HttpException(401, SharedRes.Error.Unauthorized_User); } // Organization admin can see all the users of the organization. if (RoleUtils.IsUserOrgAdmin()) { return(users); } // Other users can only see unrestricted users in their location. if (user.UserAssignedLocations.Count(l => l.LocationId == locationId.Value) > 0) { return(users.Where(u => !u.UserAccountRestrictions.Any())); } throw new HttpException(401, SharedRes.Error.Unauthorized_User); }
public ActionResult Edit(int userId, EditUserModel model) { var user = new UserEntity(userId); if (user.IsNew) { throw new HttpException(404, SharedRes.Error.NotFound_User); } if (!RoleUtils.IsUserServiceAdmin() && !RoleUtils.IsUserOrgAdmin()) { throw new HttpException(401, SharedRes.Error.Unauthorized_UserEdit); } if (RoleUtils.IsUserOrgAdmin() && user.OrganizationId != Membership.GetUser().GetUserId().OrganizationId) { throw new HttpException(401, SharedRes.Error.Unauthorized_OrganizationEdit); } if (ModelState.IsValid) { // Validate submitted role. if (!model.Role.HasValue || !(OrganizationUtils.GetAllowedRoles(model.OrganizationId).Any(r => r.RoleId == model.Role))) { throw new HttpException(417, ControllerRes.Account.Invalid_RoleSpecified); } // Locations are only valid for non-admin users. bool isAdmin = RoleUtils.IsRoleForAdmin(model.Role.Value); if (!isAdmin) { // Validate submitted locations are locations of the organization. if (model.Locations.Except(new LinqMetaData().Location.Where(l => l.OrganizationId == model.OrganizationId).Select(l => l.LocationId).ToList()).Any()) { throw new HttpException(404, SharedRes.Error.NotFound_Location); } } // Set flag to indicate whether or not it's a pending registration. // Not using the posted back value in the model for security reasons. bool isPendingRegistration = user.UserAccountRestrictions.Count > 0 && user.UserAccountRestrictions[0].AccountRestriction.AccountRestrictionType == AccountRestrictionType.NewUser; // If not pending registration and username changed, validate username is unique. // Also, set flag to indicate if it's the current user changing own username. bool isCurrentUsernameChange = false; if (!isPendingRegistration && user.Username != model.UserName) { if (UserUtils.IsUsernameUsed(model.UserName)) { throw new HttpException(417, ControllerRes.Account.Invalid_DuplicateUsername); } isCurrentUsernameChange = Membership.GetUser().GetUserId().Id == userId; } // Set flag to indicate whether or not the email address in a registration // has changed. bool isRegistrationChange = isPendingRegistration && user.EmailAddress != model.EmailAddress; Transaction transaction = new Transaction(IsolationLevel.ReadCommitted, "user add"); try { transaction.Add(user); // Username is empty in pending registrations and can't be changed. // And current user username change isn't a simple change; don't do here. if (!isPendingRegistration && !isCurrentUsernameChange) { user.Username = model.UserName; } user.EmailAddress = model.EmailAddress; user.FirstName = model.FirstName; user.LastName = model.LastName; if (RoleUtils.IsUserServiceAdmin()) { user.IsActive = model.IsActive; } // Did role change? if (user.Roles.Count == 0 || user.Roles[0].RoleId != model.Role.Value) { user.Roles.DeleteMulti(); var userRole = user.Roles.AddNew(); userRole.RoleId = model.Role.Value; } int[] newLocations = new int[0]; int[] oldLocations; if (!isAdmin) { // User is not an admin. So find the set of locations user has been added to, // and the set of location user has been removed from. newLocations = model.Locations.Except(user.UserAssignedLocations.Select(l => l.LocationId)).ToArray(); oldLocations = user.UserAssignedLocations.Select(l => l.LocationId).Except(model.Locations).ToArray(); } else { // User is admin. So user will be removed from all locations (admins aren't // assigned to locations). oldLocations = user.UserAssignedLocations.Select(l => l.LocationId).ToArray(); } if (oldLocations.Length > 0) { user.UserAssignedLocations.DeleteMulti(UserAssignedLocationFields.UserId == user.UserId & UserAssignedLocationFields.LocationId == oldLocations); } if (newLocations.Length > 0) { foreach (var loc in newLocations) { var assignedLocation = user.UserAssignedLocations.AddNew(); assignedLocation.LocationId = loc; } } // If the registration email has changed, update the email address in the account // restriction. if (isRegistrationChange) { user.UserAccountRestrictions[0].AccountRestriction.EmailAddress = model.EmailAddress; } // Is current user changing own username? if (isCurrentUsernameChange) { // Changing the current user's username requres special handling because the // forms-auth cookies must be updated with the new username. The delegate will // be invoked to save the new username updating the datbase. In this case, it // needs to be done within the transaction created here. // // Have already validated the username as unique. So the only reason for this // to fail is with some exception thrown, which will be handled in the "catch". Membership.GetUser().ChangeUsername(model.UserName, delegate(string username) { user.Username = username; user.Save(true); // ReSharper disable AccessToDisposedClosure transaction.Commit(); // ReSharper restore AccessToDisposedClosure }); } else { user.Save(true); transaction.Commit(); } } catch (Exception) { transaction.Rollback(); throw new HttpException(500, SharedRes.Error.Error_DatabaseUnknown); } finally { transaction.Dispose(); } // If registration email has changed, need to re-send the registration email. if (isRegistrationChange) { SendRegistrationEmail(model, user.UserAccountRestrictions[0].AccountRestriction.RestrictionKey); } } return((Request.IsAjaxRequest() || ControllerContext.IsChildAction) ? (ActionResult) new EmptyResult() : View(GetEditModel(userId))); }
public override bool UserHasPermission(string username, string permissionName, CommonEntityBase entity) { var user = Membership.GetUser(username).GetUserEntity(); var location = entity as LocationEntity; if (location != null) { if (RoleUtils.IsUserServiceAdmin()) { return(true); } if (RoleUtils.IsUserOrgAdmin() && location.OrganizationId == user.OrganizationId) { return(true); } if (location.UserAssignedLocations.Any(x => x.UserId == user.UserId) && permissionName == "View") { return(true); } } var organization = entity as OrganizationEntity; if (organization != null) { if (RoleUtils.IsUserServiceAdmin()) { return(true); } if (RoleUtils.IsUserOrgAdmin() && organization.OrganizationId == user.OrganizationId) { return(true); } if (organization.OrganizationId == user.OrganizationId && permissionName == "View") { return(true); } } var patient = entity as PatientEntity; if (patient != null) { if (RoleUtils.IsUserServiceAdmin()) { return(true); } if (RoleUtils.IsUserOrgAdmin() && patient.Location.OrganizationId == user.OrganizationId) { return(true); } if (patient.Location.UserAssignedLocations.Any(x => x.UserId == user.UserId)) { return(true); } } var treatment = entity as TreatmentEntity; if (treatment != null) { if (RoleUtils.IsUserServiceAdmin()) { return(true); } if (RoleUtils.IsUserOrgAdmin() && treatment.Patient.Location.OrganizationId == user.OrganizationId) { return(true); } if (treatment.Patient.Location.UserAssignedLocations.Any(x => x.UserId == user.UserId)) { return(true); } } var device = entity as DeviceEntity; if (device != null) { if (RoleUtils.IsUserServiceAdmin()) { return(true); } if (RoleUtils.IsUserOrgAdmin() && device.Location.OrganizationId == user.OrganizationId) { return(true); } if (device.Location.UserAssignedLocations.Any(x => x.UserId == user.UserId)) { return(true); } } var usr = entity as UserEntity; if (usr != null) { if (RoleUtils.IsUserServiceAdmin()) { return(true); } if (RoleUtils.IsUserOrgAdmin() && usr.OrganizationId == user.OrganizationId) { return(true); } if (usr.UserAssignedLocations.Select(x => x.LocationId).Intersect(user.UserAssignedLocations.Select(y => y.LocationId)).Any()) { return(true); } } var card = entity as CreditCardEntity; if (card != null) { if (RoleUtils.IsUserServiceAdmin()) { return(true); } if (card.UserCreditCards.Any(x => x.UserId == user.UserId)) { return(true); } } return(false); }