From e4ce006b069c0b75c9859bca9edf11be4c44b80e Mon Sep 17 00:00:00 2001 From: lukeIam Date: Tue, 30 Dec 2014 11:22:34 +0100 Subject: [PATCH] [Server] Invalidate session after a timeout --- ServerLib/CWebservice.cs | 2 ++ ServerLib/Session.cs | 8 ++++++++ ServerLib/SessionControl.cs | 34 +++++++++++++++++++++++++++++++++- 3 files changed, 43 insertions(+), 1 deletion(-) diff --git a/ServerLib/CWebservice.cs b/ServerLib/CWebservice.cs index abefcf53..1dbb6430 100644 --- a/ServerLib/CWebservice.cs +++ b/ServerLib/CWebservice.cs @@ -39,6 +39,7 @@ namespace ServerLib } catch (Exception) { } + CSessionControl.ResetSessionTimeout(sessionKey); return sessionKey; } @@ -296,6 +297,7 @@ namespace ServerLib public bool IsServerOnline() { + _GetSession(); return true; } #endregion diff --git a/ServerLib/Session.cs b/ServerLib/Session.cs index ad0f612f..416b34c9 100644 --- a/ServerLib/Session.cs +++ b/ServerLib/Session.cs @@ -38,12 +38,20 @@ namespace ServerLib { get { return _Roles; } } + + private DateTime _LastSeen; + public DateTime LastSeen + { + get { return _LastSeen; } + internal set { _LastSeen = value; } + } public CSession(Guid id, int profileId, EUserRoles roles) { _ID = id; _ProfileId = profileId; _Roles = roles; + _LastSeen = DateTime.Now; } } } \ No newline at end of file diff --git a/ServerLib/SessionControl.cs b/ServerLib/SessionControl.cs index d16f50a5..0fc80117 100644 --- a/ServerLib/SessionControl.cs +++ b/ServerLib/SessionControl.cs @@ -18,12 +18,35 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Timers; namespace ServerLib { static class CSessionControl { - private static readonly Dictionary _ActiveSessions = new Dictionary(); + private static readonly Dictionary _ActiveSessions; + private const int _UserTimeoutCheckIntervall = 120000; + private const int _UserTimeout = 120000; + + static CSessionControl() + { + _ActiveSessions = new Dictionary(); + Timer timer = new Timer(_UserTimeoutCheckIntervall) {AutoReset = true, Enabled = true}; + timer.Elapsed += _CheckForUserTimeouts; + timer.Start(); + } + + private static void _CheckForUserTimeouts(object sender, ElapsedEventArgs e) + { + var sessionIdsToRemove = _ActiveSessions.Where(pair => (DateTime.Now-pair.Value.LastSeen).TotalMilliseconds > _UserTimeout) + .Select(pair => pair.Key) + .ToList(); + + foreach (var sessionToRemove in sessionIdsToRemove) + { + InvalidateSessions(sessionToRemove); + } + } public static Guid OpenSession(string userName, string password) { @@ -83,5 +106,14 @@ namespace ServerLib return -1; return _ActiveSessions[sessionId].ProfileId; } + + internal static void ResetSessionTimeout(Guid sessionId) + { + CSession value; + if (_ActiveSessions.TryGetValue(sessionId, out value)) + { + value.LastSeen = DateTime.Now; + } + } } } \ No newline at end of file