File: client.go

package info (click to toggle)
golang-github-koofr-go-koofrclient 0.0~git20190724.8e5366d-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 136 kB
  • sloc: makefile: 5
file content (94 lines) | stat: -rw-r--r-- 1,861 bytes parent folder | download | duplicates (2)
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
package koofrclient

import (
	"fmt"
	"net/http"
	"net/url"

	"github.com/koofr/go-httpclient"
)

type KoofrClient struct {
	*httpclient.HTTPClient
	token  string
	userID string
}

func NewKoofrClient(baseUrl string, disableSecurity bool) *KoofrClient {
	var httpClient *httpclient.HTTPClient

	if disableSecurity {
		httpClient = httpclient.Insecure()
	} else {
		httpClient = httpclient.New()
	}

	return NewKoofrClientWithHTTPClient(baseUrl, httpClient)
}

func NewKoofrClientWithHTTPClient(baseUrl string, httpClient *httpclient.HTTPClient) *KoofrClient {
	apiBaseUrl, _ := url.Parse(baseUrl)

	httpClient.BaseURL = apiBaseUrl

	client:= &KoofrClient{
		HTTPClient: httpClient,
		token:      "",
		userID:     "",
	}

	client.SetUserAgent("go koofrclient")
	return client
}

func (c *KoofrClient) SetUserAgent(ua string) {
	c.Headers.Set("User-Agent", ua)
}

func (c *KoofrClient) SetToken(token string) {
	c.token = token
	c.HTTPClient.Headers.Set("Authorization", fmt.Sprintf("Token token=%s", token))
}

func (c *KoofrClient) GetToken() string {
	return c.token
}

func (c *KoofrClient) SetUserID(userID string) {
	c.userID = userID
}

func (c *KoofrClient) GetUserID() string {
	return c.userID
}

func (c *KoofrClient) Authenticate(email string, password string) (err error) {
	var tokenResponse Token

	tokenRequest := TokenRequest{
		Email:    email,
		Password: password,
	}

	request := httpclient.RequestData{
		Method:         "POST",
		Path:           "/token",
		Headers:        make(http.Header),
		ExpectedStatus: []int{http.StatusOK},
		ReqEncoding:    httpclient.EncodingJSON,
		ReqValue:       tokenRequest,
		RespEncoding:   httpclient.EncodingJSON,
		RespValue:      &tokenResponse,
	}

	res, err := c.Request(&request)

	if err != nil {
		return
	}

	c.SetToken(tokenResponse.Token)
	c.SetUserID(res.Header.Get("X-User-ID"))

	return
}