/** * Ritorna se l'email e la password passate corrispondono a un utente valido. * * @static * @param string $Email L'email dell'utente che si vuole loggare * @param string $Password La password dell'utente che si vuole loggare * @return bool Se lo login è andata a buon fine o meno */ public static function isValidLogin($Email, $Password) { $Auth = Zend_Auth::getInstance(); $Adapter = self::getAuthAdapter(); $Adapter->setIdentity($Email); $Adapter->setCredential($Password); self::$AuthResult = $Auth->authenticate($Adapter); if (self::$AuthResult->isValid()) { $Auth->getStorage()->write(self::getUserById($Adapter->getResultRowObject()->IDUser)); return true; } else { return false; } }
private function getMessages(Zend_Auth_Result $result) { switch ($result->getCode()) { case $result::FAILURE_IDENTITY_NOT_FOUND: $msg = "Login não encontrado"; break; case $result::FAILURE_IDENTITY_AMBIGUOUS: $msg = "Login em duplicidade"; break; case $result::FAILURE_CREDENTIAL_INVALID: $msg = "Senha inválida"; break; default: $msg = "Login/senha inválidos"; } return $msg; }
public function getMessage(Zend_Auth_Result $results) { switch ($results->getCode()) { case $results::FAILURE_IDENTITY_NOT_FOUND: $msg = "login não encontrado"; break; case $results::FAILURE_IDENTITY_AMBIGOUES: $msg = "login duplicado"; break; case $results::FAILURE_CREDENTIAL_INVALID: $msg = "login não corresponde"; break; case $results::FAILURE: case $results::FAILURE_UNCATEGORIZED: $msg = "Login E/Ou Senha incorretos"; } }
/** * The identity is the attribute value of 'saml_uid_attribute' * see application.ini * * @return saml_uid_attribute */ public function getIdentity() { $config = Zend_Registry::get('config'); $samlUidAttribute = $config->simplesaml->saml_uid_attribute; $this->_attributes = parent::getIdentity(); if ((int) $config->core->logSamlAttributes === 1) { $log = Zend_Registry::get('log'); $log->info(var_export($this->_attributes, true)); } return $this->_attributes[$samlUidAttribute]; }
/** * Set the result for this validator * * @param \Zend_Auth_Result $result * @return boolean True when valid */ protected function setAuthResult(\Zend_Auth_Result $result) { $this->_authResult = $result; return $this->_authResult->isValid(); }
/** * get user data from Zend_Auth result and store data in session * @param Zend_Auth_Result $auth */ protected function getAuthDetailsIntoSession($auth, $crt) { $session = Zend_Registry::get('session'); $db = Zend_Registry::get('auth_dbc'); $db2 = Zend_Registry::get('auth2_dbc'); /** * non existent in our case, look up a 2nd table (ca_mgr.system_user by login name (email)) and * get id from there, defaulting to User (1) when no db entry exists */ $auth_res = $auth->getResultRowObject(); if (!isset($auth_res->system_role_id) || $auth_res->system_role_id == 0) { $res = $db2->query('select * from system_user where login=?', array($auth_res->email)); if ($res->rowCount() > 0) { $res_ar = $res->fetch(); $system_roles_id = $res_ar['system_role_id']; } else { // no extra user info in manager database, assume standard user $system_roles_id = 1; } } else { $system_roles_id = $auth_res->system_role_id; } $session->authdata['authed'] = true; $session->authdata['authed_id'] = $auth_res->id; if (!isset($auth_res->fname) || !isset($auth_res->lname)) { $res = $db->query('select * from users where email=?', array($auth_res->login)); $res_ar = $res->fetch(); $session->authdata['authed_username'] = '******' . $res_ar['login']; $session->authdata['authed_fname'] = $res_ar['fname']; $session->authdata['authed_lname'] = $res_ar['lname']; } else { $session->authdata['authed_username'] = $auth_res->email; $session->authdata['authed_fname'] = $auth_res->fname; $session->authdata['authed_lname'] = $auth_res->lname; } $session->authdata['authed_by_crt'] = $crt; $session->authdata['authed_by_cli'] = true; $res = $db2->query('select * from system_role where id=?', array($system_roles_id)); $res_ar = $res->fetch(); $session->authdata['authed_role'] = $res_ar['role']; $acl = $this->makeAcl($db2); $session->authdata['authed_permissions'] = $acl; /* test cases Log::Log()->debug(($acl->isAllowed('User', 'Administration', 'view') == true)?'true':'false'); Log::Log()->debug(($acl->isAllowed('User', 'Administration', 'edit') == true)?'true':'false'); Log::Log()->debug(($acl->isAllowed('User', 'Account', 'view') == true)?'true':'false'); Log::Log()->debug(($acl->isAllowed('User', 'Account', 'edit') == true)?'true':'false'); Log::Log()->debug(($acl->isAllowed('Admin', 'Administration', 'view') == true)?'true':'false'); Log::Log()->debug(($acl->isAllowed('Admin', 'Account', 'view') == true)?'true':'false'); */ $this->view->session = $session; }
/** * This exists to customize the messages that people see when their attempt * to login fails. ZF has some built-in default messages, but it seems like * those messages may not make sense to a majority of people using the * software. * * @param Zend_Auth_Result * @return string */ public function getLoginErrorMessages(Zend_Auth_Result $result) { $code = $result->getCode(); switch ($code) { // Return the same output for these two cases to avoid revealing // information about valid usernames/passwords. case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND: case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID: return __('Identifiants incorrects. Merci de réessayer.'); break; case Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS: // There can never be ambiguous identities b/c the 'username' // field is unique in the database. Not sure what this message // would say. // There can never be ambiguous identities b/c the 'username' // field is unique in the database. Not sure what this message // would say. case Zend_Auth_Result::FAILURE_UNCATEGORIZED: // All other potential errors fall under this code. // All other potential errors fall under this code. default: return implode("\n", $result->getMessages()); break; } }
/** * Process everything after authentication. * * @param \Zend_Auth_Result $result */ protected function afterAuthorization(\Zend_Auth_Result $result, $lastAuthorizer = null) { try { $select = $this->db->select(); $select->from('gems__user_login_attempts', array('gula_failed_logins', 'gula_last_failed', 'gula_block_until', new \Zend_Db_Expr('UNIX_TIMESTAMP() - UNIX_TIMESTAMP(gula_last_failed) AS since_last')))->where('gula_login = ?', $this->getLoginName())->where('gula_id_organization = ?', $this->getCurrentOrganizationId())->limit(1); $values = $this->db->fetchRow($select); // The first login attempt if (!$values) { $values['gula_login'] = $this->getLoginName(); $values['gula_id_organization'] = $this->getCurrentOrganizationId(); $values['gula_failed_logins'] = 0; $values['gula_last_failed'] = null; $values['gula_block_until'] = null; $values['since_last'] = $this->failureIgnoreTime + 1; } if ($result->isValid()) { // Reset login failures $values['gula_failed_logins'] = 0; $values['gula_last_failed'] = null; $values['gula_block_until'] = null; } else { // Reset the counters when the last login was longer ago than the delay factor if ($values['since_last'] > $this->failureIgnoreTime) { $values['gula_failed_logins'] = 1; } elseif ($lastAuthorizer === 'pwd') { // Only increment failed login when password failed $values['gula_failed_logins'] += 1; } // If block is already set if ($values['gula_block_until']) { // Do not change it anymore unset($values['gula_block_until']); } else { // Only set the block when needed if ($this->failureBlockCount <= $values['gula_failed_logins']) { $values['gula_block_until'] = new \Zend_Db_Expr('DATE_ADD(CURRENT_TIMESTAMP, INTERVAL ' . $this->failureIgnoreTime . ' SECOND)'); } } // Always record the last fail $values['gula_last_failed'] = new \MUtil_Db_Expr_CurrentTimestamp(); $values['gula_failed_logins'] = max(1, $values['gula_failed_logins']); // Response gets slowly slower $sleepTime = min($values['gula_failed_logins'] - 1, 10) * 2; sleep($sleepTime); // \MUtil_Echo::track($sleepTime, $values, $result->getMessages()); } // Value not saveable unset($values['since_last']); if (isset($values['gula_login'])) { $this->db->insert('gems__user_login_attempts', $values); } else { $where = $this->db->quoteInto('gula_login = ? AND ', $this->getLoginName()); $where .= $this->db->quoteInto('gula_id_organization = ?', $this->getCurrentOrganizationId()); $this->db->update('gems__user_login_attempts', $values, $where); } } catch (\Zend_Db_Exception $e) { // Fall through as this does not work if the database upgrade did not yet run // \MUtil_Echo::r($e); } }
/** * return accessLog instance * * @param string $loginName * @param Zend_Auth_Result $authResult * @param Zend_Controller_Request_Abstract $request * @param string $clientIdString * @return Tinebase_Model_AccessLog */ public function getAccessLogEntry($loginName, Zend_Auth_Result $authResult, \Zend\Http\Request $request, $clientIdString) { if ($header = $request->getHeaders('USER-AGENT')) { $userAgent = substr($header->getFieldValue(), 0, 255); } else { $userAgent = 'unknown'; } $accessLog = new Tinebase_Model_AccessLog(array('ip' => $request->getServer('REMOTE_ADDR'), 'li' => Tinebase_DateTime::now(), 'result' => $authResult->getCode(), 'clienttype' => $clientIdString, 'login_name' => $loginName ? $loginName : $authResult->getIdentity(), 'user_agent' => $userAgent), true); return $accessLog; }
public function authenticate() { if (empty($this->_identity)) { return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND, $this->_identity, array(trlKwf('Please specify a user name.'))); } else { if ($this->_credential === null) { return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND, $this->_identity, array(trlKwf('Please specify a password.'))); } } $cache = $this->_getCache(); $failedLoginsFromThisIp = $cache->load($this->_getCacheId()); if ($failedLoginsFromThisIp && $failedLoginsFromThisIp >= 15) { return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_UNCATEGORIZED, $this->_identity, array(trlKwf('Too many wrong logins.'), trlKwf('There were too many wrong logins from your connection. Please try again in 5 minutes.'))); } $ret = null; $validLogin = false; $row = null; $users = Zend_Registry::get('userModel'); foreach ($users->getAuthMethods() as $auth) { if ($this->_useCookieToken) { if ($auth instanceof Kwf_User_Auth_Interface_AutoLogin) { $row = $auth->getRowById($this->_identity); if ($row) { if ($auth->validateAutoLoginToken($row, $this->_credential)) { $ret = new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $this->_identity, array(trlKwf('Authentication successful'))); } else { $ret = new Zend_Auth_Result(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, $this->_identity, array(trlKwf('Supplied password is invalid'))); } break; } } } else { if ($auth instanceof Kwf_User_Auth_Interface_Password) { $row = $auth->getRowByIdentity($this->_identity); if ($row) { if ($this->_credential == 'test' && Kwf_Config::getValue('debug.testPasswordAllowed')) { $ret = new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $this->_identity, array(trlKwf('Authentication successful'))); } else { if ($auth->validatePassword($row, $this->_credential)) { $ret = new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $this->_identity, array(trlKwf('Authentication successful'))); } else { $ret = new Zend_Auth_Result(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, $this->_identity, array(trlKwf('Supplied password is invalid'))); } } break; } } } } if (!$row) { $ret = new Zend_Auth_Result(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND, $this->_identity, array(trlKwf('User not existent in this web'))); } else { if ($ret->isValid()) { $users->loginUserRow($row, true); } } if (!$ret->isValid()) { $cache = $this->_getCache(); $failedLoginsFromThisIp = $cache->load($this->_getCacheId()); if (!$failedLoginsFromThisIp) { $failedLoginsFromThisIp = 0; } $failedLoginsFromThisIp++; $cache->save($failedLoginsFromThisIp, $this->_getCacheId()); $this->_sendWrongLoginMail(array('Identity' => $this->_identity)); if ($failedLoginsFromThisIp > 3) { sleep(3); } } return $ret; }
public function setIdentity(Zend_Auth_Result $authResult) { if ($authResult->isValid()) { $this->getStorage()->write($authResult->getIdentity()); } }
/** * Authenticate user * This method can * - authenticate user throught authentification process * - load already authenticated user in current session (or SSO) * - disconnect user * * @param array $params : indexed array of authentification parameters (default : nothing) * Accepted array keys are : * - authenticate : boolean : default true if disconnect is not set * - disconnect : boolean : default false * - login : string : user login to authenticate * - password : string : user password to authenticate * - remember : boolean : default false * - tokenName : string * - token : string * - type : string : type of authentification (admin|frontend) : default APPLICATION_USER_TYPE contant * - ... and any parameter needed by authentifications processes handled by modules * @return void * @access public * @static */ public static function authenticate($params = array()) { //first clean old sessions datas from database CMS_session::_cleanSessions(); // Get Zend Auth instance $auth = Zend_Auth::getInstance(); // Use CMS_auth as session storage space $auth->setStorage(new Zend_Auth_Storage_Session('atm-auth')); //set authentification type if (!isset($params['type'])) { $params['type'] = APPLICATION_USER_TYPE; } //set permanent auth status if (isset($params['remember']) && $params['remember']) { self::$_permanent = true; } else { $params['remember'] = false; } //clear auth storage if disconnection is queried and set default authenticate value if (isset($params['disconnect']) && $params['disconnect']) { //log disconection if user exists $storageValue = $auth->getStorage()->read(); if (io::isPositiveInteger($storageValue)) { //load user $user = CMS_profile_usersCatalog::getByID($storageValue); if ($user) { //log new session $log = new CMS_log(); $log->logMiscAction(CMS_log::LOG_ACTION_DISCONNECT, $user, 'IP: ' . @$_SERVER['REMOTE_ADDR'] . ', UA: ' . @$_SERVER['HTTP_USER_AGENT']); } } //clear session content CMS_session::deleteSession(true); if (!isset($params['authenticate'])) { $params['authenticate'] = false; } } else { $params['disconnect'] = false; if (!isset($params['authenticate'])) { $params['authenticate'] = true; } } //init authenticated boolean $authenticated = false; //keep old storage value, because storage will be reseted by each module authentification $storageValue = $auth->getStorage()->read(); //loop on each authentification types suupported foreach (array('credentials', 'session', 'cookie', 'sso') as $authType) { //load modules $modules = CMS_modulesCatalog::getAll('id'); //get last module $module = array_pop($modules); //set authentification type as param $params['authType'] = $authType; //then try it for each modules do { //if module has auth method, try it if (method_exists($module, 'getAuthAdapter')) { //overwrite auth storage value with old value $auth->getStorage()->write($storageValue); //get module auth adapter $authAdapter = $module->getAuthAdapter($params); //authenticate user self::$_result = $auth->authenticate($authAdapter); //To debug Auth process easily, discomment this line //CMS_grandFather::log($_SERVER['SCRIPT_NAME'].' - '.$module->getCodename().' - Auth type : '.$authType.'/'.$params['type'].' - Auth result : '.self::$_result->getCode().($auth->hasIdentity() ? ' - Identity : '.$auth->getIdentity() : '').' - Message : '.(sizeof(self::$_result->getMessages()) == 1 ? array_pop(self::$_result->getMessages()) : print_r(self::$_result->getMessages(), true))); switch (self::$_result->getCode()) { case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND: //user crendentials does not exists (ex: no login/pass provided) //nothing for now break; case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID: //invalid login/pass //nothing for now break; case Zend_Auth_Result::SUCCESS: if ($auth->hasIdentity()) { // get user from identity found $user = $authAdapter->getUser($auth->getIdentity()); //check if user is valid if (isset($user) && $user && !$user->hasError() && !$user->isDeleted() && $user->isActive()) { $authenticated = true; //overwrite auth identity with valid user Id $auth->getStorage()->write($user->getUserId()); } else { unset($user); } } break; case Zend_Auth_Result::FAILURE: //user found but has error during loading (user inactive or deleted) //nothing for now break; default: //other unidentified cases : thrown an error CMS_grandFather::raiseError('Authentification return code ' . self::$_result->getCode() . ' for module ' . $module->getCodename() . ' with parameters ' . print_r($params, true)); break; } } //get next last module $module = array_pop($modules); } while (!$authenticated && $module); //if user is authenticated, break authentification foreach if ($authenticated) { break; } } //if authenticated : set or refresh session datas in table, regenerate session Id if ($authenticated && $user) { $q = new CMS_query("\n\t\t\tselect \n\t\t\t\tid_ses, cookie_expire_ses\n\t\t\tfrom \n\t\t\t\tsessions \n\t\t\twhere \n\t\t\t\tphpid_ses='" . sensitiveIO::sanitizeSQLString(Zend_Session::getId()) . "' \n\t\t\t\tand user_ses='" . sensitiveIO::sanitizeSQLString($user->getUserId()) . "'"); //get old session Id $oldSessionId = Zend_Session::getId(); if ($q->getNumRows() > 0) { //if session already exists : update it //regenerate session Id randomly (arround 1/100 times) //removed : cause session instability /*if (!rand(0, 100)) { //session id should not be regenerated each times because in case of a lot of concurrent calls, session can be destroyed Zend_Session::regenerateId(); }*/ $r = $q->getArray(); $id = $r['id_ses']; //Cookie if (self::$_permanent || $r['cookie_expire_ses'] != '0000-00-00 00:00:00') { self::$_permanent = true; // Cookie expire in APPLICATION_COOKIE_EXPIRATION days $expires = time() + 60 * 60 * 24 * APPLICATION_COOKIE_EXPIRATION; CMS_session::setCookie(CMS_session::getAutoLoginCookieName(), base64_encode($id . '|' . Zend_Session::getId()), $expires); } //DB session $sql = "\n\t\t\t\t\tupdate \n\t\t\t\t\t\tsessions \n\t\t\t\t\tset\n\t\t\t\t\t\tlastTouch_ses=NOW(),\n\t\t\t\t\t\tuser_ses='" . sensitiveIO::sanitizeSQLString($user->getUserId()) . "',\n\t\t\t\t\t\tphpid_ses='" . sensitiveIO::sanitizeSQLString(Zend_Session::getId()) . "',\n\t\t\t\t\t\tremote_addr_ses='" . sensitiveIO::sanitizeSQLString(@$_SERVER['REMOTE_ADDR']) . "'"; if (self::$_permanent) { $sql .= ",\n\t\t\t\t\t\tcookie_expire_ses = DATE_ADD(NOW(), INTERVAL " . APPLICATION_COOKIE_EXPIRATION . " DAY)"; } $sql .= "\n\t\t\t\t\twhere\n\t\t\t\t\t \tid_ses='" . sensitiveIO::sanitizeSQLString($id) . "'"; $q = new CMS_query($sql); //if autologin : log it if (in_array(CMS_auth::AUTH_AUTOLOGIN_VALID, self::$_result->getMessages())) { //log autologin session $log = new CMS_log(); $log->logMiscAction(CMS_log::LOG_ACTION_AUTO_LOGIN, $user, 'IP: ' . @$_SERVER['REMOTE_ADDR'] . ', UA: ' . @$_SERVER['HTTP_USER_AGENT']); } } else { //otherwhise, create user session //regenerate session Id Zend_Session::regenerateId(); //delete old session record if any $q = new CMS_query("\n\t\t\t\t\tdelete\n\t\t\t\t\tfrom \n\t\t\t\t\t\tsessions \n\t\t\t\t\twhere \n\t\t\t\t\t\tphpid_ses='" . sensitiveIO::sanitizeSQLString($oldSessionId) . "'"); //insert new session record $sql = "\n\t\t\t\t\tinsert into\n\t\t\t\t\t\tsessions\n\t\t\t\t\tset\n\t\t\t\t\t\tlastTouch_ses=NOW(),\n\t\t\t\t\t\tphpid_ses='" . sensitiveIO::sanitizeSQLString(Zend_Session::getId()) . "',\n\t\t\t\t\t\tuser_ses='" . sensitiveIO::sanitizeSQLString($user->getUserId()) . "',\n\t\t\t\t\t\tremote_addr_ses='" . sensitiveIO::sanitizeSQLString(@$_SERVER['REMOTE_ADDR']) . "'\n\t\t\t\t"; if (self::$_permanent) { $sql .= ",\n\t\t\t\t\tcookie_expire_ses = DATE_ADD(NOW(), INTERVAL " . APPLICATION_COOKIE_EXPIRATION . " DAY)"; } $q = new CMS_query($sql); if (!$q->hasError() && self::$_permanent) { // Cookie expire in APPLICATION_COOKIE_EXPIRATION days $expires = time() + 60 * 60 * 24 * APPLICATION_COOKIE_EXPIRATION; CMS_session::setCookie(CMS_session::getAutoLoginCookieName(), base64_encode($q->getLastInsertedID() . '|' . Zend_Session::getId()), $expires); } //log new session $log = new CMS_log(); $log->logMiscAction(CMS_log::LOG_ACTION_LOGIN, $user, 'Permanent cookie: ' . (self::$_permanent ? 'Yes' : 'No') . ', IP: ' . @$_SERVER['REMOTE_ADDR'] . ', UA: ' . @$_SERVER['HTTP_USER_AGENT']); } //set user as currently logged user self::$_userID = $user->getUserId(); } else { if (APPLICATION_USER_TYPE == "frontend" && APPLICATION_ENFORCES_ACCESS_CONTROL) { //set public user as currently logged user self::$_userID = ANONYMOUS_PROFILEUSER_ID; } } //for backward compatibility $_SESSION["cms_context"] = new CMS_context(); }
/** * Set error message * * @param Zend_Auth_Result $authenticationResult * @return void */ protected function _invalidCredentials(Zend_Auth_Result $authResult) { $messages = $authResult->getMessages(); print_r($messages); exit; $this->view->errorMessage = $messages[0]; // Log -> "Failed login for '#{params[:username]}' from #{request.remote_ip} at #{Time.now.utc}"; // Flash error -> invalid credential }