Lecture code examples from Week 5, should be runnable on Bluehost cgi-bin/cookie-test.py #!/usr/bin/python # Philip Guo - CSC 210 # put in public_html/cgi-bin/ and set the proper execute permissions import cgi import datetime # to facilitate debugging import cgitb cgitb.enable() t = str(datetime.datetime.now()) import os cookie_string = os.environ.get('HTTP_COOKIE') import Cookie if cookie_string: c = Cookie.SimpleCookie(cookie_string) print "Content-type: text/html" print # don't forget newline print "" print "" print "

Hello I already have your cookie!

" print "

Your cookie's saved time is: " + c['current_time'].value + "

" print "" print "" else: c = Cookie.SimpleCookie() c['app_name'] = 'my_cool_app' c['current_time'] = t print "Content-type: text/html" print c print # don't forget newline print "" print "" print "

Hello I'm sending a cookie to you!

" print "

The time is: " + t + "

" print "" print "" login.html: My login screen

Please enter your name to log in:

Name:
Set up sqlite database for user accounts: sqlite> create table users(name varchar(100) primary key, sessionID varchar(100)); sqlite> insert into users values('Philip', null); sqlite> insert into users values('Jane', null); sqlite> insert into users values('Bob', null); sqlite> select * from users; Philip| Jane| Bob| cgi-bin/app.py: #!/usr/bin/python # Philip Guo - CSC 210 # put in public_html/cgi-bin/ and set the proper execute permissions import cgi, Cookie, os, sqlite3 # to facilitate debugging import cgitb cgitb.enable() conn = sqlite3.connect('accounts.db') c = conn.cursor() cookie_string = os.environ.get('HTTP_COOKIE') if cookie_string: my_cookie = Cookie.SimpleCookie(cookie_string) saved_session_id = my_cookie['session_id'].value c.execute('select * from users where sessionID=?', (saved_session_id,)) all_results = c.fetchall() if len(all_results) > 0: saved_name = all_results[0][0] print "Content-type: text/html" print # don't forget newline print "" print "" print "

Welcome back " + saved_name + "

" print "" print "" else: print "Content-type: text/html" print # don't forget newline print "" print "" print "

Error imposter wrong session_id

" print "" print "" else: form = cgi.FieldStorage() my_name = form['my_name'].value # check whether my_name is in accounts.db c.execute('select * from users where name=?;', (my_name,)) all_results = c.fetchall() if len(all_results) > 0: import uuid session_id = str(uuid.uuid4()) c.execute('update users set sessionID=? where name=?', (session_id, my_name)) conn.commit() cook = Cookie.SimpleCookie() cook['session_id'] = session_id print "Content-type: text/html" print cook print # don't forget newline print "" print "" print "

Hello, " + my_name +". You're now logged in.

" print "

session_id: " + session_id + "

" print "" print "" else: print "Content-type: text/html" print # don't forget newline print "" print "" print "

Sorry unregistered user

" print "" print ""