-
Notifications
You must be signed in to change notification settings - Fork 7
/
auth.go
98 lines (82 loc) · 2.41 KB
/
auth.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
package podio
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
type AuthToken struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
Ref map[string]interface{} `json:"ref"`
TransferToken string `json:"transfer_token"`
}
func AuthWithUserCredentials(clientId string, clientSecret string, username string, password string) (*AuthToken, error) {
data := url.Values{
"grant_type": {"password"},
"username": {username},
"password": {password},
"client_id": {clientId},
"client_secret": {clientSecret},
}
return authRequest(data)
}
func AuthWithAppCredentials(clientId, clientSecret string, appId int64, appToken string) (*AuthToken, error) {
data := url.Values{
"grant_type": {"app"},
"app_id": {fmt.Sprintf("%d", appId)},
"app_token": {appToken},
"client_id": {clientId},
"client_secret": {clientSecret},
}
return authRequest(data)
}
func RefreshTokenWithAppCredentials(clientId, clientSecret string, appId int64, refreshToken string) (*AuthToken, error) {
data := url.Values{
"grant_type": {"refresh_token"},
"app_id": {fmt.Sprintf("%d", appId)},
"refresh_token": {refreshToken},
"client_id": {clientId},
"client_secret": {clientSecret},
}
return authRequest(data)
}
func AuthWithAuthCode(clientId, clientSecret, authCode, redirectUri string) (*AuthToken, error) {
data := url.Values{
"grant_type": {"authorization_code"},
"client_id": {clientId},
"client_secret": {clientSecret},
"redirect_uri": {redirectUri},
"code": {authCode},
}
return authRequest(data)
}
func authRequest(data url.Values) (*AuthToken, error) {
var authToken AuthToken
resp, err := http.PostForm("https://api.podio.com/oauth/token", data)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if !(200 <= resp.StatusCode && resp.StatusCode <= 299) {
podioErr := &Error{}
err := json.Unmarshal(respBody, podioErr)
if err != nil {
return nil, errors.New(string(respBody))
}
return nil, podioErr
}
err = json.Unmarshal(respBody, &authToken)
if err != nil {
return nil, err
}
return &authToken, nil
}