139 lines
3 KiB
PHP
139 lines
3 KiB
PHP
<?php
|
|
|
|
namespace Httpcb;
|
|
|
|
use Httpcb\OAuth\UserData\UserDataInterface;
|
|
use Phalcon\Mvc\User\Component;
|
|
use App\Model\Data\User;
|
|
|
|
class Auth extends Component
|
|
{
|
|
/**
|
|
* @var string
|
|
*/
|
|
protected $_session_key = 'auth';
|
|
|
|
/**
|
|
* Login using email/user + password combination.
|
|
*
|
|
* @param string $email_username
|
|
* @param string $password
|
|
* @return bool
|
|
*/
|
|
public function login($email_username, $password)
|
|
{
|
|
// Look for a user with this username/email.
|
|
$user = User::findFirstByUsernameOrEmail($email_username);
|
|
|
|
if ($user) {
|
|
// Verify password
|
|
$hash = $user->getPassword();
|
|
if (strlen($hash) > 1 && $this->security->checkHash($password, $hash)) {
|
|
|
|
$this->setIdentity($user->getId());
|
|
|
|
$this->eventsManager->fire('auth:onLogin', $this, 'password');
|
|
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Login using OAuth
|
|
*
|
|
* @param UserDataInterface $data
|
|
* @return bool
|
|
*/
|
|
public function loginOauth(UserDataInterface $data)
|
|
{
|
|
$user = User::findFirstByOAuthID($data);
|
|
|
|
// Did not find any user.
|
|
if (!$user) {
|
|
return false;
|
|
}
|
|
|
|
// Here we activate the user.
|
|
// As for OAuth we perform registration if the user does not exist.
|
|
// We should therefore activate deleted accounts.
|
|
if ($user->Status == User::STATUS_DELETED) {
|
|
$user->Status = User::STATUS_ACTIVE;
|
|
$user->save();
|
|
}
|
|
|
|
$this->setIdentity($user->getId());
|
|
|
|
$this->eventsManager->fire('auth:onLogin', $this,
|
|
"OAuth {$data->getProvider()}");
|
|
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* The system logs in a user (without credentials).
|
|
*
|
|
* @param User $user
|
|
*/
|
|
public function systemLogin(User $user)
|
|
{
|
|
$this->setIdentity($user->getId());
|
|
$this->eventsManager->fire('auth:onLogin', $this, 'System');
|
|
}
|
|
|
|
/**
|
|
* @param $identity
|
|
* @return Auth
|
|
*/
|
|
public function setIdentity($identity)
|
|
{
|
|
$this->session->set($this->_session_key, $identity);
|
|
return $this;
|
|
}
|
|
|
|
/**
|
|
* return \Model\Data\User
|
|
*/
|
|
public function getIdentity()
|
|
{
|
|
$id = $this->session->get($this->_session_key);
|
|
|
|
if ($id !== null) {
|
|
return User::findFirst($id);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* return \Model\Data\User
|
|
*/
|
|
public function getUser()
|
|
{
|
|
if ($this->hasIdentity()) {
|
|
|
|
$id = $this->session->get($this->_session_key);
|
|
|
|
return User::findFirst($id);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public function hasIdentity()
|
|
{
|
|
return $this->getIdentity() !== NULL;
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
* Clears the identity information.
|
|
*
|
|
* @return Auth
|
|
*/
|
|
public function clearIdentity()
|
|
{
|
|
$this->session->remove($this->_session_key);
|
|
return $this;
|
|
}
|
|
}
|