|
Ryan Kaskel
ryan at ryankaskel.com
Thu May 10 14:39:31 EDT 2007
I am trying to fiddle around with AJAX but before I can get to that part
I need to make a little test login system will automatically log the
user in if a cookie is found. The problem is when I close the browser
the cookie is deleted. Everything else should work (when I click the
logout button I am still staying logged in because it found the cookie).
Does it have something to do with my browser or an attribute I am not
setting when I create the cookie.
Thanks,
Ryan
below is the code:
import time
from mod_python import util
from mod_python import Session, Cookie
username = "test"
password = "pass"
main_page2 = """
<html>
<head>
<title>Main</title>
</head>
<body>
Welcome!
<p> <a href=\"./logout\">Logout</a> </p>
</body>
</html>
"""
login_page = """
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Please login</h1>
<form action=\"./login\" method=\"POST\">
Username <input type=\"text\" name=\"user\"/> <br/>
Password <input type=\"text\" name=\"pass\"/> <br/>
Remember me? <input type=\"checkbox\" name=\"remember\"/> <br/>
<button type=\"submit\">Login</button>
</form>
</body>
</html>
"""
def main(req):
req.content_type = 'text/html'
main_page = main_page2
session = Session.Session(req)
cookies = Cookie.get_cookies(req, Cookie.MarshalCookie,
secret="example")
if cookies.has_key('example1'):
cookie = cookies['example1']
if type(cookie) is Cookie.MarshalCookie:
data = cookie.value
main_page = data['user'] + " " + data['passw'] + main_page
session['valid'] = 'true'
session.save()
else:
if session.is_new():
util.redirect(req,'./login')
if session['valid'] != 'true':
util.redirect(req,'./login')
req.write(main_page)
def login(req):
req.content_type = "text/html"
if req.method == 'POST':
if req.form['user'] == username and req.form['pass'] == password:
session = Session.Session(req)
session['valid'] = 'true'
session.save()
if req.form.has_key('remember') and req.form['remember']:
value = {'user': req.form['user'], 'passw':
req.form['pass']}
Cookie.add_cookie(req, Cookie.MarshalCookie('example1',
value,'example'), expires=time.time() + 3000000)
util.redirect(req,'./main')
else:
req.write("bad credentials")
else:
req.write(str(Cookie.get_cookies(req, Cookie.MarshalCookie,
secret='example')))
req.write(login_page)
def logout(req):
req.content_type = "text/html"
session = Session.Session(req)
if session.has_key('valid'):
session.delete()
util.redirect(req,'./main')
|