github.com/elliott5/community@v0.14.1-0.20160709191136-823126fb026a/sdk/auth.go (about) 1 // Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved. 2 // 3 // This software (Documize Community Edition) is licensed under 4 // GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html 5 // 6 // You can operate outside the AGPL restrictions by purchasing 7 // Documize Enterprise Edition and obtaining a commercial license 8 // by contacting <sales@documize.com>. 9 // 10 // https://documize.com 11 12 package documize 13 14 import ( 15 "encoding/base64" 16 "encoding/json" 17 "errors" 18 "io/ioutil" 19 "net/http" 20 "strings" 21 22 "github.com/documize/community/documize/api/endpoint/models" 23 "github.com/documize/community/documize/api/entity" 24 ) 25 26 // Client holds the data for a sustained connection to Documize. 27 type Client struct { 28 BaseURL string 29 Domain string 30 Client *http.Client 31 Auth models.AuthenticationModel 32 } 33 34 // HeaderAuthTokenName is the name of the authorization token required in the http header 35 const HeaderAuthTokenName = "Authorization" 36 37 // NewClient authorizes the user on Documize and returns the Client type whose methods allow API access the Documize system. 38 func NewClient(baseurl, domainEmailPassword string) (*Client, error) { 39 c := new(Client) 40 c.Client = new(http.Client) 41 c.BaseURL = strings.TrimSuffix(baseurl, "/") 42 43 req, err := http.NewRequest("POST", c.BaseURL+"/api/public/authenticate", nil) 44 if err != nil { 45 return nil, err 46 } 47 req.Header.Add(HeaderAuthTokenName, 48 "Basic "+base64.StdEncoding.EncodeToString([]byte(domainEmailPassword))) 49 resp, err := c.Client.Do(req) 50 if err != nil { 51 return nil, err 52 } 53 defer resp.Body.Close() // ignore error 54 55 msg, err := ioutil.ReadAll(resp.Body) 56 if err != nil { 57 return nil, err 58 } 59 err = json.Unmarshal(msg, &c.Auth) 60 if err != nil { 61 return nil, errors.New(trimErrors(string(msg)) + " : " + err.Error()) 62 } 63 64 if err = c.Validate(); err != nil { 65 return nil, err 66 } 67 68 c.Domain = strings.Split(domainEmailPassword, ":")[0] 69 70 return c, nil 71 } 72 73 // Validate the current user credentials. 74 func (c *Client) Validate() error { 75 req, err := http.NewRequest("GET", c.BaseURL+"/api/public/validate", nil) 76 if err != nil { 77 return err 78 } 79 req.Header.Add("Authorization", c.Auth.Token) 80 resp, err := c.Client.Do(req) 81 if err != nil { 82 return err 83 } 84 defer resp.Body.Close() // ignore error 85 var um entity.User 86 msg, err := ioutil.ReadAll(resp.Body) 87 if err != nil { 88 return err 89 } 90 err = json.Unmarshal(msg, &um) 91 if err != nil { 92 return errors.New(string(msg) + " : " + err.Error()) 93 } 94 return nil 95 }