/
auth.go
361 lines (316 loc) · 10.7 KB
/
auth.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
// Package login2 provides sign in and sign up by oauth2 and email and password.
// Inspired in omniauth and devise gem
//
package login2
import (
"encoding/base64"
"encoding/json"
"log"
"math/rand"
"net/http"
"os"
"strconv"
"strings"
"time"
"code.google.com/p/go.crypto/bcrypt"
"code.google.com/p/goauth2/oauth"
"github.com/gorilla/sessions"
)
var store = sessions.NewCookieStore([]byte(os.Getenv("SESSION_SECRET")))
// Provider is a oauth2 provider, like facebook or google
// Name is provider name, it's like a key, will can be use it after,
// the package only use it as a index.
// Key is oauth2 key
// Secret is oauth2 secret key
// RedirectURL is a url will config on provider
// TokenURL is a URL to get the token on provider
// AuthURL is a URL to auth user on provider
// UserInfoURL is a URL to get User Information on provider
// Scope is whats the scope your app wants
type Provider struct {
Name string
Key string
Secret string
RedirectURL string
TokenURL string
AuthURL string
UserInfoURL string
Scope string
}
// Internal auth config
type builderConfig struct {
Auth *oauth.Config
UserInfoURL string
}
// URLS
type URLS struct {
Redirect string
SignIn string
SignUp string
ResetPasswordSuccess string
}
// Builder is the app configuration, store providers and callbacks
//
// Follow the callbacks documentation:
//
// UserSetupFn func(provider string, user *login2.User, rawResponse *http.Response) (int64, error)
//
// Called when user return from oauth provider, this method will send a provider
// origin as string, some user information as ```login2.User``` and the raw
// response from origin(login2 will make a request to ``` UserInfoURL```
// configured on provider config). To sign in user the method expect the user
// id as int64
//
//
// UserCreateFn func(email string, password string, token string, request *http.Request) (int64, error)
//
// Called when user sign up by email/password, the method will send email and password as string, password // is encrypted hash, and expect the user id as int64
//
// UserIdByEmail func(email string) (int64, error)
//
// Called when user sign in by email/password to get the user id by email after check the password with ```UserPasswordByEmail```, the method will send the user email as string and expect the user id as int64
//
// UserPasswordByEmail func(email string) (string, bool)
//
// Called when user sign in by email/password to get user password and check with inputed password, the method will send user email as string and expect the user password as string
//
// UserResetPasswordFn func(token string, email string)
// TODO
type Builder struct {
Providers map[string]*builderConfig
UserSetupFn func(provider string, user *User, rawResponde *http.Response) (int64, error)
UserCreateFn func(email string, password string, token string, request *http.Request) (int64, error)
UserResetPasswordFn func(token string, email string)
UserIdByEmail func(email string) (int64, error) // TODO: use bool as second params
UserIdByToken func(token string) (int64, bool)
UserPasswordByEmail func(email string) (string, bool)
LoginFn func(userId string)
URLS URLS
}
type User struct {
Id string
Email string
Link string
Name string
Gender string
Locale string
Picture string
Token string
}
func NewBuilder() *Builder { // TODO: changes to NewAuth
builder := new(Builder)
builder.Providers = make(map[string]*builderConfig, 0)
return builder
}
func (b *Builder) NewProviders(providers []*Provider) {
for _, p := range providers {
b.NewProvider(p)
}
}
func (b *Builder) NewProvider(p *Provider) {
config := &oauth.Config{
ClientId: p.Key,
ClientSecret: p.Secret,
RedirectURL: p.RedirectURL,
Scope: p.Scope,
AuthURL: p.AuthURL,
TokenURL: p.TokenURL,
}
provider := new(builderConfig)
provider.Auth = config
provider.UserInfoURL = p.UserInfoURL
b.Providers[p.Name] = provider
}
// HTTP server
// OAuthAuthorize To authorize user on defined provider. Send provider name as params and method will return http handle
//
// ```
// GET /auth/google loginBuilder.OAuthAuthorize("google")
// GET /auth/facebook loginBuilder.OAuthAuthorize("facebook")
// ```
func (b *Builder) OAuthAuthorize(provider string) func(http.ResponseWriter, *http.Request) {
config := b.Providers[provider]
return func(w http.ResponseWriter, r *http.Request) {
url := config.Auth.AuthCodeURL("")
log.Println("Send user to", provider)
http.Redirect(w, r, url, http.StatusFound)
}
}
// OAuthLogin The oauth endpoint callback, configured on provider, Send provider name as params and method will return http handle
//
// ```
// GET /auth/callback/google loginBuilder.OAuthLogin("google")
// GET /auth/callback/facebook loginBuilder.OAuthLogin("facebook")
// ```
func (b *Builder) OAuthLogin(provider string) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, request *http.Request) {
userId, err := b.OAuthCallback(provider, request)
if err != nil {
http.Redirect(w, request, b.URLS.SignIn, http.StatusTemporaryRedirect)
} else {
b.login(request, w, strconv.FormatInt(userId, 10))
}
}
}
// OAuthCallback receive code params from provider and get user information
func (b *Builder) OAuthCallback(provider string, r *http.Request) (int64, error) {
config := b.Providers[provider]
code := r.FormValue("code")
t := &oauth.Transport{Config: config.Auth}
t.Exchange(code)
responseAuth, _ := t.Client().Get(config.UserInfoURL)
defer responseAuth.Body.Close()
var user User
decoder := json.NewDecoder(responseAuth.Body)
user.Token = NewUserToken()
err := decoder.Decode(&user)
if err != nil {
panic(err)
}
return b.UserSetupFn(provider, &user, responseAuth)
}
// SignUp Hanlder to sign up user, send a http POST with email and password params on body
//
// ```
// POST /users/sign_up SignUp
// ```
func (b *Builder) SignUp() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, request *http.Request) {
email := request.FormValue("email")
password := request.FormValue("password")
hpassword, err := generateHash(password)
if err != nil {
http.Redirect(w, request, b.URLS.SignUp+"?password=error", http.StatusTemporaryRedirect)
return
}
userID, err := b.UserCreateFn(email, hpassword, NewUserToken(), request)
if err != nil {
http.Redirect(w, request, b.URLS.SignIn+"?user=exists", http.StatusTemporaryRedirect)
} else {
b.login(request, w, strconv.FormatInt(userID, 10))
}
}
}
// SignIn Handler to sign in user, send a http POST with email and password params on body
//
// ```
// POST /users/sign_in SignIn
// ```
func (b *Builder) SignIn() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
email := r.FormValue("email")
password := r.FormValue("password")
userPassword, ok := b.UserPasswordByEmail(email)
if !ok {
http.Redirect(w, r, b.URLS.SignIn+"?user=not_found", http.StatusTemporaryRedirect)
}
err := checkHash(userPassword, password)
if err != nil {
http.Redirect(w, r, b.URLS.SignIn+"?user=no_match", http.StatusTemporaryRedirect)
} else {
userId, _ := b.UserIdByEmail(email)
b.login(r, w, strconv.FormatInt(userId, 10))
}
}
}
// SignOut Handler Method to sign out user, send a http GET
//
// ```
// GET /users/sign_out SignOut
// ```
func (b *Builder) SignOut() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
session := b.Logout(r)
session.Save(r, w)
http.Redirect(w, r, b.URLS.SignIn, http.StatusTemporaryRedirect)
}
}
// Protected to be used on protected path, send the original http handle as params and if user is logged Protected will pass user to original handler else Protected will save URL and send user to Sign In. Protected send as first params the user id.
//
// ```
// GET /dashboard Protected(DashboardHandle)
// ```
func (b *Builder) Protected(fn func(string, http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
userID, ok := b.CurrentUser(r)
if ok {
fn(userID, w, r)
} else {
b.SetReturnTo(w, r, r.URL.String())
http.Redirect(w, r, b.URLS.SignIn, http.StatusTemporaryRedirect)
}
}
}
func (b *Builder) SetReturnTo(w http.ResponseWriter, r *http.Request, url string) {
session, _ := store.Get(r, "_session")
session.Values["return_to"] = url
session.Save(r, w)
}
func (b *Builder) ResetPassword() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
email := r.FormValue("email")
token := NewUserToken()
go b.UserResetPasswordFn(token, email)
http.Redirect(w, r, b.URLS.ResetPasswordSuccess, http.StatusTemporaryRedirect)
}
}
func (b *Builder) Login(r *http.Request, userId string) *sessions.Session {
session, _ := store.Get(r, "_session")
session.Values["user_id"] = userId
return session
}
func (b *Builder) Logout(r *http.Request) *sessions.Session {
session, _ := store.Get(r, "_session")
session.Values["user_id"] = nil
return session
}
// helper
func (b *Builder) login(r *http.Request, w http.ResponseWriter, userId string) {
session := b.Login(r, userId)
var returnTo string
returnToSession := session.Values["return_to"]
returnTo, ok := returnToSession.(string)
if !ok {
returnTo = b.URLS.Redirect
}
go b.LoginFn(userId)
session.Values["return_to"] = nil
session.Save(r, w)
http.Redirect(w, r, returnTo, 302)
}
// CurrentUser func expect you send the request(```http.Request```) and return the user id as string and bool true if is OK
func (b *Builder) CurrentUser(r *http.Request) (id string, ok bool) {
session, _ := store.Get(r, "_session")
userId := session.Values["user_id"]
id, ok = userId.(string)
if !ok {
id, ok = b.getUserIdByAuthorizationToken(r)
}
return
}
func (b *Builder) getUserIdByAuthorizationToken(r *http.Request) (id string, ok bool) {
tokenAuthorization := strings.Split(r.Header.Get("Authorization"), " ")
if len(tokenAuthorization) == 2 {
var _id int64
_id, ok = b.UserIdByToken(tokenAuthorization[1])
id = strconv.Itoa(int(_id))
return
}
return
}
// GenerateHash wrapper to bcrypt.GenerateFromPassword
func generateHash(data string) (string, error) {
h, err := bcrypt.GenerateFromPassword([]byte(data), 0)
return string(h[:]), err
}
func checkHash(hashed, plain string) error {
return bcrypt.CompareHashAndPassword([]byte(hashed), []byte(plain))
}
func generateRandomToken() int64 {
rand.Seed(time.Now().Unix())
return rand.Int63()
}
func NewUserToken() string {
hash, _ := generateHash(strconv.Itoa(int(generateRandomToken())))
return base64.URLEncoding.EncodeToString([]byte(hash))
}