-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathgoogle.go
More file actions
133 lines (126 loc) · 3.99 KB
/
google.go
File metadata and controls
133 lines (126 loc) · 3.99 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package dmv
import (
"code.google.com/p/goauth2/oauth"
"encoding/json"
"github.com/codegangsta/martini"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
var (
googleProfileURL = "https://www.googleapis.com/oauth2/v1/userinfo"
)
// Google stores the access and refresh tokens along with the user profile.
type Google struct {
Errors []error
AccessToken string
RefreshToken string
Profile GoogleProfile
}
// GoogleProfile stores information from the users google+ profile.
type GoogleProfile struct {
ID string `json:"id"`
DisplayName string `json:"name"`
FamilyName string `json:"family_name"`
GivenName string `json:"given_name"`
Email string `json:"email"`
}
// AuthGoogle authenticates users using Google and OAuth2.0. After handling
// a callback request, a request is made to get the users Google profile
// and a Google struct will be mapped to the current request context.
//
// This function should be called twice in each application, once on the login
// handler and once on the callback handler.
//
// package main
//
// import (
// "github.com/codegangsta/martini"
// "github.com/martini-contrib/sessions"
// "github.com/thomasjsteele/dmv"
// "net/http"
// )
//
// func main() {
// googleOpts := &dmv.OAuth2Options{
// ClientID: "oauth_id",
// ClientSecret: "oauth_secret",
// RedirectURL: "http://host:port/auth/callback/google",
// Scopes: []string{"https://www.googleapis.com/auth/userinfo.email",
// "https://www.googleapis.com/auth/userinfo.profile"},
// }
//
// m := martini.Classic()
// store := sessions.NewCookieStore([]byte("secret123"))
// m.Use(sessions.Sessions("my_session", store))
//
// m.Get("/", func(s sessions.Session) string {
// return "hello" + s.Get("userID")
// })
// m.Get("/auth/google", dmv.AuthGoogle(googleOpts))
// m.Get("/auth/callback/google", dmv.AuthGoogle(googleOpts), func(goog *dmv.Google, req *http.Request, w http.ResponseWriter) {
// // Handle any errors.
// if len(goog.Errors) > 0 {
// http.Error(w, "OAuth failure", http.StatusInternalServerError)
// return
// }
// // Do something in a database to create or find the user by the Google profile id.
// s.Set("userID", goog.Profile.ID)
// http.Redirect(w, req, "/", http.StatusFound)
// })
// }
func AuthGoogle(opts *OAuth2Options) martini.Handler {
opts.AuthURL = "https://accounts.google.com/o/oauth2/auth"
opts.TokenURL = "https://accounts.google.com/o/oauth2/token"
config := &oauth.Config{
ClientId: opts.ClientID,
ClientSecret: opts.ClientSecret,
RedirectURL: opts.RedirectURL,
Scope: strings.Join(opts.Scopes, " "),
AuthURL: opts.AuthURL,
TokenURL: opts.TokenURL,
}
transport := &oauth.Transport{
Config: config,
Transport: http.DefaultTransport,
}
cbPath := ""
if u, err := url.Parse(opts.RedirectURL); err == nil {
cbPath = u.Path
}
return func(r *http.Request, w http.ResponseWriter, c martini.Context) {
if r.URL.Path != cbPath {
http.Redirect(w, r, transport.Config.AuthCodeURL(""), http.StatusFound)
return
}
goog := &Google{}
defer c.Map(goog)
code := r.FormValue("code")
tk, err := transport.Exchange(code)
if err != nil {
goog.Errors = append(goog.Errors, err)
return
}
goog.AccessToken = tk.AccessToken
goog.RefreshToken = tk.RefreshToken
resp, err := transport.Client().Get(googleProfileURL)
if err != nil {
goog.Errors = append(goog.Errors, err)
return
}
defer resp.Body.Close()
profile := &GoogleProfile{}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
goog.Errors = append(goog.Errors, err)
return
}
if err := json.Unmarshal(data, profile); err != nil {
goog.Errors = append(goog.Errors, err)
return
}
goog.Profile = *profile
return
}
}