forked from nabowler/echo-gothic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gothic.go
224 lines (183 loc) · 5.98 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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
/* Based on https://github.com/markbates/goth/blob/edc3e96387cb58c3f3d58e70db2f115815ccdf1e/gothic/gothic.go */
package echogothic
import (
"errors"
"fmt"
"net/http"
"net/url"
"os"
"github.com/gorilla/sessions"
"github.com/labstack/echo/v4"
"github.com/markbates/goth"
"github.com/markbates/goth/gothic"
)
var defaultStore sessions.Store
var keySet = false
func init() {
key := []byte(os.Getenv("SESSION_SECRET"))
keySet = len(key) != 0
defaultStore = gothic.Store
}
/*
BeginAuthHandler is a convenience handler for starting the authentication process.
It expects to be able to get the name of the provider from the query parameters
as either "provider" or ":provider".
BeginAuthHandler will redirect the user to the appropriate authentication end-point
for the requested provider.
*/
func BeginAuthHandler(ectx echo.Context) error {
url, err := GetAuthURL(ectx)
if err != nil {
return err
}
return ectx.Redirect(http.StatusTemporaryRedirect, url)
}
// SetState sets the state string associated with the given request.
// If no state string is associated with the request, one will be generated.
// This state is sent to the provider and can be retrieved during the
// callback.
var SetState = func(ectx echo.Context) string {
return gothic.SetState(ectx.Request())
}
// GetState gets the state returned by the provider during the callback.
// This is used to prevent CSRF attacks, see
// http://tools.ietf.org/html/rfc6749#section-10.12
var GetState = func(ectx echo.Context) string {
return gothic.GetState(ectx.Request())
}
/*
GetAuthURL starts the authentication process with the requested provided.
It will return a URL that should be used to send users to.
It expects to be able to get the name of the provider from the query parameters
as either "provider" or ":provider".
I would recommend using the BeginAuthHandler instead of doing all of these steps
yourself, but that's entirely up to you.
*/
func GetAuthURL(ectx echo.Context) (string, error) {
if !keySet && defaultStore == gothic.Store {
fmt.Println("goth/gothic: no SESSION_SECRET environment variable is set. The default cookie store is not available and any calls will fail. Ignore this warning if you are using a different store.")
}
providerName, err := GetProviderName(ectx)
if err != nil {
return "", err
}
provider, err := goth.GetProvider(providerName)
if err != nil {
return "", err
}
sess, err := provider.BeginAuth(SetState(ectx))
if err != nil {
return "", err
}
url, err := sess.GetAuthURL()
if err != nil {
return "", err
}
err = StoreInSession(providerName, sess.Marshal(), ectx)
if err != nil {
return "", err
}
return url, err
}
/*
CompleteUserAuth does what it says on the tin. It completes the authentication
process and fetches all of the basic information about the user from the provider.
It expects to be able to get the name of the provider from the query parameters
as either "provider" or ":provider".
*/
var CompleteUserAuth = func(ectx echo.Context) (goth.User, error) {
if !keySet && defaultStore == gothic.Store {
fmt.Println("goth/gothic: no SESSION_SECRET environment variable is set. The default cookie store is not available and any calls will fail. Ignore this warning if you are using a different store.")
}
defer func() {
// TODO: log?
_ = Logout(ectx)
}()
providerName, err := GetProviderName(ectx)
if err != nil {
return goth.User{}, err
}
provider, err := goth.GetProvider(providerName)
if err != nil {
return goth.User{}, err
}
value, err := GetFromSession(providerName, ectx)
if err != nil {
return goth.User{}, err
}
sess, err := provider.UnmarshalSession(value)
if err != nil {
return goth.User{}, err
}
err = validateState(ectx, sess)
if err != nil {
return goth.User{}, err
}
user, err := provider.FetchUser(sess)
if err == nil {
// user can be found with existing session data
return user, err
}
params := ectx.Request().URL.Query()
if params.Encode() == "" && ectx.Request().Method == "POST" {
err = ectx.Request().ParseForm()
if err != nil {
return goth.User{}, err
}
params = ectx.Request().Form
}
// get new token and retry fetch
_, err = sess.Authorize(provider, params)
if err != nil {
return goth.User{}, err
}
err = StoreInSession(providerName, sess.Marshal(), ectx)
if err != nil {
return goth.User{}, err
}
gu, err := provider.FetchUser(sess)
return gu, err
}
// validateState ensures that the state token param from the original
// AuthURL matches the one included in the current (callback) request.
func validateState(ectx echo.Context, sess goth.Session) error {
rawAuthURL, err := sess.GetAuthURL()
if err != nil {
return err
}
authURL, err := url.Parse(rawAuthURL)
if err != nil {
return err
}
reqState := GetState(ectx)
originalState := authURL.Query().Get("state")
if originalState != "" && (originalState != reqState) {
return errors.New("state token mismatch")
}
return nil
}
// Logout invalidates a user session.
func Logout(ectx echo.Context) error {
return gothic.Logout(ectx.Response(), ectx.Request())
}
// GetProviderName is a function used to get the name of a provider
// for a given request. By default, this provider is fetched from
// the URL query string. If you provide it in a different way,
// assign your own function to this variable that returns the provider
// name for your request.
var GetProviderName = getProviderName
func getProviderName(ectx echo.Context) (string, error) {
if p := ectx.Param("provider"); p != "" {
return p, nil
}
return gothic.GetProviderName(ectx.Request())
}
// StoreInSession stores a specified key/value pair in the session.
func StoreInSession(key string, value string, ectx echo.Context) error {
return gothic.StoreInSession(key, value, ectx.Request(), ectx.Response())
}
// GetFromSession retrieves a previously-stored value from the session.
// If no value has previously been stored at the specified key, it will return an error.
func GetFromSession(key string, ectx echo.Context) (string, error) {
return gothic.GetFromSession(key, ectx.Request())
}