MVC Display data based on users login - asp.net-mvc

I have this table where displaying the list of userID+SubjectID, now i want is,if the user who Logged in can only see the list of Subject that belongs to the current user,is it possible? then should i need to use asp.net identity? currently i am using empty template with custom login Authentication + Roles only, any idea on what is the best way to handle this type of scenario? all i want is my tables will show data based on the current user logged in.
Example: If User1 logged in then User1 will only see subjects belong to user1..
Note:
i was searching for tutorials on showing data based on the current user logged in, but i couldn't find,any one has better idea? or link can share with me? i don't know the better word for my scenario i just call it "show data based on current user",i appreciate if anyone can solve this..thanks in advance..
Table Controller:
[CostumAuthorize(Roles = "Admin,Teacher")]
public ActionResult Subject_List(int id)
{
var test = db.SubjectTeachers.Where(x => x.Users.Any(n => n.UserID == id)).ToList();
var subjectTeachers = db.SubjectTeachers.Include(s => s.Levels).Include(s => s.Subjects).Include(s => s.Users).Where(u => u.LevelID == id);
return View(subjectTeachers.ToList());
}
Account controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(Login l, string ReturnUrl = "")
{
if (!ModelState.IsValid)
{
return View(l);
}
using (MyContext dc = new MyContext())
{
var user = dc.Users.Where(a => a.Username.Equals(l.Username) && a.Password.Equals(l.Password)).FirstOrDefault();
if (user != null)
{
FormsAuthentication.SetAuthCookie(user.Username, l.RememberMe);
if (Url.IsLocalUrl(ReturnUrl))
{
return Redirect(ReturnUrl);
}
return RedirectToAction("Index", "Home");
}
}
ModelState.AddModelError("", "Invalid Login.");
return View(l);
}
[Authorize]
public ActionResult Logout()
{
FormsAuthentication.SignOut();
return RedirectToAction("Login", "Account");
}
}

If you can get the logged-in userid then simply use that to get Corresponding Subjects list.........
int userid = Membership.GetUser(User.Identity.Name).ProviderUserKey;
[CostumAuthorize(Roles = "Admin,Teacher")]
public ActionResult Subject_List()
{
var test = db.SubjectTeachers.Where(x => x.Users.Any(n => n.UserID == userid )).ToList();
return View(test.ToList());
}

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});

How to get items for logged in user ASP.NET MVC

I am trying to show booking of logged in user from database, but its show all data from all user. this is the original code:
// GET: Bookings
public ActionResult Index()
{
var bookings = db.Bookings.Include(b => b.Room).Include(b => b.Register);
return View(bookings.ToList());
}
Here what I have tried but the output show an error,
public ActionResult Index()
{
var bookings = db.Bookings.Include(b => b.Room).Include(b => b.Register == Session["id"]);
return View(bookings.ToList());
}
This is the user table in the database, so if I login as user no.1, the booking data should display only customerID no.1, but the problem is, the data show all user bookings.
Here is the image of booking db,
Here is the code for login:
[HttpPost]
public ActionResult Login(Register login)
{
using (HotelBookingEntities db = new HotelBookingEntities())
{
var userDetails = db.Registers.Where(x => x.email == login.email && x.password == login.password).FirstOrDefault();
if (userDetails == null)
{
ViewBag.WrongMessage = "Wrong username or password";
return View("Login", login);
}
else
{
Session["id"] = userDetails.id;
Session["username"] = userDetails.username;
return RedirectToAction("Index", "Rooms");
}
}
}
Try as follows:
public ActionResult Index()
{
int userId = Convert.ToInt32(Session["id"]);
var bookings = db.Bookings.Where.Include(b => b.Room).Where(b => b.CustomerID == userId).ToList();
return View(bookings);
}

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

Redirect to actionmethod/view

I have implemented idel time out functionality. Here when the user is idel for 1 min, we redirect the user to login page. We have kept the track of the url that the user was when the auto logout happened. Eg , of the user is on reset password view and if the auto logout happens the url which i get is as follows
http://localhost/XYZ.Portal/?returnUrl=%2FXYZ.Portal%2FUser%2FResetPassword
the above url is achieved by using the following code
'#Url.Action("Login", "User", new { returnUrl = HttpContext.Current.Request.RawUrl })'
Now when the user logs in again as he is redirected to login page, I am using the following code to redirect him back but the code doesnt seem to work. What am I doing wrong.?
[HttpPost]
public ActionResult Login(FormCollection formCollection)
{
if (ModelState.IsValid)
{
UserBE user = new UserBE();
user.Email = formCollection["Email"];
user.Password = formCollection["Password"];
user = UserBL.AuthenticateUser(user);
if (user.AuthenticUser)
{
if (Request.QueryString["returnUrl"] != null)
{
string returnUrl = Server.UrlDecode(Request.QueryString["returnUrl"]);
Redirect(returnUrl );
}
else
{
Session["Email"] = user.Email;
return RedirectToAction("DashBoard");
}
}
else
return View(user);
}
return View();
}
[HttpGet] login action method:
[HttpGet]
public ActionResult Login()
{
return View();
}
returnUrl I get as XYZ.Portal/User/ResetPassword
Thanks In advance.
You need to return the RedirectResult:
if (Request.QueryString["returnUrl"] != null)
{
string returnUrl = Server.UrlDecode(Request.QueryString["returnUrl"]);
return Redirect(returnUrl);
}
See RedirectResult
Not working. Now my URL becomes localhost/XYZ.Portal
In this case you can do 1 of 2 options:
1) Write:
string startReturnUrl = "http://www." + your returnUrl
or
2) split your returnUrl like:
string viewName = returnUrl.Split('/').Last();
But I think better change returnUrl to just only Name of View that you need

ASP.NET MVC Custom Authorization : AuthorizeAttribute

I'm following this tutorial link
I have a table users {iduser, user, pass, role}
I'm using this users : string[] users = db.users.Select(t => t.user).ToArray();
instead of : string[] users = Users.Split(','); Is it ok ?
My problem is with roles : SiteRoles role = (SiteRoles)httpContext.Session["role"];
Q: Where do I store the role for my user ?
My simplified account controller:
[HttpPost]
public ActionResult Login(LoginModel model)
{
HeliosEntities db = new HeliosEntities();
if (ModelState.IsValid)
{
bool userok = db.users.Any(t => t.user == model.UserName && t.pass == model.Password);
if (userok == true)
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
return RedirectToAction("Index", "Home");
}
{
ModelState.AddModelError("", "Incorect password or user!");
}
}
return View();
}
A quick look at your link above shows that it is getting the user's role from session:
(SiteRoles)httpContext.Session["role"];
so you need to set the session value when the user logs in, for example:
var userRole = Roles.Admin | Roles.User;
httpContext.Session["role"] = role;
I don't know where you store the information about what role the user is in though.

Resources