summary refs log tree commit diff
path: root/ModAS.Server/Services/AuthenticatedHomeserverProviderService.cs
blob: fa8e00aed8e8fc0df61fb9f862a25764011e8885 (plain) (blame)
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
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);
    }
}