/
connect.go
379 lines (338 loc) · 10.3 KB
/
connect.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"github.com/darren0609/Contact-Reviewer/o365"
"golang.org/x/oauth2"
)
var (
client *http.Client
clientID string
clientSecret string
guid string
user User
contact ContactHeader
)
// D is Data for template
type D map[string]interface{}
// User represents a Microsoft Graph user
type User struct {
Username string `json:"displayName"`
Email string `json:"mail"`
Surname string `json:"surname"`
Givenname string `json:"givenname"`
}
// ContactData is the contact detail
type ContactData struct {
Etag string `json:"odata.etag"`
ID string `json:"id"`
Createddatetime string `json:"createdDateTime"`
Lastmodifieddatetime string `json:"lastModifiedDateTime"`
Changekey string `json:"changeKey"`
Displayname string `json:"displayName"`
Officephone []string `json:"businessPhones"`
Homephone []string `json:"homePhones"`
Emailaddresses []string `json:"odata.microsoft.graph.emailAddress"`
Givenname string `json:"givenName"`
Mobilephone string `json:"mobilePhone"`
Surname string `json:"surname"`
}
// ContactHeader is the contact header and detail
type ContactHeader struct {
Context string `json:"odata.context"`
NextLink string `json:"odata.nextLink"`
Contacts []ContactData `json:"value"`
}
// Body is generally the body of the returned HTML when executing.
type Body struct {
ContentType string
Content string
}
// EmailAddress is the Email Address of the user
type EmailAddress struct {
Address string
}
// Recipient is the Receipient of the email you wish to send
type Recipient struct {
EmailAddress EmailAddress
}
// Message is the specifics of the message being sent
type Message struct {
Subject string
Body Body
ToRecipients []Recipient
}
func getContacts(w http.ResponseWriter, r *http.Request) {
var fullcont ContactHeader
// Use OData query parameters to control the results
// - Only first 10 results returned
// - Only return the GivenName, Surname, and EmailAddresses fields
// - Sort the results by the GivenName field in ascending order
//query_parameters := "$top=50",
// "$select" : "givenName,surname,emailAddresses",
// "$orderby": "givenName ASC",
//}
// Post the message to the graph API endpoint for sending email
endpointURL := "https://graph.microsoft.com/v1.0/me/contacts"
//$orderby=givenName ASC$top=50"
//endpointURL := "https://graph.microsoft.com/v1.0/me/contacts"
res, err := client.Get(endpointURL)
if err != nil {
fmt.Println("Error in get contacts:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
defer res.Body.Close()
bytes, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err)
}
err = json.Unmarshal(bytes, &fullcont)
if err != nil {
log.Println("Failed to UNMARSHAL user data:", err)
}
// Parse template for response to app client
t2, err := template.ParseFiles("tpl/contacts.html")
if err != nil {
fmt.Println("Error parsing template:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
t2.Execute(w, D{
"me": user,
"contact": fullcont,
"showSuccess": false,
"showError": false,
})
return
}
// Handler for home page
func indexHandler(w http.ResponseWriter, r *http.Request) {
// Log into the Office 365 site - and authenticate
t, err := template.ParseFiles("tpl/connect.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
t.Execute(w, struct{}{})
}
// Handler for login route
func loginHandler(w http.ResponseWriter, r *http.Request) {
// guid should be long random string, find golang uuid lib?
// guid used to only accept initiated logins, compared after response later
if guid == "" {
guid = "wbvcewiqf923h8vh139fh3491v"
}
conf := &oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
Scopes: []string{"User.Read", "Contacts.Read", "Mail.Send"},
RedirectURL: "http://localhost:8080/login",
Endpoint: oauth2.Endpoint{
AuthURL: "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
TokenURL: "https://login.microsoftonline.com/common/oauth2/v2.0/token",
},
}
var code string
code = r.URL.Query().Get("code")
if len(code) == 0 {
// Redirect user to consent page to ask for permission
// for the scopes specified above.
authurl := conf.AuthCodeURL(guid, oauth2.AccessTypeOffline)
http.Redirect(w, r, authurl, http.StatusSeeOther)
// fmt.Printf(authurl)
return
}
// Before calling Exchange, be sure to validate FormValue("state").
if r.FormValue("state") != guid {
log.Fatal("State has been messed with, end authentication")
// reset state to prevent re-use
guid = ""
}
ctx := context.Background()
tok, err := conf.Exchange(ctx, code)
if err != nil {
log.Fatal(err)
}
client = conf.Client(ctx, tok)
// Grab credentials so we can use them in displaying form detail going forward
res, err := client.Get("https://graph.microsoft.com/v1.0/me")
if err != nil {
log.Println("Failed to get user/me:", err)
return
}
defer res.Body.Close()
err = json.NewDecoder(res.Body).Decode(&user)
if err != nil {
log.Println("Failed to parse user data:", err)
}
http.Redirect(w, r, "/home", http.StatusSeeOther)
return
}
// Handler for logout route
func logoutHandler(w http.ResponseWriter, r *http.Request) {
// reset client to forget token
client = http.DefaultClient
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
// Handler for main route
func mainHandler(w http.ResponseWriter, r *http.Request) {
res, err := client.Get("https://graph.microsoft.com/v1.0/me")
if err != nil {
log.Println("Failed to get user/me:", err)
}
defer res.Body.Close()
err = json.NewDecoder(res.Body).Decode(&user)
if err != nil {
log.Println("Failed to parse user data:", err)
}
t, err := template.ParseFiles("tpl/main.html")
if err != nil {
http.Error(w, err.Error(), http.StatusSeeOther)
}
t.Execute(w, D{
"me": user,
"showSuccess": false,
"showError": false,
})
}
// Handler for sendmail route
func sendMailHandler(w http.ResponseWriter, r *http.Request) {
// Create the email to be sent via the Graph API
var emailBody bytes.Buffer
t, err := template.ParseFiles("tpl/email.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
t.Execute(&emailBody, user.Username)
// Gather and encode payload data for posting email message to graph
recip := Recipient{}
recip.EmailAddress.Address = r.URL.Query().Get("emailAddress")
recips := []Recipient{recip}
msg := D{
"Message": Message{
Subject: "Welcome to the Microsoft Graph Connect sample on GOLANG",
Body: Body{
ContentType: "HTML",
Content: emailBody.String(),
},
ToRecipients: recips,
},
}
postJSON := new(bytes.Buffer)
err = json.NewEncoder(postJSON).Encode(msg)
if err != nil {
fmt.Println("error encoding msg to json:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
// Post the message to the graph API endpoint for sending email
endpointURL := "https://graph.microsoft.com/v1.0/me/sendMail"
res, err := client.Post(endpointURL, "application/json", postJSON)
if err != nil {
fmt.Println("error posting msg:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
// Parse template for response to app client
t2, err := template.ParseFiles("tpl/home.html")
if err != nil {
fmt.Println("Error parsing template:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
// Graph API will respond with 202 if sendmail request was successful
if res.StatusCode == 202 {
t2.Execute(w, D{
"me": user,
"showSuccess": true,
"showError": false,
"recipient": recip.EmailAddress.Address,
})
} else {
t2.Execute(w, D{
"me": user,
"showSuccess": false,
"showError": true,
})
}
}
// Handler for sendmail route
func sendMailHandlerNew(w http.ResponseWriter, r *http.Request) {
// Create the email to be sent via the Graph API
var emailBody bytes.Buffer
t, err := template.ParseFiles("tpl/email.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
t.Execute(&emailBody, user.Username)
// Gather and encode payload data for posting email message to graph
recip := Recipient{}
recip.EmailAddress.Address = r.URL.Query().Get("emailAddress")
recips := []Recipient{recip}
msg := D{
"Message": Message{
Subject: "Welcome to the Microsoft Graph Connect sample for Python",
Body: Body{
ContentType: "HTML",
Content: emailBody.String(),
},
ToRecipients: recips,
},
}
postJSON := new(bytes.Buffer)
err = json.NewEncoder(postJSON).Encode(msg)
if err != nil {
fmt.Println("error encoding msg to json:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
// Post the message to the graph API endpoint for sending email
endpointURL := "https://graph.microsoft.com/v1.0/me/sendMail"
res, err := client.Post(endpointURL, "application/json", postJSON)
if err != nil {
fmt.Println("error posting msg:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
// Parse template for response to app client
t2, err := template.ParseFiles("tpl/home.html")
if err != nil {
fmt.Println("Error parsing template:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
// Graph API will respond with 202 if sendmail request was successful
if res.StatusCode == 202 {
t2.Execute(w, D{
"me": user,
"showSuccess": true,
"showError": false,
"recipient": recip.EmailAddress.Address,
})
} else {
t2.Execute(w, D{
"me": user,
"showSuccess": false,
"showError": true,
})
}
}
func main() {
var err error
configFile := "private.txt"
//templateFolder := "templates/"
clientID, clientSecret, err = o365.GetCreds(configFile)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
http.HandleFunc("/", loginHandler)
http.HandleFunc("/login", loginHandler)
http.HandleFunc("/logout", logoutHandler)
http.HandleFunc("/main", mainHandler)
http.HandleFunc("/contacts", getContacts)
http.HandleFunc("/home", sendMailHandlerNew)
http.HandleFunc("/sendmail", sendMailHandler)
http.ListenAndServe(":8080", nil)
// fmt.Println("Success", client.Head)
}