#!/usr/bin/env python

# authdemo: simple demo of authentication in web.py
# by jason pepas (jasonpepas@gmail.com), released into public domain
# inspired by http://webpy.org/cookbook/userauth

# changelog:
#
# 1 (3/23/2010):
# * innitial implementation
#
# 2 (3/23/2010):
# * use hashlib to check md5sum of password
#
# 3 (3/23/2010):
# * use sqlite to store passwd hashes

import web
import hashlib
import sqlite3

urls = (
'/authenticator', 'authenticator',
)

myrender = web.template.render('templates/')

class authenticator:
    def GET(self):
        return myrender.authenticator()

    def POST(self):
        i = web.input()
        passwdhash = hashlib.md5(i.passwd).hexdigest()
        conn = sqlite3.connect('credentials.sqlite3')
        cur = conn.cursor()
        cur.execute('select passwdhash from credentials where user=?', (i.user,))
        row = cur.fetchone()
        try:
            assert row[0] == passwdhash
        except:
            raise web.unauthorized()
        else:
            raise web.ok()

if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()
