/
ServiceExtensions.cs
232 lines (195 loc) · 8.41 KB
/
ServiceExtensions.cs
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
using System;
using System.Linq;
using System.Net;
using ServiceStack.Auth;
using ServiceStack.Caching;
using ServiceStack.Configuration;
using ServiceStack.Host;
using ServiceStack.Logging;
using ServiceStack.Redis;
using ServiceStack.Testing;
using ServiceStack.Web;
namespace ServiceStack
{
public static class ServiceExtensions
{
public static ILog Log = LogManager.GetLogger(typeof(ServiceExtensions));
public static IHttpResult Redirect(this IServiceBase service, string url)
{
return service.Redirect(url, "Moved Temporarily");
}
public static IHttpResult Redirect(this IServiceBase service, string url, string message)
{
return new HttpResult(HttpStatusCode.Redirect, message)
{
ContentType = service.Request.ResponseContentType,
Headers = {
{ HttpHeaders.Location, url }
},
};
}
public static IHttpResult AuthenticationRequired(this IServiceBase service)
{
return new HttpResult
{
StatusCode = HttpStatusCode.Unauthorized,
ContentType = service.Request.ResponseContentType,
Headers = {
{ HttpHeaders.WwwAuthenticate, $"{AuthenticateService.DefaultOAuthProvider} realm=\"{AuthenticateService.DefaultOAuthRealm}\"" }
},
};
}
public static string GetSessionId(this IServiceBase service)
{
var req = service.Request;
var sessionId = req.GetSessionId();
if (sessionId == null)
throw new ArgumentNullException("sessionId", "Session not set. Is Session being set in RequestFilters?");
return sessionId;
}
public static ICacheClient GetCacheClient(this IRequest request) => HostContext.AppHost.GetCacheClient(request);
public static void SaveSession(this IServiceBase service, IAuthSession session, TimeSpan? expiresIn = null)
{
if (service == null || session == null) return;
service.Request.SaveSession(session, expiresIn);
}
public static void RemoveSession(this IServiceBase service)
{
service?.Request.RemoveSession();
}
public static void RemoveSession(this Service service)
{
service?.Request.RemoveSession();
}
public static void CacheSet<T>(this ICacheClient cache, string key, T value, TimeSpan? expiresIn)
{
if (expiresIn.HasValue)
cache.Set(key, value, expiresIn.Value);
else
cache.Set(key, value);
}
public static void SaveSession(this IRequest httpReq, IAuthSession session, TimeSpan? expiresIn = null)
{
HostContext.AppHost.OnSaveSession(httpReq, session, expiresIn);
}
public static void RemoveSession(this IRequest httpReq)
{
RemoveSession(httpReq, httpReq.GetSessionId());
}
public static void RemoveSession(this IRequest httpReq, string sessionId)
{
if (httpReq == null) return;
if (sessionId == null)
throw new ArgumentNullException(nameof(sessionId));
var sessionKey = SessionFeature.GetSessionKey(sessionId);
httpReq.GetCacheClient().Remove(sessionKey);
httpReq.Items.Remove(Keywords.Session);
}
public static IAuthSession GetSession(this IServiceBase service, bool reload = false)
{
return service.Request.GetSession(reload);
}
public static TUserSession SessionAs<TUserSession>(this IRequest req)
{
if (HostContext.TestMode)
{
var mockSession = req.TryResolve<TUserSession>();
if (!Equals(mockSession, default(TUserSession)))
mockSession = req.TryResolve<IAuthSession>() is TUserSession
? (TUserSession)req.TryResolve<IAuthSession>()
: default(TUserSession);
if (!Equals(mockSession, default(TUserSession)))
return mockSession;
}
return SessionFeature.GetOrCreateSession<TUserSession>(req.GetCacheClient(), req, req.Response);
}
public static bool IsAuthenticated(this IRequest req)
{
//Sync with [Authenticate] impl
if (HostContext.HasValidAuthSecret(req))
return true;
var authProviders = AuthenticateService.GetAuthProviders();
AuthenticateAttribute.PreAuthenticate(req, authProviders);
if (req.Response.IsClosed)
return false;
var session = req.GetSession();
return session != null && authProviders.Any(x => session.IsAuthorized(x.Provider));
}
public static IAuthSession GetSession(this IRequest httpReq, bool reload = false)
{
if (httpReq == null)
return null;
if (HostContext.TestMode)
{
var mockSession = httpReq.TryResolve<IAuthSession>(); //testing
if (mockSession != null)
return mockSession;
}
object oSession = null;
if (!reload)
httpReq.Items.TryGetValue(Keywords.Session, out oSession);
if (oSession == null && !httpReq.Items.ContainsKey(Keywords.HasPreAuthenticated))
{
try
{
HostContext.AppHost.ApplyPreAuthenticateFilters(httpReq, httpReq.Response);
httpReq.Items.TryGetValue(Keywords.Session, out oSession);
}
catch (Exception ex)
{
Log.Error("Error in GetSession() when ApplyPreAuthenticateFilters", ex);
/*treat errors as non-existing session*/
}
}
var sessionId = httpReq.GetSessionId();
var session = oSession as IAuthSession;
if (session != null)
session = HostContext.AppHost.OnSessionFilter(httpReq, session, sessionId);
if (session != null)
return session;
var sessionKey = SessionFeature.GetSessionKey(sessionId);
if (sessionKey != null)
{
session = httpReq.GetCacheClient().Get<IAuthSession>(sessionKey);
if (session != null)
session = HostContext.AppHost.OnSessionFilter(httpReq, session, sessionId);
}
if (session == null)
{
var newSession = SessionFeature.CreateNewSession(httpReq, sessionId);
session = HostContext.AppHost.OnSessionFilter(httpReq, newSession, sessionId) ?? newSession;
}
httpReq.Items[Keywords.Session] = session;
return session;
}
public static TimeSpan? GetSessionTimeToLive(this ICacheClient cache, string sessionId)
{
var sessionKey = SessionFeature.GetSessionKey(sessionId);
return cache.GetTimeToLive(sessionKey);
}
public static TimeSpan? GetSessionTimeToLive(this IRequest httpReq)
{
return httpReq.GetCacheClient().GetSessionTimeToLive(httpReq.GetSessionId());
}
public static object RunAction<TService, TRequest>(
this TService service, TRequest request, Func<TService, TRequest, object> invokeAction,
IRequest requestContext = null)
where TService : IService
{
var actionCtx = new ActionContext
{
RequestFilters = TypeConstants<IRequestFilterBase>.EmptyArray,
ResponseFilters = TypeConstants<IResponseFilterBase>.EmptyArray,
ServiceType = typeof(TService),
RequestType = typeof(TRequest),
ServiceAction = (instance, req) => invokeAction(service, request)
};
requestContext = requestContext ?? new MockHttpRequest();
ServiceController.InjectRequestContext(service, requestContext);
var runner = HostContext.CreateServiceRunner<TRequest>(actionCtx);
var responseTask = runner.ExecuteAsync(requestContext, service, request);
var response = responseTask.Result;
return response;
}
}
}