私は新しいMVC3ユーザーであり、SQLデータベースを介して管理者を作成しようとしています。まず、Customerエンティティがあり、adminはCustomerエンティティのブール型であるadminフィールドを介して定義できます。通常の顧客ではなく、製品ページでのみ管理者にアクセスできるようにしたい。そして、[Authorize]の代わりに[Authorize(Roles = "admin")]を作成したいと思います。ただし、コードで管理者の役割を実際に作成するにはどうすればよいかわかりません。次に、HomeControllerで、このコードを記述しました。
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);
}
そして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);
}
}
最後に、カスタム[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());
}
}
これらは私のソースコードです。'AuthorizeAttribute'クラスを作成する必要がありますか?私がしなければならない場合、どうすればそれを作ることができますか?説明してもらえますか?私の場合、特定の役割を設定する方法がわかりません。どうすればいいのか教えてください。ありがとう。