forked from mattermost/mattermost-plugin-gitlab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
496 lines (410 loc) · 15 KB
/
api.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/manland/mattermost-plugin-gitlab/server/gitlab"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/plugin"
"golang.org/x/oauth2"
)
const (
API_ERROR_ID_NOT_CONNECTED = "not_connected"
GITLAB_USERNAME = "Gitlab Plugin"
)
type APIErrorResponse struct {
ID string `json:"id"`
Message string `json:"message"`
StatusCode int `json:"status_code"`
}
func (p *Plugin) writeAPIError(w http.ResponseWriter, err *APIErrorResponse) {
b, _ := json.Marshal(err)
w.WriteHeader(err.StatusCode)
if _, err := w.Write(b); err != nil {
p.API.LogError("can't write api error http response", "err", err.Error())
}
}
func (p *Plugin) writeAPIResponse(w http.ResponseWriter, resp interface{}) {
b, jsonErr := json.Marshal(resp)
if jsonErr != nil {
p.API.LogError("Error encoding JSON response", "err", jsonErr.Error())
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Encountered an unexpected error. Please try again.", StatusCode: http.StatusInternalServerError})
}
if _, err := w.Write(b); err != nil {
p.API.LogError("can't write response user to http", "err", err.Error())
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Encountered an unexpected error. Please try again.", StatusCode: http.StatusInternalServerError})
}
}
func (p *Plugin) ServeHTTP(c *plugin.Context, w http.ResponseWriter, r *http.Request) {
config := p.getConfiguration()
if err := config.IsValid(); err != nil {
http.Error(w, "This plugin is not configured.", http.StatusNotImplemented)
return
}
w.Header().Set("Content-Type", "application/json")
switch path := r.URL.Path; path {
case "/webhook":
p.handleWebhook(w, r)
case "/assets/profile.png":
p.handleProfileImage(w, r)
case "/oauth/connect":
p.connectUserToGitlab(w, r)
case "/oauth/complete":
p.completeConnectUserToGitlab(w, r)
case "/api/v1/connected":
p.getConnected(w, r)
case "/api/v1/todo":
p.postToDo(w, r)
case "/api/v1/reviews":
p.getReviews(w, r)
case "/api/v1/yourprs":
p.getYourPrs(w, r)
case "/api/v1/yourassignments":
p.getYourAssignments(w, r)
case "/api/v1/unreads":
p.getUnreads(w, r)
case "/api/v1/settings":
p.updateSettings(w, r)
case "/api/v1/user":
p.getGitlabUser(w, r)
default:
http.NotFound(w, r)
}
}
func (p *Plugin) connectUserToGitlab(w http.ResponseWriter, r *http.Request) {
userID := r.Header.Get("Mattermost-User-ID")
if userID == "" {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
conf := p.getOAuthConfig()
state := fmt.Sprintf("%v_%v", model.NewId()[0:15], userID)
if err := p.API.KVSet(state, []byte(state)); err != nil {
p.API.LogError("can't sotre state oauth2", "err", err.DetailedError)
http.Error(w, "can't sotre state oauth2", http.StatusInternalServerError)
return
}
url := conf.AuthCodeURL(state, oauth2.AccessTypeOffline)
http.Redirect(w, r, url, http.StatusFound)
}
func (p *Plugin) completeConnectUserToGitlab(w http.ResponseWriter, r *http.Request) {
config := p.getConfiguration()
ctx := context.Background()
conf := p.getOAuthConfig()
code := r.URL.Query().Get("code")
if len(code) == 0 {
http.Error(w, "missing authorization code", http.StatusBadRequest)
return
}
state := r.URL.Query().Get("state")
if storedState, err := p.API.KVGet(state); err != nil {
p.API.LogError("can't get state from store", "err", err.Error())
http.Error(w, "missing stored state", http.StatusBadRequest)
return
} else if string(storedState) != state {
http.Error(w, "invalid state", http.StatusBadRequest)
return
}
userID := strings.Split(state, "_")[1]
if err := p.API.KVDelete(state); err != nil {
p.API.LogError("can't delete state in store", "err", err.DetailedError)
}
tok, err := conf.Exchange(ctx, code)
if err != nil {
p.API.LogError("can't exchange state", "err", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
userInfo, err := p.GitlabClient.GetCurrentUser(userID, *tok)
if err != nil {
p.API.LogError("can't retreive user info from gitlab api", "err", err.Error())
http.Error(w, "Unable to connect user to Gitlab", http.StatusInternalServerError)
return
}
if err := p.storeGitlabUserInfo(userInfo); err != nil {
p.API.LogError("can't store user info", "err", err.Error())
http.Error(w, "Unable to connect user to Gitlab", http.StatusInternalServerError)
return
}
if err := p.storeGitlabToUserIDMapping(userInfo.GitlabUsername, userID); err != nil {
p.API.LogError("can't store user id mapping", "err", err.Error())
}
// Post intro post
message := fmt.Sprintf("#### Welcome to the Mattermost Gitlab Plugin!\n"+
"You've connected your Mattermost account to %s on Gitlab. Read about the features of this plugin below:\n\n"+
"##### Daily Reminders\n"+
"The first time you log in each day, you will get a post right here letting you know what messages you need to read and what pull requests are awaiting your review.\n"+
"Turn off reminders with `/gitlab settings reminders off`.\n\n"+
"##### Notifications\n"+
"When someone mentions you, requests your review, comments on or modifies one of your pull requests/issues, or assigns you, you'll get a post here about it.\n"+
"Turn off notifications with `/gitlab settings notifications off`.\n\n"+
"##### Sidebar Buttons\n"+
"Check out the buttons in the left-hand sidebar of Mattermost.\n"+
"* The first button tells you how many pull requests you have submitted.\n"+
"* The second shows the number of PR that are awaiting your review.\n"+
"* The third shows the number of PR and issues your are assiged to.\n"+
"* The fourth tracks the number of unread messages you have.\n"+
"* The fifth will refresh the numbers.\n\n"+
"Click on them!\n\n"+
"##### Slash Commands\n"+
strings.Replace(COMMAND_HELP, "|", "`", -1), userInfo.GitlabUsername)
if err := p.CreateBotDMPost(userID, message, "custom_git_welcome"); err != nil {
p.API.LogError("can't send help message with bot dm", "err", err.Error())
}
p.API.PublishWebSocketEvent(
WS_EVENT_CONNECT,
map[string]interface{}{
"connected": true,
"gitlab_username": userInfo.GitlabUsername,
"gitlab_client_id": config.GitlabOAuthClientID,
},
&model.WebsocketBroadcast{UserId: userID},
)
html := `
<!DOCTYPE html>
<html>
<head>
<script>
window.close();
</script>
</head>
<body>
<p>Completed connecting to Gitlab. Please close this window.</p>
</body>
</html>
`
w.Header().Set("Content-Type", "text/html")
if _, err := w.Write([]byte(html)); err != nil {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: ">Completed connecting to Gitlab. Please close this window.", StatusCode: http.StatusInternalServerError})
}
}
func (p *Plugin) handleProfileImage(w http.ResponseWriter, r *http.Request) {
config := p.getConfiguration()
img, err := os.Open(filepath.Join(config.PluginsDirectory, manifest.Id, "assets", "profile.png"))
if err != nil {
http.NotFound(w, r)
p.API.LogError("Unable to read gitlab profile image", "err", err.Error())
return
}
defer func() {
if err = img.Close(); err != nil {
p.API.LogError("can't close img", "err", err.Error())
}
}()
w.Header().Set("Content-Type", "image/png")
_, err = io.Copy(w, img)
if err != nil {
p.API.LogError("can't copy image profile to http response writer", "err", err.Error())
}
}
type ConnectedResponse struct {
Connected bool `json:"connected"`
GitlabUsername string `json:"gitlab_username"`
GitlabClientID string `json:"gitlab_client_id"`
EnterpriseBaseURL string `json:"enterprise_base_url,omitempty"`
Organization string `json:"organization"`
Settings *gitlab.UserSettings `json:"settings"`
}
type GitlabUserRequest struct {
UserID string `json:"user_id"`
}
type GitlabUserResponse struct {
Username string `json:"username"`
}
func (p *Plugin) getGitlabUser(w http.ResponseWriter, r *http.Request) {
requestorID := r.Header.Get("Mattermost-User-ID")
if requestorID == "" {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Not authorized.", StatusCode: http.StatusUnauthorized})
return
}
req := &GitlabUserRequest{}
dec := json.NewDecoder(r.Body)
if err := dec.Decode(&req); err != nil || req.UserID == "" {
if err != nil {
p.API.LogError("Error decoding JSON body", "err", err.Error())
}
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Please provide a JSON object with a non-blank user_id field.", StatusCode: http.StatusBadRequest})
return
}
userInfo, apiErr := p.getGitlabUserInfoByMattermostID(req.UserID)
if apiErr != nil {
if apiErr.ID == API_ERROR_ID_NOT_CONNECTED {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "User is not connected to a Gitlab account.", StatusCode: http.StatusNotFound})
} else {
p.writeAPIError(w, apiErr)
}
return
}
if userInfo == nil {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "User is not connected to a Gitlab account.", StatusCode: http.StatusNotFound})
return
}
p.writeAPIResponse(w, &GitlabUserResponse{Username: userInfo.GitlabUsername})
}
func (p *Plugin) getConnected(w http.ResponseWriter, r *http.Request) {
config := p.getConfiguration()
userID := r.Header.Get("Mattermost-User-ID")
if userID == "" {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Not authorized.", StatusCode: http.StatusUnauthorized})
return
}
resp := &ConnectedResponse{
Connected: false,
EnterpriseBaseURL: config.EnterpriseBaseURL,
Organization: config.GitlabGroup,
}
info, _ := p.getGitlabUserInfoByMattermostID(userID)
if info != nil && info.Token != nil {
resp.Connected = true
resp.GitlabUsername = info.GitlabUsername
resp.GitlabClientID = config.GitlabOAuthClientID
resp.Settings = info.Settings
if info.Settings.DailyReminder && r.URL.Query().Get("reminder") == "true" {
lastPostAt := info.LastToDoPostAt
var timezone *time.Location
offset, _ := strconv.Atoi(r.Header.Get("X-Timezone-Offset"))
timezone = time.FixedZone("local", -60*offset)
// Post to do message if it's the next day and been more than an hour since the last post
now := model.GetMillis()
nt := time.Unix(now/1000, 0).In(timezone)
lt := time.Unix(lastPostAt/1000, 0).In(timezone)
if nt.Sub(lt).Hours() >= 1 && (nt.Day() != lt.Day() || nt.Month() != lt.Month() || nt.Year() != lt.Year()) {
p.PostToDo(info)
info.LastToDoPostAt = now
if err := p.storeGitlabUserInfo(info); err != nil {
p.API.LogError("can't sotre user info", "err", err.Error())
}
}
}
}
p.writeAPIResponse(w, resp)
}
func (p *Plugin) getUnreads(w http.ResponseWriter, r *http.Request) {
userID := r.Header.Get("Mattermost-User-ID")
if userID == "" {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
user, err := p.getGitlabUserInfoByMattermostID(userID)
if err != nil {
p.writeAPIError(w, err)
return
}
result, errRequest := p.GitlabClient.GetUnreads(user)
if errRequest != nil {
p.API.LogError("unable to list unreads in gitlab api", "err", errRequest.Error())
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Unable to list unreads in gitlab api.", StatusCode: http.StatusInternalServerError})
return
}
p.writeAPIResponse(w, result)
}
func (p *Plugin) getReviews(w http.ResponseWriter, r *http.Request) {
userID := r.Header.Get("Mattermost-User-ID")
if userID == "" {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
user, err := p.getGitlabUserInfoByMattermostID(userID)
if err != nil {
p.writeAPIError(w, err)
return
}
result, errRequest := p.GitlabClient.GetReviews(user)
if errRequest != nil {
p.API.LogError("unable to list merge-request where assignee in gitlab api", "err", errRequest.Error())
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Unable to list merge-request in gitlab api.", StatusCode: http.StatusInternalServerError})
return
}
p.writeAPIResponse(w, result)
}
func (p *Plugin) getYourPrs(w http.ResponseWriter, r *http.Request) {
userID := r.Header.Get("Mattermost-User-ID")
if userID == "" {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
user, err := p.getGitlabUserInfoByMattermostID(userID)
if err != nil {
p.writeAPIError(w, err)
return
}
result, errRequest := p.GitlabClient.GetYourPrs(user)
if errRequest != nil {
p.API.LogError("can't list merge-request where author in gitlab api", "err", errRequest.Error())
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Unable to list merge-request in gitlab api.", StatusCode: http.StatusInternalServerError})
return
}
p.writeAPIResponse(w, result)
}
func (p *Plugin) getYourAssignments(w http.ResponseWriter, r *http.Request) {
userID := r.Header.Get("Mattermost-User-ID")
if userID == "" {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
user, err := p.getGitlabUserInfoByMattermostID(userID)
if err != nil {
p.writeAPIError(w, err)
return
}
result, errRequest := p.GitlabClient.GetYourAssignments(user)
if errRequest != nil {
p.API.LogError("unable to list issue where assignee in gitlab api", "err", errRequest.Error())
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Unable to list issue in gitlab api.", StatusCode: http.StatusInternalServerError})
return
}
p.writeAPIResponse(w, result)
}
func (p *Plugin) postToDo(w http.ResponseWriter, r *http.Request) {
userID := r.Header.Get("Mattermost-User-ID")
if userID == "" {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Not authorized.", StatusCode: http.StatusUnauthorized})
return
}
user, err := p.getGitlabUserInfoByMattermostID(userID)
if err != nil {
p.writeAPIError(w, err)
return
}
text, errRequest := p.GetToDo(user)
if errRequest != nil {
p.API.LogError("can't get todo", "err", errRequest.Error())
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Encountered an error getting the to do items.", StatusCode: http.StatusUnauthorized})
return
}
if err := p.CreateBotDMPost(userID, text, "custom_git_todo"); err != nil {
p.writeAPIError(w, &APIErrorResponse{ID: "", Message: "Encountered an error posting the to do items.", StatusCode: http.StatusUnauthorized})
}
p.writeAPIResponse(w, struct{ status string }{status: "OK"})
}
func (p *Plugin) updateSettings(w http.ResponseWriter, r *http.Request) {
userID := r.Header.Get("Mattermost-User-ID")
if userID == "" {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
var settings *gitlab.UserSettings
err := json.NewDecoder(r.Body).Decode(&settings)
if settings == nil || err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
info, errGitlab := p.getGitlabUserInfoByMattermostID(userID)
if errGitlab != nil {
p.writeAPIError(w, errGitlab)
return
}
info.Settings = settings
if err := p.storeGitlabUserInfo(info); err != nil {
p.API.LogError("can't store gitlab user info when update settings", "err", err.Error())
http.Error(w, "Encountered error updating settings", http.StatusInternalServerError)
}
p.writeAPIResponse(w, info.Settings)
}