Authenticate action

@return ResponseInterface|Result
508626
public function authenticate()
    {
        $request = $this->getRequest();
        $adapter = $this->getAuthenticationAdapter();
        $result  = $adapter->setRequest($request);

        if ($result instanceof ResponseInterface) {
            return $result;
        }

        $result = $this->getAuthenticationService()->authenticate($adapter);
        $messages = $result->getMessages();
        if (!$messages) {
            return $result;
        }

        $controller = $this->getController();
        /* @var $flash \Zend\Mvc\Controller\Plugin\FlashMessenger */
        $flash = $controller->flashMessenger();

        switch ($result->getCode()) {
            case Result::SUCCESS:
                foreach ($messages as $message) {
                    $flash->addSuccessMessage($controller->translate($message));
                }
                break;
            case Result::FAILURE_UNCATEGORIZED:
                foreach ($messages as $message) {
                    $flash->addErrorMessage($controller->translate($message));
                }
                break;
            case Result::FAILURE_IDENTITY_NOT_FOUND:
                $identityKey = $adapter->getEvent()->getIdentityKey();
                foreach ($messages as $message) {
                    $errors[$identityKey][] = $controller->translate($message);
                }
                $flash->addErrorMessage($errors);
                break;
            case Result::FAILURE_CREDENTIAL_INVALID:
                $credentialKey = $adapter->getEvent()->getCredentialKey();
                foreach ($messages as $message) {
                    $errors[$credentialKey][] = $controller->translate($message);
                }
                $flash->addErrorMessage($errors);
        }

        if (!$result->isValid()) {
            $adapter->resetAdapters();
        }

        return $result;
    }
377451
protected function authenticate()
    {
        $headers = [
            'Accept: application/json',
            'Content-Type: application/json; charset=utf-8',
        ];

        if (!empty($this->secret_token)) {
            $headers[] = 'X-AppSecretToken:'.$this->secret_token;
        }

        if (!empty($this->grant_token)) {
            $headers[] = 'X-AgreementGrantToken:'.$this->grant_token;
        }

        //default headers
        $options = [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_HTTPAUTH       => CURLAUTH_BASIC,
            CURLOPT_HTTPHEADER     => $headers,
        ];

        curl_setopt_array($this->ch, $options);
    }
11981
public function authenticate()
    {
        if (static::AUTH_METHOD_NOT_SET === $this->options['authmethod']) {
            $this->detectAuthMethod();
        }

        switch ($this->options['authmethod']) {
            case static::AUTH_METHOD_NULL:
                $this->executeCommand('AUTHENTICATE');
                break;

            case static::AUTH_METHOD_HASHEDPASSWORD:
                $password = $this->getOption('password');
                if (false === $password) {
                    throw new \Exception('You must set a password option');
                }

                $this->executeCommand('AUTHENTICATE '.static::quote($password));
                break;

            case static::AUTH_METHOD_COOKIE:
                $cookieFile = $this->getOption('cookiefile');
                if (false === $cookieFile) {
                    throw new \Exception('You must set a cookiefile option');
                }
                $cookie = file_get_contents($cookieFile);

                $this->executeCommand('AUTHENTICATE '.bin2hex($cookie));
                break;
        }

        return $this;
    }
1365206
public function authenticateAction()
    {
        if ($this->zfcUserAuthentication()->getAuthService()->hasIdentity()) {
            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
        }
        $adapter = $this->zfcUserAuthentication()->getAuthAdapter();
        $redirect = $this->params()->fromPost('redirect', $this->params()->fromQuery('redirect', false));
        
        $routeLoginAdmin = $this->params()->fromPost('routeLoginAdmin', $this->params()->fromQuery('routeLoginAdmin', false));

        $result = $adapter->prepareForAuthentication($this->getRequest());

        // Return early if an adapter returned a response
        if ($result instanceof Response) {
            return $result;
        }

        $auth = $this->zfcUserAuthentication()->getAuthService()->authenticate($adapter);

        if (!$auth->isValid()) {
            $this->flashMessenger()->setNamespace('zfcuser-login-form')->addMessage($this->failedLoginMessage);
            $adapter->resetAdapters();

            if (!empty($routeLoginAdmin)) {
                return $this->redirect()->toUrl($routeLoginAdmin);
            }

            return $this->redirect()->toUrl(
                $this->url()->fromRoute('frontend/zfcuser/login')
                . ($redirect ? '?redirect='.$redirect : '')
            );
        }

        $user = $this->zfcUserAuthentication()->getIdentity();
        $this->getEventManager()->trigger('login.post', $this, array('user' => $user));

        if ($this->getOptions()->getUseRedirectParameterIfPresent() && $redirect) {
            return $this->redirect()->toUrl($redirect);
        }

        return $this->redirect()->toUrl(
            $this->url()->fromRoute(
                $this->getOptions()->getLoginRedirectRoute()
            )
        );
    }
