-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
71 lines (64 loc) · 1.42 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package main
import (
"fmt"
"github.com/satori/go.uuid"
"net/http"
"time"
)
func getUser(w http.ResponseWriter, req *http.Request) user {
// get cookie
c, err := req.Cookie("session")
if err != nil {
sID, _ := uuid.NewV4()
c = &http.Cookie{
Name: "session",
Value: sID.String(),
}
}
c.MaxAge = sessionLength
http.SetCookie(w, c)
// if the user exists already, get user
var u user
if s, ok := dbSessions[c.Value]; ok {
s.lastActivity = time.Now()
dbSessions[c.Value] = s
u = dbUsers[s.un]
}
return u
}
func alreadyLoggedIn(w http.ResponseWriter, req *http.Request) bool {
c, err := req.Cookie("session")
if err != nil {
return false
}
s, ok := dbSessions[c.Value]
if ok {
s.lastActivity = time.Now()
dbSessions[c.Value] = s
}
_, ok = dbUsers[s.un]
// refresh session
c.MaxAge = sessionLength
http.SetCookie(w, c)
return ok
}
func cleanSessions() {
fmt.Println("BEFORE CLEAN") // for demonstration purposes
showSessions() // for demonstration purposes
for k, v := range dbSessions {
if time.Now().Sub(v.lastActivity) > (time.Second * 30) {
delete(dbSessions, k)
}
}
dbSessionsCleaned = time.Now()
fmt.Println("AFTER CLEAN") // for demonstration purposes
showSessions() // for demonstration purposes
}
// for demonstration purposes
func showSessions() {
fmt.Println("********")
for k, v := range dbSessions {
fmt.Println(k, v.un)
}
fmt.Println("")
}