Skip to content

Commit f9bf334

Browse files
committed
Updating to August 4, 2016
1 parent 8b73f49 commit f9bf334

8 files changed

Lines changed: 70 additions & 83 deletions

.swift-version

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
swift-DEVELOPMENT-SNAPSHOT-2016-05-31-a
1+
swift-DEVELOPMENT-SNAPSHOT-2016-08-04-a

Package.swift

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,8 @@ import PackageDescription
33
let package = Package(
44
name: "SessionMiddleware",
55
dependencies: [
6-
.Package(url: "https://github.com/Zewo/HTTP.git", majorVersion: 0, minor: 8),
7-
.Package(url: "https://github.com/open-swift/S4.git", majorVersion: 0, minor: 9),
8-
.Package(url: "https://github.com/noppoMan/Crypto.git", majorVersion: 0, minor: 4),
9-
.Package(url: "https://github.com/noppoMan/Suv.git", majorVersion: 0, minor: 8)
6+
.Package(url: "https://github.com/slimane-swift/HTTP.git", majorVersion: 0, minor: 12),
7+
.Package(url: "https://github.com/noppoMan/Crypto.git", majorVersion: 0, minor: 5),
8+
.Package(url: "https://github.com/noppoMan/Suv.git", majorVersion: 0, minor: 10)
109
]
1110
)

