3

So I only want the logged in user to be allowed to book holidays for them selves. I think the easiest way to do this is to compare 'name' of logged in user againast 'name' in person table. So....

public ActionResult Create()
    {
        string xx = (string)Session["usernameID"];
        int? currentPersonID = Convert.ToInt32(xx);

        string userNameComparedAgainstLoginName = // here is where i want to say 'name' of logged in user

        CreateModel model = new CreateModel();
        model.currentPersonID = currentPersonID.Value;
        model.PList4DD = db.People.ToList();


        if (userNameComparedAgainstLoginName == model.userName)
        {
            ViewBag.Id = new SelectList(db.People, "Id", "Name");
            return View(model);
        }
        else
        {
            TempData["canOnlyBookHolidaysForYourself"] = "I'm afraid you can only book holidays for yourself";
            return RedirectToAction("Index");
        }
    }

the name given when the user registers will be the same names used in the db.

So could someone tell me how I can access the logged in 'name'?

Thanks

John
  • 3,965
  • 21
  • 77
  • 163

2 Answers2

4

It is bad practice to store the logged user data such as users name/email/id in the Session. The good practice is to create a custom user principal or identity and store all the users data that is frequently used in the application in it.

You better create your custom principal or identity and store that information in the authentication cookie and access it via User.Identity.XXX

Here is a link where it is well described how to create a custom principal. ASP.NET MVC - Set custom IIdentity or IPrincipal

Or if you do not need such a complex mechanism that you can just user the default User.Identity that is in the HttpContext.

Good luck!

Community
  • 1
  • 1
CoffeeCode
  • 4,296
  • 9
  • 40
  • 55
1

You can get the name from the User.Identity

You just need to use User.Identity.Name

Gaz Winter
  • 2,924
  • 2
  • 25
  • 47