narsil/Tanshu.Accounts.BI/RoleBI.cs
2010-03-02 23:26:21 +05:30

75 lines
2.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Tanshu.Accounts.BI
{
public delegate bool AuthenticateUser(out string userName);
public class RoleBI : IDisposable
{
string roleID;
Guid userID;
bool elevated;
AccountsPrincipal originalUser;
AuthenticateUser authenticateUser;
public RoleBI(string roleID, Guid userID)
{
this.roleID = roleID;
this.userID = userID;
elevated = false;
originalUser = null;
authenticateUser = null;
}
public bool IsAllowed
{
get
{
return new MembershipBI().IsUserInRole(userID, roleID);
}
}
public bool IsElevated
{
get
{
return elevated;
}
}
public void Evelvate(AuthenticateUser authenticateUser)
{
this.authenticateUser = authenticateUser;
string userName;
if (this.authenticateUser(out userName))
{
originalUser = (AccountsPrincipal)Thread.CurrentPrincipal;
SetElevation(userName);
}
}
private void SetElevation(string userName)
{
if (userName.Contains(":"))
userName = userName.Substring(userName.IndexOf(":") + 1);
AccountsPrincipal principal = AccountsPrincipal.CreateAccountsPrincipal(new Tanshu.Accounts.BI.MembershipBI().GetRolesForUser(userName),
new MembershipBI().GetUserFromName(userName));
// bind the generic principal to the thread
Thread.CurrentPrincipal = principal;
userName = ((AccountsIdentity)principal.Identity).UserInfo.Name;
userID = ((AccountsIdentity)principal.Identity).UserInfo.UserID;
elevated = true;
}
public void Dispose()
{
if (elevated)
{
Thread.CurrentPrincipal = originalUser;
}
}
}
}