Skip to content

Commit f19b41b

Browse files
committed
Add the information for the session begin and end
1 parent a9d1cc3 commit f19b41b

2 files changed

Lines changed: 59 additions & 9 deletions

File tree

API.Test/AuthentificationTests.cs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,13 @@ public void Authentification()
4545
}
4646
Assert.Pass();
4747
}
48+
49+
[Test]
50+
public void GetSessionExpiresDateTime()
51+
{
52+
using WebUntisClient client = new("WebUntisAPI_TEST", TimeSpan.FromSeconds(5));
53+
client.LoginAsync(s_Server, s_LoginName, s_UserName, s_Password).Wait();
54+
_ = client.SessionExpires;
55+
_ = client.SessionBegin;
56+
}
4857
}

WebUntisAPI.Client/WebUntisClient.cs

Lines changed: 50 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,49 @@ public partial class WebUntisClient : IDisposable
2828
/// </summary>
2929
public string ClientName { get; }
3030

31+
/// <summary>
32+
/// The dateTime where the current session expires
33+
/// </summary>
34+
/// <remarks>
35+
/// You can refresh the session with <see cref="ReloadSessionAsync(CancellationToken)"/>
36+
/// </remarks>
37+
public DateTime SessionExpires
38+
{
39+
get
40+
{
41+
if (_disposedValue)
42+
throw new ObjectDisposedException(GetType().FullName);
43+
44+
if (!LoggedIn)
45+
throw new UnauthorizedAccessException("You're not logged in!");
46+
47+
string tokenString = _bearerToken.Split('.')[1]; // Get the JWT part
48+
49+
JObject token = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(tokenString)));
50+
return new DateTime(1970, 01, 01, 0, 0, 0, DateTimeKind.Utc).AddSeconds(token["exp"].Value<long>());
51+
}
52+
}
53+
54+
/// <summary>
55+
/// The date Time off beginning of the current session
56+
/// </summary>
57+
public DateTime SessionBegin
58+
{
59+
get
60+
{
61+
if (_disposedValue)
62+
throw new ObjectDisposedException(GetType().FullName);
63+
64+
if (!LoggedIn)
65+
throw new UnauthorizedAccessException("You're not logged in!");
66+
67+
string tokenString = _bearerToken.Split('.')[1]; // Get the JWT part
68+
69+
JObject token = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(tokenString)));
70+
return new DateTime(1970, 01, 01, 0, 0, 0, DateTimeKind.Utc).AddSeconds(token["iat"].Value<long>());
71+
}
72+
}
73+
3174
/// <summary>
3275
/// <see langword="true"/> when the client is currently logged in
3376
/// </summary>
@@ -195,7 +238,7 @@ public async Task<bool> LoginAsync(string server, string loginName, string usern
195238
_loggedIn = true;
196239

197240
// Get the api auth token and the logged in user
198-
Task<string> bearerTokenTask = GetBearerTokenAsync(ct);
241+
Task bearerTokenTask = ReloadSessionAsync(ct);
199242
IUser[] users;
200243
if ((UserType)responseObject["result"]["personType"].ToObject<int>() == Client.UserType.Student) // For student and teacher separate tasks
201244
{
@@ -216,8 +259,6 @@ public async Task<bool> LoginAsync(string server, string loginName, string usern
216259
return false;
217260
}
218261

219-
_bearerToken = bearerTokenTask.Result;
220-
221262
_userType = (UserType)responseObject["result"]["personType"].ToObject<int>();
222263
_user = users.FirstOrDefault(user => user.Id == responseObject["result"]["personId"].ToObject<int>());
223264

@@ -373,7 +414,7 @@ private async Task<JToken> MakeJSONRPCRequestAsync(string id, string methodName,
373414
/// Make a GET request to the API
374415
/// </summary>
375416
/// <param name="requestUrl">Url to request</param>
376-
/// <param name="ct">Cnacellation token</param>
417+
/// <param name="ct">Cancelation token</param>
377418
/// <returns>The returned content</returns>
378419
/// <exception cref="ObjectDisposedException">Thrown when the instance was disposed</exception>
379420
/// <exception cref="UnauthorizedAccessException">Thrown when the client isn't logged in</exception>
@@ -417,12 +458,11 @@ internal async Task<string> MakeAPIGetRequestAsync(string requestUrl, Cancellati
417458
}
418459

419460
/// <summary>
420-
/// Get the bearer auth token for the api authentication
461+
/// Refresh the session
421462
/// </summary>
422463
/// <param name="ct">Cancellation token</param>
423-
/// <returns>The bearer token</returns>
424464
/// <exception cref="HttpRequestException">Thrown when an error happend while the http request</exception>
425-
private async Task<string> GetBearerTokenAsync(CancellationToken ct)
465+
public async Task ReloadSessionAsync(CancellationToken ct = default)
426466
{
427467
HttpRequestMessage request = new HttpRequestMessage()
428468
{
@@ -436,13 +476,14 @@ private async Task<string> GetBearerTokenAsync(CancellationToken ct)
436476

437477
// Check cancellation token
438478
if (ct.IsCancellationRequested)
439-
return default;
479+
return;
440480

441481
// Verify response
442482
if (response.StatusCode != HttpStatusCode.OK)
443483
throw new HttpRequestException($"There was an error while the http request (Code: {response.StatusCode}).");
444484

445-
return await response.Content.ReadAsStringAsync();
485+
486+
_bearerToken = await response.Content.ReadAsStringAsync();
446487
}
447488

448489
#region IDisposable

0 commit comments

Comments
 (0)