130 lines
No EOL
2.9 KiB
PHP
130 lines
No EOL
2.9 KiB
PHP
<?php
|
|
|
|
class Mapper_User extends Fiktiv_Model_Mapper_DbTableAbstract
|
|
{
|
|
|
|
protected function _createUser($object)
|
|
{
|
|
|
|
if ($object instanceof stdClass)
|
|
$object = (array) $object;
|
|
|
|
|
|
if ($object instanceof Zend_Db_Table_Row)
|
|
$object = $object->toArray();
|
|
|
|
|
|
$user = null;
|
|
|
|
if (is_array($object))
|
|
$user = new User($object);
|
|
|
|
return $user;
|
|
}
|
|
|
|
|
|
public function findById($id)
|
|
{
|
|
if (is_numeric($id)) {
|
|
return $this->_createUser($this->_dbTable->find($id)->current());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Fetch user based on email
|
|
*
|
|
* @return User
|
|
*/
|
|
public function findByEmail($email)
|
|
{
|
|
// Atleast 6 character long
|
|
if (is_string($email) && isset($email[5])) {
|
|
|
|
$user = $this->_createUser($this->_dbTable->fetchRow($this->_dbTable->getAdapter()->quoteInto('email = ?', $email)));
|
|
|
|
return $user;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Get random user
|
|
*
|
|
* @return User
|
|
*/
|
|
public function findRandom()
|
|
{
|
|
return $this->_createUser($this->_dbTable->fetchAll(null, 'RAND()', 1)->current());
|
|
}
|
|
|
|
|
|
/**
|
|
* Authenticate user
|
|
*
|
|
* @param string $email
|
|
* @param string $password
|
|
*/
|
|
public function login($email, $password)
|
|
{
|
|
$auth = Zend_Auth::getInstance();
|
|
|
|
// Setup auth adapter
|
|
$authAdapter = new Zend_Auth_Adapter_DbTable($this->_dbTable->getAdapter(), $this->_dbTable->_name, 'email', 'password');
|
|
|
|
// Set credentials
|
|
$authAdapter->setIdentity($email);
|
|
$authAdapter->setCredential(hash('sha256',$password));
|
|
|
|
// Authenticate
|
|
$result = $auth->authenticate($authAdapter);
|
|
|
|
// Check result
|
|
if ($result->isValid()) {
|
|
|
|
// Keep all but password and salt in session.
|
|
$storage = $auth->getStorage();
|
|
$storage->write($this->_createUser($authAdapter->getResultRowObject(null, array('password', 'salt'))));
|
|
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
|
|
/**
|
|
* Change password
|
|
*/
|
|
public function setPassword($userId, $password)
|
|
{
|
|
|
|
if ($userId instanceof User)
|
|
$userId = $userId->getId();
|
|
|
|
if (!is_numeric($userId))
|
|
return false;
|
|
|
|
return $this->_dbTable->update(
|
|
array(
|
|
'password' => hash('sha256',$password)
|
|
),
|
|
$this->_dbTable->getAdapter()->quoteInto('id = ?',$userId)
|
|
);
|
|
}
|
|
|
|
|
|
/**
|
|
* Save User object
|
|
*/
|
|
public function save(User $user)
|
|
{
|
|
$data = $user->toArray();
|
|
unset($data['id']);
|
|
|
|
return $this->_dbTable->update($data,
|
|
$this->_dbTable->getAdapter()->quoteInto('id = ?',$user->getId())
|
|
);
|
|
}
|
|
|
|
} |