/
session.go
57 lines (46 loc) · 1.28 KB
/
session.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
package session
import (
"net/http"
"github.com/airware/vili/util"
)
const (
sessionCookie = "session"
)
// User is the user or robot making the request
type User struct {
Email string `json:"email"`
Username string `json:"username"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
}
var service Service
// Service is an authentication service interface
type Service interface {
Login(r *http.Request, w http.ResponseWriter, u *User) error
Logout(r *http.Request, w http.ResponseWriter) error
GetUser(r *http.Request) (*User, error)
}
// Login logs the user in with the auth service that was initialized
func Login(r *http.Request, w http.ResponseWriter, u *User) error {
return service.Login(r, w, u)
}
// Logout logs the user in with the auth service that was initialized
func Logout(r *http.Request, w http.ResponseWriter) error {
return service.Logout(r, w)
}
// GetUser logs the user in with the auth service that was initialized
func GetUser(r *http.Request) (*User, error) {
return service.GetUser(r)
}
// helper functions
func getSessionCookie(r *http.Request) string {
for _, cookie := range r.Cookies() {
if cookie.Name == sessionCookie {
return cookie.Value
}
}
return ""
}
func newSessionID() string {
return util.RandString(40)
}