385049
public function authenticate()
    {
        if (!empty($this->hashedPassword)) {
            return $this->authenticateWithPassword($this->login, $this->getTokenAuthSecret());
        } elseif (is_null($this->login)) {
            return $this->authenticateWithToken($this->token_auth);
        } elseif (!empty($this->login)) {
            return $this->authenticateWithLoginAndToken($this->token_auth, $this->login);
        }

        return new AuthResult(AuthResult::FAILURE, $this->login, $this->token_auth);
    }
1074079
public function authenticate(Request $request)
    {
        $email    = $request->input(self::AUTH_PARAM_EMAIL, null);
        $password = $request->input(self::AUTH_PARAM_PASSWORD, null);

        if ($email !== null &&
            $password !== null &&
            ($user = User::query()->where(User::FIELD_EMAIL, '=', strtolower($email))->first()) !== null
        ) {
            /** @var HasherInterface $hasher */
            $hasher = app(HasherInterface::class);
            if ($hasher->check($password, $user->{User::FIELD_PASSWORD_HASH}) === true) {
                /** @var TokenCodecInterface $codec */
                $codec = app(TokenCodecInterface::class);
                $token = $codec->encode($user);

                $this->getLogger()->debug(
                    'Account login success.',
                    [User::FIELD_EMAIL => $email, User::FIELD_ID => $user->getKey()]
                );

                return response($token);
            }
        }

        $this->getLogger()->debug('Account login failed.', [User::FIELD_EMAIL => $email]);

        return response(null, Response::HTTP_UNAUTHORIZED);
    }
248070
public function authenticate()
    {
        $hmac = $this->getRest()->getServer()->getHmac();
        $data = array_merge($this->getRequestHeaders(true), $this->getBodyData());
        $auth = $hmac->setData($data)
                     ->setRoute($this->getPlatform()->getPost('api_method'))
                     ->setMethod($_SERVER['REQUEST_METHOD'])
                     ->auth($this->settings['api_key'], $this->settings['api_secret']);
        
        if(!$auth) {
            return false;
        }
        
        return true;
    }
606611
public function authenticate()
    {
        // go to google.com to get some cookies
        $request = $this->guzzleClient->createRequest('GET', 'http://www.google.com/ncr', ['cookies' => $this->cookieJar]);
        $response = $this->guzzleClient->send($request);

        // get google auth page html and fetch GALX
        $request = $this->guzzleClient->createRequest('GET', self::AUTH_URL, ['cookies' => $this->cookieJar]);
        $response = $this->guzzleClient->send($request);

        $content = $response->getBody()->getContents();

        $document = new \DOMDocument();
        @$document->loadHTML($content);

        $inputElements = $document->getElementsByTagName("input");

        $params = [];

        foreach ($inputElements as $input) {
            $params[$input->getAttribute("name")] = $input->getAttribute("value");
        }

        $params['Email'] = $this->email;
        $params['Passwd'] = $this->password;

        $params['pstMsg'] = '1';
        $params['continue'] = 'http://www.google.com/trends';

        // authenticate
        $request = $this->guzzleClient->createRequest('POST', self::AUTH_URL, ['cookies' => $this->cookieJar]);
        $query = $request->getQuery();


        foreach ($params as $key => $param) {
            $query->set($key, $param);
        }

        $response = $this->guzzleClient->send($request);

        // verify sign in if needed
        if (strpos($response->getEffectiveUrl(), 'LoginVerification') !== false) {
            $content = $response->getBody()->getContents();

            $document = new \DOMDocument();
            @$document->loadHTML($content);

            $inputElements = $document->getElementsByTagName("input");

            $params = [];

            foreach ($inputElements as $input) {
                $params[$input->getAttribute("name")] = $input->getAttribute("value");
            }

            $params['challengetype'] = 'RecoveryEmailChallenge';
            $params['emailAnswer'] = $this->recoveryEmail;

            $url = substr($response->getEffectiveUrl(), 0, strpos($response->getEffectiveUrl(), '?'));

            $request = $this->guzzleClient->createRequest('POST', $url, ['cookies' => $this->cookieJar]);
            $query = $request->getQuery();


            foreach ($params as $key => $param) {
                $query->set($key, $param);
            }

            $response = $this->guzzleClient->send($request);
        }

        // update cookies
        $response = $this->guzzleClient->get('https://www.google.com/accounts/CheckCookie?chtml=LoginDoneHtml',
            ['cookies' => $this->cookieJar],
            ['headers' =>
                ['Referrer' => 'https://www.google.com/accounts/ServiceLoginBoxAuth'],
            ]
        );

        // set language for trends
        $I4SUserLocale = new setCookie([
            'Name'     => 'I4SUserLocale',
            'Value'    => $this->language,
            'Domain'   => 'www.google.com',
            'Path'     => '/trends',
            'Secure'   => true,
            'HttpOnly' => true
        ]);

        $this->cookieJar->setCookie($I4SUserLocale);

        return $this;
    }
