SQL-based authentication: Difference between revisions

→‎{{header|Raven}}: ++ reintegrated python with fixes (creation of salt); random gen of user-pwd for testing kept
(→‎{{header|Raven}}: ++ reintegrated python with fixes (creation of salt); random gen of user-pwd for testing kept)
Line 307:
}
</lang>
 
=={{header|Python}}==
<lang python>'''with Python 2.6, gives a deprecation warning for sets module, but works'''
import MySQLdb
import hashlib
import sys
import random
DB_HOST = "localhost"
DB_USER = "devel"
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()
 
salt = randomValue(16)
passwd_md5 = hashlib.md5(salt+passwd).hexdigest()
# If username already taken, inform it
try:
cursor.execute("INSERT INTO users (`username`, `pass_salt`, `pass_md5`) VALUES ('%s', '%s', '%s')" % (username, salt, 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()
 
try:
scheck = cursor.execute("SELECT pass_salt FROM users WHERE username='%s'" % (username))
except:
return False
salt = cursor.fetchone()[0]
passwd = hashlib.md5(salt+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:
return 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</lang>
 
=={{header|Raven}}==