Login method that receives user data

Asked

Viewed 90 times

0

I’m doing a project and trying to create a simple login method

I have the following class User

 public class Usuario
    {
        public int Id { get; set; }
        public string Nome { get; set; }
        public string Login { get; set; }
        public string Senha { get; set; }
        public bool Admin { get; set; }
    }

And the next login method

Metodo Get

[HttpGet]
        public IActionResult Login()
        {

            return View("login");
        }

Metodo post

  [HttpPost]
    public IActionResult Login(string login, string senha)
    {
        ViewBag.login = db.Usuario.Where(x => x.Login.Contains(login) && x.Senha.Contains(senha)).FirstOrDefault();

        if (ViewBag.login != null)
        {
            return RedirectToAction("Index");
        }
        else
        {

            return View("login");
        }
    }

My question is, does he log in correctly, seeing if the login and password entered match the bank’s, but, I would also like to know if I can load the admin column information along with the login and password so that later I use this information in a view for example

Example: user 1, password 123, admin: false

If I log in normally with user 1 and 123 it pulls the admin false together

1 answer

1

Felipe, first of all, I do not advise you to use the "contains()" method to test login and password. This is because the contains method will find in your database any user who has such characters and not the user with exactly the same credentials typed. The ideal in this case is to use the method equals.

Change this:

ViewBag.login = db.Usuario.Where(x => x.Login.Contains(login) && x.Senha.Contains(senha)).FirstOrDefault();

That’s why:

ViewBag.login = db.Usuario.Where(x => x.Login.Equals(login) && x.Senha.Equals(senha)).FirstOrDefault();

About your question, you need to understand a little better. Are you already pulling this data from the database? There is a "User" table. Or it’s a fixed user you’re using through the user class?

I ask this because apparently you are already picking up the admin column in this row:

ViewBag.login = db.Usuario.Where(x => x.Login.Contains(login) && x.Senha.Contains(senha)).FirstOrDefault();

Just access the view this way:

@ViewBag.login.Admin
  • It would not be good practice to include all users in Viewbag. Choose something more interesting kind of serious information, like: Viewbag.Email = user.Email; Or something like that

  • 1

    Great observation, Edvaldo. To pass the whole object it can use the heavily typed view. It would be better.

Browser other questions tagged

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