1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 # Automated session management
19 # When parsing a request, this module associate a pre-existing session
20 # to the request if there is one. It will also send the required cookie
21 # with the response if a session has been associated to the response object.
30 # A server side session
33 # Hashed id used both client and server side to identify this `Session`
34 var id_hash
: String is noinit
38 self.id_hash
= sys
.next_session_hash
39 sys
.sessions
[self.id_hash
] = self
45 var sessions
= new HashMap[String, Session]
47 # Get the next session hash available, and increment the session id cache
48 fun next_session_hash
: String
50 var id
= next_session_id_cache
51 # On firt evocation, seed the pseudo random number generator
57 next_session_id_cache
= id
+ 1
62 private var next_session_id_cache
: nullable Int = null
64 # Salt used to hash the session id
65 protected var session_salt
= "Default unitcorn session salt"
69 # Salt and hash and id to use as `Session.id_hash`
70 private fun to_id_hash
: String do return (self.to_s
+sys
.session_salt
).md5
73 redef class HttpResponse
74 # A `Session` to associate with a response
75 var session
: nullable Session = null is writable
81 var session
= self.session
82 if session
!= null then
83 header
["Set-Cookie"] = "nitcorn_session={session.id_hash}; HttpOnly"
85 # Make sure there are no cookie left client side
86 header
["Set-Cookie"] = "nitcorn_session=; HttpOnly; expires=Thu, 01 Jan 1970 00:00:00 GMT"
91 redef class HttpRequest
92 # The `Session` associated to this request
93 var session
: nullable Session = null
96 redef class HttpRequestParser
97 redef fun parse_http_request
(text
)
100 if request
!= null then
101 if request
.cookie
.keys
.has
("nitcorn_session") then
102 var id_hash
= request
.cookie
["nitcorn_session"]
104 if sys
.sessions
.keys
.has
(id_hash
) then
105 # Restore the session
106 request
.session
= sys
.sessions
[id_hash
]