In my projects I use a Class static
calling for UsuarioRepositorio
As follows below:
public class UsuarioRepositorio
{
public static bool AutenticarUsuario(string login, string senha)
{
var context = new NewsContext();
var user = context.Users.SingleOrDefault(u => u.Login == login && u.Status);
if (user == null)
{
return false;
}
if (!Crypto.VerifyHashedPassword(user.Senha, senha))
{
return false;
}
FormsAuthentication.SetAuthCookie(user.Login, false);
return true;
}
public static User GetLogedUser()
{
if (!HttpContext.Current.User.Identity.IsAuthenticated) return null;
var login = HttpContext.Current.User.Identity.Name;
var context = new NewsContext();
if (string.IsNullOrEmpty(login))
{
return null;
}
var user = context.Users.SingleOrDefault(u => u.Login == login && u.Status);
return user;
}
public static void LogOf()
{
FormsAuthentication.SignOut();
}
}
Where I have 3 methods, AutenticarUsuario
, GetLogedUser
and LogOf
.
When I need to do something I need to get the user information logged in, for example: Print the User name logged in to the Admin Panel.
I wear it like this:
@using Projeto.Repositorio
<label>Bem vindo: @UsuarioRepositorio.GetLogedUser().Nome</label>
Works perfectly for me.
And you can use in other ways, such as checking if the user has any property or Role
which defines it as Admin and print only the allowed menu items to the rule where it is located.
Follows link of the article where I learned to use these methods.
I use a Usuariorepositorio class where I have a Static method called Getusuariologated() that checks if the user is logged in and returns this user’s data to me. How you are doing your authentication?
– Hermes Autran
put as resposa and also code so I can understand better?
– Luiz Negrini