SQL-based authentication: Difference between revisions

Add Python Code
m (Switch to header template)
(Add Python Code)
Line 86:
"user successfully created and authenticated!\n" print
 
 
=={{header|Python}}==
'''Version:''' 2.4, 2.5
 
'''Note:''' In example below, mysql-python library is used. You can get it from http://mysql-python.sourceforge.net/
 
<pre><nowiki>
#!/usr/bin/python
# -*- coding: utf-8 -*-
 
import MySQLdb
import md5
 
import sys
import random
 
DB_HOST = "localhost"
DB_USER = "root"
DB_PASS = ""
DB_NAME = "test"
 
def connect_db():
''' Try to connect DB and return DB instance, if not, return False '''
try:
return MySQLdb.connect(host=DB_HOST, user=DB_USER, passwd=DB_PASS, db=DB_NAME)
except:
return False
 
def create_user(username, passwd):
''' if user was successfully created, returns its ID '''
db = connect_db()
if not db:
print 'Can\'t connect MySQL!'
sys.exit(1)
 
cursor = db.cursor()
 
passwd_md5 = md5.md5(passwd).hexdigest()
 
# If username already taken, inform it
try:
cursor.execute("INSERT INTO users (`username`, `pass_salt`, `pass_md5`) VALUES ('%s', '%s', '%s')" % (username, passwd, passwd_md5))
cursor.execute("SELECT userid FROM users WHERE username='%s'" % username)
id = cursor.fetchall()
return id[0][0]
except:
print 'Username was already taken. Please select another'
sys.exit(1)
 
def authenticate_user(username, passwd):
db = connect_db()
if not db:
print 'Can\'t connect MySQL!'
sys.exit(1)
 
cursor = db.cursor()
 
passwd = md5.md5(passwd).hexdigest()
 
# cursor returns 1 if query is successfull else it returns 0
user = cursor.execute("SELECT userid, username FROM users WHERE username='%s' AND pass_md5='%s'" % (username, passwd))
if user != 0:
return True
else:
False
 
def randomValue(length):
''' Creates random value with given length'''
salt_chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
output = ""
 
for x in range(length):
rand = random.randrange(0, 35)
output = output + salt_chars[rand]
 
return output
 
if __name__ == '__main__':
user = randomValue(10)
passwd = randomValue(16)
 
create_user(user, passwd)
auth = authenticate_user(user, passwd)
if auth:
print 'User %s authenticated successfully' % user
else:
print 'User %s failed' % user
</nowiki></pre>