diff options
author | Tim <contact@bytim.eu> | 2025-04-23 15:15:37 +0200 |
---|---|---|
committer | Tim <contact@bytim.eu> | 2025-04-23 15:15:37 +0200 |
commit | 97e7960f494bd56daaa52b39a72d57c76331d485 (patch) | |
tree | 89ed6e41b0b029f95dc667097952c3701086a55f /VPNAuth.Server | |
parent | a3fd9ff79a98259590b7004fd1bbe79be7ff8e83 (diff) | |
download | VPNAuth-97e7960f494bd56daaa52b39a72d57c76331d485.tar.xz VPNAuth-97e7960f494bd56daaa52b39a72d57c76331d485.zip |
Add garbage collector and delete auth request on auth code exchange
Diffstat (limited to 'VPNAuth.Server')
-rw-r--r-- | VPNAuth.Server/Api/OAuth2.cs | 2 | ||||
-rw-r--r-- | VPNAuth.Server/Database/GarbageCollector.cs | 52 | ||||
-rw-r--r-- | VPNAuth.Server/Program.cs | 1 |
3 files changed, 55 insertions, 0 deletions
diff --git a/VPNAuth.Server/Api/OAuth2.cs b/VPNAuth.Server/Api/OAuth2.cs index 63dc115..66799e7 100644 --- a/VPNAuth.Server/Api/OAuth2.cs +++ b/VPNAuth.Server/Api/OAuth2.cs @@ -95,6 +95,8 @@ public static class OAuth2 Token = PkceUtils.GenerateToken(), Username = authRequest.Username }); + + db.AuthRequests.Remove(authRequest); db.SaveChanges(); await context.Response.WriteAsJsonAsync(new Token diff --git a/VPNAuth.Server/Database/GarbageCollector.cs b/VPNAuth.Server/Database/GarbageCollector.cs new file mode 100644 index 0000000..c15f5a6 --- /dev/null +++ b/VPNAuth.Server/Database/GarbageCollector.cs @@ -0,0 +1,52 @@ +namespace VPNAuth.Server.Database; + +public static class GarbageCollector +{ + private static void CollectAuthRequests(Database db) + { + foreach (var authRequest in db.AuthRequests) + { + if ((DateTime.Now - authRequest.InitTime).TotalMinutes >= 5) + db.AuthRequests.Remove(authRequest); + } + } + + private static void CollectTokens(Database db) + { + foreach (var accessToken in db.AccessTokens) + { + if ((DateTime.Now - accessToken.CreationTime).TotalDays >= 7) + db.AccessTokens.Remove(accessToken); + } + } + + private static void CollectUserInformation(Database db) + { + Config config = Config.Read(); + foreach (var dbUser in db.UserInformation) + { + if (config.Users!.All(configUser => configUser.Username != dbUser.Sub)) + db.UserInformation.Remove(dbUser); + } + } + + public static void StartLoop() + { + while (true) + { + using (var db = new Database()) + { + CollectAuthRequests(db); + CollectTokens(db); + CollectUserInformation(db); + + db.SaveChanges(); + } + + Task.Delay(60000).Wait(); // Wait 1 minute + } + } + + public static void StartLoopAsync() + => new Task(StartLoop).Start(); +} diff --git a/VPNAuth.Server/Program.cs b/VPNAuth.Server/Program.cs index b52abd8..e8e5d4f 100644 --- a/VPNAuth.Server/Program.cs +++ b/VPNAuth.Server/Program.cs @@ -7,6 +7,7 @@ using VPNAuth.Server.Database; using VPNAuth.Server.Responses; Config.CreateIfNotExists(); +GarbageCollector.StartLoopAsync(); var builder = WebApplication.CreateBuilder(args); |