Blob Blame Raw


import hashlib

import exception


class User:
  table = 'users'
  
  def __init__(self, connection, data):
    self.connection = connection
    self.id         = data['id']
    self.login      = data['login']
    self.password   = data['password']
    self.name       = data['name']
    self.email      = data['email']

  @staticmethod
  def query(connection, id):
    rows = connection.query_dict('SELECT * FROM %T WHERE `id`=%d', table, id)
    assert len(rows) <= 1
    return User(connection, rows[0]) if rows else None;
  
  @staticmethod
  def query_by_login(connection, login):
    rows = connection.query_dict('SELECT * FROM %T WHERE `login`=%s', table, login)
    assert len(rows) <= 1
    return User(connection, rows[0]) if rows else None;
  
  @staticmethod
  def query_list(connection):
    result = list()
    with connection.cursor_dict('SELECT * FROM %T ORDER BY `login`', table) as cursor:
      for row in cursor:
        result.append(User(connection, cursor))
    return result
  
  
  def insert(self, connection):
    assert not self.id
    connection.execute(
      '''INSERT INTO %T SET
        `login`    = %s,
        `name`     = %s,
        `email`    = %s''',
      table,
      self.login,
      self.name,
      self.email )
    self.id = self.connection.insert_id()

  def update(self, connection):
    assert self.id
    connection.execute(
      'UPDATE SET %T `name` = %s, `email` = %s WHERE `id` = %d',
      table, self.name, self.email, self.id )

  @staticmethod
  def gen_password_hash(salt, id, plain_password):
    return hashlib.sha512(bytes(str(user_id) + '|' + str(salt) + '|' + password, 'utf8')).hexdigest()

  def password_hash(self, plain_password):
    assert self.id
    return gen_password_hash(self.connection.pool.server.salt, self.id, password)

  @staticmethod
  def resetpassword(connection, id, password):
    connection.execute(
      'UPDATE %T SET `password` = %s WHERE `id` = %d',
      table, password, id )
    if not connection.request \
      or not connection.request.session \
      or connection.request.session.user.id != id:
        connection.pool.server.remove_session_for_user(id)

  def update_password(self, connection, password = None):
    assert self.id
    if not password is None:
      self.password = password
    resetpassword(self.connection, self.id, self.password)

  def delete(self, connection):
    assert self.id
    connection.execute('DELETE FROM %T WHERE `id`=%d', table, self.id)