summary refs log tree commit diff
path: root/ModAS.Server/Services/AuthenticatedHomeserverProviderService.cs
diff options
context:
space:
mode:
Diffstat (limited to 'ModAS.Server/Services/AuthenticatedHomeserverProviderService.cs')
-rw-r--r--ModAS.Server/Services/AuthenticatedHomeserverProviderService.cs47
1 files changed, 47 insertions, 0 deletions
diff --git a/ModAS.Server/Services/AuthenticatedHomeserverProviderService.cs b/ModAS.Server/Services/AuthenticatedHomeserverProviderService.cs
new file mode 100644
index 0000000..fa8e00a
--- /dev/null
+++ b/ModAS.Server/Services/AuthenticatedHomeserverProviderService.cs
@@ -0,0 +1,47 @@
+using ArcaneLibs.Extensions;
+using LibMatrix;
+using LibMatrix.Homeservers;
+using LibMatrix.Services;
+using MxApiExtensions.Services;
+
+namespace ModAS.Server.Services;
+
+public class AuthenticatedHomeserverProviderService(
+    AuthenticationService authenticationService,
+    HomeserverProviderService homeserverProviderService,
+    IHttpContextAccessor request,
+    ModASConfiguration config,
+    AppServiceRegistration asRegistration
+    ) {
+    public HttpContext? _context = request.HttpContext;
+    public Dictionary<string, AuthenticatedHomeserverGeneric> KnownUsers { get; set; } = new();
+
+    public async Task<AuthenticatedHomeserverGeneric> GetImpersonatedHomeserver(string mxid) {
+        if (KnownUsers.TryGetValue(mxid, out var homeserver)) return homeserver;
+        var hs = await homeserverProviderService.GetAuthenticatedWithToken(config.ServerName, asRegistration.AsToken, config.HomeserverUrl);
+        await hs.SetImpersonate(mxid);
+        KnownUsers.TryAdd(mxid, hs);
+        return hs;
+    }
+    
+    public async Task<AuthenticatedHomeserverGeneric> GetHomeserver() {
+        var token = authenticationService.GetToken();
+        if (token == null) {
+            throw new MatrixException {
+                ErrorCode = "M_MISSING_TOKEN",
+                Error = "Missing access token"
+            };
+        }
+
+        var mxid = await authenticationService.GetMxidFromToken(token);
+        if (mxid == "@anonymous:*") {
+            throw new MatrixException {
+                ErrorCode = "M_MISSING_TOKEN",
+                Error = "Missing access token"
+            };
+        }
+
+        var hsCanonical = string.Join(":", mxid.Split(':').Skip(1));
+        return await homeserverProviderService.GetAuthenticatedWithToken(hsCanonical, token);
+    }
+}
\ No newline at end of file