Anonymous user
SQL-based authentication: Difference between revisions
→{{header|Python}}: Fixed SQL injection; changed library to the official one; fixed some other issues
m (format SQL as SQL) |
(→{{header|Python}}: Fixed SQL injection; changed library to the official one; fixed some other issues) |
||
Line 452:
=={{header|Python}}==
{{works with|Python|2.7}}
Uses the [http://dev.mysql.com/downloads/connector/python/ official Python MySQL connector]
<lang python>import
import hashlib
import sys
import random
DB_HOST = "localhost"
DB_USER = "devel"
DB_PASS = "devel"
DB_NAME = "test"
def connect_db():
''' Try to connect DB and return DB instance, if not, return False '''
try:
return
except:
return False
def create_user(username, passwd):
''' if user was successfully created, returns its ID; returns None on error '''
db = connect_db()
if not db:
print
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 (
cursor.execute("SELECT userid FROM users WHERE username=
id = cursor.
db.close()
except:
print 'Username was already taken. Please select another'
def authenticate_user(username, passwd):
db = connect_db()
if not db:
print
cursor = db.cursor()
row = cursor.fetchone()
cursor.close()
▲ scheck = cursor.execute("SELECT pass_salt FROM users WHERE username='%s'" % (username))
if row is None: # username not found
return False
salt = row[0]
return correct_md5 == tried_md5
▲ salt = cursor.fetchone()[0]
▲ passwd = hashlib.md5(salt+passwd).hexdigest()
▲ return True
def randomValue(length):
''' Creates random value with given length'''
salt_chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
return ''.join(random.choice(salt_chars) for x in range(length))
if __name__ == '__main__':
user = randomValue(10)
passwd = randomValue(16)
new_user_id = create_user(user, passwd)
if new_user_id is None:
print 'Failed to create user %s' % user
sys.exit(1)
auth = authenticate_user(user, passwd)
if auth:
print 'User %s authenticated successfully' % user
else:
print 'User %s failed' % user
</lang>
=={{header|Raven}}==
|