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); }
private JsonResult JsonException() { if (RouteData.Values.ContainsKey("error")) { var error = (HandleErrorInfo)RouteData.Values["error"]; // send different amount of information based on who is logged in if (RoleUtils.IsUserServiceAdmin()) { return (Json( new { error.ActionName, error.ControllerName, Data = error.Exception.Data.ToString(), error.Exception.Message, InnerException = error.Exception.InnerException != null ? error.Exception.InnerException.ToString() : "", StackTrace = error.Exception.StackTrace.ToString(), TargetSite = error.Exception.TargetSite.ToString(), Source = error.Exception.Source.ToString(), error.Exception.HelpLink, }, JsonRequestBehavior.AllowGet)); } else { return(Json(new { error.Exception.Message })); } } return(Json(Error.Error_Unspecified, JsonRequestBehavior.AllowGet)); }
public ActionResult Edit(int?organizationId) { OrganizationEntity organization; var user = Membership.GetUser().GetUserEntity(); if (!organizationId.HasValue) { // When adding new organization, default to "active". organization = RoleUtils.IsUserServiceAdmin() ? new OrganizationEntity { IsActive = true } } : user.Organization; else { organization = new OrganizationEntity(organizationId.Value); if (organization.IsNew) { throw new HttpException(404, Error.NotFound_Organization); } if (!Permissions.UserHasPermission("Edit", organization)) { throw new HttpException(401, Error.Unauthorized_Organization); } } return((Request.IsAjaxRequest() || ControllerContext.IsChildAction) ? (ActionResult)PartialView(organization) : View(organization)); }
public override System.Collections.Generic.IEnumerable <ActionMenuAttribute> GetSubMenu() { if (!RoleUtils.IsUserServiceAdmin()) { return (base.GetSubMenu().Concat( MethodBase.GetCurrentMethod().GetCustomAttributes(typeof(ActionMenuAttribute), false).Cast <ActionMenuAttribute>())); } return(base.GetSubMenu()); }
public static IQueryable <OrganizationEntity> WithPermissions(this IQueryable <OrganizationEntity> organizations) { var user = Membership.GetUser().GetUserEntity(); if (RoleUtils.IsUserServiceAdmin()) { return(organizations); } return(organizations.Where( x => x.Locations.Any( y => y.UserAssignedLocations.Any(u => u.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))); }
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))); }
/// <summary> /// Edit and existing credit card and update CIM. /// </summary> /// <param name="creditcardid"></param> /// <returns></returns> public ActionResult EditCard(int creditcardid) { var card = new CreditCardEntity(creditcardid); if (card.IsNew) { throw new HttpException(404, SharedRes.Error.NotFound_CreditCard); } if (!Permissions.UserHasPermission("Edit", card)) { throw new HttpException(401, SharedRes.Error.Unauthorized_CreditCard); } // populate the model with the card data loaded from authorize.net try { CustomerGateway cg; var customer = RoleUtils.IsUserServiceAdmin() ? EnsureProfile(out cg, card.UserCreditCards.First().User) : EnsureProfile(out cg); var profile = customer.PaymentProfiles.First(x => x.ProfileID == card.AuthorizeId); var addressLines = profile.BillingAddress.Street.Split('\n'); var model = new EditCard { AddressLine1 = addressLines[0], AddressLine2 = addressLines.Length > 1 ? addressLines[1] : "", City = profile.BillingAddress.City, Country = profile.BillingAddress.Country, FirstName = profile.BillingAddress.First, LastName = profile.BillingAddress.Last, State = profile.BillingAddress.State, Zip = profile.BillingAddress.Zip, }; return(PartialView(model)); } catch (Exception ex) { ModelState.AddModelError("", Purchase.EditCard_Error); Log.Error(Purchase.EditCard_Error, ex); } return(PartialView()); }
private FileContentResult ImageException() { using (var image = new Bitmap(300, 200)) { var g = Graphics.FromImage(image); g.InterpolationMode = InterpolationMode.High; g.CompositingQuality = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.AntiAlias; g.TextRenderingHint = TextRenderingHint.AntiAlias; g.FillRectangle(new SolidBrush(Color.Black), 0, 0, image.Width, image.Height); var fontSize = 15; Font f; var message = Error.Error_Unspecified; if (RouteData.Values.ContainsKey("error")) { var error = (HandleErrorInfo)RouteData.Values["error"]; message = error.Exception.Message; // only show stack trace if service administrator is logged in if (RoleUtils.IsUserServiceAdmin()) { message += Environment.NewLine + Environment.NewLine + "Controller: " + error.ControllerName + Environment.NewLine + Environment.NewLine + "Action: " + error.ActionName + Environment.NewLine + Environment.NewLine + "Stack Trace: " + error.Exception.StackTrace; } } float height; do { f = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold); height = g.MeasureString(message, f, 300).Height; fontSize--; } while (height > image.Height && fontSize > 4); g.DrawString(message, f, new SolidBrush(Color.White), new RectangleF(0, 0, image.Width, image.Height)); using (var mem = new MemoryStream()) { image.Save(mem, ImageFormat.Png); return(File(mem.ToArray(), "image/png")); } } }
/// <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 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 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")); }
public ActionResult View(long treatmentId, Treatment model, [ModelBinder(typeof(DataTablesRequestModelBinder))] DataTablesRequestModel dtRequestModel) { var treatment = new TreatmentEntity(treatmentId); if (treatment.IsNew) { throw new HttpException(404, SharedRes.Error.NotFound_Treatment); } // make sure the user has access to this treatment if (!Permissions.UserHasPermission("View", treatment)) { throw new HttpException(401, SharedRes.Error.Unauthorized_Treatment); } // make sure user has access to this page if (!RoleUtils.IsUserServiceAdmin() && model.Page != TreatmentPage.Summary && model.Page != TreatmentPage.System && model.Page != TreatmentPage.Definitions) { throw new HttpException(401, SharedRes.Error.Unauthorized); } // make sure treatment can be accessed by this user model.License = LicenseMode.Full; model.Name = treatment.Patient.FirstName + " " + treatment.Patient.MiddleInitial + " " + treatment.Patient.LastName; model.DateOfBirth = treatment.Patient.BirthDate; model.Gender = treatment.Patient.Gender; var age = treatment.TreatmentTime.Year - treatment.Patient.BirthDate.Year; if (treatment.TreatmentTime < treatment.Patient.BirthDate.AddYears(age)) { age--; } model.Age = age; model.VisitDate = treatment.TreatmentTime; // only load data used for each page // severities is used on the summary and the raw report page if (model.Page == TreatmentPage.Summary || model.Page == TreatmentPage.RawReport) { model.Severities = new LinqMetaData().OrganSystemOrgan .Where(x => x.LicenseOrganSystem.LicenseMode == model.License) .OrderBy(x => x.ReportOrder) .OrderBy(x => x.LicenseOrganSystem.ReportOrder) .SelectMany(x => x.Organ.Severities.Where(y => y.TreatmentId == treatmentId)) .DistinctBy(x => x.Organ.Description.Replace(" - Left", "").Replace(" - Right", "")); } // organ systems is only used on the summary page if (model.Page == TreatmentPage.Summary) { model.OrganSystems = new LinqMetaData().LicenseOrganSystem.Where(x => x.LicenseMode == model.License).OrderBy( x => x.ReportOrder).Select(x => x.OrganSystem); model.PatientPrescanQuestion = treatment.PatientPrescanQuestion; } // load all analysis results for the raw data page if (model.Page == TreatmentPage.Raw || model.Page == TreatmentPage.Summary) { model.Raw = new LinqMetaData().AnalysisResult.Where(x => x.TreatmentId == model.TreatmentId); } // load the debug data for the raw report page if (model.Page == TreatmentPage.RawReport) { model.Debug = GetDebugData(new LinqMetaData().CalculationDebugData.Where(x => x.TreatmentId == model.TreatmentId), model.Severities, model.License); model.NBScores = new LinqMetaData().NBAnalysisResult.Where(x => x.TreatmentId == model.TreatmentId); } // only load images for the images page if (!Request.IsAjaxRequest() && !ControllerContext.IsChildAction) { // get database images var energizedImages = Utilities.Treatment.ImageRetrievalHelper.GetPatientImages(treatment.EnergizedImageSetId); var calibrationImages = Utilities.Treatment.ImageRetrievalHelper.GetCalibrationImageSet(treatment.CalibrationId); // save in cache for a few minutes var caches = new LinqMetaData().ImageCache.Where( x => x.LookupKey == treatmentId && (x.Description.StartsWith("Finger-") || x.Description.StartsWith("Calibration-"))).Select(x => x.Description).ToList(); // save extracted images to database for (var i = 0; i < energizedImages.Count; i++) { if (caches.All(x => x != "Finger-" + i)) { using (var mem = new MemoryStream()) { energizedImages[i].Image.Save(mem, ImageFormat.Png); new ImageCacheEntity { LookupKey = treatmentId, Description = "Finger-" + i, Image = mem.ToArray() }.Save(); energizedImages[i].Image.Dispose(); } } } for (var i = 0; i < calibrationImages.Count; i++) { if (caches.All(x => x != "Calibration-" + i)) { using (var mem = new MemoryStream()) { calibrationImages[i].Image.Save(mem, ImageFormat.Png); new ImageCacheEntity { LookupKey = treatmentId, Description = "Calibration-" + i, Image = mem.ToArray() }.Save(); calibrationImages[i].Image.Dispose(); } } } } ViewResult result = View(model); if (dtRequestModel == null) { return(result); } return(Query(result, dtRequestModel)); }
public ActionResult Edit(int?locationId, int?organizationId, NewLocationModel locationModel) { var location = GetLocation(locationId, organizationId); if (ModelState.IsValid) { // Google limits number of lookups per day. No reason to waste them. bool needGeocode = location.IsNew || locationModel.AddressLine1 != location.AddressLine1 || (locationModel.AddressLine2 ?? "") != location.AddressLine2 || locationModel.City != location.City || locationModel.State != location.State || locationModel.Country != location.Country; // Admin can edit geocode if the lookup fails. if (!needGeocode && RoleUtils.IsUserServiceAdmin()) { // If they aren't set by admin, then lookup, ... or retry. if ((!locationModel.Latitude.HasValue || locationModel.Latitude == 0) && (!locationModel.Longitude.HasValue || locationModel.Longitude == 0)) { needGeocode = true; } else { // Admin set them manually. So use the edited values, ... or // the same unedited values as before. location.Latitude = locationModel.Latitude; location.Longitude = locationModel.Longitude; } } // this is already set at this point by GetLocation() location.OrganizationId = locationModel.OrganizationId; location.Name = locationModel.Name; location.AddressLine1 = locationModel.AddressLine1; location.AddressLine2 = locationModel.AddressLine2; location.City = locationModel.City; location.State = locationModel.State; location.Country = locationModel.Country; location.PostalCode = locationModel.PostalCode; location.PhoneNumber = locationModel.PhoneNumber; if (needGeocode) { if (GoogleMaps.GetGeocode(location) == null && RoleUtils.IsUserServiceAdmin()) { location.Latitude = locationModel.Latitude; location.Longitude = locationModel.Longitude; } } if (RoleUtils.IsUserServiceAdmin()) { location.IsActive = locationModel.IsActive; } if (location.IsNew) { location.UniqueIdentifier = LocationUtils.CreateUid(); } location.Save(); return(new EmptyResult()); } else { Response.StatusCode = 417; Response.TrySkipIisCustomErrors = true; } return(PartialView(locationModel)); }
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); }
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 EditCard(int creditcardid, EditCard model) { var card = new CreditCardEntity(creditcardid); if (card.IsNew) { throw new HttpException(404, SharedRes.Error.NotFound_CreditCard); } if (!Permissions.UserHasPermission("Edit", card)) { throw new HttpException(401, SharedRes.Error.Unauthorized_CreditCard); } if (ModelState.IsValid) { var transaction = new Transaction(IsolationLevel.ReadCommitted, "add card"); try { CustomerGateway cg; var customer = RoleUtils.IsUserServiceAdmin() ? EnsureProfile(out cg, card.UserCreditCards.First().User) : EnsureProfile(out cg); var profile = customer.PaymentProfiles.First(x => x.ProfileID == card.AuthorizeId); // update the card info if (!string.IsNullOrEmpty(model.CardNumber)) { profile.CardNumber = model.CardNumber; profile.CardCode = model.SecurityCode; profile.CardExpiration = model.CardMonth + "/" + model.CardYear; card.AccountNumber = model.CardNumber.Substring(model.CardNumber.Length - 4, 4); } // update the billing address profile.BillingAddress = new AuthorizeNet.Address { First = model.FirstName, Last = model.LastName, Street = model.AddressLine1 + Environment.NewLine + model.AddressLine2, State = model.State, Country = model.Country, City = model.City, Zip = model.Zip }; card.FirstName = model.FirstName; card.LastName = model.LastName; card.Address = model.AddressLine1; transaction.Add(card); card.Save(); cg.UpdatePaymentProfile(customer.ProfileID, profile); transaction.Commit(); return(new EmptyResult()); } catch (Exception ex) { transaction.Rollback(); ModelState.AddModelError("", Purchase.EditCard_Error); Log.Error(Purchase.EditCard_Error, ex); } finally { transaction.Dispose(); } } Response.StatusCode = 417; Response.TrySkipIisCustomErrors = true; return(PartialView(model)); }