-
Notifications
You must be signed in to change notification settings - Fork 0
/
subscriptions.go
106 lines (93 loc) · 2.64 KB
/
subscriptions.go
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package azure
import (
"encoding/json"
"fmt"
"github.com/dazfuller/azcosts/internal/model"
"github.com/lithammer/fuzzysearch/fuzzy"
"net/http"
"strings"
"time"
)
type subscriptionResponse struct {
Value []struct {
Id string `json:"id"`
SubscriptionId string `json:"subscriptionId"`
TenantId string `json:"tenantId"`
DisplayName string `json:"displayName"`
State string `json:"state"`
SubscriptionPolicies struct {
LocationPlacementId string `json:"locationPlacementId"`
QuotaId string `json:"quotaId"`
SpendingLimit string `json:"spendingLimit"`
} `json:"subscriptionPolicies"`
AuthorizationSource string `json:"authorizationSource"`
ManagedByTenants []struct {
TenantId string `json:"tenantId"`
} `json:"managedByTenants"`
Tags map[string]string `json:"tags"`
} `json:"value"`
NextLink string `json:"nextLink"`
}
type SubscriptionService struct {
azureService
apiVersion string
endpoint string
managementScope string
}
func NewSubscriptionService() SubscriptionService {
return SubscriptionService{
azureService: newAzureService(),
apiVersion: "2022-12-01",
endpoint: "https://management.azure.com/subscriptions",
managementScope: "https://management.azure.com/.default",
}
}
func (ss *SubscriptionService) FindSubscription(input string) ([]model.Subscription, error) {
subs, err := ss.GetSubscriptions()
if err != nil {
return nil, err
}
var filtered []model.Subscription
for i := range subs {
subNameParts := strings.Split(subs[i].Name, " ")
for _, part := range subNameParts {
if fuzzy.MatchFold(input, part) {
filtered = append(filtered, subs[i])
break
}
}
}
return filtered, nil
}
func (ss *SubscriptionService) GetSubscriptions() ([]model.Subscription, error) {
url := fmt.Sprintf(ss.endpoint + "?api-version=" + ss.apiVersion)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
token, err := ss.getAccessToken(ss.managementScope)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+token)
client := http.Client{Timeout: time.Second * 10}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var subResp subscriptionResponse
err = json.NewDecoder(resp.Body).Decode(&subResp)
if err != nil {
return nil, err
}
subscriptions := make([]model.Subscription, len(subResp.Value))
for i, v := range subResp.Value {
subscriptions[i] = model.Subscription{
Id: v.SubscriptionId,
TenantId: v.TenantId,
Name: v.DisplayName,
}
}
return subscriptions, nil
}