/
user.go
71 lines (57 loc) · 1.56 KB
/
user.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
package client
import (
"context"
"net/http"
"net/url"
"github.com/mightymatth/arcli/config"
"github.com/spf13/viper"
)
// User represents user model in Redmine.
type User struct {
ID int64 `json:"id"`
Username string `json:"login"`
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
Email string `json:"mail"`
APIKey string `json:"api_key"`
}
// UserAPIResponse response when user is being fetched.
type UserAPIResponse struct {
User User `json:"user"`
}
// NewAuthRequest fetches user credentials for given username and password. Method uses
// simple basic authentication.
func (c *Client) NewAuthRequest(ctx context.Context, username, password string) (*http.Request, error) {
u, err := url.Parse(viper.GetString(config.Host))
if err != nil {
return nil, err
}
u.Path = "/users/current.json"
u.User = url.UserPassword(username, password)
c.setTransport()
req, err := http.NewRequestWithContext(ctx, "GET", u.String(), nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", c.UserAgent)
return req, nil
}
func (c *Client) setTransport() {
if transport := getTransport(); transport != nil {
c.HTTPClient.Transport = transport
}
}
// GetUser fetches data of currently logged user.
func (c *Client) GetUser() (*User, error) {
req, err := c.getRequest("/users/current.json", "")
if err != nil {
return nil, err
}
var userResponse UserAPIResponse
_, err = c.Do(req, &userResponse)
if err != nil {
return nil, err
}
return &(userResponse.User), nil
}