forked from mattermost/mattermost
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client4.go
4186 lines (3619 loc) · 148 KB
/
client4.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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package model
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
const (
HEADER_REQUEST_ID = "X-Request-ID"
HEADER_VERSION_ID = "X-Version-ID"
HEADER_CLUSTER_ID = "X-Cluster-ID"
HEADER_ETAG_SERVER = "ETag"
HEADER_ETAG_CLIENT = "If-None-Match"
HEADER_FORWARDED = "X-Forwarded-For"
HEADER_REAL_IP = "X-Real-IP"
HEADER_FORWARDED_PROTO = "X-Forwarded-Proto"
HEADER_TOKEN = "token"
HEADER_BEARER = "BEARER"
HEADER_AUTH = "Authorization"
HEADER_REQUESTED_WITH = "X-Requested-With"
HEADER_REQUESTED_WITH_XML = "XMLHttpRequest"
STATUS = "status"
STATUS_OK = "OK"
STATUS_FAIL = "FAIL"
STATUS_REMOVE = "REMOVE"
CLIENT_DIR = "client"
API_URL_SUFFIX_V1 = "/api/v1"
API_URL_SUFFIX_V4 = "/api/v4"
API_URL_SUFFIX = API_URL_SUFFIX_V4
)
type Response struct {
StatusCode int
Error *AppError
RequestId string
Etag string
ServerVersion string
Header http.Header
}
type Client4 struct {
Url string // The location of the server, for example "http://localhost:8065"
ApiUrl string // The api location of the server, for example "http://localhost:8065/api/v4"
HttpClient *http.Client // The http client
AuthToken string
AuthType string
HttpHeader map[string]string // Headers to be copied over for each request
}
func closeBody(r *http.Response) {
if r.Body != nil {
_, _ = ioutil.ReadAll(r.Body)
_ = r.Body.Close()
}
}
// Must is a convenience function used for testing.
func (c *Client4) Must(result interface{}, resp *Response) interface{} {
if resp.Error != nil {
time.Sleep(time.Second)
panic(resp.Error)
}
return result
}
func NewAPIv4Client(url string) *Client4 {
return &Client4{url, url + API_URL_SUFFIX, &http.Client{}, "", "", map[string]string{}}
}
func BuildErrorResponse(r *http.Response, err *AppError) *Response {
var statusCode int
var header http.Header
if r != nil {
statusCode = r.StatusCode
header = r.Header
} else {
statusCode = 0
header = make(http.Header)
}
return &Response{
StatusCode: statusCode,
Error: err,
Header: header,
}
}
func BuildResponse(r *http.Response) *Response {
return &Response{
StatusCode: r.StatusCode,
RequestId: r.Header.Get(HEADER_REQUEST_ID),
Etag: r.Header.Get(HEADER_ETAG_SERVER),
ServerVersion: r.Header.Get(HEADER_VERSION_ID),
Header: r.Header,
}
}
func (c *Client4) MockSession(sessionToken string) {
c.AuthToken = sessionToken
c.AuthType = HEADER_BEARER
}
func (c *Client4) SetOAuthToken(token string) {
c.AuthToken = token
c.AuthType = HEADER_TOKEN
}
func (c *Client4) ClearOAuthToken() {
c.AuthToken = ""
c.AuthType = HEADER_BEARER
}
func (c *Client4) GetUsersRoute() string {
return fmt.Sprintf("/users")
}
func (c *Client4) GetUserRoute(userId string) string {
return fmt.Sprintf(c.GetUsersRoute()+"/%v", userId)
}
func (c *Client4) GetUserAccessTokensRoute() string {
return fmt.Sprintf(c.GetUsersRoute() + "/tokens")
}
func (c *Client4) GetUserAccessTokenRoute(tokenId string) string {
return fmt.Sprintf(c.GetUsersRoute()+"/tokens/%v", tokenId)
}
func (c *Client4) GetUserByUsernameRoute(userName string) string {
return fmt.Sprintf(c.GetUsersRoute()+"/username/%v", userName)
}
func (c *Client4) GetUserByEmailRoute(email string) string {
return fmt.Sprintf(c.GetUsersRoute()+"/email/%v", email)
}
func (c *Client4) GetTeamsRoute() string {
return fmt.Sprintf("/teams")
}
func (c *Client4) GetTeamRoute(teamId string) string {
return fmt.Sprintf(c.GetTeamsRoute()+"/%v", teamId)
}
func (c *Client4) GetTeamAutoCompleteCommandsRoute(teamId string) string {
return fmt.Sprintf(c.GetTeamsRoute()+"/%v/commands/autocomplete", teamId)
}
func (c *Client4) GetTeamByNameRoute(teamName string) string {
return fmt.Sprintf(c.GetTeamsRoute()+"/name/%v", teamName)
}
func (c *Client4) GetTeamMemberRoute(teamId, userId string) string {
return fmt.Sprintf(c.GetTeamRoute(teamId)+"/members/%v", userId)
}
func (c *Client4) GetTeamMembersRoute(teamId string) string {
return fmt.Sprintf(c.GetTeamRoute(teamId) + "/members")
}
func (c *Client4) GetTeamStatsRoute(teamId string) string {
return fmt.Sprintf(c.GetTeamRoute(teamId) + "/stats")
}
func (c *Client4) GetTeamImportRoute(teamId string) string {
return fmt.Sprintf(c.GetTeamRoute(teamId) + "/import")
}
func (c *Client4) GetChannelsRoute() string {
return fmt.Sprintf("/channels")
}
func (c *Client4) GetChannelsForTeamRoute(teamId string) string {
return fmt.Sprintf(c.GetTeamRoute(teamId) + "/channels")
}
func (c *Client4) GetChannelRoute(channelId string) string {
return fmt.Sprintf(c.GetChannelsRoute()+"/%v", channelId)
}
func (c *Client4) GetChannelByNameRoute(channelName, teamId string) string {
return fmt.Sprintf(c.GetTeamRoute(teamId)+"/channels/name/%v", channelName)
}
func (c *Client4) GetChannelByNameForTeamNameRoute(channelName, teamName string) string {
return fmt.Sprintf(c.GetTeamByNameRoute(teamName)+"/channels/name/%v", channelName)
}
func (c *Client4) GetChannelMembersRoute(channelId string) string {
return fmt.Sprintf(c.GetChannelRoute(channelId) + "/members")
}
func (c *Client4) GetChannelMemberRoute(channelId, userId string) string {
return fmt.Sprintf(c.GetChannelMembersRoute(channelId)+"/%v", userId)
}
func (c *Client4) GetPostsRoute() string {
return fmt.Sprintf("/posts")
}
func (c *Client4) GetPostsEphemeralRoute() string {
return fmt.Sprintf("/posts/ephemeral")
}
func (c *Client4) GetConfigRoute() string {
return fmt.Sprintf("/config")
}
func (c *Client4) GetLicenseRoute() string {
return fmt.Sprintf("/license")
}
func (c *Client4) GetPostRoute(postId string) string {
return fmt.Sprintf(c.GetPostsRoute()+"/%v", postId)
}
func (c *Client4) GetFilesRoute() string {
return fmt.Sprintf("/files")
}
func (c *Client4) GetFileRoute(fileId string) string {
return fmt.Sprintf(c.GetFilesRoute()+"/%v", fileId)
}
func (c *Client4) GetPluginsRoute() string {
return fmt.Sprintf("/plugins")
}
func (c *Client4) GetPluginRoute(pluginId string) string {
return fmt.Sprintf(c.GetPluginsRoute()+"/%v", pluginId)
}
func (c *Client4) GetSystemRoute() string {
return fmt.Sprintf("/system")
}
func (c *Client4) GetTestEmailRoute() string {
return fmt.Sprintf("/email/test")
}
func (c *Client4) GetTestS3Route() string {
return fmt.Sprintf("/file/s3_test")
}
func (c *Client4) GetDatabaseRoute() string {
return fmt.Sprintf("/database")
}
func (c *Client4) GetCacheRoute() string {
return fmt.Sprintf("/caches")
}
func (c *Client4) GetClusterRoute() string {
return fmt.Sprintf("/cluster")
}
func (c *Client4) GetIncomingWebhooksRoute() string {
return fmt.Sprintf("/hooks/incoming")
}
func (c *Client4) GetIncomingWebhookRoute(hookID string) string {
return fmt.Sprintf(c.GetIncomingWebhooksRoute()+"/%v", hookID)
}
func (c *Client4) GetComplianceReportsRoute() string {
return fmt.Sprintf("/compliance/reports")
}
func (c *Client4) GetComplianceReportRoute(reportId string) string {
return fmt.Sprintf("/compliance/reports/%v", reportId)
}
func (c *Client4) GetOutgoingWebhooksRoute() string {
return fmt.Sprintf("/hooks/outgoing")
}
func (c *Client4) GetOutgoingWebhookRoute(hookID string) string {
return fmt.Sprintf(c.GetOutgoingWebhooksRoute()+"/%v", hookID)
}
func (c *Client4) GetPreferencesRoute(userId string) string {
return fmt.Sprintf(c.GetUserRoute(userId) + "/preferences")
}
func (c *Client4) GetUserStatusRoute(userId string) string {
return fmt.Sprintf(c.GetUserRoute(userId) + "/status")
}
func (c *Client4) GetUserStatusesRoute() string {
return fmt.Sprintf(c.GetUsersRoute() + "/status")
}
func (c *Client4) GetSamlRoute() string {
return fmt.Sprintf("/saml")
}
func (c *Client4) GetLdapRoute() string {
return fmt.Sprintf("/ldap")
}
func (c *Client4) GetBrandRoute() string {
return fmt.Sprintf("/brand")
}
func (c *Client4) GetDataRetentionRoute() string {
return fmt.Sprintf("/data_retention")
}
func (c *Client4) GetElasticsearchRoute() string {
return fmt.Sprintf("/elasticsearch")
}
func (c *Client4) GetCommandsRoute() string {
return fmt.Sprintf("/commands")
}
func (c *Client4) GetCommandRoute(commandId string) string {
return fmt.Sprintf(c.GetCommandsRoute()+"/%v", commandId)
}
func (c *Client4) GetEmojisRoute() string {
return fmt.Sprintf("/emoji")
}
func (c *Client4) GetEmojiRoute(emojiId string) string {
return fmt.Sprintf(c.GetEmojisRoute()+"/%v", emojiId)
}
func (c *Client4) GetEmojiByNameRoute(name string) string {
return fmt.Sprintf(c.GetEmojisRoute()+"/name/%v", name)
}
func (c *Client4) GetReactionsRoute() string {
return fmt.Sprintf("/reactions")
}
func (c *Client4) GetOAuthAppsRoute() string {
return fmt.Sprintf("/oauth/apps")
}
func (c *Client4) GetOAuthAppRoute(appId string) string {
return fmt.Sprintf("/oauth/apps/%v", appId)
}
func (c *Client4) GetOpenGraphRoute() string {
return fmt.Sprintf("/opengraph")
}
func (c *Client4) GetJobsRoute() string {
return fmt.Sprintf("/jobs")
}
func (c *Client4) GetRolesRoute() string {
return fmt.Sprintf("/roles")
}
func (c *Client4) GetSchemesRoute() string {
return fmt.Sprintf("/schemes")
}
func (c *Client4) GetSchemeRoute(id string) string {
return c.GetSchemesRoute() + fmt.Sprintf("/%v", id)
}
func (c *Client4) GetAnalyticsRoute() string {
return fmt.Sprintf("/analytics")
}
func (c *Client4) GetTimezonesRoute() string {
return fmt.Sprintf(c.GetSystemRoute() + "/timezones")
}
func (c *Client4) GetChannelSchemeRoute(channelId string) string {
return fmt.Sprintf(c.GetChannelsRoute()+"/%v/scheme", channelId)
}
func (c *Client4) GetTeamSchemeRoute(teamId string) string {
return fmt.Sprintf(c.GetTeamsRoute()+"/%v/scheme", teamId)
}
func (c *Client4) GetTotalUsersStatsRoute() string {
return fmt.Sprintf(c.GetUsersRoute() + "/stats")
}
func (c *Client4) GetRedirectLocationRoute() string {
return fmt.Sprintf("/redirect_location")
}
func (c *Client4) GetUserTermsOfServiceRoute(userId string) string {
return c.GetUserRoute(userId) + "/terms_of_service"
}
func (c *Client4) GetTermsOfServiceRoute() string {
return "/terms_of_service"
}
func (c *Client4) GetGroupsRoute() string {
return "/groups"
}
func (c *Client4) GetGroupRoute(groupID string) string {
return fmt.Sprintf("%s/%s", c.GetGroupsRoute(), groupID)
}
func (c *Client4) GetGroupSyncableRoute(groupID, syncableID string, syncableType GroupSyncableType) string {
return fmt.Sprintf("%s/%ss/%s", c.GetGroupRoute(groupID), strings.ToLower(syncableType.String()), syncableID)
}
func (c *Client4) GetGroupSyncablesRoute(groupID string, syncableType GroupSyncableType) string {
return fmt.Sprintf("%s/%ss", c.GetGroupRoute(groupID), strings.ToLower(syncableType.String()))
}
func (c *Client4) DoApiGet(url string, etag string) (*http.Response, *AppError) {
return c.DoApiRequest(http.MethodGet, c.ApiUrl+url, "", etag)
}
func (c *Client4) DoApiPost(url string, data string) (*http.Response, *AppError) {
return c.DoApiRequest(http.MethodPost, c.ApiUrl+url, data, "")
}
func (c *Client4) doApiPostBytes(url string, data []byte) (*http.Response, *AppError) {
return c.doApiRequestBytes(http.MethodPost, c.ApiUrl+url, data, "")
}
func (c *Client4) DoApiPut(url string, data string) (*http.Response, *AppError) {
return c.DoApiRequest(http.MethodPut, c.ApiUrl+url, data, "")
}
func (c *Client4) DoApiDelete(url string) (*http.Response, *AppError) {
return c.DoApiRequest(http.MethodDelete, c.ApiUrl+url, "", "")
}
func (c *Client4) DoApiRequest(method, url, data, etag string) (*http.Response, *AppError) {
return c.doApiRequestReader(method, url, strings.NewReader(data), etag)
}
func (c *Client4) doApiRequestBytes(method, url string, data []byte, etag string) (*http.Response, *AppError) {
return c.doApiRequestReader(method, url, bytes.NewReader(data), etag)
}
func (c *Client4) doApiRequestReader(method, url string, data io.Reader, etag string) (*http.Response, *AppError) {
rq, err := http.NewRequest(method, url, data)
if err != nil {
return nil, NewAppError(url, "model.client.connecting.app_error", nil, err.Error(), http.StatusBadRequest)
}
if len(etag) > 0 {
rq.Header.Set(HEADER_ETAG_CLIENT, etag)
}
if len(c.AuthToken) > 0 {
rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken)
}
if c.HttpHeader != nil && len(c.HttpHeader) > 0 {
for k, v := range c.HttpHeader {
rq.Header.Set(k, v)
}
}
rp, err := c.HttpClient.Do(rq)
if err != nil || rp == nil {
return nil, NewAppError(url, "model.client.connecting.app_error", nil, err.Error(), 0)
}
if rp.StatusCode == 304 {
return rp, nil
}
if rp.StatusCode >= 300 {
defer closeBody(rp)
return rp, AppErrorFromJson(rp.Body)
}
return rp, nil
}
func (c *Client4) DoUploadFile(url string, data []byte, contentType string) (*FileUploadResponse, *Response) {
return c.doUploadFile(url, bytes.NewReader(data), contentType, 0)
}
func (c *Client4) doUploadFile(url string, body io.Reader, contentType string, contentLength int64) (*FileUploadResponse, *Response) {
rq, err := http.NewRequest("POST", c.ApiUrl+url, body)
if err != nil {
return nil, &Response{Error: NewAppError(url, "model.client.connecting.app_error", nil, err.Error(), http.StatusBadRequest)}
}
if contentLength != 0 {
rq.ContentLength = contentLength
}
rq.Header.Set("Content-Type", contentType)
if len(c.AuthToken) > 0 {
rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken)
}
rp, err := c.HttpClient.Do(rq)
if err != nil || rp == nil {
return nil, BuildErrorResponse(rp, NewAppError(url, "model.client.connecting.app_error", nil, err.Error(), 0))
}
defer closeBody(rp)
if rp.StatusCode >= 300 {
return nil, BuildErrorResponse(rp, AppErrorFromJson(rp.Body))
}
return FileUploadResponseFromJson(rp.Body), BuildResponse(rp)
}
func (c *Client4) DoEmojiUploadFile(url string, data []byte, contentType string) (*Emoji, *Response) {
rq, err := http.NewRequest("POST", c.ApiUrl+url, bytes.NewReader(data))
if err != nil {
return nil, &Response{Error: NewAppError(url, "model.client.connecting.app_error", nil, err.Error(), http.StatusBadRequest)}
}
rq.Header.Set("Content-Type", contentType)
if len(c.AuthToken) > 0 {
rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken)
}
rp, err := c.HttpClient.Do(rq)
if err != nil || rp == nil {
return nil, BuildErrorResponse(rp, NewAppError(url, "model.client.connecting.app_error", nil, err.Error(), 0))
}
defer closeBody(rp)
if rp.StatusCode >= 300 {
return nil, BuildErrorResponse(rp, AppErrorFromJson(rp.Body))
}
return EmojiFromJson(rp.Body), BuildResponse(rp)
}
func (c *Client4) DoUploadImportTeam(url string, data []byte, contentType string) (map[string]string, *Response) {
rq, err := http.NewRequest("POST", c.ApiUrl+url, bytes.NewReader(data))
if err != nil {
return nil, &Response{Error: NewAppError(url, "model.client.connecting.app_error", nil, err.Error(), http.StatusBadRequest)}
}
rq.Header.Set("Content-Type", contentType)
if len(c.AuthToken) > 0 {
rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken)
}
rp, err := c.HttpClient.Do(rq)
if err != nil || rp == nil {
return nil, BuildErrorResponse(rp, NewAppError(url, "model.client.connecting.app_error", nil, err.Error(), 0))
}
defer closeBody(rp)
if rp.StatusCode >= 300 {
return nil, BuildErrorResponse(rp, AppErrorFromJson(rp.Body))
}
return MapFromJson(rp.Body), BuildResponse(rp)
}
// CheckStatusOK is a convenience function for checking the standard OK response
// from the web service.
func CheckStatusOK(r *http.Response) bool {
m := MapFromJson(r.Body)
defer closeBody(r)
if m != nil && m[STATUS] == STATUS_OK {
return true
}
return false
}
// Authentication Section
// LoginById authenticates a user by user id and password.
func (c *Client4) LoginById(id string, password string) (*User, *Response) {
m := make(map[string]string)
m["id"] = id
m["password"] = password
return c.login(m)
}
// Login authenticates a user by login id, which can be username, email or some sort
// of SSO identifier based on server configuration, and a password.
func (c *Client4) Login(loginId string, password string) (*User, *Response) {
m := make(map[string]string)
m["login_id"] = loginId
m["password"] = password
return c.login(m)
}
// LoginByLdap authenticates a user by LDAP id and password.
func (c *Client4) LoginByLdap(loginId string, password string) (*User, *Response) {
m := make(map[string]string)
m["login_id"] = loginId
m["password"] = password
m["ldap_only"] = "true"
return c.login(m)
}
// LoginWithDevice authenticates a user by login id (username, email or some sort
// of SSO identifier based on configuration), password and attaches a device id to
// the session.
func (c *Client4) LoginWithDevice(loginId string, password string, deviceId string) (*User, *Response) {
m := make(map[string]string)
m["login_id"] = loginId
m["password"] = password
m["device_id"] = deviceId
return c.login(m)
}
// LoginWithMFA logs a user in with a MFA token
func (c *Client4) LoginWithMFA(loginId, password, mfaToken string) (*User, *Response) {
m := make(map[string]string)
m["login_id"] = loginId
m["password"] = password
m["token"] = mfaToken
return c.login(m)
}
func (c *Client4) login(m map[string]string) (*User, *Response) {
r, err := c.DoApiPost("/users/login", MapToJson(m))
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
c.AuthToken = r.Header.Get(HEADER_TOKEN)
c.AuthType = HEADER_BEARER
return UserFromJson(r.Body), BuildResponse(r)
}
// Logout terminates the current user's session.
func (c *Client4) Logout() (bool, *Response) {
r, err := c.DoApiPost("/users/logout", "")
if err != nil {
return false, BuildErrorResponse(r, err)
}
defer closeBody(r)
c.AuthToken = ""
c.AuthType = HEADER_BEARER
return CheckStatusOK(r), BuildResponse(r)
}
// SwitchAccountType changes a user's login type from one type to another.
func (c *Client4) SwitchAccountType(switchRequest *SwitchRequest) (string, *Response) {
r, err := c.DoApiPost(c.GetUsersRoute()+"/login/switch", switchRequest.ToJson())
if err != nil {
return "", BuildErrorResponse(r, err)
}
defer closeBody(r)
return MapFromJson(r.Body)["follow_link"], BuildResponse(r)
}
// User Section
// CreateUser creates a user in the system based on the provided user struct.
func (c *Client4) CreateUser(user *User) (*User, *Response) {
r, err := c.DoApiPost(c.GetUsersRoute(), user.ToJson())
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserFromJson(r.Body), BuildResponse(r)
}
// CreateUserWithToken creates a user in the system based on the provided tokenId.
func (c *Client4) CreateUserWithToken(user *User, tokenId string) (*User, *Response) {
if tokenId == "" {
err := NewAppError("MissingHashOrData", "api.user.create_user.missing_token.app_error", nil, "", http.StatusBadRequest)
return nil, &Response{StatusCode: err.StatusCode, Error: err}
}
query := fmt.Sprintf("?t=%v", tokenId)
r, err := c.DoApiPost(c.GetUsersRoute()+query, user.ToJson())
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserFromJson(r.Body), BuildResponse(r)
}
// CreateUserWithInviteId creates a user in the system based on the provided invited id.
func (c *Client4) CreateUserWithInviteId(user *User, inviteId string) (*User, *Response) {
if inviteId == "" {
err := NewAppError("MissingInviteId", "api.user.create_user.missing_invite_id.app_error", nil, "", http.StatusBadRequest)
return nil, &Response{StatusCode: err.StatusCode, Error: err}
}
query := fmt.Sprintf("?iid=%v", url.QueryEscape(inviteId))
r, err := c.DoApiPost(c.GetUsersRoute()+query, user.ToJson())
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserFromJson(r.Body), BuildResponse(r)
}
// GetMe returns the logged in user.
func (c *Client4) GetMe(etag string) (*User, *Response) {
r, err := c.DoApiGet(c.GetUserRoute(ME), etag)
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserFromJson(r.Body), BuildResponse(r)
}
// GetUser returns a user based on the provided user id string.
func (c *Client4) GetUser(userId, etag string) (*User, *Response) {
r, err := c.DoApiGet(c.GetUserRoute(userId), etag)
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserFromJson(r.Body), BuildResponse(r)
}
// GetUserByUsername returns a user based on the provided user name string.
func (c *Client4) GetUserByUsername(userName, etag string) (*User, *Response) {
r, err := c.DoApiGet(c.GetUserByUsernameRoute(userName), etag)
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserFromJson(r.Body), BuildResponse(r)
}
// GetUserByEmail returns a user based on the provided user email string.
func (c *Client4) GetUserByEmail(email, etag string) (*User, *Response) {
r, err := c.DoApiGet(c.GetUserByEmailRoute(email), etag)
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserFromJson(r.Body), BuildResponse(r)
}
// AutocompleteUsersInTeam returns the users on a team based on search term.
func (c *Client4) AutocompleteUsersInTeam(teamId string, username string, limit int, etag string) (*UserAutocomplete, *Response) {
query := fmt.Sprintf("?in_team=%v&name=%v&limit=%d", teamId, username, limit)
r, err := c.DoApiGet(c.GetUsersRoute()+"/autocomplete"+query, etag)
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserAutocompleteFromJson(r.Body), BuildResponse(r)
}
// AutocompleteUsersInChannel returns the users in a channel based on search term.
func (c *Client4) AutocompleteUsersInChannel(teamId string, channelId string, username string, limit int, etag string) (*UserAutocomplete, *Response) {
query := fmt.Sprintf("?in_team=%v&in_channel=%v&name=%v&limit=%d", teamId, channelId, username, limit)
r, err := c.DoApiGet(c.GetUsersRoute()+"/autocomplete"+query, etag)
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserAutocompleteFromJson(r.Body), BuildResponse(r)
}
// AutocompleteUsers returns the users in the system based on search term.
func (c *Client4) AutocompleteUsers(username string, limit int, etag string) (*UserAutocomplete, *Response) {
query := fmt.Sprintf("?name=%v&limit=%d", username, limit)
r, err := c.DoApiGet(c.GetUsersRoute()+"/autocomplete"+query, etag)
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserAutocompleteFromJson(r.Body), BuildResponse(r)
}
// GetDefaultProfileImage gets the default user's profile image. Must be logged in.
func (c *Client4) GetDefaultProfileImage(userId string) ([]byte, *Response) {
r, appErr := c.DoApiGet(c.GetUserRoute(userId)+"/image/default", "")
if appErr != nil {
return nil, BuildErrorResponse(r, appErr)
}
defer closeBody(r)
data, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, BuildErrorResponse(r, NewAppError("GetDefaultProfileImage", "model.client.read_file.app_error", nil, err.Error(), r.StatusCode))
}
return data, BuildResponse(r)
}
// GetProfileImage gets user's profile image. Must be logged in.
func (c *Client4) GetProfileImage(userId, etag string) ([]byte, *Response) {
r, appErr := c.DoApiGet(c.GetUserRoute(userId)+"/image", etag)
if appErr != nil {
return nil, BuildErrorResponse(r, appErr)
}
defer closeBody(r)
data, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, BuildErrorResponse(r, NewAppError("GetProfileImage", "model.client.read_file.app_error", nil, err.Error(), r.StatusCode))
}
return data, BuildResponse(r)
}
// GetUsers returns a page of users on the system. Page counting starts at 0.
func (c *Client4) GetUsers(page int, perPage int, etag string) ([]*User, *Response) {
query := fmt.Sprintf("?page=%v&per_page=%v", page, perPage)
r, err := c.DoApiGet(c.GetUsersRoute()+query, etag)
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserListFromJson(r.Body), BuildResponse(r)
}
// GetUsersInTeam returns a page of users on a team. Page counting starts at 0.
func (c *Client4) GetUsersInTeam(teamId string, page int, perPage int, etag string) ([]*User, *Response) {
query := fmt.Sprintf("?in_team=%v&page=%v&per_page=%v", teamId, page, perPage)
r, err := c.DoApiGet(c.GetUsersRoute()+query, etag)
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserListFromJson(r.Body), BuildResponse(r)
}
// GetNewUsersInTeam returns a page of users on a team. Page counting starts at 0.
func (c *Client4) GetNewUsersInTeam(teamId string, page int, perPage int, etag string) ([]*User, *Response) {
query := fmt.Sprintf("?sort=create_at&in_team=%v&page=%v&per_page=%v", teamId, page, perPage)
r, err := c.DoApiGet(c.GetUsersRoute()+query, etag)
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserListFromJson(r.Body), BuildResponse(r)
}
// GetRecentlyActiveUsersInTeam returns a page of users on a team. Page counting starts at 0.
func (c *Client4) GetRecentlyActiveUsersInTeam(teamId string, page int, perPage int, etag string) ([]*User, *Response) {
query := fmt.Sprintf("?sort=last_activity_at&in_team=%v&page=%v&per_page=%v", teamId, page, perPage)
r, err := c.DoApiGet(c.GetUsersRoute()+query, etag)
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserListFromJson(r.Body), BuildResponse(r)
}
// GetUsersNotInTeam returns a page of users who are not in a team. Page counting starts at 0.
func (c *Client4) GetUsersNotInTeam(teamId string, page int, perPage int, etag string) ([]*User, *Response) {
query := fmt.Sprintf("?not_in_team=%v&page=%v&per_page=%v", teamId, page, perPage)
r, err := c.DoApiGet(c.GetUsersRoute()+query, etag)
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserListFromJson(r.Body), BuildResponse(r)
}
// GetUsersInChannel returns a page of users in a channel. Page counting starts at 0.
func (c *Client4) GetUsersInChannel(channelId string, page int, perPage int, etag string) ([]*User, *Response) {
query := fmt.Sprintf("?in_channel=%v&page=%v&per_page=%v", channelId, page, perPage)
r, err := c.DoApiGet(c.GetUsersRoute()+query, etag)
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserListFromJson(r.Body), BuildResponse(r)
}
// GetUsersInChannelByStatus returns a page of users in a channel. Page counting starts at 0. Sorted by Status
func (c *Client4) GetUsersInChannelByStatus(channelId string, page int, perPage int, etag string) ([]*User, *Response) {
query := fmt.Sprintf("?in_channel=%v&page=%v&per_page=%v&sort=status", channelId, page, perPage)
r, err := c.DoApiGet(c.GetUsersRoute()+query, etag)
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserListFromJson(r.Body), BuildResponse(r)
}
// GetUsersNotInChannel returns a page of users not in a channel. Page counting starts at 0.
func (c *Client4) GetUsersNotInChannel(teamId, channelId string, page int, perPage int, etag string) ([]*User, *Response) {
query := fmt.Sprintf("?in_team=%v¬_in_channel=%v&page=%v&per_page=%v", teamId, channelId, page, perPage)
r, err := c.DoApiGet(c.GetUsersRoute()+query, etag)
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserListFromJson(r.Body), BuildResponse(r)
}
// GetUsersWithoutTeam returns a page of users on the system that aren't on any teams. Page counting starts at 0.
func (c *Client4) GetUsersWithoutTeam(page int, perPage int, etag string) ([]*User, *Response) {
query := fmt.Sprintf("?without_team=1&page=%v&per_page=%v", page, perPage)
r, err := c.DoApiGet(c.GetUsersRoute()+query, etag)
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserListFromJson(r.Body), BuildResponse(r)
}
// GetUsersByIds returns a list of users based on the provided user ids.
func (c *Client4) GetUsersByIds(userIds []string) ([]*User, *Response) {
r, err := c.DoApiPost(c.GetUsersRoute()+"/ids", ArrayToJson(userIds))
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserListFromJson(r.Body), BuildResponse(r)
}
// GetUsersByUsernames returns a list of users based on the provided usernames.
func (c *Client4) GetUsersByUsernames(usernames []string) ([]*User, *Response) {
r, err := c.DoApiPost(c.GetUsersRoute()+"/usernames", ArrayToJson(usernames))
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserListFromJson(r.Body), BuildResponse(r)
}
// SearchUsers returns a list of users based on some search criteria.
func (c *Client4) SearchUsers(search *UserSearch) ([]*User, *Response) {
r, err := c.doApiPostBytes(c.GetUsersRoute()+"/search", search.ToJson())
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserListFromJson(r.Body), BuildResponse(r)
}
// UpdateUser updates a user in the system based on the provided user struct.
func (c *Client4) UpdateUser(user *User) (*User, *Response) {
r, err := c.DoApiPut(c.GetUserRoute(user.Id), user.ToJson())
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserFromJson(r.Body), BuildResponse(r)
}
// PatchUser partially updates a user in the system. Any missing fields are not updated.
func (c *Client4) PatchUser(userId string, patch *UserPatch) (*User, *Response) {
r, err := c.DoApiPut(c.GetUserRoute(userId)+"/patch", patch.ToJson())
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserFromJson(r.Body), BuildResponse(r)
}
// UpdateUserAuth updates a user AuthData (uthData, authService and password) in the system.
func (c *Client4) UpdateUserAuth(userId string, userAuth *UserAuth) (*UserAuth, *Response) {
r, err := c.DoApiPut(c.GetUserRoute(userId)+"/auth", userAuth.ToJson())
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return UserAuthFromJson(r.Body), BuildResponse(r)
}
// UpdateUserMfa activates multi-factor authentication for a user if activate
// is true and a valid code is provided. If activate is false, then code is not
// required and multi-factor authentication is disabled for the user.
func (c *Client4) UpdateUserMfa(userId, code string, activate bool) (bool, *Response) {
requestBody := make(map[string]interface{})
requestBody["activate"] = activate
requestBody["code"] = code
r, err := c.DoApiPut(c.GetUserRoute(userId)+"/mfa", StringInterfaceToJson(requestBody))
if err != nil {
return false, BuildErrorResponse(r, err)
}
defer closeBody(r)
return CheckStatusOK(r), BuildResponse(r)
}
// CheckUserMfa checks whether a user has MFA active on their account or not based on the
// provided login id.
// Deprecated: Clients should use Login method and check for MFA Error
func (c *Client4) CheckUserMfa(loginId string) (bool, *Response) {
requestBody := make(map[string]interface{})
requestBody["login_id"] = loginId
r, err := c.DoApiPost(c.GetUsersRoute()+"/mfa", StringInterfaceToJson(requestBody))
if err != nil {
return false, BuildErrorResponse(r, err)
}