Skip to content

Instantly share code, notes, and snippets.

@kid-cavaquinho
Last active June 10, 2016 13:34
Show Gist options
  • Save kid-cavaquinho/4943933 to your computer and use it in GitHub Desktop.
Save kid-cavaquinho/4943933 to your computer and use it in GitHub Desktop.
Authorization attribute for MVC application operating outside of Umbraco environment.
public class UmbracoAuthorize : AuthorizeAttribute
{
private readonly IUmbracoService _umbracoService;
public UmbracoAuthorize()
{
_umbracoService = new UmbracoService();
}
public UmbracoAuthorize(IUmbracoService umbracoService)
{
_umbracoService = umbracoService;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (HttpContext.Current == null) { return false; }
// Do not check cookie every time, if it's logged in with correct permissions, return true.
var cookie = httpContext.Request.Cookies.Get("UMB_UCONTEXT");
if (cookie == null || string.IsNullOrEmpty(cookie.Value)) { return false; }
try
{
var cookieValue = new Guid(cookie.Value);
// Will check cookie agaisnt dbo.umbracoUserLogins and dbo.umbracoUserType
var umbracoUser = _umbracoService.GetCurrentUser(cookieValue);
if (string.IsNullOrEmpty(umbracoUser.UserName) || string.IsNullOrEmpty(umbracoUser.TypeAlias) || umbracoUser.IsDisabled)
{
return false;
}
if (CheckForUserAdminTypeAlias(umbracoUser.TypeAlias.ToLowerInvariant()))
{
return false;
}
if (cookieValue != umbracoUser.ContextId)
{
return false;
}
httpContext.User = new GenericPrincipal(new GenericIdentity(umbracoUser.UserName), new[] { umbracoUser.TypeAlias });
FormsAuthentication.SetAuthCookie(umbracoUser.UserName, false);
}
catch (Exception exception)
{
// _loggerService.Error(@"ERROR - ", exception);
return false;
}
return true;
}
private static bool CheckForAdminUserTypeAlias(string userTypeAlias)
{
return userTypeAlias != "admin";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment