forked from go-jira/jira
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
87 lines (74 loc) · 2.05 KB
/
session.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
package jira
import (
"bytes"
"encoding/json"
"github.com/go-jira/jira/jiradata"
)
type AuthProvider interface {
ProvideAuthParams() *jiradata.AuthParams
}
type AuthOptions struct {
Username string
Password string
}
func (a *AuthOptions) ProvideAuthParams() *jiradata.AuthParams {
return &jiradata.AuthParams{
Username: a.Username,
Password: a.Password,
}
}
// https://docs.atlassian.com/jira/REST/cloud/#auth/1/session-login
func (j *Jira) NewSession(ap AuthProvider) (*jiradata.AuthSuccess, error) {
return NewSession(j.UA, j.Endpoint, ap)
}
func NewSession(ua HttpClient, endpoint string, ap AuthProvider) (*jiradata.AuthSuccess, error) {
req := ap.ProvideAuthParams()
encoded, err := json.Marshal(req)
if err != nil {
return nil, err
}
uri := URLJoin(endpoint, "rest/auth/1/session")
resp, err := ua.Post(uri, "application/json", bytes.NewBuffer(encoded))
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == 200 {
results := &jiradata.AuthSuccess{}
return results, json.NewDecoder(resp.Body).Decode(results)
}
return nil, responseError(resp)
}
// https://docs.atlassian.com/jira/REST/cloud/#auth/1/session-currentUser
func (j *Jira) GetSession() (*jiradata.CurrentUser, error) {
return GetSession(j.UA, j.Endpoint)
}
func GetSession(ua HttpClient, endpoint string) (*jiradata.CurrentUser, error) {
uri := URLJoin(endpoint, "rest/auth/1/session")
resp, err := ua.GetJSON(uri)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == 200 {
results := &jiradata.CurrentUser{}
return results, json.NewDecoder(resp.Body).Decode(results)
}
return nil, responseError(resp)
}
// https://docs.atlassian.com/jira/REST/cloud/#auth/1/session-logout
func (j *Jira) DeleteSession() error {
return DeleteSession(j.UA, j.Endpoint)
}
func DeleteSession(ua HttpClient, endpoint string) error {
uri := URLJoin(endpoint, "rest/auth/1/session")
resp, err := ua.Delete(uri)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == 204 {
return nil
}
return responseError(resp)
}