aboutsummaryrefslogtreecommitdiff
path: root/docker/crupest-api/CrupestApi/CrupestApi.Secrets/SecretsWebApplicationExtensions.cs
blob: a7715475e841cee748ab595a164234d428c95c2c (plain)
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
using CrupestApi.Commons;

namespace CrupestApi.Secrets;

public static class SecretsWebApplicationExtensions
{
    public static WebApplication UseCatchVerifySecretException(this WebApplication app)
    {
        app.Use(async (context, next) =>
        {
            try
            {
                await next(context);
            }
            catch (VerifySecretException e)
            {
                await context.Response.WriteErrorMessageAsync(e.Message, 401);
            }
        });

        return app;
    }

    public static async Task CheckSecret(this HttpContext context, string key)
    {
        var secretsService = context.RequestServices.GetRequiredService<ISecretsService>();
        await secretsService.VerifySecretForHttpRequestAsync(context.Request, SecretsConstants.SecretManagementKey);
    }

    public static WebApplication MapSecrets(this WebApplication app, string path)
    {
        app.MapGet(path, async (context) =>
        {
            await context.CheckSecret(SecretsConstants.SecretManagementKey);
            var secretsService = context.RequestServices.GetRequiredService<ISecretsService>();
            var secrets = secretsService.GetSecretListAsync();
            await context.Response.WriteJsonAsync(secrets);
        });

        return app;
    }
}