forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRequiredRoleAttribute.cs
More file actions
89 lines (72 loc) · 3.03 KB
/
RequiredRoleAttribute.cs
File metadata and controls
89 lines (72 loc) · 3.03 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
80
81
82
83
84
85
86
87
88
89
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using ServiceStack.Common;
using ServiceStack.Common.Web;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface.Auth;
using ServiceStack.WebHost.Endpoints.Extensions;
namespace ServiceStack.ServiceInterface
{
/// <summary>
/// Indicates that the request dto, which is associated with this attribute,
/// can only execute, if the user has specific roles.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method /*MVC Actions*/, Inherited = false, AllowMultiple = true)]
public class RequiredRoleAttribute : RequestFilterAttribute
{
public List<string> RequiredRoles { get; set; }
public RequiredRoleAttribute(ApplyTo applyTo, params string[] roles)
{
this.RequiredRoles = roles.ToList();
this.ApplyTo = applyTo;
this.Priority = (int) RequestFilterPriority.RequiredRole;
}
public RequiredRoleAttribute(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 (HasAllRoles(req, session)) return;
res.StatusCode = (int)HttpStatusCode.Unauthorized;
res.StatusDescription = "Invalid Role";
res.EndServiceStackRequest();
}
public bool HasAllRoles(IHttpRequest req, IAuthSession session, IUserAuthRepository userAuthRepo=null)
{
if (HasAllRoles(session)) return true;
session.UpdateFromUserAuthRepo(req, userAuthRepo);
if (HasAllRoles(session))
{
req.SaveSession(session);
return true;
}
return false;
}
public bool HasAllRoles(IAuthSession session)
{
return this.RequiredRoles
.All(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.All(session.HasRole))
return;
session.UpdateFromUserAuthRepo(req);
if (session != null && requiredRoles.All(session.HasRole))
return;
throw new HttpError(HttpStatusCode.Unauthorized, "Invalid Role");
}
}
}