Skip to content

Instantly share code, notes, and snippets.

@juristr
Created August 10, 2012 05:47
Show Gist options
  • Save juristr/3311443 to your computer and use it in GitHub Desktop.
Save juristr/3311443 to your computer and use it in GitHub Desktop.
Some helper classes to create a fake principal with roles
public class IdentityStub : IIdentity
{
private readonly string _name;
private readonly string _authenticationType;
private readonly bool _isAuthenticated;
public IdentityStub(string name, string authenticationType, bool isAuthenticated)
{
_name = name;
_isAuthenticated = isAuthenticated;
_authenticationType = authenticationType;
}
public string Name
{
get
{
return _name;
}
}
public string AuthenticationType
{
get
{
return _authenticationType;
}
}
public bool IsAuthenticated
{
get
{
return _isAuthenticated;
}
}
}
public class PrincipalStub : IPrincipal
{
private readonly string _name;
private readonly string _authenticationType;
private readonly bool _isAuthenticated;
private readonly bool? _isInRoleResponse;
private readonly List<string> _roles;
public PrincipalStub(string name, string authenticationType, bool isAuthenticated, bool isInRoleResponse)
{
_name = name;
_isAuthenticated = isAuthenticated;
_authenticationType = authenticationType;
_isInRoleResponse = isInRoleResponse;
}
public PrincipalStub(string name, string authenticationType, bool isAuthenticated, params string[] roles)
{
_name = name;
_isAuthenticated = isAuthenticated;
_authenticationType = authenticationType;
_roles = new List<string>(roles);
}
public IIdentity Identity
{
get
{
return new IdentityStub(_name, _authenticationType, _isAuthenticated);
}
}
public bool IsInRole(string role)
{
if (_isInRoleResponse.HasValue)
{
return _isInRoleResponse.Value;
}
return _roles.Contains(role);
}
}
public class TestPrincipalManager
{
private PrincipalStub _principal;
public TestPrincipalManager(string username, string authenticationType, bool isAuthenticated, params string[] roles)
{
_principal = new PrincipalStub(username, authenticationType, isAuthenticated, roles);
}
public TestPrincipalManager(string username, string authenticationType, bool isAuthenticated, bool isInRoleResponse)
{
_principal = new PrincipalStub(username, authenticationType, isAuthenticated, isInRoleResponse);
}
public IDisposable Attach()
{
IPrincipal originalPrincipal = Thread.CurrentPrincipal;
Thread.CurrentPrincipal = _principal;
return new TestPrincipalCleanup(originalPrincipal);
}
public class TestPrincipalCleanup : IDisposable
{
private readonly IPrincipal _principal;
public TestPrincipalCleanup(IPrincipal principal)
{
_principal = principal;
}
public void Dispose()
{
Thread.CurrentPrincipal = _principal;
GC.SuppressFinalize(this);
}
}
}
var principalMan = new TestPrincipalManager("username", "authType", true, "PERMISSION_NAME");
using (principalMan.Attach())
{
//principalpermission given
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment