Admin Privileges in a controller in ASP.NET MVC - c#

I want to put an admin role privileges in my post method in controller.
Whatever login I use, the takes it as if everyone has an admin role. Any ideas on what needs to change so the code execute correctly in the if statement?
Thank you.
[HttpPost]
public ActionResult Autherize(Vidly2.Models.User userModel)
{
using (LoginDataBaseEntities db = new LoginDataBaseEntities())
{
var userDetails = db.Users.Where(x => x.Email == userModel.Email && x.Password == userModel.Password).FirstOrDefault();
var admins = db.Users.Where(x => x.Role.Contains("Admin")).FirstOrDefault();
if (userDetails == null)
{
userModel.LoginErrorMessage = "Wrong username or password.";
return View("Index", userModel);
}
else {
if (admins == null)
{
return RedirectToAction("Index", "Home");
}
else
{
Session["userID"] = userDetails.Email;
return RedirectToAction("Index", "Keys");
}
}
}
return View();
}

Related

How to display user data after he logs in MVC

I need to display the users info when he selects View Profile. How can I do this as im new to mvc. Links to help or an explanation will help a lot. Thanks
Here is my Login Action:
public ActionResult Authorize(The_Pizzatorium.Models.tblUser userModel)
{
using (The_PizzatoriumEntities1 db = new The_PizzatoriumEntities1())
{
var userDetails = db.tblUsers.Where(x => x.dUSerName == userModel.dUSerName && x.dPassword == userModel.dPassword).FirstOrDefault();
if (userDetails == null)
{
userModel.LoginErrorMessage = "Wrong username or password.";
return View("Index", userModel);
}
else
{
Session["UserID"] = userDetails.dID;
Session["userName"] = userDetails.dUSerName;
return RedirectToAction("Index", "Home");
}
}
}
How will I need to make the View Profile Action to display the logged in Users Details?
public ActionResult ViewProfile()
{
return View();
}
when user come to viewprofile action check use session
public ActionResult ViewProfile()
{
if(Session["UserID"]!=null)
{
//check user uid datatype
//then store in variable
int useesionid=COnvert.toint32(Session["UserID"].tosting())
var userDetails = db.tblUsers.Where(x => x.uid==useesionid).ToList();
///here your code
return View( userDetails );
}
Check the below code, to get the user details if logged in other wise redirecting to login page.
public ActionResult ViewProfile()
{
if(Session["UserID"] != null)
{
using (The_PizzatoriumEntities1 db = new The_PizzatoriumEntities1())
{
int userId = Convert.ToInt32(Session["UserID"].ToString());
var userDetails = db.tblUsers.Where(x => x.dID == userId).FirstOrDefault();
if (userDetails != null)
{
return View(userDetails);
}
}
}
return RedirectToAction("Login", "Account"); // Redirect to your login page
}

How can I redict to same page after session expire in MVC project?

//I Have a Action Method
[HttpGet]
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(VmUser_User VmUser_User)
{
if (VmUser_User.User_User.UserName == null ||
VmUser_User.User_User.Password == null)
{
VmUser_User.LblError = "Please enter Username and Password";
return View(VmUser_User);
}
//Return valid user
if (VmUser_User.LoginUser() > 0)
{
Session["One"] = VmUser_User;
return RedirectToAction("Index", "Home");
}
else
{
VmUser_User.LblError = "User/Password does not match!";
}
return View(VmUser_User);
}
//And another Action Method
public async Task<ActionResult> Common_Unit()
{
Oss.Romo.ViewModels.User.VmUser_User user =
(Oss.Romo.ViewModels.User.VmUser_User)Session["One"];
if (user == null)
{
return RedirectToAction("Login", "Home");
}
vmCommon_Unit = new VmCommon_Unit();
await Task.Run(() => vmCommon_Unit.InitialDataLoad());
return View(vmCommon_Unit);
}
When a valid user login application, it redirect to Home/Index page, then he request for Common/Common_Unit page. After expire the session and user relogin the application I want to redirect in last requested page like Common/Common_Unit, please someone help me to solve this problem.
My Question : When a authorized user browse a specific page then he inactive some time. In the min time session out occurred and user go to login page. After login I want to redirect user on this specific page. Sorry for my Bad English
Try to use ReturnUrl parameter, like this:
[HttpGet]
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(VmUser_User VmUser_User)
{
if (VmUser_User.User_User.UserName == null ||
VmUser_User.User_User.Password == null)
{
VmUser_User.LblError = "Please enter Username and Password";
return View(VmUser_User);
}
//Return valid user
if (VmUser_User.LoginUser() > 0)
{
Session["One"] = VmUser_User;
if (Request.QueryString["ReturnUrl"] != null & Request.QueryString["ReturnUrl"] != "")
{
Response.Redirect(Request.QueryString["ReturnUrl"]);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
VmUser_User.LblError = "User/Password does not match!";
}
return View(VmUser_User);
}
//And another Action Method
public async Task<ActionResult> Common_Unit()
{
Oss.Romo.ViewModels.User.VmUser_User user =
(Oss.Romo.ViewModels.User.VmUser_User)Session["One"];
if (user == null)
{
return RedirectToAction("Login", "Home", new { ReturnUrl = "/Common/Common_Unit" });
}
vmCommon_Unit = new VmCommon_Unit();
await Task.Run(() => vmCommon_Unit.InitialDataLoad());
return View(vmCommon_Unit);
}

Adding Partial View with Switch Case in Controller

I am working on a Partial view that is controlled by a Switch case statement in my controller function for Login and Register but after logging in successfully, it only refreshes the page and doesnt redirect on the case that is used on the login controller function , My problem is how can I prevent to go in the return View(model)
Here is my Main Controller
[HttpPost]
public ActionResult Dashboard(RegisterModel model1, LogOnModel model2, string returnUrl, string btnReturn, string Role, FormCollection formCollection)
{
switch (btnReturn)
{
case "Register":
DashboardRegister(model1, Role, formCollection);
break;
case "Login":
DashboardLogin(model2, returnUrl);
break;
}
ViewBag.Roles = new SelectList(Roles.GetAllRoles().ToList());
DashboardRegisterLogin model = new DashboardRegisterLogin
{
RegisterModel = model1,
LogOnModel = model2
};
// If we got this far, something failed, redisplay form
return View(model);
}
Controller Function for Register:
public ActionResult DashboardRegister(RegisterModel model1, string Role, FormCollection formCollection)
{
String name = formCollection["txtClientName"];
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model1.UserName = model1.Email, model1.Password, model1.Email, null, null, true, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
Roles.AddUserToRole(model1.UserName, Role);
FormsAuthentication.SetAuthCookie(model1.UserName, false /* createPersistentCookie */);
if (Roles.IsUserInRole(model1.UserName, "Employer"))
{
return RedirectToAction("ClientCustomerDetails", "Customer");
}
else if (Roles.IsUserInRole(model1.UserName, "Worker"))
{
return RedirectToAction("WorkerInfo", "Worker");
}
else if (Roles.IsUserInRole(model1.UserName, "Administrator"))
{
return RedirectToAction("ClientDetails", "Client");
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
// If we got this far, something failed, redisplay form
return View(model1);
}
Controller Function for Login:
[HttpPost]
public ActionResult DashboardLogin(LogOnModel model2, string returnUrl)
{
if (Membership.ValidateUser(model2.UserName, model2.Password))
{
FormsAuthentication.SetAuthCookie(model2.UserName, model2.RememberMe);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
if (Roles.IsUserInRole(model2.UserName, "Employer"))
{
return RedirectToAction("WorkerIndex", "Worker");
}
else if (Roles.IsUserInRole(model2.UserName, "Worker"))
{
return RedirectToAction("PositionIndex", "Position");
}
else if (Roles.IsUserInRole(model2.UserName, "Administrator"))
{
return RedirectToAction("ClientDetails", "Client");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
// If we got this far, something failed, redisplay form
return View(model2);
}
You need to return here as you're not using the results of those methods:
switch (btnReturn)
{
case "Register":
return DashboardRegister(model1, Role, formCollection);
case "Login":
return DashboardLogin(model2, returnUrl);
}

Get a null parameter in action

i have an asp.net mvc4 application in which i have in an action X :
impaire_target = u.Get_Impaire_List().Find(x => x.id_paire == identificateur);
Session["id_paire"] = a;
return RedirectToAction("Page2","Pages",impaire_target );
The action Page2
public ActionResult Page2(Impaire impa)
{
try
{
User u = (User)Session["user"];
if (u.Login == null) RedirectToAction("Index", "Home");
}
catch { return RedirectToAction("Index", "Home"); }
if (impa == null)
{
return View();
}
return View(impa);
}
the problem is that the parameters impa is always null . even i try to replace return RedirectToAction("Page2","Pages",impaire_target ); by return RedirectToAction("Page2","Pages",new{ impa=impaire_target} ); i got the same result.
What is the reasons of this problem?
You can't use ModelBinding with RedirectToAction, so no complex type as anonymous object. Try to convert the object to a RouteValueDictionary:
return RedirectToAction("Page2", "Pages", new RouteValueDictionary(impaire_target));
Side note: you always have to return the RedirectToAction, or it won't work.
You should use Session or TempData for passing complex data between controller actions. Here it is described in details.
Example:
impaire_target = u.Get_Impaire_List().Find(x => x.id_paire == identificateur);
TempData["impa"] = impaire_target;
Session["id_paire"] = a;
return RedirectToAction("Page2","Pages");
The action Page2
public ActionResult Page2()
{
Impaire impa = TempData["impa"] as Impaire;
try
{
User u = (User)Session["user"];
if (u.Login == null) RedirectToAction("Index", "Home");
}
catch { return RedirectToAction("Index", "Home"); }
if (impa == null)
{
return View();
}
return View(impa);
}

MVC 4 Error 404 on Created View

I have this controller:
[Authorize]
public class CheckoutController : Controller
{
ShoppingCartContext storeDB = new ShoppingCartContext();
const string PromoCode = "FREE";
[HttpPost]
public ActionResult AddressAndPayment(FormCollection values)
{
var order = new Order();
TryUpdateModel(order);
try
{
if (string.Equals(values["PromoCode"], PromoCode,
StringComparison.OrdinalIgnoreCase) == false)
{
return View(order);
}
else
{
order.Username = User.Identity.Name;
order.OrderDate = DateTime.Now;
//Save Order
storeDB.Orders.Add(order);
storeDB.SaveChanges();
//Process the order
var cart = Models.ShoppingCart.GetCart(this.HttpContext);
cart.CreateOrder(order);
return RedirectToAction("Complete",
new { id = order.OrderId });
}
}
catch
{
//Invalid - redisplay with errors
return View(order);
}
}
public ActionResult Complete(int id)
{
// Validate customer owns this order
bool isValid = storeDB.Orders.Any(
o => o.OrderId == id &&
o.Username == User.Identity.Name);
if (isValid)
{
return View(id);
}
else
{
return View("Error");
}
}
}
And I have created a View called AddressAndPayment under Checkout, so it goes to localhost/Checkout/AddressAndPayment but I only get a 404 error, even if I right click on the View and click on view in Page Inspector. I don't know why its not even showing the view when it is created.
You need a corresponding HttpGet method, as your current one only accepts a HttpPost request. Add the following:
[HttpGet]
public ActionResult AddressAndPayment()
{
return View();
}

Categories

Resources