/
context.go
51 lines (46 loc) · 1.34 KB
/
context.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
package main
import (
"github.com/gorilla/securecookie"
"net/http"
"time"
)
type Context struct {
Database
// the key used to sign client-side secure session cookies.
// should probably be changed in production, but not random
// so that cookies stay valid across nodes/app restarts.
SecureKey []byte
// how long to keep a stream online after the broadcaster has disconnected.
// if the stream does not resume within this time, all clients get dropped.
StreamKeepAlive time.Duration
cookieCodec *securecookie.SecureCookie
}
func (c *Context) GetAuthInfo(r *http.Request) (*UserData, error) {
if c.cookieCodec == nil {
c.cookieCodec = securecookie.New(c.SecureKey, nil)
}
var uid int64
if cookie, err := r.Cookie("uid"); err == nil {
if err = c.cookieCodec.Decode("uid", cookie.Value, &uid); err == nil {
return c.GetUserFull(uid)
}
}
return nil, ErrUserNotExist
}
func (c *Context) SetAuthInfo(w http.ResponseWriter, id int64) error {
if id == -1 {
http.SetCookie(w, &http.Cookie{Name: "uid", Value: "", Path: "/", MaxAge: 0})
} else {
if c.cookieCodec == nil {
c.cookieCodec = securecookie.New(c.SecureKey, nil)
}
enc, err := c.cookieCodec.Encode("uid", id)
if err != nil {
return err
}
http.SetCookie(w, &http.Cookie{
Name: "uid", Value: enc, Path: "/", HttpOnly: true, MaxAge: 31536000,
})
}
return nil
}