Get Logged In User (Current User's)'s Information - asp.net-mvc

I have user information stored like this in my table:
ID(PK) | Email | Pass | DepartmentID
1 abc#g.com hash 301
2 abcd#g.com hash 302
3 abcd#g.com hash 303
Now , I need to get current user's (logged in user's ) Department ID via a jQuery getJson Call from the view side but cannot find any suitable approach to do so.
My Script(snippet) in view is something like :
var url="#Url.Action("Details","Users")";
$.getJSON(url, function(data){
$("#DeptID").val(data.DepartmentID);
});
And My code in controller (snippet) is:
public ActionResult Details()
{
var user = User.Identity.Name;
return Json(user, JsonRequestBehavior.AllowGet);
}
Please help with an appropriate method.
Thank You.

Assuming your derived ApplicationUser/IdentityUser has the properties you described in your original post
public async Task<ActionResult> Details(){
var username = User.Identity.Name;
//retrieve user based on some identifier.
var user = await userManager.FindByNameAsync(username);
object result = new object();
if (user != null) {
//construct a result with the data you want to send to the client.
result = new {
Email = user.Email,
DepartmentID = user.DepartmentID,
}
}
return Json(result, JsonRequestBehavior.AllowGet);
}

Related

How to Pass Value from a login Page

Hello I need help please
I am creating my first asp mvc Webpage.
I created a login and registration page connected with database.
I want to pass CustomerId from the customer that logged in to a Bookings table
So that it shows bookings related to that customer only.
Bookings table has CustomerId as a foreign key. This is what I have done so far.
public class BookingController : Controller
{
// GET: Booking
public ActionResult Index(int customerId)
{
TravelExpertsEntities bookingdb = new TravelExpertsEntities();
List<Booking> bookings = bookingdb.Bookings.Where(book =>
book.CustomerId == customerId).ToList();
return View(bookings);
}
}
}
//This is from login Controller
public ActionResult Login(Customer reg)
{
if (ModelState.IsValid)
{
var details = (from userlist in db.Customers
where userlist.UserName == reg.UserName &&
userlist.Password == reg.Password
select new
{
userlist.CustomerId,
userlist.UserName
}).ToList();
if (details.FirstOrDefault() != null)
{
Session["CustomerId"] =
details.FirstOrDefault().CustomerId;
Session["Username"] = details.FirstOrDefault().UserName;
return RedirectToAction("Index", "Booking");
}
}
else
{
ModelState.AddModelError("", "Invalid UserName or Password");
}
return View(reg);
}
I was able to pull all bookings but I want to filter it with the Customer that logged in.
Replace your RedirectToAction as below, to pass customerId as parameter
var CustomerIdparam=details.FirstOrDefault().CustomerId;
RedirectToAction("Index", "Booking", new{customerId=CustomerIdparam});

Simple Login Function using RavenDB in MVC

I understand the way I'm doing the login function is non-secure. But since I'm a novice I don't want to go into too deep first and prefer to do in a most simple and basic way first.
So far what I've done, I have a Admin Model
public class Admin
{
public string AdminUsername { get; set; }
public string Password { get; set; }
}
I have 2 views namely AdminRegister.cshtml and AdminLogin.cshtml
I have done the Register part, I know the password should not be stored in DB and password hashing instead. But as for now, I just want to complete the login function in a basic manner.
Their respective action method in controller are as follow
public ActionResult AdminRegister(Admin model)
{
using (var store = new DocumentStore
{
Url = "http://localhost:8080/",
DefaultDatabase = "foodfurydb"
})
{
store.Initialize();
using (var session = store.OpenSession())
{
session.Store(model);
session.SaveChanges();
}
}
return RedirectToAction("Home");
}
[HttpPost]
public ActionResult AdminLogin(Admin model)
{
Admin login = new Admin();
using (var store = new DocumentStore
{
Url = "http://localhost:8080/",
DefaultDatabase = "foodfurydb"
})
{
store.Initialize();
using (var session = store.OpenSession())
{
var adminInput = session
.Query<Admin>()
.Where(u => u.AdminUsername.Equals(model.AdminUsername) && u.Password.Equals(model.Password));
if (adminInput != null)
{
}
}
}
return View();
}
For the login part, I assume that I should query to check whether the user with the particular username and password exist in DB or not. And then, I'm stuck and don't know how to compare the login input and the data from db! Appreciate if someone kind enough to lead me! Just a simple one though! Thank you very much.
Find out whether the user exists first
var count = session
.Query<Admin>()
.Where(u => u.AdminUsername == model.AdminUsername);
if (count > 0)
{
return RedirectToAction("AddRestaurant");
}
else
{
// user exist in db
return RedirectToAction("Home");
}
I managed to find out whether the username in login field exist in DB or not. If yes it will login, else it will stay at home page. But till this stage, I haven't get an idea how to verify the password. Appreciate if anyone can guide me on this.
Let us avoid storing the password in plain text entirely.
We'll first start by loading the document for that user:
var adminInput = session
.Query<Admin>()
.Where(u => u.AdminUsername == model.AdminUsername)
.FirstOrDefault();
Note that I'm using FirstOrDefault to actually execute the query so we'll have the result.
Then, you check if the user exists, and if he does, you need to compare the number.
See this post on how to do this properly: How to hash a password

Remove User from Roles in ASP.NET Identity 2.x

