How to Implement User Authentication

Posted by Prolific Programmer Wed, 09 Jan 2008 02:30:00 GMT

The code after the flip will write apache formatted password files and in an sqlite table.


class htpasswd(object):
    def __init__(self, user):
        self.user = user
        self.password = None
        self.sqlstatement = 'INSERT into Users (name, password) VALUES (?,?)'

    def __str__(self):
        import pysqlite2.dbapi2 as sqlite
        sql=sqlite.connect('user')
        cursor = sql.cursor()
        res=cursor.execute(self.sqlstatement, (self.user, self.password,))
        sql.commit()
        cursor.close()
        sql.close()
        return '%s:%s' % (self.user, self.password)

    def set_password(self, passwd):
        import crypt
        self.password = crypt.crypt(passwd, passwd[0:1])

if __name__ == '__main__':
    import sys
    outfile = open('httppass', mode='a')
    o=htpasswd(sys.argv[1])
    o.set_password(sys.argv[2])
    outfile.write(str(o)+'\n')
    outfile.close()