-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.go
110 lines (88 loc) · 2.31 KB
/
graph.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
107
108
109
110
package graph
import (
"context"
"errors"
"io"
"log"
"net/http"
"net/url"
"github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential"
"github.com/tonyeung/microsoft-graph-client-go/graph/query"
)
type HttpDoer interface {
Do(req *http.Request) (*http.Response, error)
}
type Client struct {
msal confidential.Client
graphClient HttpDoer
scopes []string
graphHost string
version string
}
func New(app confidential.Client, httpClient HttpDoer) (*Client, error) {
return &Client{
msal: app,
graphClient: httpClient,
scopes: []string{"https://graph.microsoft.com/.default"},
graphHost: "graph.microsoft.com",
version: "v1.0",
}, nil
}
func (g Client) Api(resource string, method string, opts ...query.QueryOption) (string, error) {
url := url.URL{
Scheme: "https",
Host: g.graphHost,
Path: g.version + resource,
}
for _, opt := range opts {
url = opt(url)
}
switch method {
case "GET":
return g.get(url.String())
case "DELETE":
return g.delete(url.String())
default:
return "", errors.New("invalid method")
}
}
func (g Client) get(url string) (string, error) {
authResult, err := g.msal.AcquireTokenSilent(context.Background(), g.scopes)
if err != nil {
authResult, err = g.msal.AcquireTokenByCredential(context.Background(), g.scopes)
if err != nil {
log.Fatal(err)
}
}
bearer := "Bearer " + authResult.AccessToken
//fmt.Print(bearer)
request, _ := http.NewRequest(http.MethodGet, url, nil)
request.Header.Add("Authorization", bearer)
response, _ := g.graphClient.Do(request)
defer response.Body.Close()
b, err := io.ReadAll(response.Body)
if err != nil {
log.Fatalln(err)
}
return string(b), nil
}
func (g Client) delete(url string) (string, error) {
authResult, err := g.msal.AcquireTokenSilent(context.Background(), g.scopes)
if err != nil {
authResult, err = g.msal.AcquireTokenByCredential(context.Background(), g.scopes)
if err != nil {
log.Fatal(err)
}
}
bearer := "Bearer " + authResult.AccessToken
//fmt.Print(bearer)
request, _ := http.NewRequest(http.MethodDelete, url, nil)
request.Header.Add("Authorization", bearer)
response, _ := g.graphClient.Do(request)
defer response.Body.Close()
b, err := io.ReadAll(response.Body)
if err != nil {
log.Fatalln(err)
}
return string(b), nil
}