How can I remove User from Roles in ASP.NET Identity 2.x ?
about adding role to user there is no problem but when I want to remove a role from a user I cannot.It should be mentioned that there is no exception or error!
//POST: Admin/User/Edit/5
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Prefix = "")]UserViewModel userViewModel, List<int> availableRoles)
{
if (ModelState.IsValid)
{
List<int> newListOfRolesIDs = availableRoles;
List<int> oldListOfRolesIDs = UserBLL.Instance.GetRolesIDs(userViewModel.Id);
List<int> deletedList;
List<int> addedList;
var haschanged = oldListOfRolesIDs.ChangeTracking(newListOfRolesIDs, out deletedList, out addedList);
using (new EFUnitOfWorkFactory().Create())
{
if (haschanged)
{
UserBLL.Instance.InsertRoles(addedList, userViewModel.Id);
UserBLL.Instance.DeleteRoles(deletedList, userViewModel.Id);
}
await UserBLL.Instance.UpdateAsync(userViewModel);
}
//ArticleBLL.Instance.UpdatePartial(articleViewModel, m => m.Title);
return RedirectToAction("Edit");
}
return View(userViewModel);
}
Delete Role method:
public void DeleteRoles(List<int> deleteList, int? userId)
{
if (userId != null)
{
User user = UserManager.FindByIdAsync(userId.Value).Result;
foreach (var i in deleteList)
{
user.Roles.Remove(new UserRole { RoleId = i, UserId = user.Id }); // What's the problem?!
}
}
}
Insert Role method:
public void InsertRoles(List<int> insertList, int? userId)
{
if (userId != null)
{
User user = UserManager.FindByIdAsync(userId.Value).Result;
foreach (var i in insertList)
{
user.Roles.Add(new UserRole { RoleId = i, UserId = user.Id });
}
}
}
What you are looking for is the RemoveFromRoleAsync method. An example would look similar to the following:
public async Task DeleteRolesAsync(List<string> deleteList, int? userId)
{
if (userId != null)
{
foreach (var roleName in deleteList)
{
IdentityResult deletionResult = await UserManager.RemoveFromRoleAsync(userId, roleName);
}
}
}
If you already have the ID of the user, there's no need to get the user again (only if you want to make sure that the user really exists; then you have to wrap your foreach with an if-statement). The deletion methods needs the name of the role, instead of the ID, to delete the user from the role. You can use the result of the operation (in my example stored in deletionResult) to make sure that the operation was successful. Remember that the name of the user manager (in my example UserManager) can vary depending on your implementation.
I had the same issue and what I ended up using was the
RemoveFromRolesAsync(string userId, params string[] roles) Method
from the UserManager.
Using the role names in an array works.
But has an issue that is if the user is not in one of the roles in the array the user will not be removed from any roles in the array.
All or nothing.
var usr = UserManager.FindById(usrV.ID.ToString());
string[] deleteList;
deleteList= new string[1];
deleteList[0] = "Engineer";
var rresult1 = UserManager.RemoveFromRolesAsync(usr.Id, deleteList);
Hope it helps
You might want to check out this blog post. The ASP.NET team has a sample that includes adding and removing roles from a user.
ASP.NET Identity 2.0: Customizing Users and Roles

Save userid on database when create new object

I have a Controller where on the Create action I need the user ID.
Here's the controller.
public ActionResult Create(MyCreateViewModel model)
{
if (ModelState.IsValid)
{
var myobject = new MyObject
{
Attrib1 = DateTime.Now.Date,
Attrib2 = model.Etichetta,
UserId = // I need the user ID...
};
// Save the object on database...
return RedirectToAction("Index");
}
return View(model);
}
I'm using the UserProfile table provided with the SimpleMembership of MVC 4.
Which is the best practice in MVC 4 to manage the userID across the application?
Do I have to include a User attribute inside every Entity class?
Should I use a Session[] variable or what?
You can use this line to get the userId from the UserProfiles table.
var userId = WebSecurity.GetUserId(HttpContext.Current.User.Identity.Name);
You can also use this function to get the users complete profile, including any custom columns you may be populating.
public static UserProfile GetUserProfile()
{
using (var db = new UsersContext())
{
var userId = WebSecurity.GetUserId
(HttpContext.Current.User.Identity.Name);
var user = db.UserProfiles
.FirstOrDefault(u => u.UserId == userId);
if (user == null)
{
//couldn't find the profile for some reason
return null;
}
return user;
}
}

Authenticating User via Ajax: User.Identity.IsAuthenticated in ajax method, but False elsewhere

I'm using Facebook to preautheticate users, so when they visit a page, an ajax function is called to login the user, and the server will also check to see if the user is already authenticated to the site. These users have entries in the user database on the server.
The server side code is below, which is called by ajax. After that, is a second method I use to get more information on the user that is stored in the database.
When I call User.Identity.IsAuthticaed in the second method, in the same Controller, the User object is still null. The User object contains all the information in FBReg below.
Edit:
After further troubleshooting I found that the ActionResult that calls getUserInfo() has the User object populated. So I'm not sure why getUserInfo() has a null User. I guess I can just pass the object then, but I'm still just curious why this happens.
[HttpPost]
public String FBReg(FBInfo userinfo)
{
..
..
..
if (!User.Identity.IsAuthenticated)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(userinfo.id, "FBPassword"))
{
FormsAuthentication.SetAuthCookie(userinfo.id, true);
var result = (from u in db.users where (u.username == userinfo.id) select u).FirstOrDefault();
result.LastLoginDate = DateTime.Now;
db.SaveChanges();
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
..
..
..
return "";
}
public UserRepository getUserInfo()
{
bool isauth = false;
try
{
if (User.Identity.IsAuthenticated) // User is always null even after FBReg has User as Authnticated with all the correct information
{
isauth = User.Identity.IsAuthenticated;
}
}
catch { }
// get user info from database to display on page
..
..
..
return userInfo;
}

Resources