210248
public function ajaxauthenticateAction()
    {
        // $this->getServiceLocator()->get('Zend\Log')->info('ajaxloginAction -
        // AUTHENT : ');
        if ($this->zfcUserAuthentication()
            ->getAuthService()
            ->hasIdentity()) {
            return true;
        }
        $adapter = $this->zfcUserAuthentication()->getAuthAdapter();
        $adapter->prepareForAuthentication($this->getRequest());
        $auth = $this->zfcUserAuthentication()->getAuthService()->authenticate($adapter);

        if (! $auth->isValid()) {
            $adapter->resetAdapters();

            return false;
        }

        $user = $this->zfcUserAuthentication()->getIdentity();

        if ($user->getState() && $user->getState() === 2) {
            $this->getUserService()->getUserMapper()->activate($user);
        }
        $this->getEventManager()->trigger('login.post', $this, array('user' => $user));
        return true;
    }
22424
public function authenticate()
    {
        $optionsRequired = array('filename', 'realm', 'username', 'password');
        foreach ($optionsRequired as $optionRequired) {
            if (null === $this->{"_$optionRequired"}) {
                /**
                 * @see Zend_Auth_Adapter_Exception
                 */
                require_once 'Zend/Auth/Adapter/Exception.php';
                throw new Zend_Auth_Adapter_Exception("Option '$optionRequired' must be set before authentication");
            }
        }

        if (false === ($fileHandle = @fopen($this->_filename, 'r'))) {
            /**
             * @see Zend_Auth_Adapter_Exception
             */
            require_once 'Zend/Auth/Adapter/Exception.php';
            throw new Zend_Auth_Adapter_Exception("Cannot open '$this->_filename' for reading");
        }

        $id       = "$this->_username:$this->_realm";
        $idLength = strlen($id);

        $result = array(
            'code'  => Zend_Auth_Result::FAILURE,
            'identity' => array(
                'realm'    => $this->_realm,
                'username' => $this->_username,
                ),
            'messages' => array()
            );

        while ($line = trim(fgets($fileHandle))) {
            if (substr($line, 0, $idLength) === $id) {
                if ($this->_secureStringCompare(substr($line, -32), md5("$this->_username:$this->_realm:$this->_password"))) {
                    $result['code'] = Zend_Auth_Result::SUCCESS;
                } else {
                    $result['code'] = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
                    $result['messages'][] = 'Password incorrect';
                }
                return new Zend_Auth_Result($result['code'], $result['identity'], $result['messages']);
            }
        }

        $result['code'] = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND;
        $result['messages'][] = "Username '$this->_username' and realm '$this->_realm' combination not found";
        return new Zend_Auth_Result($result['code'], $result['identity'], $result['messages']);
    }
763606
public function authenticate()
    {
        $allowOverride = $this->shardServiceManager->getAllowOverride();
        $this->shardServiceManager->setAllowOverride(true);

        $sysUser = new User;
        $sysUser->addRole('sys::authenticate');
        $this->shardServiceManager->setService('user', $sysUser);
        
        $this->doctrineAdapter->setIdentity($this->identity);
        $this->doctrineAdapter->setCredential($this->credential);
        $result = $this->doctrineAdapter->authenticate();
             
        if ($result->isValid()) {
            $this->shardServiceManager->setService('user', $result->getIdentity());
        } else {
            $sysUser->removeRole('sys::authenticate');
        }
        $this->shardServiceManager->setAllowOverride($allowOverride);
            
        return $result;
    }
137868
public function authentication()
    {
        $response = \Aperdia\Clef::authentication($_GET['code']);

        // error
        if (!$response) {
            $error = 'Error';
        // error
        } elseif (isset($response['error'])) {
            $error = $response['error'];
        // success
        } elseif (isset($response['success'])) {
            // verif if exists account in Authentication table
            $verif = Authentication::whereprovider("clef")->whereprovider_uid($response['info']['id'])->first();

            // no account
            if (empty($verif)) {


            // Find account
            } else {
                // Find the user using the user id
                $user = User::find($verif->user_id);

                // RAZ logout
                if ($user->logout == 1) {
                    $user->logout = 0;
                    $user->save();
                }

                // Log the user in
                Auth::login($user);

                return Redirect::intended('/');
            }
        // error
        } else {
            $error = 'Unknown error';
        }

        return Redirect::to("login")->withErrors($error);
    }
368957
public function authenticate()
    {
        // Build the form data
        $data = $this->uniBody->Form(['secret' => $this->secret]);
        // Send a post request to the API
        $response = $this->uniRequest->post($this->authURL, $this->headers, $data);
        // Set the authentication response
        $this->authResponse = $response;
        // Check that we get 20X back
        if (in_array($response->code, $this->validCodes)) {
            // Grab the jwt from the response body
            $token = $response->body->token;
            $this->jwt = $token;
            // Set the authorization header
            $this->headers['Authorization'] = implode(' ', ['Bearer', $token]);
            // Return the response
            return $response;
        } else {
            // If we did not get 20X throw an exception
            throw new Exception($response->body->message, $response->code);
        }
    }
