web.py authentication with Beaker example

 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
from beaker.session import SessionMiddleware
import web
from web import form
log_in = form.Form(
form.Textbox("login", form.notnull, description="User name"),
form.Password("password", form.notnull, description="Password")
)
def logged(session):
if "logeddin" in session:
if session["logeddin"] == 1:
return True
return False
urls = (
'/', 'index',
'/logout', 'logout',)
users = {"sl": "123"}
class index:
def GET(self):
web.header("Content-Type","text/html; charset=utf-8")
session = web.ctx.environ['beaker.session']
if logged(session):
print "U logged as <b>%s</b>"%session["username"]
print "<a href='/logout'>logout</a>"
else:
print "<form name='main' method='post'> "+ log_in.render() + "<input type='submit' />"
def POST(self):
session = web.ctx.environ['beaker.session']
i = web.input()
if i.login in users and users[i.login] == i.password:
session['logeddin'] = 1
session['username'] = i.login
session.save()
web.seeother("/")
class logout:
def GET(self):
session = web.ctx.environ['beaker.session']
session.invalidate()
web.seeother("/")
"""
or
session.delete()
session.save()
"""
def session_mw(app):
return SessionMiddleware(app, key = "sid")
if __name__ == "__main__":
web.run(urls, globals(), *(web.reloader, session_mw))