aboutsummaryrefslogtreecommitdiff
path: root/app/controllers/api_region_list.go
blob: 5bd1f7e1b35536306f448c51020d447a62a08c14 (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
54
55
56
57
58
59
60
61
package controllers

import (
	"net/http"

	glecho "code.crute.us/mcrute/golib/echo"
	"code.crute.us/mcrute/golib/echo/controller"
	"github.com/labstack/echo/v4"
)

type jsonRegion struct {
	Name           string `json:"name"`
	Enabled        bool   `json:"enabled"`
	Default        bool   `json:"default"`
	CredentialsURL string `json:"credentials_url,omitempty"`
}

type APIRegionListHandler struct {
	*AWSAPI
}

func NewAPIRegionListHandler(a *AWSAPI) echo.HandlerFunc {
	al := &APIRegionListHandler{a}
	h := &controller.ContentTypeNegotiatingHandler{
		DefaultHandler: al.Handle,
		Handlers: map[string]echo.HandlerFunc{
			contentTypeV1: al.Handle,
		},
	}
	return h.Handle
}

func (h *APIRegionListHandler) Handle(c echo.Context) error {
	rc, err := h.GetContext(c) // Does authorization checks
	if err != nil {
		return err
	}

	regions, err := rc.AWS.GetRegionList()
	if err != nil {
		c.Logger().Errorf("Failed to load region list: %w", err)
		return echo.ErrInternalServerError
	}

	out := make([]*jsonRegion, len(regions))

	for i, r := range regions {
		out[i] = &jsonRegion{
			Name:    r.Name,
			Enabled: r.Enabled,
			Default: rc.Account.DefaultRegion == r.Name,
		}
		if r.Enabled {
			out[i].CredentialsURL = glecho.URLFor(c,
				"/api/account", rc.Account.ShortName, "credentials", r.Name,
			).String()
		}
	}

	return c.JSON(http.StatusOK, out)
}