Files
2021-09-17 12:41:45 +02:00

112 lines
3.6 KiB
PHP

<?php
class App_Service_WebServiceV1Auth
{
//ERRORI GENERATI DALLO ZEND_AUTH RICODIFICATI DA ME
const NO_CREDENTIAL_CLOUDUSER = 'V1AUTH_ERROR_NO_CREDENTIAL_CLOUDUSER';
const FAILURE_IDENTITY_NOT_FOUND = 'V1AUTH_ERROR_FAILURE_IDENTITY_NOT_FOUND';
const FAILURE_CREDENTIAL_INVALID = 'V1AUTH_ERROR_FAILURE_CREDENTIAL_INVALID';
const ACCOUNT_DEACTIVATED = 'V1AUTH_ERROR_ACCOUNT_DEACTIVATED';
const FAILURE = 'V1AUTH_ERROR_FAILURE';
protected $_model;
protected $_auth;
protected $_configs;
protected $_ipManager;
public function __construct()
{
$this->_model = new Application_Model_Generic();
$this->_configs = new App_Service_ConfigManager();
$this->_ipManager = new App_Service_IpManager();
}
public function authenticate($username, $password, $staylogin = 0)
{
$adapter = $this->getAuthAdapter(array('username' => $username, 'password' => $password));
$auth = $this->getAuth();
$result = $auth->authenticate($adapter);
if (!$result->isValid()) {
return $result->getCode();
}
$user = (array)$adapter->getResultRowObject();
if (!$user['stato']) {
return self::ACCOUNT_DEACTIVATED;
}
//Generazione del Token temporaneo per l'accesso
if ($user['token'] != null) {
$token = $user['token']; //Esistente uso quello già presente
} else {
do { //se non esiste ne genero uno nuovo e controllo che sia univoco
$token = hash('sha1', $user['username'] . date('H:i:s') . mt_rand(5, 10));
if ($this->_model->getByColumnName('Users', 'token', $token)) {
$exist = true;
} else {
$exist = false;
}
$user['token'] = $token;
} while ($exist);
}
//Imposto il DB MONGO dell'utente
$mongoDbName = $this->_ipManager->getMongoDbName($user['NomeDB']);
if(Zend_Registry::isRegistered(App_Model_Mongo_Adapter::MONGO_DB_ADAPTER_REG_NAME))
Zend_Registry::get(App_Model_Mongo_Adapter::MONGO_DB_ADAPTER_REG_NAME)->setDbname($mongoDbName);
else
Zend_Registry::set(App_Model_Mongo_Adapter::MONGO_DB_NAME, $mongoDbName);
//Memorizzo l'ultimo accesso dell'utente
$this->_model->update('Users', $user['id'], array(
'token' => $token,
'UltimoLogin' => date('Y-m-d H:i:s'),
'staylogin' => $staylogin)
);
$auth->getStorage()->write($user);
return $user;
}
public function getAuth()
{
if (null === $this->_auth) {
$this->_auth = Zend_Auth::getInstance();
$this->_auth->setStorage(new Zend_Auth_Storage_Session('Web_Auth'));
}
return $this->_auth;
}
public function getIdentity()
{
$auth = $this->getAuth();
if ($auth->hasIdentity()) {
return $auth->getIdentity();
}
return false;
}
public function clear()
{
$this->getAuth()->clearIdentity();
}
public function getAuthAdapter($values)
{
$salt = Zend_Registry::get('ENVIROMENTS')->get('password_salt');
$authAdapter = new Zend_Auth_Adapter_DbTable(
Zend_Db_Table_Abstract::getDefaultAdapter(),
'users',
'username',
'password',
"MD5(CONCAT('$salt',?))"
);
$authAdapter->setIdentity($values['username']);
$authAdapter->setCredential($values['password']);
return $authAdapter;
}
}