-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebContext.cs
207 lines (176 loc) · 6.67 KB
/
WebContext.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
using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Web;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Numerics;
using System.Security.Cryptography;
using System.Text.Json;
namespace Maussoft.Mvc
{
public class WebContext<TSession> where TSession : new()
{
public string Method;
public string Url;
public string Controller;
public string Action;
public string View;
public string RedirectUrl;
public bool Sent;
public Dictionary<string, string> Post;
public CookieCollection Cookies;
public dynamic Data;
public string SessionIdentifier;
public TSession Session;
private int sessionHashCode;
private HttpListenerContext context;
private string sessionSavePath;
private FileStream sessionStream;
public WebContext(HttpListenerContext context, string sessionSavePath)
{
this.context = context;
this.sessionSavePath = sessionSavePath;
this.Method = this.context.Request.HttpMethod;
this.Url = this.context.Request.RawUrl;
this.Post = new Dictionary<string, string>();
this.ReadPostData();
this.Data = new ViewData();
this.RedirectUrl = null;
this.Sent = false;
}
private String CreateSessionIdentifier()
{
Byte[] data = RandomNumberGenerator.GetBytes(18);
return Convert.ToBase64String(data).Replace("/", "_").Replace("+", "-");
}
public void StartSession(Boolean readOnly)
{
Cookie cookie = this.context.Request.Cookies["Maussoft.Mvc"];
if (cookie == null)
{
SessionIdentifier = CreateSessionIdentifier();
string appName = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
string setCookieString = appName + "=" + SessionIdentifier + "; HttpOnly; SameSite=Lax";
if (!this.context.Request.IsLocal)
{
setCookieString += "; Secure";
}
this.context.Response.AddHeader("Set-Cookie", setCookieString);
}
else
{
SessionIdentifier = cookie.Value;
}
this.sessionStream = WaitForFile(this.sessionSavePath + SessionIdentifier, FileMode.OpenOrCreate, readOnly ? FileAccess.Read : FileAccess.ReadWrite, FileShare.Read);
if (this.sessionStream.Length == 0)
{
this.Session = new TSession();
var bytes = JsonSerializer.SerializeToUtf8Bytes<TSession>(Session);
sessionHashCode = ComputeHash(bytes);
}
else
{
byte[] bytes = new byte[this.sessionStream.Length];
this.sessionStream.Read(bytes, 0, bytes.Length);
this.Session = JsonSerializer.Deserialize<TSession>(bytes);
sessionHashCode = ComputeHash(bytes);
}
if (readOnly)
{
this.sessionStream.Close();
this.sessionStream = null;
}
}
private static int ComputeHash(params byte[] data)
{
return new BigInteger(data).GetHashCode();
}
public void WriteSession()
{
var bytes = JsonSerializer.SerializeToUtf8Bytes<TSession>(Session);
var newSessionHashCode = ComputeHash(bytes);
if (newSessionHashCode != this.sessionHashCode)
{
if (this.sessionStream != null)
{
this.sessionStream.SetLength(0);
this.sessionStream.Write(bytes, 0, bytes.Length);
this.sessionHashCode = newSessionHashCode;
}
else
{
throw new Exception("A '" + Method + "' on '" + Controller + "." + Action + "' shouldn't write to the session in the Controller");
}
}
if (this.sessionStream != null)
{
this.sessionStream.Close();
}
}
public void FinalizeSession()
{
var bytes = JsonSerializer.SerializeToUtf8Bytes<TSession>(Session);
var newSessionHashCode = ComputeHash(bytes);
if (newSessionHashCode != this.sessionHashCode)
{
throw new Exception("A '" + Method + "' on '" + Controller + "." + Action + "' shouldn't write to the session in the View '" + View + "'");
}
}
FileStream WaitForFile(string fullPath, FileMode mode, FileAccess access, FileShare share)
{
for (int numTries = 0; numTries < 3000; numTries++)
{
try
{
FileStream fs = new FileStream(fullPath, mode, access, share);
fs.ReadByte();
fs.Seek(0, SeekOrigin.Begin);
return fs;
}
catch (IOException)
{
Thread.Sleep(100);
}
}
return null;
}
public void Redirect(string url)
{
this.RedirectUrl = url;
}
private void ReadPostData()
{
HttpListenerRequest request = this.context.Request;
if (request.HasEntityBody)
{
StreamReader reader = new StreamReader(request.InputStream, request.ContentEncoding);
NameValueCollection rawParams = HttpUtility.ParseQueryString(reader.ReadToEnd());
foreach (string key in rawParams.AllKeys)
{
string value = rawParams[key];
Post.Add(key, value);
}
}
}
internal void SendString(string output, string mimeType = "text/html", int StatusCode = 200)
{
if (this.Sent)
{
throw new Exception("Output has already been sent");
}
if (RedirectUrl != null)
{
this.context.Response.StatusCode = 302;
this.context.Response.AddHeader("Location", RedirectUrl);
return;
}
if (StatusCode != 200) this.context.Response.StatusCode = StatusCode;
byte[] buf = System.Text.Encoding.UTF8.GetBytes(output);
this.context.Response.ContentLength64 = buf.Length;
this.context.Response.OutputStream.Write(buf, 0, buf.Length);
this.Sent = true;
}
}
}