public class CustomPrincipal : IPrincipal
{
private string[] _roles;
private CustomIdentity _identity;
public string[] Roles
{
get { return _roles; }
set { _roles = value; }
}
public virtual IIdentity Identity
{
get { return _identity; }
}
/// <summary>
/// Required due to deserialization
/// </summary>
public CustomPrincipal()
{
_identity = CreateIdentity();
}
public CustomPrincipal(CustomIdentity identity, string[] roles)
{
_identity = identity;
_roles = roles;
}
protected virtual CustomIdentity CreateIdentity()
{
return new CustomIdentity();
}
public virtual object SaveState()
{
return new Pair(((CustomIdentity)Identity).SaveState(), _roles);
}
public virtual void LoadState(object state)
{
Pair props = state as Pair;
if (props != null)
{
if (_identity == null)
_identity = new CustomIdentity();
((CustomIdentity)Identity).LoadState(props.First);
_roles = (string[])props.Second;
}
}
public virtual void LoadStateFromBase64String(string sState)
{
byte[] arrBytes = Convert.FromBase64String(sState);
object state = null;
if (arrBytes.Length != 0)
{
BinaryFormatter binFormatter = new BinaryFormatter();
using (MemoryStream memStrm = new MemoryStream(arrBytes))
state = binFormatter.Deserialize(memStrm);
LoadState(state);
}
}
public virtual string SaveStateAsBase64String()
{
object state = SaveState();
byte[] arrBytes = new byte[0] { };
if (state != null)
{
BinaryFormatter binFormatter = new BinaryFormatter();
using (MemoryStream memStrm = new MemoryStream())
{
binFormatter.Serialize(memStrm, state);
arrBytes = memStrm.ToArray();
}
}
return Convert.ToBase64String(arrBytes);
}
IIdentity IPrincipal.Identity
{
get { return _identity; }
}
public bool IsInRole(string role)
{
if (_roles == null)
return false;
return ((IList)_roles).Contains(role);
}
public bool IsInAnyRole(IList roles)
{
foreach (string role in roles)
if (((IList)_roles).Contains(role))
return true;
return false;
}
}