forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExecuteServiceStackFiltersAttribute.cs
More file actions
79 lines (63 loc) · 2.84 KB
/
Copy pathExecuteServiceStackFiltersAttribute.cs
File metadata and controls
79 lines (63 loc) · 2.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
#if !NETSTANDARD2_0
using System.Web.Mvc;
#else
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Controllers;
#endif
namespace ServiceStack.Mvc
{
public class ExecuteServiceStackFiltersAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!(filterContext.Controller is ServiceStackController ssController)) return;
ssController.ViewData[Keywords.IRequest] = ssController.ServiceStackRequest;
var authAttr = GetActionAndControllerAttributes<AuthenticateAttribute>(filterContext)
.FirstOrDefault();
if (!ssController.IsAuthorized(authAttr))
{
var authError = authAttr?.HtmlRedirect != null
? new RedirectResult(authAttr.HtmlRedirect.AddQueryParam("redirect", ssController.Request.GetPathAndQuery()))
: ssController.AuthenticationErrorResult;
filterContext.Result = authError;
return;
}
var roleAttrs = GetActionAndControllerAttributes<RequiredRoleAttribute>(filterContext);
var anyRoleAttrs = GetActionAndControllerAttributes<RequiresAnyRoleAttribute>(filterContext);
var permAttrs = GetActionAndControllerAttributes<RequiredPermissionAttribute>(filterContext);
var anyPermAttrs = GetActionAndControllerAttributes<RequiresAnyPermissionAttribute>(filterContext);
if (!ssController.HasAccess(roleAttrs, anyRoleAttrs, permAttrs, anyPermAttrs))
{
var authError = authAttr?.HtmlRedirect != null
? new RedirectResult(authAttr.HtmlRedirect.AddQueryParam("redirect", ssController.Request.GetPathAndQuery()))
: ssController.ForbiddenErrorResult;
filterContext.Result = authError;
}
}
private static List<T> GetActionAndControllerAttributes<T>(ActionExecutingContext filterContext)
where T : Attribute
{
var attrs = new List<T>();
#if !NETSTANDARD2_0
var attr = filterContext.ActionDescriptor
.GetCustomAttributes(typeof(T), true)
.FirstOrDefault() as T;
#else
var controllerActionDescriptor = filterContext.ActionDescriptor as ControllerActionDescriptor;
var attr = controllerActionDescriptor?.MethodInfo.FirstAttribute<T>();
#endif
if (attr != null)
attrs.Add(attr);
attr = filterContext.Controller.GetType().FirstAttribute<T>();
if (attr != null)
attrs.Add(attr);
return attrs;
}
}
}