Authenticates to the api and sets up client information.
356376
def _authenticate(self):
        """"""
        data = {'username': self.username,
                'password': self.password}
        url = '{base}/client/login'.format(base=self.base_url)
        response = self._session.get(url, params=data)
        print(response.text)
        data = response.json()
        if not data.get('success'):
            raise InvalidCredentials(data.get('reason', None))
        self._populate_info(data)
92515
public void start()
        throws Exception
    {
        if (getHttpContext().getAuthenticator()==null)
        {
            // Find out the Authenticator.
            if (SecurityConstraint.__BASIC_AUTH.equalsIgnoreCase(_authMethod))
                getHttpContext().setAuthenticator(new BasicAuthenticator());
            else if (SecurityConstraint.__CERT_AUTH.equalsIgnoreCase(_authMethod))
                getHttpContext().setAuthenticator(new ClientCertAuthenticator());
            else
                log.warn("Unknown Authentication method:"+_authMethod);
        }
        
        super.start();
    }
202875
def authenticate(params)
      credentials = Authenticate.configuration.user_model_class.credentials(params)
      Authenticate.configuration.user_model_class.authenticate(credentials)
    end
1243386
def _authenticate(self):
        """"""
        if not self._get_provider_option(
                'auth_username') or not self._get_provider_option('auth_password'):
            raise Exception(
                'No valid authentication data passed, expected: auth-username and auth-password')
        response = self._request_login(self._get_provider_option('auth_username'),
                                       self._get_provider_option('auth_password'))
        if 'ssid' in response:
            self.ssid = response['ssid']
            domains = self.domains_list()
            if any((domain['name'] == self.domain for domain in domains)):
                self.domain_id = self.domain
            else:
                raise Exception("Unknown domain {}".format(self.domain))
        else:
            raise Exception("No SSID provided by server")
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;

    }
1253160
def authentication(self, event):
        """"""

        try:
            self.log("Authorization has been granted by DB check:",
                     event.username, lvl=debug)

            account, profile, clientconfig = event.userdata

            useruuid = event.useruuid
            originatingclientuuid = event.clientuuid
            clientuuid = clientconfig.uuid

            if clientuuid != originatingclientuuid:
                self.log("Mutating client uuid to request id:",
                         clientuuid, lvl=network)
            # Assign client to user
            if useruuid in self._users:
                signedinuser = self._users[useruuid]
            else:
                signedinuser = User(account, profile, useruuid)
                self._users[account.uuid] = signedinuser

            if clientuuid in signedinuser.clients:
                self.log("Client configuration already logged in.",
                         lvl=critical)
                # TODO: What now??
                # Probably senseful would be to add the socket to the
                # client's other socket
                # The clients would be identical then - that could cause
                # problems
                # which could be remedied by duplicating the configuration
            else:
                signedinuser.clients.append(clientuuid)
                self.log("Active client (", clientuuid, ") registered to "
                                                        "user", useruuid,
                         lvl=debug)

            # Update socket..
            socket = self._sockets[event.sock]
            socket.clientuuid = clientuuid
            self._sockets[event.sock] = socket

            # ..and client lists

            try:
                language = clientconfig.language
            except AttributeError:
                language = "en"

            # TODO: Rewrite and simplify this:
            newclient = Client(
                sock=event.sock,
                ip=socket.ip,
                clientuuid=clientuuid,
                useruuid=useruuid,
                name=clientconfig.name,
                config=clientconfig,
                language=language
            )

            del (self._clients[originatingclientuuid])
            self._clients[clientuuid] = newclient

            authpacket = {"component": "auth", "action": "login",
                          "data": account.serializablefields()}
            self.log("Transmitting Authorization to client", authpacket,
                     lvl=network)
            self.fireEvent(
                write(event.sock, json.dumps(authpacket)),
                "wsserver"
            )

            profilepacket = {"component": "profile", "action": "get",
                             "data": profile.serializablefields()}
            self.log("Transmitting Profile to client", profilepacket,
                     lvl=network)
            self.fireEvent(write(event.sock, json.dumps(profilepacket)),
                           "wsserver")

            clientconfigpacket = {"component": "clientconfig", "action": "get",
                                  "data": clientconfig.serializablefields()}
            self.log("Transmitting client configuration to client",
                     clientconfigpacket, lvl=network)
            self.fireEvent(write(event.sock, json.dumps(clientconfigpacket)),
                           "wsserver")

            self.fireEvent(userlogin(clientuuid, useruuid, clientconfig, signedinuser))

            self.log("User configured: Name",
                     signedinuser.account.name, "Profile",
                     signedinuser.profile.uuid, "Clients",
                     signedinuser.clients,
                     lvl=debug)

        except Exception as e:
            self.log("Error (%s, %s) during auth grant: %s" % (
                type(e), e, event), lvl=error)
928798
protected function authenticate()
    {
        // Check if the enough attributes have been set to perform authentication.
        // Note that password is not required by all methods.
        if (empty($this->username) || empty($this->authMethod)) {
            throw new ConfigurationException(
                sprintf(
                    'Missing authentication parameters. Method: "%s", username "%s".',
                    $this->authMethod,
                    $this->username
                )
            );
        }

        // Make sure a valid authentication method has been set.
        $authMethodMap = array(
            'http-token' => Client::AUTH_HTTP_TOKEN,
            'password' => Client::AUTH_HTTP_PASSWORD,
            'client-id' => Client::AUTH_URL_CLIENT_ID,
            'url-token' => Client::AUTH_URL_TOKEN,
        );
        if (!isset($authMethodMap[$this->authMethod])) {
            throw new ConfigurationException(
                sprintf(
                    'Unknown authentication method "%s". Supported methods "%s"',
                    $this->authMethod,
                    implode('", "', array_keys($authMethodMap))
                )
            );
        }

        // Set authentication.
        $this->client->authenticate($this->username, $this->password, $authMethodMap[$this->authMethod]);
    }
