Merge: doc: fixed some typos and other misc. corrections
[nit.git] / lib / nitcorn / sessions.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
4 #
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
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
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.
16
17 # Automated session management
18 #
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.
22 module sessions
23
24 import md5
25
26 import server_config
27 import http_request
28 import http_response
29 import token
30
31 # A server side session
32 class Session
33
34 # Hashed id used both client and server side to identify this `Session`
35 var id_hash: String is noinit
36
37 init
38 do
39 loop
40 var token = generate_token
41 if sys.sessions.keys.has(token) then continue
42
43 sys.sessions[token] = self
44 self.id_hash = token
45 break
46 end
47 end
48 end
49
50 redef class Sys
51 # Active sessions
52 var sessions = new HashMap[String, Session]
53 end
54
55 redef class HttpResponse
56 # A `Session` to associate with a response
57 var session: nullable Session = null is writable
58
59 redef fun finalize
60 do
61 super
62
63 var session = self.session
64 if session != null then
65 header["Set-Cookie"] = "nitcorn_session={session.id_hash}; HttpOnly"
66 else
67 # Make sure there are no cookie left client side
68 header["Set-Cookie"] = "nitcorn_session=; HttpOnly; expires=Thu, 01 Jan 1970 00:00:00 GMT"
69 end
70 end
71 end
72
73 redef class HttpRequest
74 # The `Session` associated to this request
75 var session: nullable Session = null is writable
76 end
77
78 redef class HttpRequestParser
79 redef fun parse_http_request(text)
80 do
81 var request = super
82 if request != null then
83 if request.cookie.keys.has("nitcorn_session") then
84 var id_hash = request.cookie["nitcorn_session"]
85
86 if sys.sessions.keys.has(id_hash) then
87 # Restore the session
88 request.session = sys.sessions[id_hash]
89 end
90 end
91 end
92 return request
93 end
94 end