forked from tomsteele/dmv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
facebook.go
139 lines (131 loc) · 3.94 KB
/
facebook.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
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
134
135
136
137
138
139
package dmv
import (
"code.google.com/p/goauth2/oauth"
"encoding/json"
"github.com/codegangsta/martini"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
var (
fbProfileURL = "https://graph.facebook.com/me"
)
// Facebook stores the access and refresh tokens along with the users
// profile.
type Facebook struct {
Errors []error
AccessToken string
RefreshToken string
Profile FacebookProfile
}
// FacebookProfile stores information about the user from facebook.
type FacebookProfile struct {
ID string `json:"id"`
Username string `json:"username"`
Name string `json:"name"`
LastName string `json:"last_name"`
FirstName string `json:"first_name"`
MiddleName string `json:"middle_name"`
Gender string `json:"gender"`
Link string `json:"link"`
Email string `json:"email"`
}
// AuthFacebook authenticates users using Facebook and OAuth2.0. After
// handling a callback request, a request is made to get the users
// facebook profile and a Facebook 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"
// "net/http"
// )
//
// func main() {
// fbOpts := &dmv.OAuth2.0Options{
// ClientID: "oauth_id",
// ClientSecret: "oauth_secret",
// RedirectURL: "http://host:port/auth/callback/facebook",
// }
//
// m := martini.Classic()
// store := sessions.NewCookieStore([]byte("secret123"))
// m.Use(sessions.Sessions("my_session", store))
//
// m.Get("/", func(s sessions.Session) string {
// return "hi" + s.Get("userID")
// })
// m.Get("/auth/facebook", dmv.AuthFacebook(fbOpts))
// m.Get("/auth/callback/facebook", dmv.AuthFacebook(fbOpts), func(fb *dmv.Facebook, req *http.Request, w http.ResponseWriter) {
// // Handle any errors.
// if len(fb.Errors) > 0 {
// http.Error(w, "Oauth failure", http.StatusInternalServerError)
// return
// }
// // Do something in a database to create or find the user by the facebook profile id.
// user := findOrCreateByFacebookID(fb.Profile.ID)
// s.Set("userID", user.ID)
// http.Redirect(w, req, "/", http.StatusFound)
// })
// }
func AuthFacebook(opts *OAuth2Options) martini.Handler {
opts.AuthURL = "https://www.facebook.com/dialog/oauth"
opts.TokenURL = "https://graph.facebook.com/oauth/access_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
}
fb := &Facebook{}
defer c.Map(fb)
code := r.FormValue("code")
tk, err := transport.Exchange(code)
if err != nil {
fb.Errors = append(fb.Errors, err)
return
}
fb.AccessToken = tk.AccessToken
fb.RefreshToken = tk.RefreshToken
resp, err := transport.Client().Get(fbProfileURL)
if err != nil {
fb.Errors = append(fb.Errors, err)
return
}
defer resp.Body.Close()
profile := &FacebookProfile{}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
fb.Errors = append(fb.Errors, err)
return
}
if err := json.Unmarshal(data, profile); err != nil {
fb.Errors = append(fb.Errors, err)
return
}
fb.Profile = *profile
return
}
}