summary refs log tree commit diff
path: root/MxApiExtensions/Services/AuthenticatedHomeserverProviderService.cs
blob: 296663d593109261c05f29b451cff8d60f149e3d (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
48
49
50
51
52
53
54
55
using ArcaneLibs.Extensions;
using LibMatrix.Homeservers;
using LibMatrix.Services;
using MxApiExtensions.Classes.LibMatrix;

namespace MxApiExtensions.Services;

public class AuthenticatedHomeserverProviderService(AuthenticationService authenticationService, HomeserverProviderService homeserverProviderService, IHttpContextAccessor request) {
    public HttpContext? _context = request.HttpContext;
    public async Task<RemoteHomeserver?> TryGetRemoteHomeserver() {
        try {
            return await GetRemoteHomeserver();
        }
        catch {
            return null;
        }
    }

    public async Task<RemoteHomeserver> GetRemoteHomeserver() {
        try {
            return await GetHomeserver();
        }
        catch (MxApiMatrixException e) {
            if (e is not { ErrorCode: "M_MISSING_TOKEN" }) throw;
            if (request is null) throw new MxApiMatrixException() { ErrorCode = "M_UNKNOWN", Error = "[MxApiExtensions] Request was null for unauthenticated request!" };
            if (!_context.Request.Headers.Keys.Any(x => x.ToUpper() == "MXAE_UPSTREAM"))
                throw new MxApiMatrixException() {
                    ErrorCode = "MXAE_MISSING_UPSTREAM",
                    Error = "[MxApiExtensions] Missing MXAE_UPSTREAM header for unauthenticated request, this should be a server_name!"
                };
            return await homeserverProviderService.GetRemoteHomeserver(request.HttpContext.Request.Headers.GetByCaseInsensitiveKey("MXAE_UPSTREAM")[0]);
        }
    }

    public async Task<AuthenticatedHomeserverGeneric> GetHomeserver() {
        var token = authenticationService.GetToken();
        if (token == null) {
            throw new MxApiMatrixException {
                ErrorCode = "M_MISSING_TOKEN",
                Error = "Missing access token"
            };
        }

        var mxid = await authenticationService.GetMxidFromToken(token);
        if (mxid == "@anonymous:*") {
            throw new MxApiMatrixException {
                ErrorCode = "M_MISSING_TOKEN",
                Error = "Missing access token"
            };
        }

        var hsCanonical = string.Join(":", mxid.Split(':').Skip(1));
        return await homeserverProviderService.GetAuthenticatedWithToken(hsCanonical, token);
    }
}