IPrincipal.IsInRole(role)
に内蔵機能を使用することをおすすめします。
サンプル単純な実装:
class User : IPrincipal
{
private readonly bool IsAdmin;
// or better
private readonly string[] roles; // or HashSet<string> to speed up lookup
public User(string name)
{
// fetch and fill from db
}
bool IPrincipal.IsInRole(string role)
{
return role == "admin" && this.IsAdmin;
// or better
return this.roles.Contains(role);
}
}
用途:また
var user = new User("Joe");
if (user.IsInRole("admin"))
// do stuff
else
throw new SEcurityException("Insufficient rights");
することができますハードコード役割行列:
[AccessAttribute(Roles.Administrator)]
class AdminForm : BaseForm { }
abstract class BaseForm
{
protected override void OnLoad(EventArgs e)
{
CheckAccess(); //check current user against attribute of form
base.OnLoad(e);
}
}
enum Roles
{
Administrator,
User
}
class AccessAttribute : Attribute { }
class User
{
private bool? isAdmin;
public bool IsAdmin
{
get
{
if (!isAdmin.HasValue) // better to move to private static method
{
bool b = false;
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "select IsHeAdmin from Users where Name = @UserName";
command.Paratemters.AddWithValue("@UserName", this.Name);
connection.Open();
b = command.ExecuteScalar() as bool? ?? false; // if null then false, otherwise assign the value
}
isAdmin = b;
}
return isAdmin.Value;
}
}
}
ORM(http://en.wikipedia.org/wiki/Object-relational_mapping)を使用してオブジェクトを取得するか、ORMが状況に応じて複雑すぎる場合は、DBからのデータを使用してオブジェクトを作成します。ユーザーをどこかに見えるようにする最も簡単な方法(ただし必ずしも最良ではない)は、いくつかの静的プロパティを使用することです。 – svick