aboutsummaryrefslogtreecommitdiff
path: root/app/controllers/api_region_list.go
blob: c34ac3a0bbb89c5840bb6fa09c28df829e214f39 (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
62
63
64
65
package controllers

import (
	"net/http"

	"code.crute.us/mcrute/cloud-identity-broker/app"
	"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
	urls app.AppURL
}

func NewAPIRegionListHandler(a *AWSAPI) echo.HandlerFunc {
	al := &APIRegionListHandler{
		AWSAPI: a,
		urls:   app.AppURL{},
	}
	h := &controller.ContentTypeNegotiatingHandler{
		DefaultHandler: al.Handle,
		Handlers: map[string]echo.HandlerFunc{
			contentTypeV1: al.Handle,
			contentTypeV2: 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 = h.urls.AccountCredentials(
				c, "aws", rc.Account.ShortName, r.Name)
		}
	}

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