/
gothic.go
168 lines (140 loc) · 4.09 KB
/
gothic.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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
package gothic
// this code is based on https://github.com/markbates/goth/blob/master/gothic/gothic.go
import (
"encoding/base64"
"errors"
"net/http"
"os"
"time"
"github.com/gorilla/securecookie"
"github.com/markbates/goth"
)
// Options stores configuration for a secure cookie.
//
// Fields are a subset of http.Cookie fields.
type Options struct {
Path string
Domain string
// MaxAge=0 means no 'Max-Age' attribute specified.
// MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'.
// MaxAge>0 means Max-Age attribute present and given in seconds.
MaxAge int
Secure bool
HttpOnly bool
}
// CookieName is the key used to access the secure cookie.
var CookieName = "_gothic"
// CookieOptions is the options used to access the secure cookie.
var CookieOptions = Options{
Path: "/",
HttpOnly: true,
}
// StateUnsupportedProvider is the list of OAuth2.0 state parameter unsupported provider.
var StateUnsupportedProvider = map[string]struct{}{
"twitter": struct{}{},
"lastfm": struct{}{},
}
var codecs []securecookie.Codec
const stateLen = 16
func init() {
a := []byte(os.Getenv("GOTHIC_COOKIE_AUTH"))
if len(a) == 0 {
a = securecookie.GenerateRandomKey(64)
}
e := []byte(os.Getenv("GOTHIC_COOKIE_ENCRYPT"))
if len(e) == 0 {
codecs = securecookie.CodecsFromPairs(a)
} else {
codecs = securecookie.CodecsFromPairs(a, e)
}
}
// BeginAuth is a convienence function for starting the authentication process.
//
// BeginAuth will redirect the user to the appropriate authentication end-point
// for the requested provider.
func BeginAuth(providerName string, w http.ResponseWriter, r *http.Request) error {
url, err := GetAuthURL(providerName, w, r)
if err != nil {
return err
}
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
return nil
}
// GetAuthURL starts the authentication process with the requested provided.
// It will return a URL that should be used to send users to.
//
// I would recommend using the BeginAuth instead of doing all of these steps
// yourself.
func GetAuthURL(providerName string, w http.ResponseWriter, r *http.Request) (string, error) {
provider, err := goth.GetProvider(providerName)
if err != nil {
return "", err
}
state := base64.URLEncoding.EncodeToString(securecookie.GenerateRandomKey(stateLen * 3 / 4))
sess, err := provider.BeginAuth(state)
if err != nil {
return "", err
}
url, err := sess.GetAuthURL()
if err != nil {
return "", err
}
encoded, err := securecookie.EncodeMulti(CookieName, state+sess.Marshal(), codecs...)
if err != nil {
return "", err
}
http.SetCookie(w, cookie(CookieName, encoded, &CookieOptions))
return url, err
}
// CompleteAuth completes the authentication process and fetches all of the
// basic information about the user from the provider.
func CompleteAuth(providerName string, w http.ResponseWriter, r *http.Request) (goth.User, error) {
provider, err := goth.GetProvider(providerName)
if err != nil {
return goth.User{}, err
}
c, err := r.Cookie(CookieName)
if err != nil {
return goth.User{}, err
}
var ss string
err = securecookie.DecodeMulti(CookieName, c.Value, &ss, codecs...)
if err != nil {
return goth.User{}, err
}
co := CookieOptions
co.MaxAge = -1
http.SetCookie(w, cookie(CookieName, "", &co))
// verify state
_, stateUnsupported := StateUnsupportedProvider[providerName]
if len(ss) < stateLen || (!stateUnsupported && r.URL.Query().Get("state") != ss[:stateLen]) {
return goth.User{}, errors.New("oauth 2.0 state parameter does not match")
}
sess, err := provider.UnmarshalSession(ss[stateLen:])
if err != nil {
return goth.User{}, err
}
_, err = sess.Authorize(provider, r.URL.Query())
if err != nil {
return goth.User{}, err
}
return provider.FetchUser(sess)
}
func cookie(name, value string, opt *Options) *http.Cookie {
c := http.Cookie{
Name: name,
Value: value,
Path: opt.Path,
Domain: opt.Domain,
MaxAge: opt.MaxAge,
Secure: opt.Secure,
HttpOnly: opt.HttpOnly,
}
switch {
case c.MaxAge < 0:
c.Expires = time.Unix(1, 0)
case c.MaxAge > 0:
c.Expires = time.Now().Add(time.Duration(c.MaxAge) * time.Second)
}
return &c
}