Permissions of users

Asked

Viewed 1,214 times

2

I do not know how I can be implementing in my systems the permissions of users and I would like you to give me some north.

From my own class:

public class Loja_Usuarios
{
    public int ID { get; set; }
    public string Nome { get; set; }
    public string Login { get; set; }
    public string Senha { get; set; }
    public bool Pedido { get; set; }
    public bool Produto { get; set; }
    public bool Cliente { get; set; }
    public bool Carrossel { get; set; }
    public bool Carta { get; set; }
    public bool Usuario { get; set; }
    public bool Codigo { get; set; }
    public bool Ativo { get; set; }
    public bool Menu { get; set; }
}

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

    [Required(ErrorMessage = "Nome deve ser preenchido")]
    public string Nome { get; set; }

    [Required(ErrorMessage = "Imagem deve ser preenchido")]
    public string Imagem { get; set; }

    [Required(ErrorMessage = "URL deve ser preenchido")]
    public string URL { get; set; }
}

Where Order, Product, Customer..., are all user permissions. But from here I don’t know how to do it. I don’t know if you use ASP.Net Identity or other. When I did this in other systems, I only validated whether I was logged in or not.

  • Look for themes linked to the "Role/Membership Provider". A reference class is Roleprovider Class.

  • @I have a question similar to yours, so I’ll put the link here so you can see how it’s done. Just pointing out that in my system, in the user model, I have the attribute Profile, and I do a Dictionary with the possible profiles that exist in my system, and it looks for this attribute and restricts the areas that cannot be accessed by certain profiles. I hope I’ve helped !

1 answer

4


I’m guessing the following in your Models:

Models/Loja.Cs

public class Loja 
{
    [Key]
    public int LojaId { get; set; }

    [Required]
    public String Nome { get; set; }
    ...

    public virtual ICollection<Loja_Usuario> Usuarios { get; set; }
}

Models/Loja_usuario.Cs

public class Loja_Usuarios
{
    public int ID { get; set; }
    public int LojaId { get; set; }

    public string Nome { get; set; }
    public string Login { get; set; }
    public string Senha { get; set; }
    public bool Pedido { get; set; }
    public bool Produto { get; set; }
    public bool Cliente { get; set; }
    public bool Carrossel { get; set; }
    public bool Carta { get; set; }
    public bool Usuario { get; set; }
    public bool Codigo { get; set; }
    public bool Ativo { get; set; }
    public bool Menu { get; set; }

    public virtual Loja Loja { get; set; }
}

State also the following Enum:

Enums/Permissao.Cs

public enum Permissao 
{
    Pedido,
    Produto,
    Cliente,
    Carrossel,
    Carta,
    Usuario,
    Codigo,
    Ativo,
    Menu
}

Implement your own authorization attribute:

Attributes/Customauthorizationattibute.Cs

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    private Permissao[] _permissoes;
    private MeuProjetoContext context = new MeuProjetoContext();

    public CustomAuthorizeAttribute(params Permissao[] permissoes) 
    {
        _permissoes = permissoes;
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {
            return false;
        }

        if (!_permissoes.Any()) return true;

        var usuarioId = LoggedUserHelper.UsuarioId(httpContext.User);
        var usuario = context.Loja_Usuarios.SingleOrDefault(u => u.ID == usuarioId);

        foreach (permissao in _permissoes) 
        {
            switch (permissao) 
            {
                case Permissao.Pedido:
                    return usuario.Pedido;
                case Permissao.Produto:
                    return usuario.Produto;
                case Permissao.Cliente:
                    return usuario.Cliente;
                case Permissao.Carrossel:
                    return usuario.Carrossel;
                case Permissao.Carta:
                    return usuario.Carta;
                case Permissao.Usuario:
                    return usuario.Usuario;
                case Permissao.Codigo:
                    return usuario.Codigo;
                case Permissao.Ativo:
                    return usuario.Ativo;
                case Permissao.Menu:
                    return usuario.Menu;
            }
        }

        return false;
    }

    // Implemente abaixo pra onde a requisição vai se o usuário não estiver autorizado
    /* protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new RedirectToRouteResult(
            new RouteValueDictionary(
                new
                {
                    controller = "Error",
                    action = "Unauthorised"
                })
            );
    } */
}

Use in your Controller:

// Para poder ter acesso a esta action, o usuário precisa ter permissão ou de 
// Cliente, ou de Usuario.
[CustomAuthorize(Permissao.Cliente, Permissao.Usuario)]
public ActionResult Index() 
{
   ...
}

Can only be used to check if the user is authenticated.

[CustomAuthorize]
public ActionResult Index() 
{
   ...
}
  • is giving error here: foreach (permission in permissions)

  • I made an edition for you to better visualize my classes models.

  • @Diegozanardo What mistake?

  • The type or namespace name "permissao" could not be found...

  • I fixed this line to: foreach (permissao in _permissoes) . Look now.

  • It worked right here... Now this with error in the cases! " case permissao.Request:" error: "Members 'Ui.Web.Enums.Permissao.Request' cannot be accessed with as instance Reference; qualify it with a type name Instead"

  • to resolve the foreach error I did the following: foreach (Enums.Permission permission in _)

  • Why are you permissao.Pedido in lowercase? It has to be uppercase: Permissao.Pedido, because it refers to enum, and not the variable of foreach.

  • 1

    I got here @Gypsy, when the user login would look like this: Formsauthentication.Setauthcookie(id, false);

Show 4 more comments

Browser other questions tagged

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