-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathExtensions.Session.cs
More file actions
360 lines (336 loc) · 15.3 KB
/
Extensions.Session.cs
File metadata and controls
360 lines (336 loc) · 15.3 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
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
#region Related components
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using net.vieapps.Components.Security;
using net.vieapps.Components.Utility;
#endregion
namespace net.vieapps.Services
{
public static partial class Extensions
{
#region Location
/// <summary>
/// Gets the current location (IP-based)
/// </summary>
public static string CurrentLocation { get; private set; } = "Unknown";
/// <summary>
/// Gets the location of the session (IP-based)
/// </summary>
/// <param name="session"></param>
/// <param name="ipAddress"></param>
/// <param name="correlationID"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static async Task<string> GetLocationAsync(this Session session, string ipAddress, string correlationID, CancellationToken cancellationToken)
{
correlationID = correlationID ?? UtilityService.NewUUID;
var location = "Unknown";
try
{
var service = Router.GetService("IPLocations");
var requestInfo = new RequestInfo(session, "IPLocations")
{
Header = new Dictionary<string, string> { ["x-requester"] = "vieapps-ngx-base" },
CorrelationID = correlationID
};
if (!string.IsNullOrWhiteSpace(ipAddress))
requestInfo.Query["IP"] = ipAddress;
var response = await service.ProcessRequestAsync(requestInfo, cancellationToken).ConfigureAwait(false);
var city = response.Get("City", "N/A");
var region = response.Get("Region", "N/A");
if (region.Equals(city) && !"N/A".IsEquals(city))
region = "";
var country = response.Get("Country", "N/A");
if ("N/A".IsEquals(city) && "N/A".IsEquals(region) && "N/A".IsEquals(country) && "Unknown".IsEquals(Extensions.CurrentLocation))
{
response = await service.ProcessRequestAsync(new RequestInfo(requestInfo) { ObjectName = "Current" }, cancellationToken).ConfigureAwait(false);
city = response.Get("City", "N/A");
region = response.Get("Region", "N/A");
if (region.Equals(city) && !"N/A".IsEquals(city))
region = "";
country = response.Get("Country", "N/A");
location = Extensions.CurrentLocation = $"{city}, {region}, {country}".Replace(", ,", ",");
}
else
location = $"{city}, {region}, {country}".Replace(", ,", ",");
}
catch { }
return location;
}
/// <summary>
/// Gets the location of the session (IP-based)
/// </summary>
/// <param name="session"></param>
/// <param name="correlationID"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task<string> GetLocationAsync(this Session session, string correlationID = null, CancellationToken cancellationToken = default)
=> session == null
? Task.FromResult("Unknown")
: session.GetLocationAsync(null, correlationID, cancellationToken);
/// <summary>
/// Gets the location of the request (IP-based)
/// </summary>
/// <param name="requestInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task<string> GetLocationAsync(this RequestInfo requestInfo, CancellationToken cancellationToken = default)
=> requestInfo.Session == null
? Task.FromResult("Unknown")
: requestInfo.Session.GetLocationAsync(null, requestInfo.CorrelationID, cancellationToken);
#endregion
#region Get encryption keys
/// <summary>
/// Gest a key for encrypting/decrypting data with this session
/// </summary>
/// <param name="session"></param>
/// <param name="seeds">The seeds for hashing</param>
/// <returns></returns>
public static byte[] GetEncryptionKey(this Session session, byte[] seeds = null)
=> session.SessionID.GetHMACHash(seeds ?? CryptoService.DEFAULT_PASS_PHRASE.ToBytes(), "SHA512").GenerateHashKey(256);
/// <summary>
/// Gest a key for encrypting/decrypting data with this session
/// </summary>
/// <param name="session"></param>
/// <param name="seeds">The seeds for hashing</param>
/// <returns></returns>
public static byte[] GetEncryptionKey(this Session session, string seeds)
=> session.GetEncryptionKey(seeds?.ToBytes());
/// <summary>
/// Gest an initialize vector for encrypting/decrypting data with this session
/// </summary>
/// <param name="session"></param>
/// <param name="seeds">The seeds for hashing</param>
/// <returns></returns>
public static byte[] GetEncryptionIV(this Session session, byte[] seeds = null)
=> session.SessionID.GetHMACHash(seeds ?? CryptoService.DEFAULT_PASS_PHRASE.ToBytes(), "SHA256").GenerateHashKey(128);
/// <summary>
/// Gest an initialize vector for encrypting/decrypting data with this session
/// </summary>
/// <param name="session"></param>
/// <param name="seeds">The seeds for hashing</param>
/// <returns></returns>
public static byte[] GetEncryptionIV(this Session session, string seeds)
=> session.GetEncryptionIV(seeds?.ToBytes());
/// <summary>
/// Encrypts the identity (hexa-string)
/// </summary>
/// <param name="session"></param>
/// <param name="id">The identity (hexa-string)</param>
/// <param name="keySeeds">The seeds for generating key</param>
/// <param name="ivSeeds">The seeds for generating initialize vector</param>
/// <returns></returns>
public static string GetEncryptedID(this Session session, string id, string keySeeds = null, string ivSeeds = null)
=> !string.IsNullOrWhiteSpace(id)
? id.HexToBytes().Encrypt(session.GetEncryptionKey(keySeeds?.ToBytes()), session.GetEncryptionIV(ivSeeds?.ToBytes())).ToHex()
: null;
/// <summary>
/// Decrypts the identity (hexa-string)
/// </summary>
/// <param name="session"></param>
/// <param name="id">The identity (hexa-string)</param>
/// <param name="keySeeds">The seeds for generating key</param>
/// <param name="ivSeeds">The seeds for generating initialize vector</param>
/// <returns></returns>
public static string GetDecryptedID(this Session session, string id, string keySeeds = null, string ivSeeds = null)
=> !string.IsNullOrWhiteSpace(id)
? id.HexToBytes().Decrypt(session.GetEncryptionKey(keySeeds?.ToBytes()), session.GetEncryptionIV(ivSeeds?.ToBytes())).ToHex()
: null;
#endregion
#region Check is system administrator/account
/// <summary>
/// Calls the Users service to check this user is system administrator or not
/// </summary>
/// <param name="user"></param>
/// <param name="correlationID"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static async Task<bool> IsSystemAdministratorAsync(this IUser user, string correlationID = null, CancellationToken cancellationToken = default)
{
if (user == null || !user.IsAuthenticated)
return false;
var isSystemAdministrator = user.IsSystemAdministrator;
if (!isSystemAdministrator)
{
var requestInfo = new RequestInfo(new Session { User = new User(user) }, "Users", "Account", "GET")
{
Extra = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { ["IsSystemAdministrator"] = "" },
CorrelationID = correlationID
};
var response = await requestInfo.CallServiceAsync(cancellationToken).ConfigureAwait(false);
isSystemAdministrator = user.ID.IsEquals(response.Get<string>("ID")) && response.Get<bool>("IsSystemAdministrator");
}
return isSystemAdministrator;
}
/// <summary>
/// Calls the Users service to check this user is system administrator or not
/// </summary>
/// <param name="session"></param>
/// <param name="correlationID"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task<bool> IsSystemAdministratorAsync(this Session session, string correlationID = null, CancellationToken cancellationToken = default)
=> session == null || session.User == null
? Task.FromResult(false)
: session.User.IsSystemAdministratorAsync(correlationID, cancellationToken);
/// <summary>
/// Calls the Users service to check this user is system administrator or not
/// </summary>
/// <param name="requestInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task<bool> IsSystemAdministratorAsync(this RequestInfo requestInfo, CancellationToken cancellationToken = default)
=> requestInfo == null || requestInfo.Session == null || requestInfo.Session.User == null
? Task.FromResult(false)
: requestInfo.Session.User.IsSystemAdministratorAsync(requestInfo.CorrelationID, cancellationToken);
#endregion
#region Send session state
/// <summary>
/// Sends session state
/// </summary>
/// <param name="session"></param>
/// <param name="serviceName"></param>
/// <param name="serviceURI"></param>
/// <param name="serviceSystemID"></param>
/// <param name="online"></param>
/// <param name="trackStatistics"></param>
/// <param name="sendClientMessage"></param>
/// <param name="onCommunicateMessagePrepared"></param>
/// <param name="onUpdateMessagePrepared"></param>
/// <param name="correlationID"></param>
/// <returns></returns>
public static async Task<Session> SendSessionStateAsync(this Session session, string serviceName, string serviceURI, string serviceSystemID, bool online, bool trackStatistics, bool sendClientMessage, Action<CommunicateMessage> onCommunicateMessagePrepared = null, Action<UpdateMessage> onUpdateMessagePrepared = null, string correlationID = null)
{
var communicateMessage = new CommunicateMessage("Users")
{
Type = "Session#State",
Data = session.ToJson(json =>
{
json["SessionID"] = session.SessionID;
json["DeviceID"] = session.DeviceID;
json["UserID"] = session.User?.ID;
json["Online"] = online;
json["Track"] = online && trackStatistics;
json["AppInfo"] = $"{session.AppName} @ {session.AppPlatform}";
json["OSInfo"] = $"{Extensions.GetOSInfo(session.AppAgent)} [{session.AppAgent}]";
})
};
if (!string.IsNullOrWhiteSpace(serviceName) && !string.IsNullOrWhiteSpace(serviceURI))
communicateMessage.Data["Service"] = new JObject
{
["Name"] = serviceName.ToLower(),
["URI"] = serviceURI,
["SystemID"] = string.IsNullOrWhiteSpace(serviceSystemID) ? null : serviceSystemID
};
if (!string.IsNullOrWhiteSpace(correlationID))
communicateMessage.Data["CorrelationID"] = correlationID;
onCommunicateMessagePrepared?.Invoke(communicateMessage);
communicateMessage.Send(Router.GotBackupRouter());
if (sendClientMessage && !string.IsNullOrWhiteSpace(session.User.ID))
{
var updateMessage = new UpdateMessage
{
Type = "Users#Session#State",
DeviceID = "*",
Data = new JObject
{
["SessionID"] = session.GetEncryptedID(session.SessionID),
["UserID"] = session.User.ID,
["DeviceID"] = session.DeviceID,
["IsOnline"] = online,
["Location"] = await session.GetLocationAsync().ConfigureAwait(false),
["AppName"] = session.AppName,
["AppPlatform"] = session.AppPlatform
}
};
onUpdateMessagePrepared?.Invoke(updateMessage);
updateMessage.Send();
}
return session;
}
/// <summary>
/// Sends session state
/// </summary>
/// <param name="session"></param>
/// <param name="serviceName"></param>
/// <param name="serviceURI"></param>
/// <param name="serviceSystemID"></param>
/// <param name="online"></param>
/// <param name="trackStatistics"></param>
/// <param name="sendClientMessage"></param>
/// <param name="onCommunicateMessagePrepared"></param>
/// <param name="onUpdateMessagePrepared"></param>
/// <param name="correlationID"></param>
public static void SendSessionState(this Session session, string serviceName, string serviceURI, string serviceSystemID, bool online, bool trackStatistics, bool sendClientMessage, Action<CommunicateMessage> onCommunicateMessagePrepared = null, Action<UpdateMessage> onUpdateMessagePrepared = null, string correlationID = null)
=> session.SendSessionStateAsync(serviceName, serviceURI, serviceSystemID, online, trackStatistics, sendClientMessage, onCommunicateMessagePrepared, onUpdateMessagePrepared, correlationID).Execute();
/// <summary>
/// Sends session state
/// </summary>
/// <param name="session"></param>
/// <param name="serviceName"></param>
/// <param name="serviceURI"></param>
/// <param name="online"></param>
/// <param name="trackStatistics"></param>
/// <param name="sendClientMessage"></param>
/// <param name="onCommunicateMessagePrepared"></param>
/// <param name="onUpdateMessagePrepared"></param>
/// <param name="correlationID"></param>
public static void SendSessionState(this Session session, string serviceName, string serviceURI, bool online = true, bool trackStatistics = true, bool sendClientMessage = false, Action<CommunicateMessage> onCommunicateMessagePrepared = null, Action<UpdateMessage> onUpdateMessagePrepared = null, string correlationID = null)
=> session.SendSessionState(serviceName, serviceURI, null, online, trackStatistics, sendClientMessage, onCommunicateMessagePrepared, onUpdateMessagePrepared, correlationID);
/// <summary>
/// Sends tracking statistics
/// </summary>
/// <param name="session"></param>
public static void TrackStatistics(this Session session, string correlationID)
=> new CommunicateMessage("Users")
{
Type = "Statistics#Track",
Data = new JObject
{
["SessionID"] = session?.SessionID,
["UserID"] = session?.User?.ID,
["CorrelationID"] = correlationID
}
}.Send(Router.GotBackupRouter());
#endregion
#region Connection info
/// <summary>
/// Prepares connection information of the session
/// </summary>
/// <param name="session"></param>
/// <param name="correlationID"></param>
/// <param name="cancellationToken"></param>
/// <param name="logger"></param>
/// <returns></returns>
public static async Task<(string Account, string Location)> PrepareConnectionInfoAsync(this Session session, string correlationID = null, CancellationToken cancellationToken = default, Microsoft.Extensions.Logging.ILogger logger = null)
{
correlationID = correlationID ?? UtilityService.NewUUID;
var account = "Visitor";
if (!string.IsNullOrWhiteSpace(session?.User?.ID))
try
{
var json = await Router.GetService("Users").ProcessRequestAsync(new RequestInfo(session, "Users", "Profile", "GET") { CorrelationID = correlationID }, cancellationToken).ConfigureAwait(false);
account = $"{json?.Get<string>("Name") ?? "Unknown"} ({session.User.ID})";
}
catch (Exception ex)
{
account = $"Unknown ({session.User.ID})";
logger?.LogError($"Error occurred while fetching an account profile => {ex.Message}", ex);
}
return (account, (session != null ? await session.GetLocationAsync(correlationID, cancellationToken).ConfigureAwait(false) : null) ?? "Unknown");
}
/// <summary>
/// Gets the information of the connection
/// </summary>
/// <param name="session"></param>
/// <returns></returns>
public static string GetConnectionInfo(this Session session, Dictionary<string, string> headers = null)
=> $"- Session ID: {session?.SessionID ?? "Unknown"} - Device ID: {session?.DeviceID ?? "Unknown"} - Origin: {(headers != null && headers.TryGetValue("Origin", out var origin) ? origin : session?.AppOrigin ?? "Unknown")}" + "\r\n" +
$"- App: {session?.AppName ?? "Unknown"} @ {session?.AppPlatform ?? "Unknown"} [{session?.AppAgent ?? "Unknown"}]" + "\r\n" +
$"- Connection IP: {session?.IP ?? "Unknown"}";
#endregion
}
}