/
Session.swift
274 lines (216 loc) · 6.91 KB
/
Session.swift
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
//
// Session.swift
// Noze.io
//
// Created by Helge Heß on 6/16/16.
// Copyright © 2016 ZeeZide GmbH. All rights reserved.
//
import console
import http
fileprivate let sessionIdCookie = Cookie(name: "NzSID", maxAge: 3600)
fileprivate var sessionIdCounter = 0
public typealias SessionIdGenerator = ( IncomingMessage ) -> String
func nextSessionID(msg: IncomingMessage) -> String {
// Hahahaha, Ha ha, ha, Haha!
sessionIdCounter += 1
return "\(sessionIdCounter)"
}
public func session(store s : SessionStore = InMemorySessionStore(),
cookie : Cookie? = nil,
genid : SessionIdGenerator? = nil)
-> Middleware
{
return { req, res, next in
// This is just a workaround for recursive funcs crashing the compiler.
let ctx = SessionContext(request: req, response: res,
store : s,
templateCookie : cookie ?? sessionIdCookie,
genid : genid ?? nextSessionID)
guard let sessionID = ctx.sessionID else {
// no cookie with session-ID, register new
ctx.configureNewSession()
return next()
}
// retrieve from store
s.get(sessionID: sessionID) { err, session in
guard err == nil else {
console.log("could not retrieve session with ID \(sessionID): \(err!)")
ctx.configureNewSession()
return next()
}
guard let rsession = session else {
console.log("No error, but could not retrieve session with ID" +
" \(sessionID)")
ctx.configureNewSession()
return next()
}
// found a session, store into request
req.extra[requestKey] = rsession
ctx.pushSessionCookie()
_ = res.onceFinish {
s.set(sessionID: sessionID, session: req.session) { err in
if let err = err {
console.error("could not save session \(sessionID): \(err)")
}
}
}
next()
}
}
}
class SessionContext {
// FIXME: This is temporary until the swiftc crash with inner functions
// is fixed.
// A class because we pass it around in closures.
let req : IncomingMessage
let res : ServerResponse
let store : SessionStore
let template : Cookie
let genid : SessionIdGenerator
let cookies : Cookies
var sessionID : String? = nil
init(request: IncomingMessage, response: ServerResponse,
store: SessionStore, templateCookie: Cookie,
genid: @escaping SessionIdGenerator)
{
self.req = request
self.res = response
self.store = store
self.template = templateCookie
self.genid = genid
// Derived
self.cookies = Cookies(req, res)
self.sessionID = self.cookies[templateCookie.name]
}
func pushSessionCookie() {
guard let sessionID = self.sessionID else { return }
var ourCookie = self.template
ourCookie.value = sessionID
cookies.set(cookie: ourCookie)
}
func configureNewSession() {
let newSessionID = genid(self.req)
self.req.extra[requestKey] = Session()
self.sessionID = newSessionID
pushSessionCookie()
// capture some stuff locally
let req = self.req
let store = self.store
_ = res.onceFinish {
store.set(sessionID: newSessionID, session: req.session) { err in
if let err = err {
console.error("could not save new session \(newSessionID): \(err)")
}
}
}
}
var hasSessionID : Bool { return self.sessionID != nil }
}
// MARK: - Session Class
public class Session {
// Reference type, so that we can do stuff like:
//
// req.session["a"] = 10
//
// Think about it, kinda non-obvious ;-)
public var values = Dictionary<String, Any>()
public subscript(key: String) -> Any? {
set {
if let v = newValue { values[key] = v }
else { values.removeValue(forKey: key) }
}
get { return values[key] }
}
public subscript(int key: String) -> Int {
guard let v = values[key] else { return 0 }
guard let iv = v as? Int else { return 0 }
return iv
}
}
// MARK: - IncomingMessage extension
private let requestKey = "io.noze.connect.session"
public extension IncomingMessage {
func registerNewSession() -> Session {
let newSession = Session()
extra[requestKey] = newSession
return newSession
}
var session : Session {
guard let rawSN = extra[requestKey] else { return registerNewSession() }
guard let session = rawSN as? Session else {
console.error("unexpected session object: \(requestKey) \(rawSN)")
return registerNewSession()
}
return session
}
}
// MARK: - Session Store
public enum SessionStoreError : Error {
case SessionNotFound
case NotImplemented
}
public protocol SessionStore {
// TODO: this needs the cookie timeout, so that the store can expire old
// stuff
// I don't particularily like the naming, but lets keep it close.
/// Retrieve the session for the given ID
func get(sessionID sid: String, _ cb: ( Error?, Session? ) -> Void)
/// Store the session for the given ID
func set(sessionID sid: String, session: Session,
_ cb: ( Error? ) -> Void)
/// Touch the session for the given ID
func touch(sessionID sid: String, session: Session,
_ cb: ( Error? ) -> Void)
/// Destroy the session with the given session ID
func destroy(sessionID sid: String, _ cb: ( String ) -> Void)
/// Clear all sessions in the store
func clear(cb: ( Error? ) -> Void )
/// Return the number of sessions in the store
func length(cb: ( Error?, Int) -> Void)
/// Return all sessions in the store, optional
func all(cb: ( Error?, [ Session ] ) -> Void)
}
public extension SessionStore {
func all(cb: ( Error?, [ Session ] ) -> Void) {
cb(SessionStoreError.NotImplemented, [])
}
}
public class InMemorySessionStore : SessionStore {
var store : [ String : Session ]
public init() {
store = [:]
}
public func get(sessionID sid: String, _ cb: ( Error?, Session? ) -> Void ) {
guard let session = store[sid] else {
cb(SessionStoreError.SessionNotFound, nil)
return
}
cb(nil, session)
}
public func set(sessionID sid: String, session: Session,
_ cb: ( Error? ) -> Void )
{
store[sid] = session
cb(nil)
}
public func touch(sessionID sid: String, session: Session,
_ cb: ( Error? ) -> Void )
{
cb(nil)
}
public func destroy(sessionID sid: String, _ cb: ( String ) -> Void) {
store.removeValue(forKey: sid)
cb(sid)
}
public func clear(cb: ( Error? ) -> Void ) {
store.removeAll()
cb(nil)
}
public func length(cb: ( Error?, Int) -> Void) {
cb(nil, store.count)
}
public func all(cb: ( Error?, [ Session ] ) -> Void) {
let values = Array(store.values)
cb(nil, values)
}
}