1087407
private function authenticate()
    {

// Get the consumer
        $doSaveConsumer = false;
// Check all required launch parameters
        $this->ok = isset($_POST['lti_message_type']) && array_key_exists($_POST['lti_message_type'], self::$MESSAGE_TYPES);
        if (!$this->ok) {
            $this->reason = 'Invalid or missing lti_message_type parameter.';
        }
        if ($this->ok) {
            $this->ok = isset($_POST['lti_version']) && in_array($_POST['lti_version'], self::$LTI_VERSIONS);
            if (!$this->ok) {
                $this->reason = 'Invalid or missing lti_version parameter.';
            }
        }
        if ($this->ok) {
            if ($_POST['lti_message_type'] === 'basic-lti-launch-request') {
                $this->ok = isset($_POST['resource_link_id']) && (strlen(trim($_POST['resource_link_id'])) > 0);
                if (!$this->ok) {
                    $this->reason = 'Missing resource link ID.';
                }
            } else if ($_POST['lti_message_type'] === 'ContentItemSelectionRequest') {
                if (isset($_POST['accept_media_types']) && (strlen(trim($_POST['accept_media_types'])) > 0)) {
                    $mediaTypes = array_filter(explode(',', str_replace(' ', '', $_POST['accept_media_types'])), 'strlen');
                    $mediaTypes = array_unique($mediaTypes);
                    $this->ok = count($mediaTypes) > 0;
                    if (!$this->ok) {
                        $this->reason = 'No accept_media_types found.';
                    } else {
                        $this->mediaTypes = $mediaTypes;
                    }
                } else {
                    $this->ok = false;
                }
                if ($this->ok && isset($_POST['accept_presentation_document_targets']) && (strlen(trim($_POST['accept_presentation_document_targets'])) > 0)) {
                    $documentTargets = array_filter(explode(',', str_replace(' ', '', $_POST['accept_presentation_document_targets'])), 'strlen');
                    $documentTargets = array_unique($documentTargets);
                    $this->ok = count($documentTargets) > 0;
                    if (!$this->ok) {
                        $this->reason = 'Missing or empty accept_presentation_document_targets parameter.';
                    } else {
                        foreach ($documentTargets as $documentTarget) {
                            $this->ok = $this->checkValue($documentTarget, array('embed', 'frame', 'iframe', 'window', 'popup', 'overlay', 'none'),
                                 'Invalid value in accept_presentation_document_targets parameter: %s.');
                            if (!$this->ok) {
                                break;
                            }
                        }
                        if ($this->ok) {
                            $this->documentTargets = $documentTargets;
                        }
                    }
                } else {
                    $this->ok = false;
                }
                if ($this->ok) {
                    $this->ok = isset($_POST['content_item_return_url']) && (strlen(trim($_POST['content_item_return_url'])) > 0);
                    if (!$this->ok) {
                        $this->reason = 'Missing content_item_return_url parameter.';
                    }
                }
            } else if ($_POST['lti_message_type'] == 'ToolProxyRegistrationRequest') {
                $this->ok = ((isset($_POST['reg_key']) && (strlen(trim($_POST['reg_key'])) > 0)) &&
                             (isset($_POST['reg_password']) && (strlen(trim($_POST['reg_password'])) > 0)) &&
                             (isset($_POST['tc_profile_url']) && (strlen(trim($_POST['tc_profile_url'])) > 0)) &&
                             (isset($_POST['launch_presentation_return_url']) && (strlen(trim($_POST['launch_presentation_return_url'])) > 0)));
                if ($this->debugMode && !$this->ok) {
                    $this->reason = 'Missing message parameters.';
                }
            }
        }
        $now = time();
// Check consumer key
        if ($this->ok && ($_POST['lti_message_type'] != 'ToolProxyRegistrationRequest')) {
            $this->ok = isset($_POST['oauth_consumer_key']);
            if (!$this->ok) {
                $this->reason = 'Missing consumer key.';
            }
            if ($this->ok) {
                $this->consumer = new ToolConsumer($_POST['oauth_consumer_key'], $this->dataConnector);
                $this->ok = !is_null($this->consumer->created);
                if (!$this->ok) {
                    $this->reason = 'Invalid consumer key.';
                }
            }
            if ($this->ok) {
                $today = date('Y-m-d', $now);
                if (is_null($this->consumer->lastAccess)) {
                    $doSaveConsumer = true;
                } else {
                    $last = date('Y-m-d', $this->consumer->lastAccess);
                    $doSaveConsumer = $doSaveConsumer || ($last !== $today);
                }
                $this->consumer->last_access = $now;
                try {
                    $store = new OAuthDataStore($this);
                    $server = new OAuth\OAuthServer($store);
                    $method = new OAuth\OAuthSignatureMethod_HMAC_SHA1();
                    $server->add_signature_method($method);
                    $request = OAuth\OAuthRequest::from_request();
                    $res = $server->verify_request($request);
                } catch (\Exception $e) {
                    $this->ok = false;
                    if (empty($this->reason)) {
                        if ($this->debugMode) {
                            $consumer = new OAuth\OAuthConsumer($this->consumer->getKey(), $this->consumer->secret);
                            $signature = $request->build_signature($method, $consumer, false);
                            $this->reason = $e->getMessage();
                            if (empty($this->reason)) {
                                $this->reason = 'OAuth exception';
                            }
                            $this->details[] = 'Timestamp: ' . time();
                            $this->details[] = "Signature: {$signature}";
                            $this->details[] = "Base string: {$request->base_string}]";
                        } else {
                            $this->reason = 'OAuth signature check failed - perhaps an incorrect secret or timestamp.';
                        }
                    }
                }
            }
            if ($this->ok) {
                $today = date('Y-m-d', $now);
                if (is_null($this->consumer->lastAccess)) {
                    $doSaveConsumer = true;
                } else {
                    $last = date('Y-m-d', $this->consumer->lastAccess);
                    $doSaveConsumer = $doSaveConsumer || ($last !== $today);
                }
                $this->consumer->last_access = $now;
                if ($this->consumer->protected) {
                    if (!is_null($this->consumer->consumerGuid)) {
                        $this->ok = empty($_POST['tool_consumer_instance_guid']) ||
                             ($this->consumer->consumerGuid === $_POST['tool_consumer_instance_guid']);
                        if (!$this->ok) {
                            $this->reason = 'Request is from an invalid tool consumer.';
                        }
                    }
                }
                if ($this->ok) {
                    $this->ok = $this->consumer->enabled;
                    if (!$this->ok) {
                        $this->reason = 'Tool consumer has not been enabled by the tool provider.';
                    }
                }
                if ($this->ok) {
                    $this->ok = is_null($this->consumer->enableFrom) || ($this->consumer->enableFrom <= $now);
                    if ($this->ok) {
                        $this->ok = is_null($this->consumer->enableUntil) || ($this->consumer->enableUntil > $now);
                        if (!$this->ok) {
                            $this->reason = 'Tool consumer access has expired.';
                        }
                    } else {
                        $this->reason = 'Tool consumer access is not yet available.';
                    }
                }
            }

// Validate other message parameter values
            if ($this->ok) {
                if ($_POST['lti_message_type'] === 'ContentItemSelectionRequest') {
                    if (isset($_POST['accept_unsigned'])) {
                        $this->ok = $this->checkValue($_POST['accept_unsigned'], array('true', 'false'), 'Invalid value for accept_unsigned parameter: %s.');
                    }
                    if ($this->ok && isset($_POST['accept_multiple'])) {
                        $this->ok = $this->checkValue($_POST['accept_multiple'], array('true', 'false'), 'Invalid value for accept_multiple parameter: %s.');
                    }
                    if ($this->ok && isset($_POST['accept_copy_advice'])) {
                        $this->ok = $this->checkValue($_POST['accept_copy_advice'], array('true', 'false'), 'Invalid value for accept_copy_advice parameter: %s.');
                    }
                    if ($this->ok && isset($_POST['auto_create'])) {
                        $this->ok = $this->checkValue($_POST['auto_create'], array('true', 'false'), 'Invalid value for auto_create parameter: %s.');
                    }
                    if ($this->ok && isset($_POST['can_confirm'])) {
                        $this->ok = $this->checkValue($_POST['can_confirm'], array('true', 'false'), 'Invalid value for can_confirm parameter: %s.');
                    }
                } else if (isset($_POST['launch_presentation_document_target'])) {
                    $this->ok = $this->checkValue($_POST['launch_presentation_document_target'], array('embed', 'frame', 'iframe', 'window', 'popup', 'overlay'),
                         'Invalid value for launch_presentation_document_target parameter: %s.');
                }
            }
        }

        if ($this->ok && ($_POST['lti_message_type'] === 'ToolProxyRegistrationRequest')) {
            $this->ok = $_POST['lti_version'] == self::LTI_VERSION2;
            if (!$this->ok) {
                $this->reason = 'Invalid lti_version parameter';
            }
            if ($this->ok) {
                $http = new HTTPMessage($_POST['tc_profile_url'], 'GET', null, 'Accept: application/vnd.ims.lti.v2.toolconsumerprofile+json');
                $this->ok = $http->send();
                if (!$this->ok) {
                    $this->reason = 'Tool consumer profile not accessible.';
                } else {
                    $tcProfile = json_decode($http->response);
                    $this->ok = !is_null($tcProfile);
                    if (!$this->ok) {
                        $this->reason = 'Invalid JSON in tool consumer profile.';
                    }
                }
            }
// Check for required capabilities
            if ($this->ok) {
                $this->consumer = new ToolConsumer($_POST['reg_key'], $this->dataConnector);
                $this->consumer->profile = $tcProfile;
                $capabilities = $this->consumer->profile->capability_offered;
                $missing = array();
                foreach ($this->resourceHandlers as $resourceHandler) {
                    foreach ($resourceHandler->requiredMessages as $message) {
                        if (!in_array($message->type, $capabilities)) {
                            $missing[$message->type] = true;
                        }
                    }
                }
                foreach ($this->constraints as $name => $constraint) {
                    if ($constraint['required']) {
                        if (!in_array($name, $capabilities) && !in_array($name, array_flip($capabilities))) {
                            $missing[$name] = true;
                        }
                    }
                }
                if (!empty($missing)) {
                    ksort($missing);
                    $this->reason = 'Required capability not offered - \'' . implode('\', \'', array_keys($missing)) . '\'';
                    $this->ok = false;
                }
            }
// Check for required services
            if ($this->ok) {
                foreach ($this->requiredServices as $service) {
                    foreach ($service->formats as $format) {
                        if (!$this->findService($format, $service->actions)) {
                            if ($this->ok) {
                                $this->reason = 'Required service(s) not offered - ';
                                $this->ok = false;
                            } else {
                                $this->reason .= ', ';
                            }
                            $this->reason .= "'{$format}' [" . implode(', ', $service->actions) . ']';
                        }
                    }
                }
            }
            if ($this->ok) {
                if ($_POST['lti_message_type'] === 'ToolProxyRegistrationRequest') {
                    $this->consumer->profile = $tcProfile;
                    $this->consumer->secret = $_POST['reg_password'];
                    $this->consumer->ltiVersion = $_POST['lti_version'];
                    $this->consumer->name = $tcProfile->product_instance->service_owner->service_owner_name->default_value;
                    $this->consumer->consumerName = $this->consumer->name;
                    $this->consumer->consumerVersion = "{$tcProfile->product_instance->product_info->product_family->code}-{$tcProfile->product_instance->product_info->product_version}";
                    $this->consumer->consumerGuid = $tcProfile->product_instance->guid;
                    $this->consumer->enabled = true;
                    $this->consumer->protected = true;
                    $doSaveConsumer = true;
                }
            }
        } else if ($this->ok && !empty($_POST['custom_tc_profile_url']) && empty($this->consumer->profile)) {
            $http = new HTTPMessage($_POST['custom_tc_profile_url'], 'GET', null, 'Accept: application/vnd.ims.lti.v2.toolconsumerprofile+json');
            if ($http->send()) {
                $tcProfile = json_decode($http->response);
                if (!is_null($tcProfile)) {
                    $this->consumer->profile = $tcProfile;
                    $doSaveConsumer = true;
                }
            }
        }

// Validate message parameter constraints
        if ($this->ok) {
            $invalidParameters = array();
            foreach ($this->constraints as $name => $constraint) {
                if (empty($constraint['messages']) || in_array($_POST['lti_message_type'], $constraint['messages'])) {
                    $ok = true;
                    if ($constraint['required']) {
                        if (!isset($_POST[$name]) || (strlen(trim($_POST[$name])) <= 0)) {
                            $invalidParameters[] = "{$name} (missing)";
                            $ok = false;
                        }
                    }
                    if ($ok && !is_null($constraint['max_length']) && isset($_POST[$name])) {
                        if (strlen(trim($_POST[$name])) > $constraint['max_length']) {
                            $invalidParameters[] = "{$name} (too long)";
                        }
                    }
                }
            }
            if (count($invalidParameters) > 0) {
                $this->ok = false;
                if (empty($this->reason)) {
                    $this->reason = 'Invalid parameter(s): ' . implode(', ', $invalidParameters) . '.';
                }
            }
        }

        if ($this->ok) {

// Set the request context
            if (isset($_POST['context_id'])) {
                $this->context = Context::fromConsumer($this->consumer, trim($_POST['context_id']));
                $title = '';
                if (isset($_POST['context_title'])) {
                    $title = trim($_POST['context_title']);
                }
                if (empty($title)) {
                    $title = "Course {$this->context->getId()}";
                }
                if (isset($_POST['context_type'])) {
                    $this->context->type = trim($_POST['context_type']);
                }
                $this->context->title = $title;
            }

// Set the request resource link
            if (isset($_POST['resource_link_id'])) {
                $contentItemId = '';
                if (isset($_POST['custom_content_item_id'])) {
                    $contentItemId = $_POST['custom_content_item_id'];
                }
                $this->resourceLink = ResourceLink::fromConsumer($this->consumer, trim($_POST['resource_link_id']), $contentItemId);
                if (!empty($this->context)) {
                    $this->resourceLink->setContextId($this->context->getRecordId());
                }
                $title = '';
                if (isset($_POST['resource_link_title'])) {
                    $title = trim($_POST['resource_link_title']);
                }
                if (empty($title)) {
                    $title = "Resource {$this->resourceLink->getId()}";
                }
                $this->resourceLink->title = $title;
// Delete any existing custom parameters
                foreach ($this->consumer->getSettings() as $name => $value) {
                    if (strpos($name, 'custom_') === 0) {
                        $this->consumer->setSetting($name);
                        $doSaveConsumer = true;
                    }
                }
                if (!empty($this->context)) {
                    foreach ($this->context->getSettings() as $name => $value) {
                        if (strpos($name, 'custom_') === 0) {
                            $this->context->setSetting($name);
                        }
                    }
                }
                foreach ($this->resourceLink->getSettings() as $name => $value) {
                    if (strpos($name, 'custom_') === 0) {
                        $this->resourceLink->setSetting($name);
                    }
                }
// Save LTI parameters
                foreach (self::$LTI_CONSUMER_SETTING_NAMES as $name) {
                    if (isset($_POST[$name])) {
                        $this->consumer->setSetting($name, $_POST[$name]);
                    } else {
                        $this->consumer->setSetting($name);
                    }
                }
                if (!empty($this->context)) {
                    foreach (self::$LTI_CONTEXT_SETTING_NAMES as $name) {
                        if (isset($_POST[$name])) {
                            $this->context->setSetting($name, $_POST[$name]);
                        } else {
                            $this->context->setSetting($name);
                        }
                    }
                }
                foreach (self::$LTI_RESOURCE_LINK_SETTING_NAMES as $name) {
                    if (isset($_POST[$name])) {
                        $this->resourceLink->setSetting($name, $_POST[$name]);
                    } else {
                        $this->resourceLink->setSetting($name);
                    }
                }
// Save other custom parameters
                foreach ($_POST as $name => $value) {
                    if ((strpos($name, 'custom_') === 0) &&
                        !in_array($name, array_merge(self::$LTI_CONSUMER_SETTING_NAMES, self::$LTI_CONTEXT_SETTING_NAMES, self::$LTI_RESOURCE_LINK_SETTING_NAMES))) {
                        $this->resourceLink->setSetting($name, $value);
                    }
                }
            }

// Set the user instance
            $userId = '';
            if (isset($_POST['user_id'])) {
                $userId = trim($_POST['user_id']);
            }

            $this->user = User::fromResourceLink($this->resourceLink, $userId);

// Set the user name
            $firstname = (isset($_POST['lis_person_name_given'])) ? $_POST['lis_person_name_given'] : '';
            $lastname = (isset($_POST['lis_person_name_family'])) ? $_POST['lis_person_name_family'] : '';
            $fullname = (isset($_POST['lis_person_name_full'])) ? $_POST['lis_person_name_full'] : '';
            $this->user->setNames($firstname, $lastname, $fullname);

// Set the user email
            $email = (isset($_POST['lis_person_contact_email_primary'])) ? $_POST['lis_person_contact_email_primary'] : '';
            $this->user->setEmail($email, $this->defaultEmail);

// Set the user image URI
            if (isset($_POST['user_image'])) {
                $this->user->image = $_POST['user_image'];
            }

// Set the user roles
            if (isset($_POST['roles'])) {
                $this->user->roles = self::parseRoles($_POST['roles']);
            }

// Initialise the consumer and check for changes
            $this->consumer->defaultEmail = $this->defaultEmail;
            if ($this->consumer->ltiVersion !== $_POST['lti_version']) {
                $this->consumer->ltiVersion = $_POST['lti_version'];
                $doSaveConsumer = true;
            }
            if (isset($_POST['tool_consumer_instance_name'])) {
                if ($this->consumer->consumerName !== $_POST['tool_consumer_instance_name']) {
                    $this->consumer->consumerName = $_POST['tool_consumer_instance_name'];
                    $doSaveConsumer = true;
                }
            }
            if (isset($_POST['tool_consumer_info_product_family_code'])) {
                $version = $_POST['tool_consumer_info_product_family_code'];
                if (isset($_POST['tool_consumer_info_version'])) {
                    $version .= "-{$_POST['tool_consumer_info_version']}";
                }
// do not delete any existing consumer version if none is passed
                if ($this->consumer->consumerVersion !== $version) {
                    $this->consumer->consumerVersion = $version;
                    $doSaveConsumer = true;
                }
            } else if (isset($_POST['ext_lms']) && ($this->consumer->consumerName !== $_POST['ext_lms'])) {
                $this->consumer->consumerVersion = $_POST['ext_lms'];
                $doSaveConsumer = true;
            }
            if (isset($_POST['tool_consumer_instance_guid'])) {
                if (is_null($this->consumer->consumerGuid)) {
                    $this->consumer->consumerGuid = $_POST['tool_consumer_instance_guid'];
                    $doSaveConsumer = true;
                } else if (!$this->consumer->protected) {
                    $doSaveConsumer = ($this->consumer->consumerGuid !== $_POST['tool_consumer_instance_guid']);
                    if ($doSaveConsumer) {
                        $this->consumer->consumerGuid = $_POST['tool_consumer_instance_guid'];
                    }
                }
            }
            if (isset($_POST['launch_presentation_css_url'])) {
                if ($this->consumer->cssPath !== $_POST['launch_presentation_css_url']) {
                    $this->consumer->cssPath = $_POST['launch_presentation_css_url'];
                    $doSaveConsumer = true;
                }
            } else if (isset($_POST['ext_launch_presentation_css_url']) &&
                 ($this->consumer->cssPath !== $_POST['ext_launch_presentation_css_url'])) {
                $this->consumer->cssPath = $_POST['ext_launch_presentation_css_url'];
                $doSaveConsumer = true;
            } else if (!empty($this->consumer->cssPath)) {
                $this->consumer->cssPath = null;
                $doSaveConsumer = true;
            }
        }

// Persist changes to consumer
        if ($doSaveConsumer) {
            $this->consumer->save();
        }
        if ($this->ok && isset($this->context)) {
            $this->context->save();
        }
        if ($this->ok && isset($this->resourceLink)) {

// Check if a share arrangement is in place for this resource link
            $this->ok = $this->checkForShare();

// Persist changes to resource link
            $this->resourceLink->save();

// Save the user instance
            if (isset($_POST['lis_result_sourcedid'])) {
                if ($this->user->ltiResultSourcedId !== $_POST['lis_result_sourcedid']) {
                    $this->user->ltiResultSourcedId = $_POST['lis_result_sourcedid'];
                    $this->user->save();
                }
            } else if (!empty($this->user->ltiResultSourcedId)) {
                $this->user->ltiResultSourcedId = '';
                $this->user->save();
            }
        }

        return $this->ok;

    }
