You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

210 lines
7.9 KiB
Python

'''
Created on 19.09.2010
@author: Sergey Morozov
'''
import MySQLdb, json, hashlib, sys, os, smtplib, string
from random import choice
from email.mime.text import MIMEText
includedir = os.path.dirname(__file__)
serverdir = includedir + os.sep + '..'
sys.path.append(serverdir)
import config
class user:
def __init__(self, form, post=None):
if form['password'] == None:
form['password'] = ''
try:
self.db = MySQLdb.connect(
host = config.mysql_server,
user = config.mysql_user,
passwd = config.mysql_password,
db = config.mysql_database,
port = int(config.mysql_port))
except MySQLdb.OperationalError:
self.status = {'retval': 1,
'alert_message': 'Database operation failed!',
'status_message': 'Database error.'}
else:
self.cursor = self.db.cursor()
self.form = form
self.post = post
self.status = {'retval': 0,
'alert_message': None,
'status_message': None}
# Database operations
def _getUserData(self):
q = "SELECT `email`, `password`, `jsondata` FROM `users` WHERE `email` = '%s'" % self.form['email']
self.cursor.execute(q)
result = self.cursor.fetchone()
try:
result= {'email': result[0],
'password': result[1],
'jsondata': result[2],
'found': True}
except TypeError:
result = {'found': False}
return result
def _setUserData(self):
q = "UPDATE `users` SET `password`='%s', `jsondata`='%s' WHERE `email`='%s'" % (hashlib.sha1(self.form['password']).hexdigest(), self._rmObjectSource(self.post), self.form['email'])
self.cursor.execute(q)
def _setUserPass(self):
q = "UPDATE `users` SET `password`='%s', `pwkey`='' WHERE `email`='%s'" % (hashlib.sha1(self.form['password']).hexdigest(), self.form['email'])
self.cursor.execute(q, None)
def _setUserKey(self, key):
q = "UPDATE `users` SET `pwkey`='%s' WHERE `email`='%s'" % (key, self.form['email'])
self.cursor.execute(q)
def resetKey(self):
self._setUserKey(None)
def getKey(self):
q = "SELECT `pwkey` FROM `users` WHERE `email`='%s' LIMIT 1" % (self.form['email'])
self.cursor.execute(q)
result = self.cursor.fetchone()
try:
return result[0]
except:
return None
def _registerUser(self):
q = "INSERT INTO `users` (`email`, `password`) VALUES ('%s', '%s')" % (self.form['email'], hashlib.sha1(self.form['password']).hexdigest())
self.cursor.execute(q)
def _keyGen(self):
return ''.join([choice(string.letters + string.digits) for i in range(20)])
# Check password
def auth(self):
try:
data = self._getUserData()
except MySQLdb.OperationalError:
output = {'retval': 1,
'alert_message': 'Database operation failed!',
'status_message': 'Database error.'}
else:
if data['found'] == True and hashlib.sha1(self.form['password']).hexdigest() == data['password']:
output = {'retval': 0,
'alert_message': None,
'status_message': None}
else:
output = {'retval': 1,
'alert_message': 'Authorization failed!',
'status_message': 'Authorization failed!'}
return output
# Remove objectSource field from addon properties
def _rmObjectSource(self, jsonstring):
result = ''
for i in jsonstring.split('"objectSource"'):
result += i.split('})",')[-1]
return result
# Return user data to client
def getUser(self):
authstatus = self.auth()
if authstatus['retval'] == 0:
data = self._getUserData()
if data['jsondata'] == "" or data['jsondata'] == None:
data['jsondata'] = '{}'
output = {'retval': 0,
'alert_message': None,
'status_message': 'Data loaded.',
'addons': json.loads(data['jsondata'])}
else:
output = authstatus
return(output)
# Save user data from client to database
def setUser(self):
authstatus = self.auth()
if authstatus['retval'] == 0:
self._setUserData()
output = {'retval': 0,
'alert_message': None,
'status_message': 'Data uploaded.'}
else:
output = authstatus
return(output)
# Set new password
def setPass(self, newPassword):
self.form['password'] = newPassword
try:
self._setUserPass()
except MySQLdb.OperationalError:
output = {'retval': 1,
'alert_message': 'Database operation failed!',
'status_message': 'Database error.'}
else:
output = {'retval': 0,
'alert_message': 'Password changed.',
'status_message': 'Password changed.'}
return output
# User registration
def signup(self):
if config.allow_register:
try:
self._registerUser()
except MySQLdb.OperationalError:
output = {'retval': 1,
'alert_message': 'Database operation failed!',
'status_message}': 'Database error.'}
except MySQLdb.IntegrityError:
output = {'retval': 1,
'alert_message': 'User already exist!',
'status_message': 'User exist.'}
else:
output = {'retval': 0,
'alert_message': None,
'status_message': 'Successful registration!'}
else:
output = {'retval': 1,
'alert_message': 'Registration disabled by server administrator.',
'status_message': 'Registration failed!'}
return(output)
# Restore password
def forgot(self, urlBase):
try:
data = self._getUserData()
except MySQLdb.OperationalError:
output = {'retval': 1,
'alert_message': 'Database operation failed!',
'status_message': 'Database error.'}
else:
if data['found'] == True:
key = self._keyGen()
self._setUserKey(key)
pwChangeUrl = urlBase + 'pwchange.py?user=' + data['email'] + '&key=' + key
if config.message_html == True:
msgType = 'html'
else:
msgType = 'plain'
message = MIMEText(config.message_body.replace('@@URL@@', pwChangeUrl), msgType, config.message_encoding)
message['Subject'] = config.message_subject
message['From'] = config.message_from
message['To'] = data['email']
s = smtplib.SMTP(config.smtp_server, config.smtp_port)
s.sendmail(config.message_from, data['email'], message.as_string())
s.quit
output = {'retval': 0,
'alert_message': 'If the specified address is true, the e-mail with instructions is sent you.',
'status_message': None}
return output
# Generate api error
def unsupportedFunction(self):
output = {'retval': 1,
'alert_message': 'Called unsupported function.',
'status_message': 'API mismatch.'}
return(output)