How to hide items from a C# MVC template menu?

Asked

Viewed 501 times

1

I am having difficulty in being able to restrict access to some menu items of my application, because there is a type of user who will have access only to certain items and the Admin user after logging in will have access to all content, that is, while not logged in the menu will be hidden displaying only two items, if the admin logs in it will have access to the entire menu, if the common user logs in it will have access only to a few menu items. Show me an example of how to do this, because even following the microsoft documentation I could not do this implementation on my system!

At the moment my problem is in this line of code:

 public bool IsAdminUser()
    {
        if (User.Identity.IsAuthenticated)
        {
            var user = User.Identity;
            ApplicationDbContext context = new ApplicationDbContext();
            var UserManager = new UserManager<ApplicationUser>(new Microsoft.AspNet.Identity.EntityFramework.UserStore<ApplicationUser>(context));
            var s = UserManager.GetRoles(user.GetUserId());
            if (s[0].ToString() == "Admin")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        return false;
    }

Now the problem is here, not seeking admin user!

And here’s how I’m doing the menu

    <!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - Meu Aplicativo ASP.NET</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a href="@Url.Action("Index", "Home")" class="navbar-brand">
                    <img src="http://www.ebasesistemas.com.br/assets/img/logo.png" title="title" alt="additional title" />
                </a>
            </div>
            <div class="navbar-collapse collapse">

                @if (ViewBag.displayMenu == "Yes")
                {
                    <ul class="nav navbar-nav">
                        <li>@Html.ActionLink("Início", "Index", "Home")</li>
                        <li>@Html.ActionLink("Cadastros", "Cadastros", "Home")</li><!---adm-->
                        <li>@Html.ActionLink("Relatorios", "Relatorios", "Home")</li><!--adm-->
                        <li>@Html.ActionLink("Contato", "Contact", "Home")</li><!--apenas logado-->
                        <li>@Html.ActionLink("Sobre", "About", "Home")</li><!--todos-->
                    </ul>
                }
                else
                {
                    <h2>  Seja bem vindo <strong>@ViewBag.Name</strong> :) .Você é um usuário com acesso premium!! </h2>
                }


                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>

    <div class="body-content">
        @RenderBody()
    </div>


    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

here are the three models:

AccountViewModels

    using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace PaginaWeb.Models
{
    public class ExternalLoginConfirmationViewModel
    {
        [Required]
        [Display(Name = "Email")]
        public string Email { get; set; }
    }

    public class ExternalLoginListViewModel
    {
        public string ReturnUrl { get; set; }
    }

    public class SendCodeViewModel
    {
        public string SelectedProvider { get; set; }
        public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; }
        public string ReturnUrl { get; set; }
        public bool RememberMe { get; set; }
    }

    public class VerifyCodeViewModel
    {
        [Required]
        public string Provider { get; set; }

        [Required]
        [Display(Name = "Código")]
        public string Code { get; set; }
        public string ReturnUrl { get; set; }

        [Display(Name = "Lembrar deste navegador?")]
        public bool RememberBrowser { get; set; }

        public bool RememberMe { get; set; }
    }

    public class ForgotViewModel
    {
        [Required]
        [Display(Name = "Email")]
        public string Email { get; set; }
    }

    public class LoginViewModel
    {


        [Required]
        [Display(Name = "Email")]
        [EmailAddress]
        public string Email { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Senha")]
        public string Password { get; set; }

        [Display(Name = "Lembrar-me?")]
        public bool RememberMe { get; set; }
    }

    public class RegisterViewModel


    {
        [Required]
        [Display(Name = "Nome da Empresa")]
        public string nomeEmpresa
        {
            get; set;
        }

        [Required]
        [Display(Name = "Telefone")]
        public string telefone
        {
            get; set;
        }

        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "O/A {0} deve ter no mínimo {2} caracteres.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Senha")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirmar Senha")]
        [Compare("Password", ErrorMessage = "A senha e a senha de confirmação não correspondem.")]
        public string ConfirmPassword { get; set; }
    }

    public class ResetPasswordViewModel
    {
        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "O/A {0} deve ter no mínimo {2} caracteres.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Senha")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirmar senha")]
        [Compare("Password", ErrorMessage = "A senha e a senha de confirmação não coincidem.")]
        public string ConfirmPassword { get; set; }

        public string Code { get; set; }
    }

    public class ForgotPasswordViewModel
    {
        [Required]
        [EmailAddress]
        [Display(Name = "E-mail")]
        public string Email { get; set; }
    }
}

This is Identitymodels:

  using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;

namespace PaginaWeb.Models
{


