app.go
author Ollivier Robert <roberto@keltia.net>
Tue, 11 Apr 2017 17:04:40 +0200
changeset 67 1ff7afce37fe
parent 66 965586c1e3ed
child 80 d6e8807818c4
permissions -rw-r--r--
Add a baseURL parameter to NewApp(). This allow for overriding the URL of the instance you are going to talk to during the first call to NewApp(). We have a chicken-and-egg issue otherwise. We need to register before doing anything.

package gondole

import (
	"encoding/json"
	"github.com/sendgrid/rest"
	"log"
	"strings"
)

var (
	ourScopes = []string{
		"read",
		"write",
		"follow",
	}
)

type registerApp struct {
	ID           string `json:"id"`
	ClientID     string `json:"client_id"`
	ClientSecret string `json:"client_secret"`
}

func registerApplication(name string, scopes []string, redirectURI, baseURL string) (g *Gondole, err error) {
	g = &Gondole{
		Name: name,
	}

	req := g.prepareRequest("apps")
	if redirectURI != "" {
		req.QueryParams["redirect_uris"] = redirectURI
	} else {
		req.QueryParams["redirect_uris"] = NoRedirect
	}
	req.QueryParams["client_name"] = name
	req.QueryParams["scopes"] = strings.Join(scopes, " ")
	req.Method = rest.Post

	r, err := rest.API(req)
	if err != nil {
		log.Fatalf("error can not register app: %v", err)
	}

	var resp registerApp

	err = json.Unmarshal([]byte(r.Body), &resp)
	if err != nil {
		log.Fatalf("error can not register app: %v", err)
	}
	g.ID = resp.ClientID
	g.Secret = resp.ClientSecret

	server := &Server{
		ID:          g.ID,
		Name:        name,
		BearerToken: g.Secret,
		BaseURL:     baseURL,
	}
	err = server.WriteToken(name)
	if err != nil {
		log.Fatalf("error: can not write token for %s", name)
	}
	return
}

// NewApp registers a new instance
func NewApp(name string, scopes []string, redirectURI, baseURL  string) (g *Gondole, err error) {

	if baseURL != "" {
		APIEndpoint = baseURL
	}

	// Load configuration, will register if none is found
	cnf, err := LoadConfig(name)
	if err != nil {
		// Nothing exist yet
		cnf := Config{
			Default: name,
		}
		err = cnf.Write()
		if err != nil {
			log.Fatalf("error: can not write config for %s", name)
		}

		// Now register this through OAuth
		if scopes == nil {
			scopes = ourScopes
		}

		g, err = registerApplication(name, scopes, redirectURI, baseURL)

	} else {
		g = &Gondole{
			Name:   cnf.Name,
			ID:     cnf.ID,
			Secret: cnf.BearerToken,
		}
	}

	return
}