about summary refs log tree commit diff
path: root/Utilities/LibMatrix.HomeserverEmulator/Services/TokenService.cs
blob: cf79aae791ce515950590a51a8cb6bb539eb9d91 (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
namespace LibMatrix.HomeserverEmulator.Services;

public class TokenService{
    public string? GetAccessTokenOrNull(HttpContext ctx) {
        //qry
        if (ctx.Request.Query.TryGetValue("access_token", out var token)) {
            return token;
        }
        //header
        if (ctx.Request.Headers.TryGetValue("Authorization", out var auth)) {
            var parts = auth.ToString().Split(' ');
            if (parts is ["Bearer", _]) {
                return parts[1];
            }
        }
        return null;
    }

    public string GetAccessToken(HttpContext ctx) {
        return GetAccessTokenOrNull(ctx) ?? throw new MatrixException() {
            ErrorCode = MatrixException.ErrorCodes.M_UNKNOWN_TOKEN,
            Error = "Missing token"
        };
    }

    public string? GenerateServerName(HttpContext ctx) {
        return ctx.Request.Host.ToString();
    }
}