~thrrgilag/woodstock

woodstock/access_token.go -rw-r--r-- 1.9 KiB
62b10b5cMorgan McMillian Update for new project location and module name 3 months ago
                                                                                
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
package woodstock

import (
	"net/url"
	"strings"
)

// App or client object, https://pnut.io/docs/resources/clients
type App struct {
	ID   string `json:"id"`
	Link string `json:"link"`
	Name string `json:"name"`
}

// Token object, https://pnut.io/docs/resources/token
type Token struct {
	App      App      `json:"app"`
	Scopes   []string `json:"scopes"`
	User     User     `json:"user"`
	ClientID string   `json:"client_id"`
}

// AccessTokenResult object
type AccessTokenResult struct {
	AccessToken string `json:"access_token"`
	Token       Token  `json:"token"`
	UserID      string `json:"user_id"`
	Username    string `json:"username"`
}

// AccessToken retrieves an access token using an authorization code
// https://pnut.io/docs/authentication/web-flows
func (c *Client) AccessToken(code string, redirectURI string) (result AccessTokenResult, err error) {
	v := url.Values{}
	v.Set("client_id", c.clientID)
	v.Set("client_secret", c.clientSecret)
	v.Set("code", code)
	v.Set("redirect_uri", redirectURI)
	v.Set("grant_type", "authorization_code")
	responseCh := make(chan response)
	c.queryQueue <- query{url: OAuthAccessTokenAPI, form: v, data: &result, method: "POST", responseCh: responseCh}
	return result, (<-responseCh).err
}

// AccessTokenFromPassword retrieves an access token from using a password
// https://pnut.io/docs/authentication/password-flow
func (c *Client) AccessTokenFromPassword(username string, password string, scope []string) (result AccessTokenResult, err error) {
	v := url.Values{}
	v.Set("client_id", c.clientID)
	v.Set("password_grant_secret", c.passwordGrantSecret)
	v.Set("username", username)
	v.Set("password", password)
	v.Set("grant_type", "password")
	v.Set("scope", strings.Join(scope, ","))
	responseCh := make(chan response)
	c.queryQueue <- query{url: OAuthAccessTokenAPI, form: v, data: &result, method: "POST", responseCh: responseCh}
	return result, (<-responseCh).err
}