This repository has been archived by the owner on Apr 2, 2021. It is now read-only.
forked from centimitr/oauth2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeviceauth.go
80 lines (69 loc) · 1.93 KB
/
deviceauth.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
package oauth2
import (
"context"
"encoding/json"
"fmt"
"golang.org/x/net/context/ctxhttp"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
const (
errAuthorizationPending = "authorization_pending"
errSlowDown = "slow_down"
errAccessDenied = "access_denied"
errExpiredToken = "expired_token"
)
type DeviceAuth struct {
DeviceCode string `json:"device_code"`
UserCode string `json:"user_code"`
VerificationURI string `json:"verification_uri,verification_url"`
VerificationURIComplete string `json:"verification_uri_complete,omitempty"`
ExpiresIn int `json:"expires_in"`
Interval int `json:"interval,omitempty"`
raw map[string]interface{}
}
func retrieveDeviceAuth(ctx context.Context, c *Config, v url.Values) (*DeviceAuth, error) {
req, err := http.NewRequest("POST", c.Endpoint.DeviceAuthURL, strings.NewReader(v.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
r, err := ctxhttp.Do(ctx, nil, req)
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1<<20))
if err != nil {
return nil, fmt.Errorf("oauth2: cannot auth device: %v", err)
}
if code := r.StatusCode; code < 200 || code > 299 {
return nil, &RetrieveError{
Response: r,
Body: body,
}
}
var da = &DeviceAuth{}
err = json.Unmarshal(body, &da)
if err != nil {
return nil, err
}
_ = json.Unmarshal(body, &da.raw)
// Azure AD supplies verification_url instead of verification_uri
if da.VerificationURI == "" {
da.VerificationURI, _ = da.raw["verification_url"].(string)
}
return da, nil
}
func parseError(err error) string {
e, ok := err.(*RetrieveError)
if ok {
eResp := make(map[string]string)
_ = json.Unmarshal(e.Body, &eResp)
return eResp["error"]
}
return ""
}