-
Notifications
You must be signed in to change notification settings - Fork 1
/
user.go
82 lines (71 loc) · 2.21 KB
/
user.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
package auth
import (
"encoding/base64"
"math/rand"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/gorilla/sessions"
)
var store = sessions.NewCookieStore([]byte(os.Getenv("SESSION_SECRET")))
// UserHelper interface has some important method to auth works
//
// PasswordByEmail 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
//
//
// FindUserDataByEmail func(email string) (string, bool)
//
// Should returns a user data in string format(json/xml)
// Will be use to SignIn handler after user SignIn
type UserHelper interface {
PasswordByEmail(email string) (string, bool)
FindUserDataByEmail(email string) (string, string, bool)
FindUserByToken(token string) (string, bool)
FindUserFromOAuth(provider string, user *User, rawResponse *http.Response) (string, error)
}
// CurrentUser func expect you send the request(```http.Request```) and return the user id as string and bool true if is OK
func (a *Auth) CurrentUser(r *http.Request) (id string, ok bool) {
tokenAuthorization := strings.Split(r.Header.Get("Authorization"), " ")
tokenQuery := r.URL.Query().Get("token")
if len(tokenAuthorization) == 2 {
id, ok = a.Helper.FindUserByToken(tokenAuthorization[1])
} else if tokenQuery != "" {
id, ok = a.Helper.FindUserByToken(tokenQuery)
} else {
session, _ := store.Get(r, "_session")
id, ok = session.Values["user_id"].(string)
}
return
}
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))
}
func (a *Auth) Login(r *http.Request, userId string) *sessions.Session {
session, _ := store.Get(r, "_session")
session.Values["user_id"] = userId
return session
}
func (a *Auth) Logout(r *http.Request) *sessions.Session {
session, _ := store.Get(r, "_session")
session.Values["user_id"] = ""
return session
}
type User struct {
Id string
Email string
Link string
Name string
Gender string
Locale string
Picture string
Token string
}