forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSessionFeature.cs
More file actions
90 lines (75 loc) · 2.93 KB
/
SessionFeature.cs
File metadata and controls
90 lines (75 loc) · 2.93 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
90
using System;
using System.Web;
using ServiceStack.CacheAccess;
using ServiceStack.Common.Utils;
using ServiceStack.Common.Web;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface.Auth;
using ServiceStack.WebHost.Endpoints;
using ServiceStack.WebHost.Endpoints.Extensions;
namespace ServiceStack.ServiceInterface
{
public class SessionFeature : IPlugin
{
public const string OnlyAspNet = "Only ASP.NET Requests accessible via Singletons are supported";
public const string SessionId = "ss-id";
public const string PermanentSessionId = "ss-pid";
public const string SessionOptionsKey = "ss-opt";
public const string XUserAuthId = HttpHeaders.XUserAuthId;
private static bool alreadyConfigured;
public void Register(IAppHost appHost)
{
if (alreadyConfigured) return;
alreadyConfigured = true;
//Add permanent and session cookies if not already set.
appHost.RequestFilters.Add(AddSessionIdToRequestFilter);
}
public static void AddSessionIdToRequestFilter(IHttpRequest req, IHttpResponse res, object requestDto)
{
if (req.GetItemOrCookie(SessionId) == null)
{
res.CreateTemporarySessionId(req);
}
if (req.GetItemOrCookie(PermanentSessionId) == null)
{
res.CreatePermanentSessionId(req);
}
}
public static string GetSessionId(IHttpRequest httpReq = null)
{
if (httpReq == null && HttpContext.Current == null)
throw new NotImplementedException(OnlyAspNet);
httpReq = httpReq ?? HttpContext.Current.Request.ToRequest();
return httpReq.GetSessionId();
}
public static void CreateSessionIds(IHttpRequest httpReq = null, IHttpResponse httpRes = null)
{
if (httpReq == null || httpRes == null)
{
if (HttpContext.Current == null)
throw new NotImplementedException(OnlyAspNet);
}
httpReq = httpReq ?? HttpContext.Current.Request.ToRequest();
httpRes = httpRes ?? HttpContext.Current.Response.ToResponse();
httpRes.CreateSessionIds(httpReq);
}
public static string GetSessionKey()
{
var sessionId = GetSessionId();
return sessionId == null ? null : GetSessionKey(sessionId);
}
public static string GetSessionKey(string sessionId)
{
return IdUtils.CreateUrn<IAuthSession>(sessionId);
}
public static T GetOrCreateSession<T>(ICacheClient cacheClient) where T : class, new()
{
T session = null;
if (GetSessionKey() != null)
session = cacheClient.Get<T>(GetSessionKey());
else
CreateSessionIds();
return session ?? new T();
}
}
}