-
Notifications
You must be signed in to change notification settings - Fork 0
/
UserSession.cs
315 lines (267 loc) · 11.6 KB
/
UserSession.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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Microsoft.VisualBasic;
using System.IdentityModel.Tokens.Jwt; // Add this directive for JWT token
using System.Text; // Add this directive for Encoding
using GeFeSLE;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Primitives;
public static class UserSessionService
{
// public static void ConfigureServices(IServiceCollection services)
// {
// services.AddSingleton<UserSessionService>();
// // Other service registrations...
// }
public static GeFeSLEUser? UpdateSessionAccessTime(HttpContext context,
GeFeSLEDb db,
UserManager<GeFeSLEUser> userManager)
{
var sessionUser = amILoggedIn(context);
if (sessionUser.IsAuthenticated)
{
GeFeSLEUser? user = userManager.FindByIdAsync(sessionUser.Id).Result;
if (user != null)
{
user.LastAccessTime = DateTime.UtcNow;
_ = db.SaveChangesAsync();
// var roles = userManager.GetRolesAsync(user).Result; //TODO: use role from DTo not this
// string realizedRole = GlobalStatic.FindHighestRole(roles);
DBg.d(LogLevel.Debug, $"User {sessionUser.UserName} [{sessionUser.Role}] TO {context.Request.Path} FROM {context.Connection.RemoteIpAddress}");
return user;
} // user in db
else
{
// could be an anonymous OAuth user - someone who has logged in via an OAuth source
// but they're not in our database (i.e. have been invited/added by a legit usesr)
DBg.d(LogLevel.Debug, $"User {sessionUser.UserName} (OAuth guest) [{sessionUser.Role}] to {context.Request.Path} from {context.Connection.RemoteIpAddress}");
return null;
} // user NOT in db.
}
else // not authenticated
{
DBg.d(LogLevel.Debug, $"Anonymous access TO {context.Request.Path} FROM {context.Connection.RemoteIpAddress}");
return null;
}
}
public static string createJWToken(string userid, string username, string role)
{
DBg.d(LogLevel.Trace, $"{userid ?? "no userid"} // {username ?? "no username"} / {role ?? "no role"}");
// create a claims identity
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, userid), //TODO: change to email (or add email as a claim
new Claim(ClaimTypes.Name, username),
new Claim(ClaimTypes.Role, role)
};
var claimsIdentity = new ClaimsIdentity(claims, "jwt");
var principal = new ClaimsPrincipal(claimsIdentity);
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes(GlobalConfig.apiTokenSecretKey!);
DBg.d(LogLevel.Trace, "Token Create Time: " + DateTime.UtcNow.ToString());
var expiretime = DateTime.UtcNow.Add(GlobalConfig.apiTokenDuration);
DBg.d(LogLevel.Trace, "Token Expires: " + expiretime.ToString());
string bearerRealm = $"{GlobalConfig.Hostname}";
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = principal.Identity as ClaimsIdentity,
Expires = expiretime,
Audience = bearerRealm,
Issuer = bearerRealm,
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
return tokenString;
}
public static void storeProvider(HttpContext httpContext, string provider)
{
DBg.d(LogLevel.Trace, provider);
httpContext.Session.SetString("provider", provider);
}
public static string? getProvider(HttpContext httpContext)
{
DBg.d(LogLevel.Trace, null);
return httpContext.Session.GetString("provider");
}
public static void createSession(HttpContext httpContext, string userid, string username, string role)
{
DBg.d(LogLevel.Trace, null);
// create a claims identity
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, userid),
new Claim(ClaimTypes.Name, username),
new Claim(ClaimTypes.Role, role)
};
DBg.d(LogLevel.Trace, "createSession: " + username + " [" + role + "]");
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
// create the auth properties
var authProperties = new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30)
};
// sign in the user
httpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
}
// a method that takes username and an OAuth2AccessTokenResponse and stores it in the user session
public static void AddAccessToken(HttpContext context, string provider, string accessToken)
{
DBg.d(LogLevel.Trace, null);
if (provider == null || accessToken == null)
{
DBg.d(LogLevel.Error, "AddAccessTokenResponse: provider or accessToken is null");
return;
}
else
{
context.Session.SetString(provider, accessToken);
}
}
// a method that takes username and provider and returns the OAuth2AccessTokenResponse
public static string? GetAccessToken(HttpContext context, string provider)
{
DBg.d(LogLevel.Trace, null);
if (provider == null)
{
DBg.d(LogLevel.Error, "Provider is null");
return null;
}
else
{
string? token = context.Session.GetString(provider);
if (token == null)
{
DBg.d(LogLevel.Error, "No token found for provider: " + provider);
return null; // Add null check here
}
return token;
}
}
public static async Task<GeFeSLEUser?> mapUserNameToDBUser(string username,
UserManager<GeFeSLEUser> userManager)
{
DBg.d(LogLevel.Trace, null);
if (username == null)
{
DBg.d(LogLevel.Trace, $"Null username");
return null;
}
else
{
// FindByNameAsync uses the NORMALIZED (uppercase) username, so we want to
// uppercase it
username = username.ToUpper();
GeFeSLEUser? user = await userManager.FindByNameAsync(username);
if (user == null)
{
DBg.d(LogLevel.Debug, $"Username {username} does NOT exist in the Database!");
return null;
}
else
{
DBg.d(LogLevel.Debug, $"Username {user.UserName} does exist in the Database!");
return user;
}
}
}
// This function is the sole arbiter of "what does 'logged in' mean?"
// A logged in user session for our purposes has a username, is authenticated, and has a role in the claims.
// Returns a tuple of username, isAuthenticated and first/default role claims
// TODO: should unpack/investigate ALL claims, not just the first one.
// TODO: handle missing context.User/Identity gracefully
// TODO: in all uses, see if we check for username == null and isAuthenticated == false; if so,
// can we even have .isAuthenticated with a non-nul username? i.e. can we just check isAuthenticated?
public static UserDto amILoggedIn(HttpContext context)
{
UserDto sessionUser = new UserDto();
//GlobalStatic.dumpRequest(httpContext);
sessionUser.Id = context.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
sessionUser.UserName = context.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
sessionUser.IsAuthenticated = context.User.Identity?.IsAuthenticated ?? false;
sessionUser.Role = context.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role)?.Value;
return sessionUser;
}
public static string dumpClaims(HttpContext context) {
string? Id = context.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
string? UserName = context.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
bool IsAuthenticated = context.User.Identity?.IsAuthenticated ?? false;
//DBg.d(LogLevel.Trace, $"{fn} isAuthenticated: {isAuthenticated}");
string? Role = context.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role)?.Value;
return $"id:{Id ?? "no userid"} / username:{UserName ?? "no username"} / role:{Role ?? "no role"} / isauth: {IsAuthenticated}";
}
public static async Task<string?> dumpSession(HttpContext context)
{
var fn = "dumpSession"; DBg.d(LogLevel.Trace, fn);
IdentityUser? user = context.User?.Identity as IdentityUser;
var claims = context.User?.Claims.Select(c => new { c.Type, c.Value });
var cookies = context.Request.Headers["Cookie"].ToString();
var prettyCookies = PrettifyCookieHeader(cookies);
context.Request.Headers["Cookie"] = "have been prettified - see below";
// also get the session data:
var sessionData = new Dictionary<string, string>();
foreach (var key in context.Session.Keys)
{
sessionData[key] = context.Session.GetString(key);
}
var serializableContext = new
{
Request = new
{
context.Request.Method,
context.Request.Scheme,
context.Request.Host,
context.Request.Path,
context.Request.QueryString,
context.Request.Headers,
context.Request.ContentType,
context.Request.ContentLength,
context.Request.Protocol
},
Response = new
{
context.Response.StatusCode,
Headers = context.Response.Headers.ToDictionary(h => h.Key, h => h.Value.ToString())
},
User = new
{
user,
claims
},
context.TraceIdentifier,
context.Connection.Id,
prettyCookies,
Session = sessionData
};
var session = JsonConvert.SerializeObject(serializableContext, new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
Formatting = Formatting.Indented
});
//DBg.d(LogLevel.Trace, $"{fn}: {session}");
return session;
}
private static List<KeyValuePair<string, string>> PrettifyCookieHeader(string cookieHeader)
{
var cookies = cookieHeader.Split(";", StringSplitOptions.RemoveEmptyEntries);
var prettyCookies = new List<KeyValuePair<string, string>>();
foreach (var cookie in cookies)
{
// split it into name and value
var parts = cookie.Split("=", StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 2)
{
prettyCookies.Add(new KeyValuePair<string, string>(parts[0].Trim(), parts[1].Trim()));
}
}
return prettyCookies;
}
}