Sources/CookieParser.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ func decode(_ val: String) throws -> String {
2424
let str = val.substring(from: val.index(val.startIndex, offsetBy: 2))
2525
let searchCharacter: Character = "."
2626
guard let index = str.lowercased().characters.index(of: searchCharacter) else {
27-
throw Error.cookieParserFailure("Invalid cookie value")
27+
throw SessionError.cookieParserFailure
2828
}
2929
return str.substring(to: index)
3030
}
@@ -54,7 +54,7 @@ func unsignSync(_ val: String, secret: String) throws -> String {
5454
let sha1val = try sha1.hashSync(val)
5555

5656
if sha1mac.bytes != sha1val.bytes {
57-
throw Error.cookieParserFailure("Invalid session value")
57+
throw SessionError.cookieParserFailure
5858
}
5959

6060
return str

Sources/Error.swift

Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,8 @@
66
// Copyright © 2016 MikeTOKYO. All rights reserved.
77
//
88

9-
internal enum Error: ErrorProtocol, CustomStringConvertible {
10-
case serializerFailure(String)
11-
case cookieParserFailure(String)
9+
internal enum SessionError: Error {
10+
case serializerFailure
11+
case cookieParserFailure
1212
case noSessionID
13-
14-
var description: String {
15-
switch(self) {
16-
case .serializerFailure(let message):
17-
return message
18-
case .cookieParserFailure(let message):
19-
return message
20-
case .noSessionID:
21-
return "No session id"
22-
}
23-
}
2413
}

Sources/Session.swift

Lines changed: 27 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@ public struct SessionConfig {
1313

1414
public let secret: String
1515

16-
public let expires: Int?
16+
public let expiration: Int?
1717

18-
public let HTTPOnly: Bool
18+
public let httpOnly: Bool
1919

2020
public let secure: Bool
2121

@@ -25,12 +25,12 @@ public struct SessionConfig {
2525

2626
public let path: String?
2727

28-
public init(keyName: String = "slimane_sesid", secret: String, expires: Int? = nil, HTTPOnly: Bool = false, maxAge: Int? = nil, domain: String? = nil, path: String? = nil, secure: Bool = false, store: SessionStoreType = SessionMemoryStore()){
28+
public init(keyName: String = "slimane_sesid", secret: String, expiration: Int? = nil, httpOnly: Bool = false, maxAge: Int? = nil, domain: String? = nil, path: String? = "/", secure: Bool = false, store: SessionStoreType = SessionMemoryStore()){
2929
self.keyName = keyName
3030
self.secret = secret
3131
self.store = store
32-
self.expires = expires
33-
self.HTTPOnly = HTTPOnly
32+
self.expiration = expiration
33+
self.httpOnly = httpOnly
3434
self.secure = secure
3535
self.maxAge = maxAge
3636
self.domain = domain
@@ -40,77 +40,79 @@ public struct SessionConfig {
4040

4141
public struct Session {
4242

43-
private var conf: SessionConfig
43+
private var config: SessionConfig
4444

4545
public internal(set) var id: String? = nil
4646

4747
var values = [String: String]() {
4848
didSet {
4949
if let id = self.id {
5050
// Need to emit string error
51-
self.conf.store.store(id, values: values, expires: ttl) { _ in }
51+
self.config.store.store(id, values: values, expiration: ttl) { _ in }
5252
}
5353
}
5454
}
5555

56-
init(conf: SessionConfig){
57-
self.conf = conf
56+
init(config: SessionConfig){
57+
self.config = config
5858
}
5959

6060
public var keyName: String {
61-
return self.conf.keyName
61+
return self.config.keyName
6262
}
6363

6464
public var secret: String {
65-
return self.conf.secret
65+
return self.config.secret
6666
}
6767

68-
public var HTTPOnly: Bool {
69-
return self.conf.HTTPOnly
68+
public var httpOnly: Bool {
69+
return self.config.httpOnly
7070
}
7171

7272
public var secure: Bool {
73-
return self.conf.secure
73+
return self.config.secure
7474
}
7575

7676
public var maxAge: Int? {
77-
return self.conf.maxAge
77+
return self.config.maxAge
7878
}
7979

8080
public var domain: String? {
81-
return self.conf.domain
81+
return self.config.domain
8282
}
8383

8484
public var path: String? {
85-
return self.conf.path
85+
return self.config.path
8686
}
8787

88-
public var expires: Time? {
88+
public var expiration: Time? {
8989
if let ttl = self.ttl {
9090
return Time(tz: .Local).addSec(ttl)
9191
}
9292
return nil
9393
}
9494

9595
public var ttl: Int? {
96-
return self.conf.expires
96+
return self.config.expiration
9797
}
9898

9999
public var hashValue: Int {
100-
return self.conf.keyName.hashValue
100+
return self.config.keyName.hashValue
101101
}
102102

103-
public func load(_ completion: (SessionResult<[String: String]>) -> Void){
103+
public func load(_ completion: @escaping ((Void) throws -> [String: String]) -> Void){
104104
if let id = self.id {
105-
self.conf.store.load(id, completion: completion)
105+
self.config.store.load(id, completion: completion)
106106
} else {
107-
completion(.error(Error.noSessionID))
107+
completion {
108+
throw SessionError.noSessionID
109+
}
108110
}
109111
}
110112

111113
public func destroy(){
112114
if let id = self.id {
113-
self.conf.store.destroy(id)
115+
self.config.store.destroy(id)
114116
}
115117
}
116118

@@ -121,15 +123,9 @@ public struct Session {
121123

122124
extension Session: Sequence {
123125

124-
#if swift(>=3.0)
125126
public func makeIterator() -> DictionaryIterator<String, String> {
126127
return values.makeIterator()
127128
}
128-
#else
129-
public func generate() -> DictionaryGenerator<String, String> {
130-
return values.generate()
131-
}
132-
#endif
133129

134130
public var count: Int {
135131
return values.count
@@ -152,4 +148,4 @@ extension Session: Sequence {
152148
self.values[key] = newValue
153149
}
154150
}
155-
}
151+
}

Sources/SessionMemoryStore.swift

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,14 @@ public struct SessionMemoryStore: SessionStoreType {
1212

1313
public init(){}
1414

15-
public func load(_ sessionId: String, completion: (SessionResult<[String: String]>) -> Void) {
15+
public func load(_ sessionId: String, completion: @escaping ((Void) throws -> [String: String]) -> Void) {
1616
guard let sesValues = sessionMap[sessionId] else {
17-
return completion(.data([:]))
17+
return completion { [:] }
1818
}
19-
completion(.data(sesValues))
19+
completion { sesValues }
2020
}
2121

22-
public func store(_ key: String, values: [String: String], expires: Int?, completion: () -> Void) {
22+
public func store(_ key: String, values: [String: String], expiration: Int?, completion: @escaping () -> Void) {
2323
sessionMap[key] = values
2424
completion()
2525
}

Sources/SessionMiddleware.swift

Lines changed: 28 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -34,28 +34,28 @@ extension Request {
3434
public struct SessionMiddleware: AsyncMiddleware {
3535
var session: Session
3636

37-
public init(conf: SessionConfig){
38-
session = Session(conf: conf)
37+
public init(config: SessionConfig){
38+
session = Session(config: config)
3939
}
4040

41-
public func respond(to request: Request, chainingTo next: AsyncResponder, result: ((Void) throws -> Response) -> Void) {
41+
public func respond(to request: Request, chainingTo next: AsyncResponder, result: @escaping ((Void) throws -> Response) -> Void) {
4242
var req = request
4343
req.storage[makeKey("session")] = session
4444

45-
var err: ErrorProtocol? = nil
46-
var setCookie: S4.Cookies? = nil
45+
var err: Error? = nil
46+
var setCookie: Set<AttributedCookie>? = nil
4747

4848
let onThread = {
4949
// Parse signedCookies
50-
if let cookieString = req.headers["cookie"], cookies = HTTP.Cookie.parse(string: cookieString) {
50+
if let cookieString = req.headers["cookie"], let cookies = Set<Cookie>(cookieHeader: cookieString) {
5151
req.storage["signedCookies"] = signedCookies(cookies, secret: self.session.secret)
5252
}
5353

5454
if self.shouldSetCookie(req) {
5555
do {
56-
let cookie = try self.initCookieForSet()
57-
setCookie = S4.Cookies(cookies: [cookie])
58-
req.session?.id = signedCookies(Set([HTTP.Cookie(name: cookie.name, value: cookie.value)]), secret: self.session.secret)[self.session.keyName]
56+
let cookie = try self.createCookieForSet()
57+
setCookie = Set<AttributedCookie>([cookie])
58+
req.session?.id = signedCookies(Set([Cookie(name: cookie.name, value: cookie.value)]), secret: self.session.secret)[self.session.keyName]
5959
} catch {
6060
err = error
6161
}
@@ -88,27 +88,27 @@ public struct SessionMiddleware: AsyncMiddleware {
8888

8989
req.session?.id = sessionId
9090

91-
req.session?.load() {
91+
req.session?.load() { getData in
9292
req.session?.values = [:]
93-
94-
if case .error(let error) = $0 {
95-
result {
93+
94+
do {
95+
let data = try getData()
96+
req.session?.values = data
97+
} catch {
98+
return result {
9699
throw error
97100
}
98101
}
99-
else if case .data(let sesValue) = $0 {
100-
req.session?.values = sesValue
101-
}
102+
102103
next.respond(to: req, result: result)
103104
}
104105
}
105106

106107
Process.qwork(onThread: onThread, onFinish: onFinish)
107108
}
108109

109-
110110
private func shouldSetCookie(_ req: Request) -> Bool {
111-
guard let cookieValue = req.cookies.filter({ (k,_) in k.trim() == session.keyName }).map({ (_,v) in v}).first else {
111+
guard let cookieValue = req.cookies.filter({ $0.name.trim() == session.keyName }).map({ $0.value }).first else {
112112
return true
113113
}
114114

@@ -121,8 +121,16 @@ public struct SessionMiddleware: AsyncMiddleware {
121121
}
122122
}
123123

124-
private func initCookieForSet() throws -> S4.Cookie {
124+
private func createCookieForSet() throws -> AttributedCookie {
125125
let sessionId = try signSync(Session.generateId().hexadecimalString(), secret: session.secret)
126-
return S4.Cookie(name: session.keyName, value: sessionId, expires: session.expires?.rfc822, maxAge: session.maxAge, domain: session.domain, path: session.path, secure: session.secure, HTTPOnly: session.HTTPOnly)
126+
127+
var maxAge: AttributedCookie.Expiration?
128+
if let ttl = session.ttl {
129+
maxAge = .maxAge(ttl)
130+
} else {
131+
maxAge = nil
132+
}
133+
134+
return AttributedCookie(name: session.keyName, value: sessionId, expiration: maxAge , domain: session.domain, path: session.path, secure: session.secure, httpOnly: session.httpOnly)
127135
}
128136
}

Sources/SessionStoreType.swift

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,8 @@
66
// Copyright © 2016 MikeTOKYO. All rights reserved.
77
//
88

9-
public enum SessionResult<T> {
10-
case data(T)
11-
case error(ErrorProtocol)
12-
}
13-
149
public protocol SessionStoreType {
1510
func destroy(_ sessionId: String)
16-
func load(_ sessionId: String, completion: (SessionResult<[String: String]>) -> Void)
17-
func store(_ sessionId: String, values: [String: String], expires: Int?, completion: () -> Void)
11+
func load(_ sessionId: String, completion: @escaping ((Void) throws -> [String: String]) -> Void)
12+
func store(_ sessionId: String, values: [String: String], expiration: Int?, completion: @escaping () -> Void)
1813
}

0 commit comments

Comments
 (0)