File indexing completed on 2024-12-22 05:33:31

0001 <?php
0002 
0003 /**
0004  *  ocs-webserver
0005  *
0006  *  Copyright 2016 by pling GmbH.
0007  *
0008  *    This file is part of ocs-webserver.
0009  *
0010  *    This program is free software: you can redistribute it and/or modify
0011  *    it under the terms of the GNU Affero General Public License as
0012  *    published by the Free Software Foundation, either version 3 of the
0013  *    License, or (at your option) any later version.
0014  *
0015  *    This program is distributed in the hope that it will be useful,
0016  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
0017  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
0018  *    GNU Affero General Public License for more details.
0019  *
0020  *    You should have received a copy of the GNU Affero General Public License
0021  *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
0022  **/
0023 class AuthorizationController extends Local_Controller_Action_DomainSwitch
0024 {
0025 
0026     const DEFAULT_ROLE_ID = 300;
0027     const PROFILE_IMG_SRC_LOCAL = 'local';
0028 
0029     public function githubAction()
0030     {
0031         require_once APPLICATION_LIB . '/Local/CrawlerDetect.php';
0032         if (crawlerDetect($_SERVER['HTTP_USER_AGENT'])) {
0033             $this->getResponse()->setHttpResponseCode(404);
0034             $this->forward('index', 'explore');
0035 
0036             return;
0037         }
0038         $this->forward('login', 'oauth', 'default',
0039             array('provider' => 'github', 'redirect' => $this->getParam('redirect')));
0040     }
0041 
0042     public function ocsAction()
0043     {
0044         require_once APPLICATION_LIB . '/Local/CrawlerDetect.php';
0045         if (crawlerDetect($_SERVER['HTTP_USER_AGENT'])) {
0046             $this->getResponse()->setHttpResponseCode(404);
0047             $this->forward('index', 'explore');
0048 
0049             return;
0050         }
0051         $this->forward('login', 'oauth', 'default',
0052             array('provider' => 'ocs', 'redirect' => $this->getParam('redirect')));
0053     }
0054 
0055     public function redirectAction()
0056     {
0057         $param = null;
0058         if (preg_match("/redirect\/(.*?)$/i", $this->getRequest()->getRequestUri(), $result)) {
0059             $param = array('redirect' => $result[1]);
0060         }
0061         $this->forward('login', null, null, $param);
0062     }
0063 
0064     /**
0065      * login from cookie
0066      *
0067      * @throws Zend_Auth_Storage_Exception
0068      * @throws Zend_Form_Exception
0069      * @throws Zend_Session_Exception
0070      * @throws exception
0071      */
0072     public function lfcAction()
0073     {
0074         $this->view->success = 0;
0075         $this->view->noPopup = true;
0076 
0077         //TODO: check redirect for a local valid url.
0078         $this->view->redirect = $this->getParam('redirect');
0079 
0080         $formLogin = new Default_Form_Login();
0081         $formLogin->setAction('/login/lfc/');
0082         $formLogin->getElement('remember_me')->setValue(true);
0083 
0084         if ($this->_request->isGet()) { // not a POST request
0085             $this->view->form = $formLogin->populate(array('redirect' => $this->view->redirect));
0086             $this->view->error = 0;
0087 
0088             return;
0089         }
0090 
0091         Zend_Registry::get('logger')->info(__METHOD__
0092                                            . PHP_EOL . ' - authentication attempt on host: ' . Zend_Registry::get('store_host')
0093                                            . PHP_EOL . ' - param redirect: ' . $this->getParam('redirect')
0094                                            . PHP_EOL . ' - from ip: ' . $this->_request->getClientIp()
0095         );
0096 
0097         if (false === $formLogin->isValid($_POST)) { // form not valid
0098             Zend_Registry::get('logger')->info(__METHOD__
0099                                                . PHP_EOL . ' - ip: ' . $this->_request->getClientIp()
0100                                                . PHP_EOL . ' - form not valid:'
0101                                                . PHP_EOL . print_r($formLogin->getMessages(), true));
0102 
0103             $this->view->form = $formLogin;
0104             $this->view->errorText = 'index.login.error.auth';
0105             $this->view->error = 1;
0106 
0107             return;
0108         }
0109 
0110         $values = $formLogin->getValues();
0111         $authModel = new Default_Model_Authorization();
0112         $authResult = $authModel->authenticateUser($values['mail'], $values['password'], $values['remember_me']);
0113 
0114         if (false == $authResult->isValid()) { // authentication fail
0115             Zend_Registry::get('logger')->info(__METHOD__
0116                                                . PHP_EOL . ' - ip: ' . $this->_request->getClientIp()
0117                                                . PHP_EOL . ' - authentication fail: '
0118                                                . PHP_EOL . print_r($authResult->getMessages(), true)
0119             );
0120             $this->view->errorText = 'index.login.error.auth';
0121             $this->view->form = $formLogin;
0122             $this->view->error = 1;
0123             $this->_helper->viewRenderer('login');
0124 
0125             return;
0126         }
0127 
0128         $auth = Zend_Auth::getInstance();
0129         $userId = $auth->getStorage()->read()->member_id;
0130 
0131         // handle redirect
0132         if (false === empty($this->view->redirect)) {
0133             $redirect = $this->decodeString($this->view->redirect);
0134             if (false !== strpos('/register', $redirect)) {
0135                 
0136                 //20200120 ronald: redirect to www.opendesktop.org/start
0137                 //$redirect = '/member/' . $userId . '/activities/';
0138                 $baseurl = Zend_Registry::get('config')->settings->client->default->baseurl;
0139                 $redirect = $baseurl.'/start';
0140             }
0141             $this->redirect($redirect);
0142         } else {
0143             //20200120 ronald: redirect to www.opendesktop.org/start
0144             //$redirect = '/member/' . $userId . '/activities/';
0145             $baseurl = Zend_Registry::get('config')->settings->client->default->baseurl;
0146             $redirect = $baseurl.'/start';
0147         }
0148     }
0149 
0150     /**
0151      * @param string $string
0152      *
0153      * @return string
0154      */
0155     protected function decodeString($string)
0156     {
0157         $decodeFilter = new Local_Filter_Url_Decrypt();
0158 
0159         return $decodeFilter->filter($string);
0160     }
0161 
0162     /**
0163      * @throws Zend_Auth_Storage_Exception
0164      * @throws Zend_Exception
0165      * @throws Zend_Session_Exception
0166      * @throws exception
0167      */
0168     public function propagateAction()
0169     {
0170         $this->_helper->layout()->disableLayout();
0171         $this->_helper->viewRenderer->setNoRender(true);
0172 
0173         if (Zend_Auth::getInstance()->hasIdentity()) {
0174             $this->_helper->json(array('status' => 'ok', 'message' => 'Already logged in.'));
0175         }
0176 
0177         Zend_Registry::get('logger')->info(__METHOD__
0178                                            . PHP_EOL . ' - token: ' . $this->getParam('token')
0179                                            . PHP_EOL . ' - host: ' . Zend_Registry::get('store_host')
0180                                            . PHP_EOL . ' - ip: ' . $this->_request->getClientIp()
0181         );
0182 
0183         $modelAuthToken = new Default_Model_SingleSignOnToken();
0184         $token_data = $modelAuthToken->getData($this->getParam('token'));
0185         if (false === $token_data) {
0186             Zend_Registry::get('logger')->warn(__METHOD__
0187                                                . PHP_EOL . ' - Login failed: no token exists'
0188                                                . PHP_EOL . ' - host: ' . Zend_Registry::get('store_host')
0189                                                . PHP_EOL . ' - ip: ' . $this->_request->getClientIp()
0190             );
0191             $this->_helper->json(array('status' => 'fail', 'message' => 'Login failed.'));
0192         }
0193         $remember_me = isset($token_data['remember_me']) ? (boolean)$token_data['remember_me'] : false;
0194         $member_id = isset($token_data['member_id']) ? (int)$token_data['member_id'] : null;
0195 
0196         $modelAuth = new Default_Model_Authorization();
0197         $authResult = $modelAuth->authenticateUser($member_id, null, $remember_me,
0198             Local_Auth_AdapterFactory::LOGIN_SSO);
0199 
0200         if ($authResult->isValid()) {
0201             Zend_Registry::get('logger')->info(__METHOD__
0202                                                . PHP_EOL . ' - authentication successful: '
0203                                                . PHP_EOL . ' - host: ' . Zend_Registry::get('store_host')
0204                                                . PHP_EOL . ' - ip: ' . $this->_request->getClientIp()
0205             );
0206             $this->getResponse()->setHeader('Access-Control-Allow-Origin', $this->getParam('origin'))
0207                  ->setHeader('Access-Control-Allow-Credentials', 'true')
0208                  ->setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
0209                  ->setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept');
0210 
0211             $this->_helper->json(array('status' => 'ok', 'message' => 'Login successful.'));
0212         } else {
0213             Zend_Registry::get('logger')->info(__METHOD__
0214                                                . PHP_EOL . ' - authentication fail: '
0215                                                . PHP_EOL . ' - host: ' . Zend_Registry::get('store_host')
0216                                                . PHP_EOL . ' - ip: ' . $this->_request->getClientIp()
0217                                                . PHP_EOL . print_r($authResult->getMessages(), true)
0218             );
0219             $this->_helper->json(array('status' => 'fail', 'message' => 'Login failed.'));
0220         }
0221     }
0222 
0223     public function checkuserAction()
0224     {
0225         $this->_helper->layout()->disableLayout();
0226         $this->_helper->viewRenderer->setNoRender(true);
0227 
0228         $this->getResponse()->setHeader('Access-Control-Allow-Origin', 'https://gitlab.pling.cc')
0229              ->setHeader('Access-Control-Allow-Credentials', 'true')->setHeader('Access-Control-Allow-Methods',
0230                 'POST, GET, OPTIONS')
0231              ->setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept');
0232 
0233         $formLogin = new Default_Form_Login();
0234 
0235         if (false === $formLogin->isValid($_GET)) { // form not valid
0236             $this->_helper->json(array('status' => 'error', 'message' => 'not valid'));
0237 
0238             return;
0239         }
0240 
0241         $values = $formLogin->getValues();
0242         $authModel = new Default_Model_Authorization();
0243         $authResult = $authModel->authenticateUser($values['mail'], $values['password'], $values['remember_me']);
0244 
0245         if (false == $authResult->isValid()) { // authentication fail
0246             $this->_helper->json(array('status' => 'error', 'message' => 'not valid'));
0247 
0248             return;
0249         }
0250 
0251         $auth = Zend_Auth::getInstance();
0252         $userId = $auth->getStorage()->read()->member_id;
0253 
0254 
0255         //Send user to LDAP
0256         try {
0257             $ldap_server = new Default_Model_Ocs_Ldap();
0258             $ldap_server->createUser($userId);
0259             Zend_Registry::get('logger')->debug(__METHOD__ . ' - ldap : ' . implode(PHP_EOL . " - ",
0260                     $ldap_server->getMessages()));
0261         } catch (Exception $e) {
0262             Zend_Registry::get('logger')->err($e->getMessage() . PHP_EOL . $e->getTraceAsString());
0263         }
0264 
0265         //If the user is a hive user, we have to update his password
0266         $this->changePasswordIfNeeded($userId, $values['password']);
0267 
0268         $this->_helper->json(array('status' => 'ok', 'message' => 'User is OK.'));
0269     }
0270 
0271     /**
0272      * @param int $member_id
0273      * @param string $password
0274      * @throws Zend_Db_Statement_Exception
0275      * @throws Zend_Exception
0276      */
0277     private function changePasswordIfNeeded($member_id, $password)
0278     {
0279         $userTabel = new Default_Model_Member();
0280         $showMember = $userTabel->fetchMember($member_id);
0281         $memberSettings = $showMember;
0282 
0283         //User with OCS Password
0284         if ($showMember->password_type == Default_Model_Member::PASSWORD_TYPE_OCS) {
0285             return;
0286         }
0287 
0288         //Hive User
0289         if ($memberSettings->password_type == Default_Model_Member::PASSWORD_TYPE_HIVE) {
0290             //Save old data
0291             $memberSettings->password_old = $memberSettings->password;
0292             $memberSettings->password_type_old = Default_Model_Member::PASSWORD_TYPE_HIVE;
0293 
0294             //Change type and password
0295             $memberSettings->password_type = Default_Model_Member::PASSWORD_TYPE_OCS;
0296             $memberSettings->password = Local_Auth_Adapter_Ocs::getEncryptedPassword($password, Default_Model_Member::PASSWORD_TYPE_OCS);
0297             $memberSettings->save();
0298 
0299             //Update Auth-Services
0300             try {
0301                 $id_server = new Default_Model_Ocs_OAuth();
0302                 $id_server->updatePasswordForUser($memberSettings->member_id);
0303                 $messages = $id_server->getMessages();
0304                 if (false == empty($messages)) {
0305                     Zend_Registry::get('logger')->info(json_encode($messages));
0306                 }
0307             } catch (Exception $e) {
0308                 Zend_Registry::get('logger')->err($e->getMessage() . PHP_EOL . $e->getTraceAsString());
0309             }
0310             try {
0311                 $ldap_server = new Default_Model_Ocs_Ldap();
0312                 $ldap_server->updatePassword($memberSettings->member_id,$password);
0313                 $messages = $ldap_server->getMessages();
0314                 if (false == empty($messages)) {
0315                     Zend_Registry::get('logger')->info(json_encode($messages));
0316                 }
0317             } catch (Exception $e) {
0318                 Zend_Registry::get('logger')->err($e->getMessage() . PHP_EOL . $e->getTraceAsString());
0319             }
0320         }
0321 
0322         return;
0323     }
0324 
0325     /**
0326      * @throws Zend_Auth_Storage_Exception
0327      * @throws Zend_Exception
0328      * @throws Zend_Form_Exception
0329      * @throws Zend_Session_Exception
0330      * @throws exception
0331      */
0332     public function loginAction()
0333     {
0334         $this->view->noheader = true;
0335         //TODO: check redirect for a local valid url.
0336         $this->view->redirect = $this->getParam('redirect');
0337 
0338         // if the user is still logged in, we do not show the login page. They should log out first.
0339         if (Zend_Auth::getInstance()->hasIdentity()) {
0340             $this->_helper->flashMessenger->addMessage('<p class="text-danger center">You are still logged in. Please click <a href="/logout" class="bold">here</a> to log out first.</p>');
0341             $this->handleRedirect(Zend_Auth::getInstance()->getIdentity()->member_id);
0342         }
0343 
0344         $formLogin = new Default_Form_Login();
0345 
0346         if ($this->_request->isGet()) { // not a POST request
0347             $this->view->formLogin = $formLogin->populate(array('redirect' => $this->view->redirect));
0348             $this->view->error = 0;
0349 
0350             return;
0351         }
0352 
0353         Zend_Registry::get('logger')->info(__METHOD__
0354                                            . PHP_EOL . ' - authentication attempt on host: ' . Zend_Registry::get('store_host')
0355                                            . PHP_EOL . ' - param redirect: ' . $this->getParam('redirect')
0356                                            . PHP_EOL . ' - from ip: ' . $this->_request->getClientIp()
0357                                            . PHP_EOL . ' - http method: ' . $this->_request->getMethod()
0358                                            . PHP_EOL . ' - csrf string: ' . (isset($_POST['login_csrf']) ? $_POST['login_csrf'] : '')
0359         );
0360 
0361         if (false === Default_Model_CsrfProtection::validateCsrfToken($_POST['login_csrf'])) {
0362             Zend_Registry::get('logger')->info(__METHOD__
0363                                                . PHP_EOL . ' - ip: ' . $this->_request->getClientIp()
0364                                                . PHP_EOL . ' - validate CSRF token failed:'
0365                                                . PHP_EOL . ' - received token: ' . $_POST['login_csrf']
0366                                                . PHP_EOL . ' - stored token: ' . Default_Model_CsrfProtection::getCsrfToken()
0367             );
0368 
0369             $this->view->error = 0;
0370             $this->view->formLogin = $formLogin;
0371             if ($this->_request->isXmlHttpRequest()) {
0372                 $viewLoginForm = $this->view->render('authorization/partials/loginForm.phtml');
0373                 $this->_helper->json(array('status' => 'ok', 'message' => $viewLoginForm));
0374             }
0375 
0376             return;
0377         }
0378 
0379         if (false === $formLogin->isValid($_POST)) { // form not valid
0380             Zend_Registry::get('logger')->info(__METHOD__
0381                                                . PHP_EOL . ' - ip: ' . $this->_request->getClientIp()
0382                                                . PHP_EOL . ' - form not valid:'
0383                                                . PHP_EOL . print_r($formLogin->getMessages(), true)
0384             );
0385             $this->view->formLogin = $formLogin;
0386             $this->view->errorText = 'index.login.error.auth';
0387             $this->view->error = 1;
0388 
0389             if ($this->_request->isXmlHttpRequest()) {
0390                 $viewLoginForm = $this->view->render('authorization/partials/loginForm.phtml');
0391                 $this->_helper->json(array('status' => 'ok', 'message' => $viewLoginForm));
0392             }
0393 
0394             return;
0395         }
0396 
0397         $values = $formLogin->getValues();
0398         $authModel = new Default_Model_Authorization();
0399         $authResult = $authModel->authenticateUser($values['mail'], $values['password'], $values['remember_me']);
0400 
0401         if (false == $authResult->isValid()) { // authentication fail
0402             Zend_Registry::get('logger')->info(__METHOD__
0403                                                . PHP_EOL . ' - authentication fail.'
0404                                                . PHP_EOL . ' - user: ' . $values['mail']
0405                                                . PHP_EOL . ' - remember_me: ' . $values['remember_me']
0406                                                . PHP_EOL . ' - ip: ' . $this->_request->getClientIp()
0407                                                . PHP_EOL . print_r($authResult->getMessages(), true)
0408             );
0409 
0410             if ($authResult->getCode() == Local_Auth_Result::MAIL_ADDRESS_NOT_VALIDATED) {
0411                 $session = new Zend_Session_Namespace();
0412                 $session->mail_verify_member_id = $authResult->getIdentity();
0413 
0414                 if ($this->_request->isXmlHttpRequest()) {
0415                     $viewMessage = $this->view->render('verify/resend.phtml');
0416                     $this->_helper->json(array('status' => 'ok', 'message' => $viewMessage));
0417                 }
0418             }
0419 
0420             $this->view->errorText = 'index.login.error.auth';
0421             $this->view->formLogin = $formLogin;
0422             $this->view->error = 1;
0423 
0424             if ($this->_request->isXmlHttpRequest()) {
0425                 $viewLoginForm = $this->view->render('authorization/partials/loginForm.phtml');
0426                 $this->_helper->json(array('status' => 'ok', 'message' => $viewLoginForm));
0427             }
0428 
0429             return;
0430         }
0431 
0432         Zend_Registry::get('logger')->info(__METHOD__
0433                                            . PHP_EOL . ' - authentication successful.'
0434                                            . PHP_EOL . ' - user: ' . $values['mail']
0435                                            . PHP_EOL . ' - user_id: ' . isset(Zend_Auth::getInstance()->getStorage()->read()->member_id) ? Zend_Auth::getInstance()->getStorage()->read()->member_id : ''
0436                                                                                                                                                                                                        . PHP_EOL . ' - remember_me: ' . $values['remember_me']
0437                                                                                                                                                                                                        . PHP_EOL . ' - ip: ' . $this->_request->getClientIp()
0438         );
0439 
0440 
0441         $filter = new Local_Filter_Url_Encrypt();
0442         $p = $filter->filter($values['password']);
0443         $sess = new Zend_Session_Namespace('ocs_meta');
0444         $sess->phash = $p;
0445 
0446         $auth = Zend_Auth::getInstance();
0447         $userId = $auth->getStorage()->read()->member_id;
0448 
0449         $jwt = Default_Model_Jwt::encode($userId);
0450         $sess->openid = $jwt;
0451 
0452         //If the user is a hive user, we have to update his password
0453         $this->changePasswordIfNeeded($userId, $values['password']);
0454 
0455         //log login
0456         try {
0457             $ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']) : $_SERVER['REMOTE_ADDR'];
0458 
0459             if (is_array($ip)) {
0460                 $ip = $ip[0];
0461             }
0462 
0463             $agent = null;
0464             if ( isset( $_SERVER ) ) {
0465                 $agent = $_SERVER['HTTP_USER_AGENT'];
0466             }
0467             
0468             $fingerprint = null;
0469             
0470             $session = new Zend_Session_Namespace();
0471             $fp = $session->client_fp;
0472             if (!empty($fp)) {
0473                 $fingerprint = $fp;
0474             }
0475             
0476             $ipv4 = null;
0477             $ipv6 = null;
0478             
0479             if($this->hasParam('ipv4')) {
0480                 $ipv4 = $this->getParam('ipv4');
0481             }
0482             if($this->hasParam('ipv6')) {
0483                 $ipv6 = $this->getParam('ipv6');
0484             }
0485             $loginHistory = new Default_Model_LoginHistory();
0486             $loginHistory->log($userId, $ip, $ipv4, $ipv6, $agent, $fingerprint);
0487         } catch (Exception $exc) {
0488         }
0489 
0490         
0491         
0492         //$modelToken = new Default_Model_SingleSignOnToken();
0493         //$data = array(
0494         //    'remember_me' => $values['remember_me'],
0495         //    //'redirect'    => $this->getParam('redirect'),
0496         //    'redirect'    => $this->view->redirect,
0497         //    'action'      => Default_Model_SingleSignOnToken::ACTION_LOGIN,
0498         //    'member_id'   => $userId
0499         //);
0500         //$token_id = $modelToken->createToken($data);
0501         //setcookie(Default_Model_SingleSignOnToken::ACTION_LOGIN, $token_id, time() + 120, '/',
0502         //    Local_Tools_ParseDomain::get_domain($this->getRequest()->getHttpHost()), null, true);
0503 
0504         //user has to correct his data?
0505         $modelReviewProfile = new Default_Model_ReviewProfileData();
0506         if (false === $modelReviewProfile->hasValidProfile($auth->getStorage()->read())) {
0507             Zend_Registry::get('logger')->info(__METHOD__
0508                                                . PHP_EOL . ' - User has to change user data!'
0509                                                . PHP_EOL . ' - error code: ' . print_r($modelReviewProfile->getErrorCode(),
0510                     true)
0511             );
0512 
0513             if ($this->_request->isXmlHttpRequest()) {
0514                 $redirect = $this->getParam('redirect') ? '/redirect/' . $this->getParam('redirect') : '';
0515                 $this->_helper->json(array(
0516                     'status'   => 'ok',
0517                     'redirect' => '/r/change/e/' . $modelReviewProfile->getErrorCode() . $redirect
0518                 ));
0519             } else {
0520                 $this->getRequest()->setParam('member_id', $userId);
0521                 $this->redirect("/r/change/e/" . $modelReviewProfile->getErrorCode(), $this->getAllParams());
0522             }
0523 
0524             return;
0525         }
0526 
0527         // handle redirect
0528         $this->view->loginok = true;
0529         $this->handleRedirect($userId);
0530     }
0531 
0532     /**
0533      * @param int $userId
0534      *
0535      * @throws Zend_Exception
0536      * @throws Zend_Filter_Exception
0537      */
0538     protected function handleRedirect($userId)
0539     {
0540         if (empty($this->view->redirect)) {
0541 
0542             Zend_Registry::get('logger')->info(__METHOD__ . PHP_EOL . ' - user_id: ' . $userId . PHP_EOL . ' - redirect: empty');
0543 
0544             if ($this->_request->isXmlHttpRequest()) {
0545                 //20200120 ronald: redirect to www.opendesktop.org/start
0546                 //$redirect_url = $this->encodeString('/member/' . $userId . '/activities/');
0547                 $baseurl = Zend_Registry::get('config')->settings->client->default->baseurl;
0548                 $redirect_url = $this->encodeString($baseurl.'/start');
0549                 
0550                 
0551                 $redirect = '/home/redirectme?redirect=' . $redirect_url;
0552                 $this->_helper->json(array('status' => 'ok', 'redirect' => $redirect));
0553 
0554                 return;
0555             }
0556 
0557             $this->getRequest()->setParam('member_id', $userId);
0558             //20200120 ronald: redirect to www.opendesktop.org/start
0559             //$redirect_url = $this->encodeString('/member/' . $userId . '/activities/');
0560             $baseurl = Zend_Registry::get('config')->settings->client->default->baseurl;
0561             $redirect_url = $this->encodeString($baseurl.'/start');
0562             $redirect = '/home/redirectme?redirect=' . $redirect_url;
0563             $this->redirect($redirect, $this->getAllParams());
0564 
0565             return;
0566         }
0567 
0568         $redirect = $this->decodeString($this->view->redirect);
0569         Zend_Registry::get('logger')->info(__METHOD__ . PHP_EOL . ' - user_id: ' . $userId . PHP_EOL . ' - redirect: ' . $redirect);
0570         if (false !== strpos('/register', $redirect)) {
0571             //20200120 ronald: redirect to www.opendesktop.org/start
0572             //$redirect = '/member/' . $userId . '/activities/';
0573             $baseurl = Zend_Registry::get('config')->settings->client->default->baseurl;
0574             $redirect = $this->encodeString($baseurl.'/start');
0575             
0576         }
0577 
0578         $redirect = '/home/redirectme?redirect=' . $this->encodeString($redirect);
0579         if ($this->_request->isXmlHttpRequest()) {
0580 
0581             $this->_helper->json(array('status' => 'ok', 'redirect' => $redirect));
0582 
0583             return;
0584         }
0585 
0586         $this->redirect($redirect);
0587 
0588         return;
0589     }
0590 
0591     /**
0592      * @param string $string
0593      *
0594      * @return string
0595      * @throws Zend_Filter_Exception
0596      */
0597     protected function encodeString($string)
0598     {
0599         $encodeFilter = new Local_Filter_Url_Encrypt();
0600 
0601         return $encodeFilter->filter($string);
0602     }
0603 
0604     /**
0605      * @throws Exception
0606      * @throws Zend_Exception
0607      * @throws Zend_Form_Exception
0608      */
0609     public function registerAction()
0610     {
0611         $this->view->redirect = $this->getParam('redirect');
0612 
0613         $this->view->headScript()->appendFile('//www.google.com/recaptcha/api.js');
0614         $this->view->addHelperPath(APPLICATION_LIB . '/Cgsmith/View/Helper', 'Cgsmith\\View\\Helper\\');
0615         $formRegister = new Default_Form_Register();
0616 
0617         if ($this->_request->isGet()) {
0618             $this->view->formRegister = $formRegister->populate(array('redirect' => urlencode($this->view->redirect)));
0619             $this->view->error = 0;
0620 
0621             return;
0622         }
0623 
0624         if (false === $formRegister->isValid($_POST)) {
0625 
0626             $this->view->formRegister = $formRegister;
0627             $this->view->error = 1;
0628 
0629             if ($this->_request->isXmlHttpRequest()) {
0630                 $viewRegisterForm = $this->view->render('authorization/partials/registerForm.phtml');
0631                 $this->_helper->json(array('status' => 'ok', 'message' => $viewRegisterForm));
0632             }
0633 
0634             return;
0635         }
0636 
0637         $formRegisterValues = $formRegister->getValues();
0638         unset($formRegisterValues['g-recaptcha-response']);
0639         $formRegisterValues['password'] = $formRegisterValues['password1'];
0640 
0641         $formRegisterValues['username'] = Default_Model_HtmlPurify::purify($formRegisterValues['username']);
0642         $formRegisterValues['mail'] = strtolower($formRegisterValues['mail']);
0643 
0644         $doubleOptIn = (boolean)Zend_Registry::get('config')->settings->double_opt_in->active;
0645         $newUserData = $this->createNewUser($formRegisterValues, $doubleOptIn);
0646 
0647         Default_Model_ActivityLog::logActivity($newUserData['main_project_id'], null, $newUserData['member_id'],
0648             Default_Model_ActivityLog::MEMBER_JOINED, array());
0649 
0650         if ($doubleOptIn) {
0651             $this->sendConfirmationMail($formRegisterValues, $newUserData['verificationVal']);
0652         }
0653 
0654         Zend_Registry::get('logger')->debug(__METHOD__ . ' - member_id: ' . $newUserData['member_id'] . ' - Link for verification: '
0655                                             . 'http://' . $this->getServerName() . '/verification/' . $newUserData['verificationVal']);
0656 
0657         
0658         
0659         
0660         //log login
0661         try {
0662             $ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']) : $_SERVER['REMOTE_ADDR'];
0663 
0664             if (is_array($ip)) {
0665                 $ip = $ip[0];
0666             }
0667 
0668             $agent = null;
0669             if ( isset( $_SERVER ) ) {
0670                 $agent = $_SERVER['HTTP_USER_AGENT'];
0671             }
0672             
0673             $fingerprint = null;
0674             
0675             $session = new Zend_Session_Namespace();
0676             $fp = $session->client_fp;
0677             if (!empty($fp)) {
0678                 $fingerprint = $fp;
0679             }
0680             
0681             $ipv4 = null;
0682             $ipv6 = null;
0683             
0684             if($this->hasParam('ipv4')) {
0685                 $ipv4 = $this->getParam('ipv4');
0686             }
0687             if($this->hasParam('ipv6')) {
0688                 $ipv6 = $this->getParam('ipv6');
0689             }
0690             $loginHistory = new Default_Model_LoginHistory();
0691             $loginHistory->log($newUserData['member_id'], $ip, $ipv4, $ipv6, $agent, $fingerprint);
0692         } catch (Exception $exc) {
0693         }
0694         
0695         
0696         
0697         if ($this->_request->isXmlHttpRequest()) {
0698             $viewRegisterForm = $this->view->render('authorization/partials/registerSuccess.phtml');
0699             $this->_helper->json(array('status' => 'ok', 'message' => $viewRegisterForm));
0700         } else {
0701             $this->view->overlay = $this->view->render('authorization/registerSuccess.phtml');
0702             $this->forward('index', 'explore', 'default');
0703         }
0704     }
0705 
0706     /**
0707      * @param array $userData
0708      *
0709      * @return array
0710      * @throws Exception
0711      */
0712     protected function createNewUser($userData, $doubleOptIn = true)
0713     {
0714         if (false === $doubleOptIn) {
0715             $userData['mail_checked'] = 1;
0716             $userData['is_active'] = 1;
0717             $userData['is_deleted'] = 0;
0718         }
0719         $userTable = new Default_Model_Member();
0720         $userData = $userTable->createNewUser($userData);
0721 
0722         return $userData;
0723     }
0724 
0725     /**
0726      * @param array  $val
0727      * @param string $verificationVal
0728      */
0729     protected function sendConfirmationMail($val, $verificationVal)
0730     {
0731         $confirmMail = new Default_Plugin_SendMail('tpl_verify_user');
0732         $confirmMail->setTemplateVar('servername', $this->getServerName());
0733         $confirmMail->setTemplateVar('username', $val['username']);
0734         $confirmMail->setTemplateVar('verificationlinktext',
0735             '<a href="https://' . $this->getServerName() . '/verification/' . $verificationVal
0736             . '">Click here to verify your email address</a>');
0737         $confirmMail->setTemplateVar('verificationlink',
0738             '<a href="https://' . $this->getServerName() . '/verification/' . $verificationVal . '">https://' . $this->getServerName()
0739             . '/verification/' . $verificationVal . '</a>');
0740         $confirmMail->setTemplateVar('verificationurl',
0741             'https://' . $this->getServerName() . '/verification/' . $verificationVal);
0742         $confirmMail->setReceiverMail($val['mail']);
0743         $confirmMail->setFromMail('registration@opendesktop.org');
0744         $confirmMail->send();
0745     }
0746 
0747     /**
0748      * @return mixed
0749      */
0750     protected function getServerName()
0751     {
0752         /** @var Zend_Controller_Request_Http $request */
0753         $request = $this->getRequest();
0754 
0755         return $request->getHttpHost();
0756     }
0757 
0758     /**
0759      * @throws Zend_Controller_Action_Exception
0760      * @throws Zend_Exception
0761      * @throws Zend_Session_Exception
0762      */
0763     public function propagatelogoutAction()
0764     {
0765         $this->_helper->layout()->disableLayout();
0766         $this->_helper->viewRenderer->setNoRender(true);
0767 
0768         if (false == Zend_Auth::getInstance()->hasIdentity()) {
0769             $this->_helper->json(array('status' => 'ok', 'message' => 'Already logged out.'));
0770         }
0771 
0772         $modelAuth = new Default_Model_Authorization();
0773         $modelAuth->logout();
0774 
0775         $this->_helper->json(array('status' => 'ok', 'message' => 'Logout successful.'));
0776     }
0777 
0778     /**
0779      * @throws Zend_Cache_Exception
0780      * @throws Zend_Controller_Action_Exception
0781      * @throws Zend_Exception
0782      * @throws Zend_Session_Exception
0783      * @deprecated
0784      */
0785     public function logoutAction()
0786     {
0787         $this->_helper->layout()->disableLayout();
0788         $this->_helper->viewRenderer->setNoRender(true);
0789 
0790         if (Zend_Auth::getInstance()->hasIdentity()) {
0791             $modelAuth = new Default_Model_Authorization();
0792             $modelAuth->logout();
0793 
0794             $modelToken = new Default_Model_SingleSignOnToken();
0795             $data = array(
0796                 'remember_me' => false,
0797                 'redirect'    => $this->getParam('redirect'),
0798                 'action'      => Default_Model_SingleSignOnToken::ACTION_LOGOUT
0799             );
0800             $token_id = $modelToken->createToken($data);
0801             setcookie(Default_Model_SingleSignOnToken::ACTION_LOGOUT, $token_id, time() + 120, '/',
0802                 Local_Tools_ParseDomain::get_domain($this->getRequest()->getHttpHost()), null, true);
0803         }
0804 
0805         if ($this->_request->isXmlHttpRequest()) {
0806             $this->_helper->json(array('status' => 'ok', 'message' => 'Logout successful.'));
0807         } else {
0808             $this->redirect('/');
0809         }
0810     }
0811 
0812     public function init()
0813     {
0814         parent::init(); // TODO: Change the autogenerated stub
0815         $this->getResponse()->clearHeaders(array('Expires', 'Pragma', 'Cache-Control'))->setHeader('Pragma', 'no-cache',
0816             true)
0817              ->setHeader('Cache-Control', 'private, no-cache, must-revalidate', true);
0818     }
0819 
0820     /**
0821      * @throws Zend_Auth_Storage_Exception
0822      * @throws Zend_Controller_Action_Exception
0823      * @throws Zend_Exception
0824      * @throws exception
0825      */
0826     public function verificationAction()
0827     {
0828         $filterInput = new Zend_Filter_Input(array('*' => 'StringTrim', 'vid' => 'Alnum'),
0829             array('vid' => array('Alnum', 'presence' => 'required')), $this->getAllParams());
0830         $_vId = $filterInput->getEscaped('vid');
0831 
0832         if (!$_vId) {
0833             $this->redirect('/');
0834         }
0835 
0836         $translate = Zend_Registry::get('Zend_Translate');
0837         $this->view->title = $translate->_('member.email.verification.title');
0838 
0839         $authModel = new Default_Model_Authorization();
0840         $authUser = $authModel->getAuthUserDataFromUnverified($_vId);
0841 
0842         if (empty($authUser)) {
0843             throw new Zend_Controller_Action_Exception('This member account could not activated. verification id:'
0844                                                        . print_r($this->getParam('vid'), true));
0845         }
0846 
0847         if ($authUser AND (false == empty($authUser->email_checked))) {
0848             $this->view->headScript()->appendFile('//www.google.com/recaptcha/api.js');
0849             $this->view->addHelperPath(APPLICATION_LIB . '/Cgsmith/View/Helper', 'Cgsmith\\View\\Helper\\');
0850             $this->view->formRegister = new Default_Form_Register();
0851             $this->view->registerErrMsg =
0852                 "<p>Your account has already been activated.</p><p class='small'><a href='/login'>Log in</a> or try to generate a <a href='/login/forgot'>new password</a> for your account. </p> ";
0853             $this->view->overlay = $this->view->render('authorization/registerError.phtml');
0854             $this->_helper->viewRenderer('register');
0855 
0856             return;
0857         }
0858 
0859         Zend_Registry::get('logger')->info(__METHOD__ . ' - activate user from email link. (member_id, username): ('
0860                                            . print_r($authUser->member_id, true) . ', ' . print_r($authUser->username,
0861                 true) . ')');
0862         $modelMember = new Default_Model_Member();
0863         $result = $modelMember->activateMemberFromVerification($authUser->member_id, $_vId);
0864 
0865         if (false == $result) {
0866             throw new Zend_Controller_Action_Exception('Your member account could not activated.');
0867         }
0868 
0869         Zend_Registry::get('logger')->info(__METHOD__ . ' - user activated. member_id: ' . print_r($authUser->member_id,
0870                 true));
0871 
0872         $modelMember = new  Default_Model_Member();
0873         $record = $modelMember->fetchMemberData($authUser->member_id, false);
0874 
0875         try {
0876             $oauth = new Default_Model_Ocs_OAuth();
0877             $oauth->createUserFromArray($record->toArray());
0878             Zend_Registry::get('logger')->debug(__METHOD__ . ' - oauth : ' . implode(PHP_EOL . " - ",
0879                     $oauth->getMessages()));
0880         } catch (Exception $e) {
0881             Zend_Registry::get('logger')->err($e->getMessage() . PHP_EOL . $e->getTraceAsString());
0882         }
0883         try {
0884             $ldap = new Default_Model_Ocs_Ldap();
0885             $ldap->addUserFromArray($record->toArray());
0886             Zend_Registry::get('logger')->debug(__METHOD__ . ' - ldap : ' . implode(PHP_EOL . " - ",
0887                     $ldap->getMessages()));
0888         } catch (Exception $e) {
0889             Zend_Registry::get('logger')->err($e->getMessage() . PHP_EOL . $e->getTraceAsString());
0890         }
0891         try {
0892             $openCode = new Default_Model_Ocs_Gitlab();
0893             $openCode->createUserFromArray($record->toArray());
0894             Zend_Registry::get('logger')->debug(__METHOD__ . ' - opencode : ' . implode(PHP_EOL . " - ",
0895                     $openCode->getMessages()));
0896         } catch (Exception $e) {
0897             Zend_Registry::get('logger')->err($e->getMessage() . PHP_EOL . $e->getTraceAsString());
0898         }
0899         try {
0900             $forum = new Default_Model_Ocs_Forum();
0901             $forum->createUserFromArray($record->toArray());
0902             Zend_Registry::get('logger')->debug(__METHOD__ . ' - forum : ' . implode(PHP_EOL . " - ",
0903                     $forum->getMessages()));
0904         } catch (Exception $e) {
0905             Zend_Registry::get('logger')->err($e->getMessage() . PHP_EOL . $e->getTraceAsString());
0906         }
0907 
0908 
0909         Default_Model_ActivityLog::logActivity($authUser->member_id, null, $authUser->member_id,
0910             Default_Model_ActivityLog::MEMBER_EMAIL_CONFIRMED, array());
0911         $this->view->member = $authUser;
0912         $this->view->username = $authUser->username;
0913 
0914         $this->view->headScript()->appendFile('//www.google.com/recaptcha/api.js');
0915         $this->view->addHelperPath(APPLICATION_LIB . '/Cgsmith/View/Helper', 'Cgsmith\\View\\Helper\\');
0916         $this->view->form = new Default_Form_Register();
0917         $this->view->overlay = $this->view->render('authorization/registerWelcome.phtml');
0918 
0919         $this->storeAuthSessionData($authUser->member_id);
0920 
0921         $tableProduct = new Default_Model_Project();
0922         $this->view->products = $tableProduct->fetchAllProjectsForMember($authUser->member_id);
0923 
0924         $this->forward('index', 'settings', 'default', array('member_id' => $authUser->member_id));
0925     }
0926 
0927     /**
0928      * @param string|int $identity
0929      *
0930      * @throws Zend_Auth_Storage_Exception
0931      * @throws exception
0932      */
0933     protected function storeAuthSessionData($identity)
0934     {
0935         $authDataModel = new Default_Model_Authorization();
0936         $authDataModel->storeAuthSessionDataByIdentity($identity);
0937     }
0938 
0939     /**
0940      * ppload
0941      */
0942     public function pploadloginAction()
0943     {
0944         $this->_helper->layout()->disableLayout();
0945 
0946         // Init identity and credential
0947         $identity = null;
0948         $credential = null;
0949         if (!empty($_REQUEST['identity'])) {
0950             $identity = $_REQUEST['identity'];
0951         } else {
0952             if (!empty($_SERVER['PHP_AUTH_USER'])) {
0953                 $identity = $_SERVER['PHP_AUTH_USER'];
0954             }
0955         }
0956         if (!empty($_REQUEST['credential'])) {
0957             $credential = $_REQUEST['credential'];
0958         } else {
0959             if (!empty($_SERVER['PHP_AUTH_PW'])) {
0960                 $credential = $_SERVER['PHP_AUTH_PW'];
0961             }
0962         }
0963 
0964         // Authenticate and get user data
0965         $response = array('status' => 'error');
0966         if ($identity && $credential) {
0967             $authModel = new Default_Model_Authorization();
0968             $authData = $authModel->getAuthDataFromApi($identity, $credential);
0969             if (!empty($authData->member_id)) {
0970                 $response = array(
0971                     'status'    => 'ok',
0972                     'member_id' => $authData->member_id
0973                 );
0974             }
0975         }
0976 
0977         $this->_helper->json($response);
0978     }
0979 
0980     public function htmlloginAction()
0981     {
0982         $this->_helper->layout()->disableLayout();
0983         //$this->_helper->viewRenderer->setNoRender(true);
0984     }
0985 
0986     public function validateAction()
0987     {
0988         $this->_helper->layout->disableLayout();
0989         $this->_helper->viewRenderer->setNoRender(true);
0990 
0991         $this->view->headScript()->appendFile('//www.google.com/recaptcha/api.js');
0992         $this->view->addHelperPath(APPLICATION_LIB . '/Cgsmith/View/Helper', 'Cgsmith\\View\\Helper\\');
0993         $formRegister = new Default_Form_Register();
0994 
0995         $name = $this->getParam('name');
0996         $value = $this->getParam('value');
0997 
0998         $result = $formRegister->getElement($name)->isValid($value);
0999 
1000         $this->_helper->json(array('status' => $result, $name => $formRegister->getElement($name)->getMessages()));
1001     }
1002 
1003     /**
1004      * @param array $val
1005      *
1006      * @throws Zend_Exception
1007      */
1008     protected function sendAdminNotificationMail($val)
1009     {
1010         $config = Zend_Registry::get('config');
1011         $receiver = $config->admin->email;
1012         $oNotificationMail = new Default_Plugin_SendMail('tpl_newuser_notification');
1013         $oNotificationMail->setReceiverMail($receiver);
1014         $oNotificationMail->setTemplateVar('username', $val['username']);
1015         $oNotificationMail->send();
1016     }
1017 
1018     /**
1019      * @param array $userData
1020      *
1021      * @return int
1022      */
1023     protected function storeNewUser($userData)
1024     {
1025         $userTable = new Default_Model_Member();
1026         $userData = $userTable->storeNewUser($userData);
1027 
1028         return $userData->member_id;
1029     }
1030 
1031     /**
1032      * @param int $identity
1033      */
1034     protected function updateUsersLastOnline($identity)
1035     {
1036         $authModel = new Default_Model_Authorization();
1037         $authModel->updateUserLastOnline('member_id', $identity);
1038     }
1039     
1040     private function logLogin() {
1041         
1042     }
1043 
1044 }