-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsessions.go
118 lines (97 loc) · 2.37 KB
/
sessions.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
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
"net/http"
)
var cookie_store = sessions.NewCookieStore(securecookie.GenerateRandomKey(64))
type Session struct {
SessionId int64
SessionSecret string `json:"-"`
UserId int64
}
func (s *Session) Write(w http.ResponseWriter) error {
enc := json.NewEncoder(w)
return enc.Encode(s)
}
func GetSession(r *http.Request) (*Session, error) {
var s Session
session, _ := cookie_store.Get(r, "togodo")
_, ok := session.Values["session-secret"]
if !ok {
return nil, fmt.Errorf("session-secret cookie not set")
}
s.SessionSecret = session.Values["session-secret"].(string)
err := DB.SelectOne(&s, "SELECT * from sessions where SessionSecret=?", s.SessionSecret)
if err != nil {
return nil, err
}
return &s, nil
}
func DeleteSessionIfExists(r *http.Request) {
session, err := GetSession(r)
if err == nil {
DB.Delete(session)
}
}
func NewSession(w http.ResponseWriter, r *http.Request, userid int64) (*Session, error) {
s := Session{}
session, _ := cookie_store.Get(r, "togodo")
session.Values["session-secret"] = string(securecookie.GenerateRandomKey(64))
s.SessionSecret = session.Values["session-secret"].(string)
s.UserId = userid
err := DB.Insert(&s)
if err != nil {
return nil, err
}
err = session.Save(r, w)
if err != nil {
return nil, err
} else {
return &s, nil
}
}
func SessionHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" || r.Method == "PUT" {
user_json := r.PostFormValue("user")
if user_json == "" {
WriteError(w, 3 /*Invalid Request*/)
return
}
user := User{}
err := user.Read(user_json)
if err != nil {
WriteError(w, 3 /*Invalid Request*/)
return
}
dbuser, err := GetUserByUsername(user.Username)
if err != nil {
WriteError(w, 2 /*Unauthorized Access*/)
return
}
user.HashPassword()
if user.PasswordHash != dbuser.PasswordHash {
WriteError(w, 2 /*Unauthorized Access*/)
return
}
DeleteSessionIfExists(r)
_, err = NewSession(w, r, dbuser.UserId)
if err != nil {
WriteError(w, 999 /*Internal Error*/)
return
}
WriteSuccess(w)
} else if r.Method == "GET" {
s, err := GetSession(r)
if err != nil {
WriteError(w, 1 /*Not Signed In*/)
return
}
s.Write(w)
} else if r.Method == "DELETE" {
DeleteSessionIfExists(r)
WriteSuccess(w)
}
}