1312778
private function authenticateBySession()
    {
        $u = $this->userFactory()->create($this->userType());
        // Call static method on user
        $u = call_user_func([get_class($u), 'getAuthenticated'], $this->userFactory());

        if ($u && $u->id()) {
            $u->saveToSession();

            return $u;
        } else {
            return null;
        }
    }
395460
public function authenticate()
    {
        if (empty($this->_request) ||
            empty($this->_response)) {
            /**
             * @see Zend_Auth_Adapter_Exception
             */
            require_once 'Zend/Auth/Adapter/Exception.php';
            throw new Zend_Auth_Adapter_Exception('Request and Response objects must be set before calling '
                                                . 'authenticate()');
        }

        if ($this->_imaProxy) {
            $getHeader = 'Proxy-Authorization';
        } else {
            $getHeader = 'Authorization';
        }

        $authHeader = $this->_request->getHeader($getHeader);
        if (!$authHeader) {
            return $this->_challengeClient();
        }

        list($clientScheme) = explode(' ', $authHeader);
        $clientScheme = strtolower($clientScheme);

        // The server can issue multiple challenges, but the client should
        // answer with only the selected auth scheme.
        if (!in_array($clientScheme, $this->_supportedSchemes)) {
            $this->_response->setHttpResponseCode(400);
            return new Zend_Auth_Result(
                Zend_Auth_Result::FAILURE_UNCATEGORIZED,
                array(),
                array('Client requested an incorrect or unsupported authentication scheme')
            );
        }

        // client sent a scheme that is not the one required
        if (!in_array($clientScheme, $this->_acceptSchemes)) {
            // challenge again the client
            return $this->_challengeClient();
        }

        switch ($clientScheme) {
            case 'basic':
                $result = $this->_basicAuth($authHeader);
                break;
            case 'digest':
                $result = $this->_digestAuth($authHeader);
            break;
            default:
                /**
                 * @see Zend_Auth_Adapter_Exception
                 */
                require_once 'Zend/Auth/Adapter/Exception.php';
                throw new Zend_Auth_Adapter_Exception('Unsupported authentication scheme');
        }

        return $result;
    }
50055
protected function authenticate() {

		$vo_handle = curl_init($this->ops_auth_url);

		curl_setopt($vo_handle, CURLOPT_CUSTOMREQUEST, 'GET');
		curl_setopt($vo_handle, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($vo_handle, CURLOPT_TIMEOUT, 3);
		curl_setopt($vo_handle, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($vo_handle, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($vo_handle, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($vo_handle, CURLOPT_FOLLOWLOCATION, true);

		// basic auth
		curl_setopt($vo_handle, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
		curl_setopt($vo_handle, CURLOPT_USERPWD, $this->ops_user.':'.$this->ops_key);

		$vs_exec = curl_exec($vo_handle);
		curl_close($vo_handle);

		$va_ret = json_decode($vs_exec, true);

		if(!is_array($va_ret) || !isset($va_ret['authToken']) || (strlen($va_ret['authToken']) != 64)) { return false; }
		$this->ops_auth_token = $va_ret['authToken'];

		// dump token into a file so we can find it later
		@file_put_contents($this->ops_token_storage_path, $this->ops_auth_token);

		return true;
	}