Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class User:
- table = 'users'
- fields = {
- 'nickname': '',
- 'email': '',
- 'password': '',
- 'googlemail': None,
- 'facebookid': None,
- 'birthdate': '',
- 'vkontakteid': None,
- 'activate': False,
- 'activation_key': None,
- 'img': '',
- }
- def __init__(self, user_id=0):
- if user_id:
- self.id = user_id
- self.load()
- def load(self):
- """
- loads user's data
- """
- with db.connection as conn:
- query = """
- SELECT *
- FROM """ + self.table + """
- WHERE id = %(id)s
- """
- cursor = conn.cursor(cursor_factory=DictCursor)
- cursor.execute(query, dict(id=self.id))
- row = cursor.fetchone()
- if row is not None:
- for field in self.fields:
- self.__setattr__(field, row[field])
- # try:
- # self.nickname = row['nickname']
- # self.email = row['email']
- # self.hashed_password = row['password']
- # self.googlemail = row['googlemail']
- # self.facebookid = row['facebookid']
- # self.birthdate = row['birthdate']
- # self.vkontakteid = row['vkontakteid']
- # self.activate = row['activate']
- # except:
- # logging.error(traceback.print_exc())
- def save(self):
- """
- saves user's data
- """
- params = {}
- if self.id:
- query = """
- UPDATE """ + self.table + """
- SET """ + ', '.join(['%s = %%(%s)s' % (field, field) for field in self.fields]) + """
- WHERE id = %(id)s
- """
- params = {field: self.__dict__[field] for field in self.fields}
- params['id'] = self.id
- else:
- query = """
- INSERT INTO """ + self.table + """
- (""" + ', '.join(['%s' % field for field in self.fields]) + """)
- VALUES (""" + ', '.join(['%%(%s)s' % field for field in self.fields]) + """)
- """
- params = {field: self.__dict__[field] for field in self.fields}
- with db.connection as conn:
- cursor = conn.cursor()
- cursor.execute(query, params)
- logging.info(cursor.query.decode())
- user_id = cursor.lastrowid
- if user_id:
- self.id = user_id
- @staticmethod
- def hash_password(password):
- """
- returns hashed user's password
- """
- md5 = hashlib.md5()
- md5.update(password.encode('utf-8'))
- return md5.hexdigest()
- def gen_password(self):
- """
- generates user's password and return it
- """
- #todo: generate random password
- password = '123'
- self.password = User.hash_password(password)
- return password
- def check_password(self, password):
- query = "SELECT TRUE FROM users WHERE id = %(user_id)s AND password = %(passwd)s"
- params = {'user_id': self.id, 'passwd': User.hash_password(password)}
- with db.connection as conn:
- cursor = conn.cursor()
- cursor.execute(query, params)
- if cursor.fetchone():
- return True
- return False
- @classmethod
- def check(cls, email, password):
- """
- checks email+password combination and returns user id if them are correct, else - None
- """
- if not email or not password:
- return None
- hashed_password = User.hash_password(password)
- #Email/Password Validation:
- query = """
- SELECT id
- FROM """ + cls.table + """
- WHERE email = %(email)s AND password = %(password_hash)s AND activate = 't'
- """
- params = {'email': email, 'password_hash': hashed_password}
- with db.connection as conn:
- cursor = conn.cursor()
- cursor.execute(query, params)
- user_id = cursor.fetchone()
- if user_id is not None:
- return user_id[0]
- return None
- @classmethod
- def reset_activation(cls, email):
- sql = 'SELECT email FROM ' + cls.table + ' WHERE email = %(email)s'
- params = {'email': email}
- with db.connection as conn:
- cursor = conn.cursor()
- cursor.execute(sql, params)
- if cursor.fetchone():
- activation_key = hashlib.new('md5')
- activation_key.update((email + str(datetime.datetime.now())).encode('utf-8'))
- activation_key = activation_key.hexdigest()
- sql = 'UPDATE ' + cls.table + ' SET activate = False, activation_key= %(hash)s WHERE email = %(email)s'
- params = {'hash': activation_key, 'email': email}
- cursor.execute(sql, params)
- return activation_key
- return None # in case of no such email
- @classmethod
- def find_by_actkey(cls, key):
- sql = """SELECT id FROM """ + cls.table + """ WHERE activation_key = %(key)s"""
- params = {'key': key}
- with db.connection as conn:
- cursor = conn.cursor()
- cursor.execute(sql, params)
- row = cursor.fetchone()
- if row is not None:
- return User(row[0])
- return None
- @classmethod
- def gen_actkey(cls,passwd,email):
- md5 = hashlib.md5()
- md5.update((passwd+email).encode('utf-8'))
- return md5.hexdigest()
- class MyHandler(tornado.web.RequestHandler):
- def initialize(self):
- self.user = None
- self.db = db
- sid = self.get_secure_cookie('sid')
- if sid is not None:
- sid = str(sid, 'UTF-8')
- self.session = Session(sid=sid)
- if self.session.user_id is not None:
- self.user = User(self.session.user_id)
- def get_template_path(self):
- return os.path.join(os.path.dirname(__file__), 'templates')
- def get_current_user(self):
- if self.user is not None:
- return self.user.id
- return None
Add Comment
Please, Sign In to add comment