Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/cherrypy/test/sessiondemo.py
blob: 342e5b597bf44851c7a3cebe87ff88b0870a9d3c (plain)
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
#!/usr/bin/python
"""A session demonstration app."""

import calendar
from datetime import datetime
import sys
import cherrypy
from cherrypy.lib import sessions
from cherrypy._cpcompat import copyitems


page = """
<html>
<head>
<style type='text/css'>
table { border-collapse: collapse; border: 1px solid #663333; }
th { text-align: right; background-color: #663333; color: white; padding: 0.5em; }
td { white-space: pre-wrap; font-family: monospace; padding: 0.5em; 
     border: 1px solid #663333; }
.warn { font-family: serif; color: #990000; }
</style>
<script type="text/javascript">
<!--
function twodigit(d) { return d < 10 ? "0" + d : d; }
function formattime(t) {
    var month = t.getUTCMonth() + 1;
    var day = t.getUTCDate();
    var year = t.getUTCFullYear();
    var hours = t.getUTCHours();
    var minutes = t.getUTCMinutes();
    return (year + "/" + twodigit(month) + "/" + twodigit(day) + " " +
            hours + ":" + twodigit(minutes) + " UTC");
}

function interval(s) {
    // Return the given interval (in seconds) as an English phrase
    var seconds = s %% 60;
    s = Math.floor(s / 60);
    var minutes = s %% 60;
    s = Math.floor(s / 60);
    var hours = s %% 24;
    var v = twodigit(hours) + ":" + twodigit(minutes) + ":" + twodigit(seconds);
    var days = Math.floor(s / 24);
    if (days != 0) v = days + ' days, ' + v;
    return v;
}

var fudge_seconds = 5;

function init() {
    // Set the content of the 'btime' cell.
    var currentTime = new Date();
    var bunixtime = Math.floor(currentTime.getTime() / 1000);
    
    var v = formattime(currentTime);
    v += " (Unix time: " + bunixtime + ")";
    
    var diff = Math.abs(%(serverunixtime)s - bunixtime);
    if (diff > fudge_seconds) v += "<p class='warn'>Browser and Server times disagree.</p>";
    
    document.getElementById('btime').innerHTML = v;
    
    // Warn if response cookie expires is not close to one hour in the future.
    // Yes, we want this to happen when wit hit the 'Expire' link, too.
    var expires = Date.parse("%(expires)s") / 1000;
    var onehour = (60 * 60);
    if (Math.abs(expires - (bunixtime + onehour)) > fudge_seconds) {
        diff = Math.floor(expires - bunixtime);
        if (expires > (bunixtime + onehour)) {
            var msg = "Response cookie 'expires' date is " + interval(diff) + " in the future.";
        } else {
            var msg = "Response cookie 'expires' date is " + interval(0 - diff) + " in the past.";
        }
        document.getElementById('respcookiewarn').innerHTML = msg;
    }
}
//-->
</script>
</head>

<body onload='init()'>
<h2>Session Demo</h2>
<p>Reload this page. The session ID should not change from one reload to the next</p>
<p><a href='../'>Index</a> | <a href='expire'>Expire</a> | <a href='regen'>Regenerate</a></p>
<table>
    <tr><th>Session ID:</th><td>%(sessionid)s<p class='warn'>%(changemsg)s</p></td></tr>
    <tr><th>Request Cookie</th><td>%(reqcookie)s</td></tr>
    <tr><th>Response Cookie</th><td>%(respcookie)s<p id='respcookiewarn' class='warn'></p></td></tr>
    <tr><th>Session Data</th><td>%(sessiondata)s</td></tr>
    <tr><th>Server Time</th><td id='stime'>%(servertime)s (Unix time: %(serverunixtime)s)</td></tr>
    <tr><th>Browser Time</th><td id='btime'>&nbsp;</td></tr>
    <tr><th>Cherrypy Version:</th><td>%(cpversion)s</td></tr>
    <tr><th>Python Version:</th><td>%(pyversion)s</td></tr>
</table>
</body></html>
"""

class Root(object):
    
    def page(self):
        changemsg = []
        if cherrypy.session.id != cherrypy.session.originalid:
            if cherrypy.session.originalid is None:
                changemsg.append('Created new session because no session id was given.')
            if cherrypy.session.missing:
                changemsg.append('Created new session due to missing (expired or malicious) session.')
            if cherrypy.session.regenerated:
                changemsg.append('Application generated a new session.')
        
        try:
            expires = cherrypy.response.cookie['session_id']['expires']
        except KeyError:
            expires = ''
        
        return page % {
            'sessionid': cherrypy.session.id,
            'changemsg': '<br>'.join(changemsg),
            'respcookie': cherrypy.response.cookie.output(),
            'reqcookie': cherrypy.request.cookie.output(),
            'sessiondata': copyitems(cherrypy.session),
            'servertime': datetime.utcnow().strftime("%Y/%m/%d %H:%M") + " UTC",
            'serverunixtime': calendar.timegm(datetime.utcnow().timetuple()),
            'cpversion': cherrypy.__version__,
            'pyversion': sys.version,
            'expires': expires,
            }
    
    def index(self):
        # Must modify data or the session will not be saved.
        cherrypy.session['color'] = 'green'
        return self.page()
    index.exposed = True
    
    def expire(self):
        sessions.expire()
        return self.page()
    expire.exposed = True
    
    def regen(self):
        cherrypy.session.regenerate()
        # Must modify data or the session will not be saved.
        cherrypy.session['color'] = 'yellow'
        return self.page()
    regen.exposed = True

if __name__ == '__main__':
    cherrypy.config.update({
        #'environment': 'production',
        'log.screen': True,
        'tools.sessions.on': True,
        })
    cherrypy.quickstart(Root())