1279005
public function authenticate(ClientContract $client): void
    {
        if ($this->cookie !== '' || $this->isAuthenticating) {
            return;
        }

        $this->isAuthenticating = true;
        $response = $client->request('POST', '/user/login', [
            'login' => $this->username,
            'password' => $this->password,
        ]);
        $this->isAuthenticating = false;

        if ($response->isStatusCode(200)) {
            $this->cookie = $response->cookie();
        }
    }
1260786
function setClientInfo(req) {

	let client = req.client = {};

	initUserAgendAndOS(req.headers, client);
	initClientIp(req, client);
}
129340
public function authenticate()
    {
        $object = 'login';
        $url = sprintf('/api/%s/version/%s', $object, $this->version);
        $parameters = array(
            'email'    => $this->email,
            'password' => $this->password,
            'user_key' => $this->userKey,
            'format'   => $this->format
        );

        $this->apiKey = $this->doPost($object, $url, $parameters);

        return $this->apiKey;
    }
172043
def authenticate(self):
        """"""
        try:
            payload = self._api.domain.info(self._api_key, self._domain)
            self._zone_id = payload['zone_id']
            return payload['id']
        except xmlrpclib.Fault as err:
            raise Exception("Failed to authenticate: '{0}'".format(err))
472272
public function setupAuthentication() {
		if (!in_array('Auth', $this->components()->loaded())) {
			$this->components()->load('Auth');
		}

		$this->components()->Auth->setConfig('authenticate', [
			'Form' => [
				'userModel' => 'Users',
				'fields' => [
					'username' => 'email',
					'password' => 'password'
				],
				'scope' => [
					'Users.email_verified' => 1
				]
			]
		]);
	}
37200
protected function authenticate()
    {
        if (!$this->isAuthenticated) {
            list($url, $this->cdnUrl, $this->authToken) = $this->auth->authenticate();
            if ($this->useServicenet) {
                $url = str_replace('https://', 'https://snet-%s', $url);
            }

            $this->connectionUrlInfo = Utils::parseUrl($url);
            $this->httpConnect();

            if ($this->cdnUrl) {
                $this->cdnConnect();
            }

            $this->isAuthenticated = true;
        }
    }
963980
def authenticate(self, client_id, client_secret, use_cache=True):
        
        # We will reuse a token for as long as we have one cached
        # and it hasn't expired.
        if use_cache:
            client = self._get_client_from_cache(client_id)
            if (client) and (not self.is_expired_token(client)):
                self.authenticated = True
                self.client = client
                return

        # Let's authenticate the client
        client = {
            'id': client_id,
            'secret': client_secret
        }

        res = self._authenticate_client(client_id, client_secret)
        client.update(res)

        expires = datetime.datetime.now() + \
                  datetime.timedelta(seconds=res['expires_in'])
        client['expires'] = expires.isoformat()

        # Cache it for repeated use until expired
        self._write_to_uaa_cache(client)

        self.client = client
        self.authenticated = True
512062
def main(client_id, client_secret, scopes):
  """"""
  client_config = ClientConfigBuilder(
      client_type=ClientConfigBuilder.CLIENT_TYPE_WEB, client_id=client_id,
      client_secret=client_secret)

  flow = InstalledAppFlow.from_client_config(
      client_config.Build(), scopes=scopes)
  # Note that from_client_config will not produce a flow with the
  # redirect_uris (if any) set in the client_config. This must be set
  # separately.
  flow.redirect_uri = _REDIRECT_URI

  auth_url, _ = flow.authorization_url(prompt='consent')

  print ('Log into the Google Account you use to access your Ad Manager account'
         'and go to the following URL: \n%s\n' % (auth_url))
  print 'After approving the token enter the verification code (if specified).'
  code = raw_input('Code: ').strip()

  try:
    flow.fetch_token(code=code)
  except InvalidGrantError as ex:
    print 'Authentication has failed: %s' % ex
    sys.exit(1)

  print 'Access token: %s' % flow.credentials.token
  print 'Refresh token: %s' % flow.credentials.refresh_token
684896
def _client(self, id, secret):
        """"""
        url = self.api_url + self.auth_token_url
        auth_string = '%s:%s' % (id, secret)
        authorization = base64.b64encode(auth_string.encode()).decode()
        headers = {
            'Authorization': "Basic " + authorization,
            'Content-Type': "application/x-www-form-urlencoded"
        }
        params = {
            'grant_type': 'client_credentials',
            'response_type': 'token'
        }
        return self.session.post(url, params=params, headers=headers)
54393
function(){
    // Initialize the API object
    if (this.mainView) {
      this.mainView.clear();
    }
    var url = this.options.url;
    if (url && url.indexOf('http') !== 0) {
      url = this.buildUrl(window.location.href.toString(), url);
    }
    if(this.api) {
      this.options.authorizations = this.api.clientAuthorizations.authz;
    }
    this.options.url = url;
    this.headerView.update(url);

    this.api = new SwaggerClient(this.options);
  }