forked from McKael/madon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
99 lines (82 loc) · 2.18 KB
/
app.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
96
97
98
99
/*
Copyright 2017-2018 Mikael Berthe
Copyright 2017 Ollivier Robert
Licensed under the MIT license. Please see the LICENSE file is this directory.
*/
package madon
import (
"net/url"
"strings"
"github.com/pkg/errors"
"github.com/sendgrid/rest"
)
type registerApp struct {
ID int64 `json:"id,string"`
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
}
// buildInstanceURL creates the URL from the instance name or cleans up the
// provided URL
func buildInstanceURL(instanceName string) (string, error) {
if instanceName == "" {
return "", errors.New("no instance provided")
}
instanceURL := instanceName
if !strings.Contains(instanceURL, "/") {
instanceURL = "https://" + instanceName
}
u, err := url.ParseRequestURI(instanceURL)
if err != nil {
return "", err
}
u.Path = ""
u.RawPath = ""
u.RawQuery = ""
u.Fragment = ""
return u.String(), nil
}
// NewApp registers a new application with a given instance
func NewApp(name, website string, scopes []string, redirectURI, instanceName string) (mc *Client, err error) {
instanceURL, err := buildInstanceURL(instanceName)
if err != nil {
return nil, err
}
mc = &Client{
Name: name,
InstanceURL: instanceURL,
APIBase: instanceURL + currentAPIPath,
}
params := make(apiCallParams)
params["client_name"] = name
if website != "" {
params["website"] = website
}
params["scopes"] = strings.Join(scopes, " ")
if redirectURI != "" {
params["redirect_uris"] = redirectURI
} else {
params["redirect_uris"] = NoRedirect
}
var app registerApp
if err := mc.apiCall("v1/apps", rest.Post, params, nil, nil, &app); err != nil {
return nil, err
}
mc.ID = app.ClientID
mc.Secret = app.ClientSecret
return
}
// RestoreApp recreates an application client with existing secrets
func RestoreApp(name, instanceName, appID, appSecret string, userToken *UserToken) (mc *Client, err error) {
instanceURL, err := buildInstanceURL(instanceName)
if err != nil {
return nil, err
}
return &Client{
Name: name,
InstanceURL: instanceURL,
APIBase: instanceURL + currentAPIPath,
ID: appID,
Secret: appSecret,
UserToken: userToken,
}, nil
}