-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
207 lines (177 loc) · 5.04 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
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
// ==================================================
// Copyright (c) 2016 tacigar. All rights reserved.
// ==================================================
package mixo
import (
"bufio"
"bytes"
"crypto/rand"
"encoding/base64"
"io"
"net/http"
"net/url"
"os"
"regexp"
)
// --------------------------------------------------
type Session struct {
sessionName string
sessionID string
sessionFileName string
}
type SessionManager struct {
sessionName string
maxLifeTime int
}
// session manager is managed by session manager manager
// session manager manager is passed for context by default key
type sessionManagerManager map[string]*SessionManager
// --------------------------------------------------
// key for context's metadata
const sessionDefaultKey = "assdfqw82987ep98dofi22asdoif9j"
// session file directory. do not change it.
var tempDir = "/tmp"
// var tempDir, _ = ioutil.TempDir("", "mixo-sessions")
func generateSessionFileName(sessionName, sessionID string) string {
buffer := bytes.NewBufferString(tempDir)
buffer.WriteRune('/')
buffer.WriteString(sessionName)
buffer.WriteRune('_')
buffer.WriteString(sessionID)
return buffer.String()
}
// generate random session id
func generateSessionID() string {
b := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, b); err != nil {
return ""
}
return base64.URLEncoding.EncodeToString(b)
}
// --------------------------------------------------
func SessionStart(sessionName string, maxLifeTime int) Handler {
sessionManager := &SessionManager{
sessionName: sessionName,
maxLifeTime: maxLifeTime,
}
// return handler for router
return func(context *Context) {
tmp, exists := context.GetMetadata(sessionDefaultKey)
var smm sessionManagerManager
if !exists {
smm = sessionManagerManager{}
} else {
smm = tmp.(sessionManagerManager)
}
// register session manager
smm[sessionName] = sessionManager
context.SetMetadata(sessionDefaultKey, smm)
}
}
func GetSessionManager(context *Context, sessionName string) *SessionManager {
tmp, _ := context.GetMetadata(sessionDefaultKey)
smm := tmp.(sessionManagerManager)
sessionManager, _ := smm[sessionName]
return sessionManager
}
// --------------------------------------------------
// generate new session and bake to cookie.
func (sessionManager *SessionManager) NewSession(context *Context) *Session {
sessionName := sessionManager.sessionName
sessionID := url.QueryEscape(generateSessionID())
newSession := &Session{
sessionName: sessionName,
sessionID: sessionID,
sessionFileName: generateSessionFileName(sessionName, sessionID),
}
// baking to cookie
cookie := &http.Cookie{
Name: sessionManager.sessionName,
Value: sessionID,
Path: "/",
HttpOnly: true,
MaxAge: sessionManager.maxLifeTime,
}
http.SetCookie(context.ResponseWriter, cookie)
return newSession
}
// load session files and return session object
func (sessionManager *SessionManager) GetSession(context *Context) *Session {
request := context.Request
sessionName := sessionManager.sessionName
cookie, err := request.Cookie(sessionName)
if err != nil {
return nil
}
sessionID := cookie.Value
sessionFileName := generateSessionFileName(sessionName, sessionID)
return &Session{
sessionName: sessionName,
sessionID: sessionID,
sessionFileName: sessionFileName,
}
}
// --------------------------------------------------
// regular expression object to divide key and value of session file
var divideSessionFileLineRegexp = regexp.MustCompile("(.*)=(.*)")
func divideSessionFileLine(lineStr string) (string, string) {
groups := divideSessionFileLineRegexp.FindSubmatch([]byte(lineStr))
return string(groups[1]), string(groups[2])
}
// --------------------------------------------------
// set key and value to session file
func (session *Session) Set(key, value string) error {
buffer := bytes.NewBufferString("")
file, err := os.Open(session.sessionFileName)
keyIsFound := false
if err == nil {
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lineStr := scanner.Text()
k, _ := divideSessionFileLine(lineStr)
if k == key {
buffer.WriteString(key)
buffer.WriteRune('=')
buffer.WriteString(value)
buffer.WriteRune('\n')
keyIsFound = true
} else {
buffer.WriteString(lineStr)
buffer.WriteRune('\n')
}
}
file.Close()
}
// if key isn't found, add new line.
if !keyIsFound {
buffer.WriteString(key)
buffer.WriteRune('=')
buffer.WriteString(value)
buffer.WriteRune('\n')
}
file, err = os.Create(session.sessionFileName)
if err != nil {
return err
}
file.Write(buffer.Bytes())
file.Close()
return nil
}
// get key and value from session file
func (session *Session) Get(key string) (string, error) {
file, err := os.Open(session.sessionFileName)
if err != nil {
return "", err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lineStr := scanner.Text()
k, v := divideSessionFileLine(lineStr)
if k == key {
return v, nil
}
}
// if cannot find key, return empty string, but return error
return "", nil
}