forked from tomsteele/dmv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
github.go
132 lines (125 loc) · 3.73 KB
/
github.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
package dmv
import (
"code.google.com/p/goauth2/oauth"
"encoding/json"
"github.com/codegangsta/martini"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
var (
ghProfileURL = "https://api.github.com/user"
)
// Github stores the access and refresh tokens along with the users profile.
type Github struct {
Errors []error
AccessToken string
RefreshToken string
Profile GithubProfile
}
// GithubProfile stores information about the user from Github.
type GithubProfile struct {
ID int `json:"id"`
Name string `json:"name"`
Login string `json:"login"`
HTMLURL string `json:"html_url"`
Email string `json:"email"`
}
// AuthGithub authenticates users using Github and OAuth2.0. After handling
// a callback request, a request is made to get the users Github profile
// and a Github 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() {
// ghOpts := &dmv.OAuth2.0Options{
// ClientID: "oauth_id",
// ClientSecret: "oauth_secret",
// RedirectURL: "http://host:port/auth/callback/github",
// }
//
// 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/github", dmv.AuthGithub(ghOpts))
// m.Get("/auth/callback/github", dmv.AuthGithub(ghOpts), func(gh *dmv.Github, req *http.Request, w http.ResponseWriter) {
// // Handle any errors.
// if len(gh.Errors) > 0 {
// http.Error(w, "Oauth failure", http.StatusInternalServerError)
// return
// }
// // Do something in a database to create or find the user by the Github profile id.
// user := findOrCreateByGithubID(gh.Profile.ID)
// s.Set("userID", user.ID)
// http.Redirect(w, req, "/", http.StatusFound)
// })
// }
func AuthGithub(opts *OAuth2Options) martini.Handler {
opts.AuthURL = "https://github.com/login/oauth/authorize"
opts.TokenURL = "https://github.com/login/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
}
gh := &Github{}
defer c.Map(gh)
code := r.FormValue("code")
tk, err := transport.Exchange(code)
if err != nil {
gh.Errors = append(gh.Errors, err)
return
}
gh.AccessToken = tk.AccessToken
gh.RefreshToken = tk.RefreshToken
resp, err := transport.Client().Get(ghProfileURL)
if err != nil {
gh.Errors = append(gh.Errors, err)
return
}
defer resp.Body.Close()
profile := &GithubProfile{}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
gh.Errors = append(gh.Errors, err)
return
}
if err := json.Unmarshal(data, profile); err != nil {
gh.Errors = append(gh.Errors, err)
return
}
gh.Profile = *profile
return
}
}