login.go
changeset 85 abf0f5e40281
child 89 8a7a33bec6e1
equal deleted inserted replaced
84:519be52bfced 85:abf0f5e40281
       
     1 package gondole
       
     2 
       
     3 import (
       
     4 	"encoding/json"
       
     5 	"fmt"
       
     6 
       
     7 	"github.com/sendgrid/rest"
       
     8 )
       
     9 
       
    10 type UserToken struct {
       
    11 	Access_token string `json:"access_token"`
       
    12 	CreatedAt    int    `json:"created_at"`
       
    13 	Scope        string `json:"scope"`
       
    14 	TokenType    string `json:"token_type"`
       
    15 }
       
    16 
       
    17 func (g *Client) Login(username, password string) error {
       
    18 	if username == "" {
       
    19 		return fmt.Errorf("missing username")
       
    20 	}
       
    21 	if password == "" {
       
    22 		return fmt.Errorf("missing password")
       
    23 	}
       
    24 
       
    25 	hdrs := make(map[string]string)
       
    26 	opts := make(map[string]string)
       
    27 
       
    28 	hdrs["User-Agent"] = "Gondole/" + GondoleVersion
       
    29 	hdrs["Authorization"] = "Bearer %s" + g.Secret
       
    30 
       
    31 	opts["grant_type"] = "password"
       
    32 	opts["client_id"] = g.ID
       
    33 	opts["client_secret"] = g.Secret
       
    34 	opts["username"] = username
       
    35 	opts["password"] = password
       
    36 
       
    37 	req := rest.Request{
       
    38 		BaseURL:     g.InstanceURL + "/oauth/token",
       
    39 		Headers:     hdrs,
       
    40 		QueryParams: opts,
       
    41 		Method:      rest.Post,
       
    42 	}
       
    43 
       
    44 	r, err := rest.API(req)
       
    45 	if err != nil {
       
    46 		return err
       
    47 	}
       
    48 
       
    49 	var resp UserToken
       
    50 
       
    51 	println(r.Body)
       
    52 	err = json.Unmarshal([]byte(r.Body), &resp)
       
    53 	if err != nil {
       
    54 		return err
       
    55 	}
       
    56 
       
    57 	g.userToken = &resp
       
    58 	return nil
       
    59 }