I am a new MVC 3 user and I am trying to do admin through an SQL database. First of all, I have a Customer and admin object, which can be defined through the admin field, which is a boolean in the Customer object. I want to make access to the administrator only on the Product page, and not in the regular client. And I want to do [Log in (Roles = "admin")] instead of [Log in]. However, I do not know how I can make the administrator role in my code. Then in my HomeController I wrote this code.
public class HomeController : Controller { [HttpPost] public ActionResult Index(Customer model) { if (ModelState.IsValid) { //define user whether admin or customer SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["rentalDB"].ToString()); String find_admin_query = "SELECT admin FROM Customer WHERE userName = '" + model.userName + "' AND admin ='true'"; SqlCommand cmd = new SqlCommand(find_admin_query, conn); conn.Open(); SqlDataReader sdr = cmd.ExecuteReader(); //it defines admin which is true or false model.admin = sdr.HasRows; conn.Close(); //if admin is logged in if (model.admin == true) { Roles.IsUserInRole(model.userName, "admin"); //Is it right? if (DAL.UserIsVaild(model.userName, model.password)) { FormsAuthentication.SetAuthCookie(model.userName, true); return RedirectToAction("Index", "Product"); } } //if customer is logged in if (model.admin == false) { if (DAL.UserIsVaild(model.userName, model.password)) { FormsAuthentication.SetAuthCookie(model.userName, true); return RedirectToAction("Index", "Home"); } } ModelState.AddModelError("", "The user name or password is incorrect."); } // If we got this far, something failed, redisplay form return View(model); }
And class DAL
public class DAL { static SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["rentalDB"].ToString()); public static bool UserIsVaild(string userName, string password) { bool authenticated = false; string customer_query = string.Format("SELECT * FROM [Customer] WHERE userName = '{0}' AND password = '{1}'", userName, password); SqlCommand cmd = new SqlCommand(customer_query, conn); conn.Open(); SqlDataReader sdr = cmd.ExecuteReader(); authenticated = sdr.HasRows; conn.Close(); return (authenticated); } }
Finally, I want to do custom [Authorize (Roles = "admin")]
[Authorize(Roles="admin")] public class ProductController : Controller { public ViewResult Index() { var product = db.Product.Include(a => a.Category); return View(product.ToList()); } }
This is my source code. Should I use the AuthorizeAttribute class? If I have to do this, how can I do this? Could you explain to me? I cannot figure out how to establish a special role in my case. Please help me how can I do this. Thanks.
source share