简体   繁体   中英

restricting access to a dropdownlist in C#

Hello I have a 'RestrictAccessController' That looks like this

 public class RestrictAccessController : Controller
    {
        private PIC_Program_1_0Context db = new PIC_Program_1_0Context();
        public ActionResult Index()
        {
            return View ();
        }
    }

    [AttributeUsage(AttributeTargets.Method, AllowMultiple=true)]
    public class RestrictAccessAttribute : ActionFilterAttribute  
    {
        private PIC_Program_1_0Context db = new PIC_Program_1_0Context();
        public AccessRestrictions restriction { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

           // here's where we check that the current action is allowed by the current user

            if (!IGT.canAccess(IGT.userId, restriction, false))
            {
                string url = IGT.baseUrl+"/Home/NotAllowed";
                string msg = "This page requires " + IGT.DisplayEnum(restriction) + " access";

                filterContext.Result = new RedirectResult("~/Home/NotAllowed?msg="+HttpUtility.HtmlEncode(msg));

            }           
        }

And a Config model that looks like this

 public enum AccessRestrictions
    {      
        [Display(Name = "Disposal Orders")]
        ModifyDisposalOrder, 
        [Display(Name = "Admin")]
        Admin
    }
    public class userAccess
    {
        [Key]
        public int ID { get; set; }
        public AccessRestrictions restriction { get; set; }
        public bool allow { get; set; }
        public int userID { get; set; }

    }
    public class configDetails
    {
        public int ID {get; set;}
        public string Name {get; set;}
        public string Value {get;set;}
        public bool deleted {get;set;}
        public DateTime updateTime { get; set; }

    }
    public class Config
    {
        public int ID { get; set; }

        [Display(Name = "Configuration Date")]
        public DateTime TargetDate { get; set; }

           [Display(Name = "Enable Access Restrictions")]
        public bool restrictAccess { get; set; }

     }    

What I want to do is edit what my 'ChangeStatus' dropdown looks like based on whether they have the Admin access restriction or not. Here is the controller method that I want to edit

 [RestrictAccess(restriction = AccessRestrictions.ModifyDisposalOrder)]
        public ActionResult ChangeStatus(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            DisposalOrder disposalOrder = db.disposalOrders.Find(id);

            if (disposalOrder == null)
            {
                return HttpNotFound();
            }

            switch (disposalOrder.Status)
            {
                case DOStatus.Pending:
                    ViewBag.statusList = new List<Object>
                {
                    new {value = DOStatus.Pending, text = "Pending"},
                    new {value = DOStatus.Disposed, text = "Disposed" }

                };
                    break;
                case DOStatus.Disposed:
                   // if(restriction = AccessRestrictions.ModifyDisposalOrder)
                    ViewBag.statusList = new List<Object>
                {
                    new {value = DOStatus.Pending, text = "Pending"},
                    new {value = DOStatus.Disposed, text = "Disposed" }
                };
                    //else
                    //{
                    //    new { value = DOStatus.Disposed, text = "Disposed" }
                    // };
                break;

            };

            return View(disposalOrder);
        }

Here is my Startup file

 public class LdapAuthentication
    {
        private string _adUser = ConfigurationManager.AppSettings["ADUserName"];
        private string _adPW = ConfigurationManager.AppSettings["ADPassword"];
        private string _domain = ConfigurationManager.AppSettings["ADDomain"];
        public LdapAuthentication() {   
        }

        public string authenticate(string username, string pwd)
        {
            using (var context = new PrincipalContext(ContextType.Domain, _domain, _adUser, _adPW)) {
                //Username and password for authentication.
                if (context.ValidateCredentials(username, pwd)) {
                    UserPrincipal user = UserPrincipal.FindByIdentity(context, username);
                    Internal internalUser = new Internal {
                        UserName = user.SamAccountName,
                        ContactName = user.DisplayName,
                        Email = user.UserPrincipalName
                    };

                    //Search if the user account already exists in the database
                    PIC_Program_1_0Context db = new PIC_Program_1_0Context();
                    Internal existing = db.Internals.Where(x => x.UserName == user.SamAccountName).FirstOrDefault();
                    // If it does not, create a new user account
                    if (existing == null) {
                        // add a new Internal entry for this user
                        existing = new Internal {
                            UserName = user.SamAccountName,
                            ContactName = user.DisplayName,
                            Email = user.UserPrincipalName
                        };
                        db.Internals.Add(existing);
                        db.SaveChanges();
                    // If it does exist, but some of the data does not match, update the data
                    } else if(existing != internalUser) {
                        existing.ContactName = internalUser.ContactName;
                        existing.Email = internalUser.Email;
                        db.SaveChanges();
                    }
                    return user.SamAccountName;
                } else {
                    return null;
                }
            }
        }

        public UserPrincipal getUserPrincipal(string username)
        {
            using (var context = new PrincipalContext(ContextType.Domain, _domain, _adUser, _adPW))
            {
                return UserPrincipal.FindByIdentity(context, username);
            }
        }

Is it possible for me to accomplish this?

Ok, I think I understand your question now. You need to access the User's claims. MVC Controllers have this, half way, built in.

        if (User.HasClaim("ClaimNameHere", "Admin"))
        {

        }

Solved by adding

if (IGT.canAccess(IGT.userId, AccessRestrictions.Admin, false)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM