forked from bradrydzewski/go.auth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoauth2.go
85 lines (69 loc) · 2.02 KB
/
oauth2.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
package auth
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"net/url"
"math/rand"
"time"
"strconv"
"github.com/bradrydzewski/go.auth/oauth2"
)
// State generator, seeded with current time
var stateGenerator = rand.New(rand.NewSource(time.Now().Unix()))
// Abstract implementation of OAuth2 for user authentication.
type OAuth2Mixin struct {
oauth2.Client
}
// RedirectRequired returns a boolean value indicating if the request should
// be redirected to the Provider's login screen, in order to provide an OAuth
// Access Token.
func (self *OAuth2Mixin) RedirectRequired(r *http.Request) bool {
return r.URL.Query().Get("code") == ""
}
// Redirects the User to the Login Screen
func (self *OAuth2Mixin) AuthorizeRedirect(w http.ResponseWriter, r *http.Request, scope string) {
state := strconv.FormatInt(stateGenerator.Int63(), 10)
url := self.Client.AuthorizeRedirect(scope, state)
http.Redirect(w, r, url, http.StatusSeeOther)
}
// Exchanges the verifier for an OAuth2 Access Token.
func (self *OAuth2Mixin) GetAccessToken(r *http.Request) (*oauth2.Token, error) {
code := r.URL.Query().Get("code")
if len(code) == 0 {
return nil, errors.New("No Access Code in the Request URL")
}
accessToken, err := self.Client.GrantToken(code)
if err != nil {
return nil, err
}
return accessToken, err
}
// Gets the Authenticated User
func (self *OAuth2Mixin) GetAuthenticatedUser(endpoint string, accessToken string, resp interface{}) error {
//create the user url
endpointUrl, _ := url.Parse(endpoint)
endpointUrl.RawQuery = "access_token="+accessToken
//create the http request for the user Url
req := http.Request{
URL: endpointUrl,
Method: "GET",
ProtoMajor: 1,
ProtoMinor: 1,
Close: true,
}
//do the http request and get the response
r, err := http.DefaultClient.Do(&req)
if err != nil {
return err
}
//get the response body
userData, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
return err
}
//unmarshal user json
return json.Unmarshal(userData, &resp)
}