43 lines
1.5 KiB
C#
43 lines
1.5 KiB
C#
using System;
|
|
using System.Linq;
|
|
using Flexitime.Objects;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Mvc.Filters;
|
|
|
|
namespace FlexitimeAPI.Helpers
|
|
{
|
|
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
|
|
public class AuthorizeAttribute : Attribute, IAuthorizationFilter
|
|
{
|
|
public AuthorizeAttribute()
|
|
{
|
|
Permissions = new string[] { };
|
|
}
|
|
|
|
public AuthorizeAttribute(params string[] permissions)
|
|
{
|
|
Permissions = permissions;
|
|
}
|
|
|
|
public string[] Permissions { get; set; }
|
|
|
|
public void OnAuthorization(AuthorizationFilterContext context)
|
|
{
|
|
var user = (User) context.HttpContext.Items["User"];
|
|
if (user == null)
|
|
// not logged in
|
|
context.Result = new JsonResult(
|
|
new { message = "Unauthorized" })
|
|
{ StatusCode = StatusCodes.Status401Unauthorized };
|
|
else if (Permissions.Any()
|
|
&& user.Permissions != null
|
|
&& !user.Permissions.Select(y => y.Tag)
|
|
.Intersect(Permissions.ToList())
|
|
.Any()) //check we have permissions if they have been specified
|
|
context.Result = new JsonResult(
|
|
new { message = "Unauthorized" })
|
|
{ StatusCode = StatusCodes.Status401Unauthorized };
|
|
}
|
|
}
|
|
} |