    // É possível adicionar dados do perfil do usuário adicionando mais propriedades na sua classe ApplicationUser, visite https://go.microsoft.com/fwlink/?LinkID=317594 para obter mais informações.
    public class ApplicationUser : IdentityUser
    {

        public string nomeEmpresa
        {
            get; set;
        }

        public string telefone
        {
            get; set;
        }

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Observe que o authenticationType deve corresponder àquele definido em CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Adicionar declarações de usuário personalizado aqui
            return userIdentity;
        }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }
}

Here Manageviewmodels:

   using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;

namespace PaginaWeb.Models
{
    public class IndexViewModel
    {
        public bool HasPassword { get; set; }
        public IList<UserLoginInfo> Logins { get; set; }
        public string PhoneNumber { get; set; }
        public bool TwoFactor { get; set; }
        public bool BrowserRemembered { get; set; }
    }

    public class ManageLoginsViewModel
    {
        public IList<UserLoginInfo> CurrentLogins { get; set; }
        public IList<AuthenticationDescription> OtherLogins { get; set; }
    }

    public class FactorViewModel
    {
        public string Purpose { get; set; }
    }

    public class SetPasswordViewModel
    {
        [Required]
        [StringLength(100, ErrorMessage = "{0} deve ter pelo menos {2} caracteres.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Nova senha")]
        public string NewPassword { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirmar nova senha")]
        [Compare("NewPassword", ErrorMessage = "A nova senha e a senha de confirmação não correspondem.")]
        public string ConfirmPassword { get; set; }
    }

    public class ChangePasswordViewModel
    {
        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Senha atual")]
        public string OldPassword { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "{0} deve ter pelo menos {2} caracteres.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Nova senha")]
        public string NewPassword { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirmar nova senha")]
        [Compare("NewPassword", ErrorMessage = "A nova senha e a senha de confirmação não correspondem.")]
        public string ConfirmPassword { get; set; }
    }

    public class AddPhoneNumberViewModel
    {
        [Required]
        [Phone]
        [Display(Name = "Número de telefone")]
        public string Number { get; set; }
    }

    public class VerifyPhoneNumberViewModel
    {
        [Required]
        [Display(Name = "Código")]
        public string Code { get; set; }

        [Required]
        [Phone]
        [Display(Name = "Número de telefone")]
        public string PhoneNumber { get; set; }
    }

    public class ConfigureTwoFactorViewModel
    {
        public string SelectedProvider { get; set; }
        public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; }
    }
}
  • What code do you currently have?

  • Man I’ve done a lot of things, it’s even hard to show the codes here

  • Have the code with the MENU items I believe you will have to do a check on that.

  • @Paulohdsousa managed to solve the problem of the line of code that I put before, now the problem is in this part ai... You can not make an example of that there for me to base not???? I knew to do it using sitemap, more visual studio 2017 n allows more this!

  • How you are doing the MENU, is a PARTIAL VIEW with the links or you do on the server?

  • I will edit the question and put as to doing the menu, it is in the partial layout view!

Show 1 more comment

1 answer

4


Do 2 methods like this

public bool IsAdmin()
{
        if (!IsAuthenticated())
            return false;

        var user = User.Identity;
        ApplicationDbContext context = new ApplicationDbContext();
        var UserManager = new UserManager<ApplicationUser>(new Microsoft.AspNet.Identity.EntityFramework.UserStore<ApplicationUser>(context));
        var s = UserManager.GetRoles(user.GetUserId());
        if (s[0].ToString() == "Admin")
            return true;
        return false;
}

public bool IsAuthenticated()
{
    return User.Identity.IsAuthenticated;
}

Put in your Model,

Model.IsAuthenticated = IsAuthenticated();
Model.IsAdmin = IsAdmin();

In your View

<ul class="nav navbar-nav">
    <li>@Html.ActionLink("Início", "Index", "Home")</li>
    @if(Model.IsAdmin){
    <li>@Html.ActionLink("Cadastros", "Cadastros", "Home")</li><!---adm-->
    <li>@Html.ActionLink("Relatorios", "Relatorios", "Home")</li><!--adm-->
    }
    @if(Model.IsAuthenticated){
    <li>@Html.ActionLink("Contato", "Contact", "Home")</li><!--apenas logado-->
    }
    <li>@Html.ActionLink("Sobre", "About", "Home")</li><!--todos-->
</ul>
  • Which model should I insert???

  • 1

    In the model you return with the View, if you don’t have create a

  • Any place I put on the model is giving error

  • Have you ever used a model? creates a question or edits this one with the contents of your controller that I show you how it does

  • I’ll edit it now

Browser other questions tagged

You are not signed in. Login or sign up in order to post.