summaryrefslogtreecommitdiff
path: root/src/FundLab.Api/App.fs
blob: 44628abd6e7cdc247ab1a46b90a586969d9ccc59 (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
43
44
45
46
47
48
49
50
51
52
53
namespace FundLab.Api

open System
open Giraffe
open Microsoft.AspNetCore.Http

type EmptyPortfolioResponse =
    {
        status: string
        message: string
    }

module App =
    let private unauthorized : HttpHandler =
        setStatusCode 401
        >=> setHttpHeader "WWW-Authenticate" "Bearer"
        >=> text "Unauthorized"

    let private requireBearer (next: HttpFunc) (ctx: HttpContext) =
        let expectedToken =
            Environment.GetEnvironmentVariable("FUND_LAB_AUTH_TOKEN")
            |> Option.ofObj
            |> Option.defaultValue ""

        let authorizationHeader = ctx.Request.Headers.Authorization.ToString()

        match Authentication.authorize expectedToken authorizationHeader with
        | AuthDecision.Authorized -> next ctx
        | AuthDecision.Unauthorized -> unauthorized next ctx

    let private health : HttpHandler =
        json ({
            service = "fund-lab-api"
            status = "ok"
        } : HealthResponse)

    let private emptyPortfolio : HttpHandler =
        json {
            status = "empty"
            message = "尚未创建基金/尚未选择投资"
        }

    let createApplication () : HttpHandler =
        choose [
            GET >=> route "/health" >=> health
            subRoute "/api" (
                requireBearer
                >=> choose [
                    GET >=> route "/portfolio/summary" >=> emptyPortfolio
                ]
            )
            setStatusCode 404 >=> text "Not Found"
        ]