-
Notifications
You must be signed in to change notification settings - Fork 208
/
auth.go
95 lines (83 loc) · 2.4 KB
/
auth.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
// Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved.
//
// This software (Documize Community Edition) is licensed under
// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
//
// You can operate outside the AGPL restrictions by purchasing
// Documize Enterprise Edition and obtaining a commercial license
// by contacting <sales@documize.com>.
//
// https://documize.com
package documize
import (
"encoding/base64"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"strings"
"github.com/documize/community/core/api/endpoint/models"
"github.com/documize/community/core/api/entity"
)
// Client holds the data for a sustained connection to Documize.
type Client struct {
BaseURL string
Domain string
Client *http.Client
Auth models.AuthenticationModel
}
// HeaderAuthTokenName is the name of the authorization token required in the http header
const HeaderAuthTokenName = "Authorization"
// NewClient authorizes the user on Documize and returns the Client type whose methods allow API access the Documize system.
func NewClient(baseurl, domainEmailPassword string) (*Client, error) {
c := new(Client)
c.Client = new(http.Client)
c.BaseURL = strings.TrimSuffix(baseurl, "/")
req, err := http.NewRequest("POST", c.BaseURL+"/api/public/authenticate", nil)
if err != nil {
return nil, err
}
req.Header.Add(HeaderAuthTokenName,
"Basic "+base64.StdEncoding.EncodeToString([]byte(domainEmailPassword)))
resp, err := c.Client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close() // ignore error
msg, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
err = json.Unmarshal(msg, &c.Auth)
if err != nil {
return nil, errors.New(trimErrors(string(msg)) + " : " + err.Error())
}
if err = c.Validate(); err != nil {
return nil, err
}
c.Domain = strings.Split(domainEmailPassword, ":")[0]
return c, nil
}
// Validate the current user credentials.
func (c *Client) Validate() error {
req, err := http.NewRequest("GET", c.BaseURL+"/api/public/validate", nil)
if err != nil {
return err
}
req.Header.Add("Authorization", c.Auth.Token)
resp, err := c.Client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close() // ignore error
var um entity.User
msg, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
err = json.Unmarshal(msg, &um)
if err != nil {
return errors.New(string(msg) + " : " + err.Error())
}
return nil
}