Created
August 13, 2013 13:48
-
-
Save anonymous/6221307 to your computer and use it in GitHub Desktop.
Based on ServiceStack's RequiredRoleAttribute, this class requires that you have AT LEAST one of the roles -- not all, like the default ServiceStack implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] | |
public class RequiredOneRoleOfAttribute : RequestFilterAttribute | |
{ | |
public List<string> RequiredRoles { get; set; } | |
public RequiredOneRoleOfAttribute(ApplyTo applyTo, params string[] roles) | |
{ | |
this.RequiredRoles = roles.ToList(); | |
this.ApplyTo = applyTo; | |
this.Priority = (int)RequestFilterPriority.RequiredRole; | |
} | |
public RequiredOneRoleOfAttribute(params string[] roles) | |
: this(ApplyTo.All, roles) { } | |
public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto) | |
{ | |
AuthenticateAttribute.AuthenticateIfBasicAuth(req, res); | |
var session = req.GetSession(); | |
if(HasOneOf(req, session)) return; | |
res.StatusCode = (int)HttpStatusCode.Unauthorized; | |
res.StatusDescription = "Invalid Role"; | |
res.EndServiceStackRequest(); | |
} | |
public bool HasOneOf(IHttpRequest req, IAuthSession session, IUserAuthRepository userAuthRepo = null) | |
{ | |
if(HasAnyRole(session)) return true; | |
session.UpdateFromUserAuthRepo(req, userAuthRepo); | |
if(HasAnyRole(session)) | |
{ | |
req.SaveSession(session); | |
return true; | |
} | |
return false; | |
} | |
public bool HasAnyRole(IAuthSession session) | |
{ | |
return this.RequiredRoles | |
.Any(requiredRole => session != null | |
&& session.HasRole(requiredRole)); | |
} | |
/// <summary> | |
/// Check all session is in all supplied roles otherwise a 401 HttpError is thrown | |
/// </summary> | |
/// <param name="requestContext"></param> | |
/// <param name="requiredRoles"></param> | |
public static void AssertRequiredRoles(IRequestContext requestContext, params string[] requiredRoles) | |
{ | |
if(requiredRoles.IsEmpty()) return; | |
var req = requestContext.Get<IHttpRequest>(); | |
var session = req.GetSession(); | |
if(session != null && requiredRoles.Any(session.HasRole)) | |
return; | |
session.UpdateFromUserAuthRepo(req); | |
if(session != null && requiredRoles.Any(session.HasRole)) | |
return; | |
throw new HttpError(HttpStatusCode.Unauthorized, "Invalid Role"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment