Login to UniFi Controller
-------------------------
returns true upon success
486591
public function login()
    {
        /**
         * if $_SESSION['unificookie'] is set, skip the login
         */
        if (isset($_SESSION['unificookie'])) {
            return $this->is_loggedin = true;
        }

        $ch = $this->get_curl_obj();

        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_REFERER, $this->baseurl . '/login');
        curl_setopt($ch, CURLOPT_URL, $this->baseurl . '/api/login');
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['username' => $this->user, 'password' => $this->password]));

        /**
         * execute the cURL request
         */
        $content = curl_exec($ch);

        if (curl_errno($ch)) {
            trigger_error('cURL error: ' . curl_error($ch));
        }

        if ($this->debug) {
            curl_setopt($ch, CURLOPT_VERBOSE, true);

            print '<pre>';
            print PHP_EOL . '-----------LOGIN-------------' . PHP_EOL;
            print_r(curl_getinfo($ch));
            print PHP_EOL . '----------RESPONSE-----------' . PHP_EOL;
            print $content;
            print PHP_EOL . '-----------------------------' . PHP_EOL;
            print '</pre>';
        }

        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $headers     = substr($content, 0, $header_size);
        $body        = trim(substr($content, $header_size));
        $http_code   = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        preg_match_all('|Set-Cookie: (.*);|Ui', $headers, $results);

        if (isset($results[1])) {
            $this->cookies = implode(';', $results[1]);
            if (!empty($body)) {
                if (($http_code >= 200) && ($http_code < 400)) {
                    if (strpos($this->cookies, 'unifises') !== false) {
                        return $this->is_loggedin = true;
                    }
                }

                if ($http_code === 400) {
                    trigger_error('We have received an HTTP response status: 400. Probably a controller login failure');

                    return $http_code;
                }
            }
        }

        return false;
    }
635956
function check_loginout()
	{
		switch (arg('action'))
		{
			case 'login':
				$this->login(arg('user'), $this->password_hash(arg('password')), arg('autologin', 'int'));
				HTTP::redirect($this->request['url']);
			break;
			case 'logout':
				$this->logout(true);
				HTTP::redirect($this->root.'admin/');
			break;
		}
	}
868246
public function init(): bool
    {
        // Sets the protected $_url
        $this->_getUrl();

        // Load the default Controller if no URL is set
        // eg: Visit http://localhost it loads Default Controller
        if (empty($this->_url[0])) {
            $this->_loadDefaultController();

            return false;
        }

        $this->_loadExistingController();
        $this->_callControllerMethod();

        return true;
    }
409173
public function force_login($user_id = '')
	{
		if (empty($user_id))
		{
			return false;
		}

		$this->user = \DB::select_array(\Config::get('simpleauth.table_columns', array('*')))
			->where_open()
			->where('id', '=', $user_id)
			->where_close()
			->from(\Config::get('simpleauth.table_name'))
			->execute(\Config::get('simpleauth.db_connection'))
			->current();

		if ($this->user == false)
		{
			$this->user = \Config::get('simpleauth.guest_login', true) ? static::$guest_login : false;
			\Session::delete('username');
			\Session::delete('login_hash');
			return false;
		}

		\Session::set('username', $this->user['username']);
		\Session::set('login_hash', $this->create_login_hash());
		return true;
	}
462061
protected function perform_login()
    {
        if (empty($this->email)) {
            $this->error = 601;
            return false;
        } elseif (empty($this->password)) {
            $this->error = 602;
            return false;
        } else {
            // Make some cookies. We all like cookies. Microsoft just likes them more.
            $this->add_cookie('.xbox.com', 'MC0', time(), '/', time() + (60*60*24*365));
            $this->add_cookie('.xbox.com', 's_vi', '[CS]v1|26AD59C185011B4D-40000113004213F1[CE]', '/', time() + (60*60*24*365));
            $this->add_cookie('.xbox.com', 's_nr', '1297891791797', '/', time() + (60*60*24*365));
            $this->add_cookie('.xbox.com', 's_sess', '%20s_cc%3Dtrue%3B%20s_ria%3Dflash%252011%257Csilverlight%2520not%2520detected%3B%20s_sq%3D%3B', '/', time() + (60*60*24*365));
            $this->add_cookie('.xbox.com', 's_pers', '%20s_vnum%3D1352674046430%2526vn%253D4%7C1352674046430%3B%20s_lastvisit%3D1324587801077%7C1419195801077%3B%20s_invisit%3Dtrue%7C1324589873289%3B', '/', time() + (60*60*24*365));
            $this->add_cookie('.xbox.com', 'UtcOffsetMinutes', '60', '/', time() + (60*60*24*365));
            $this->add_cookie('.xbox.com', 'xbox_info', 't=6', '/', time() + (60*60*24*365));
            $this->add_cookie('.xbox.com', 'PersistentId', '0a652e56e40f42caac3ac84fad02ed01', '/', time() + (60*60*24*365));

            // Send the data to Xbox and retrieve the response.
            $url = 'https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=12&ct=' . time() . '&rver=6.2.6289.0&wp=MBI_SSL&wreply=https:%2F%2Faccount.xbox.com:443%2Fpassport%2FsetCookies.ashx%3Frru%3Dhttps%253a%252f%252faccount.xbox.com%252fen-US%252f&lc=1033&id=292543&cbcxt=0';
            $result = $this->fetch_url($url, 'http://www.xbox.com/en-US/');

            $this->stack_trace[] = array(
                'url'      => $url,
                'postdata' => '',
                'result'   => $result
            );

            // More cookies...
            $this->add_cookie('.login.live.com', 'WLOpt', 'act=[1]', time() + (60*60*24*365));
            $this->add_cookie('.login.live.com', 'CkTst', 'G' . time(), '/', time() + (60*60*24*365));

            // Find the right parameters. We need this data for the next request.
            $url  = $this->find($result, 'urlPost:\'', '\',');
            $PPFT = $this->find($result, 'name="PPFT" id="i0327" value="', '"');
            $PPSX = $this->find($result, 'srf_sRBlob=\'', '\';');

            // Send the data back to Xbox and retrieve the response.
            $post_data = 'login=' . $this->email . '&passwd=' . $this->password . '&KMSI=1&mest=0&type=11&LoginOptions=3&PPSX=' . $PPSX . '&PPFT=' . $PPFT . '&idsbho=1&PwdPad=&sso=&i1=1&i2=1&i3=12035&i12=1&i13=1&i14=323&i15=3762&i18=__Login_Strings%7C1%2C__Login_Core%7C1%2C';
            $result = $this->fetch_url($url, 'https://login.live.com/login.srf', null, $post_data);

            $this->stack_trace[] = array(
                'url'       => $url,
                'post_data' => $post_data,
                'result'    => $result
            );

            // MOAR COOKIESSSSSSSS!!!
            $this->add_cookie('.live.com', 'wlidperf', 'throughput=3&latency=961&FR=L&ST=1297790188859', '/', time() + (60*60*24*365));
            $this->add_cookie('login.live.com', 'CkTst', time(), '/ppsecure/', time() + (60*60*24*365));

            $url  = $this->find($result, 'id="fmHF" action="', '"');
            $NAP  = $this->find($result, 'id="NAP" value="', '"');
            $ANON = $this->find($result, 'id="ANON" value="', '"');
            $t    = $this->find($result, 'id="t" value="', '"');

            $this->add_cookie('.xbox.com', 'ANON', $ANON, '/', time() + (60*60*24*365));
            $this->add_cookie('.xbox.com', 'NAP', $NAP, '/', time() + (60*60*24*365));

            // OK, last time we send data to Xbox and retrieve the response.
            $post_data = 'NAPExp=' . date('c', mktime(date('H'), date('i'), date('s'), date('n') + 1)) . '&NAP=' . $NAP . '&ANONExp=' . date('c', mktime(date('H'), date('i'), date('s'), date('n') + 1)) . '&ANON=' . $ANON . '&t=' . $t;
            $result = $this->fetch_url($url, '', 16, $post_data);

            $this->stack_trace[] = array(
                'url'       => $url,
                'post_data' => $post_data,
                'result'    => $result
            );

            $result = $this->fetch_url('https://account.xbox.com/en-US/social');

            // Make sure we got signed in...
            if (stripos($result, '<h3 class="feedSectionTitle">Activity feed</h3>') !== false) {
                $this->logged_in = true;
                return true;
            } else {
                $this->error = 600;
                $this->save_stack_trace();
                return false;
            }
			
        }
    }
100793
def login_user(self, request):
        
        # only actavted users can login if activation required.
        user = auth.authenticate(identity=self.identity, provider=self.provider)
        if user and settings.ACTIVATION_REQUIRED and not user.is_active:
            messages.add_message(request, messages.ERROR, lang.NOT_ACTIVATED)
            return redirect(settings.ACTIVATION_REDIRECT_URL)
        # login
        if user:
            auth.login(request, user)
            return True

        return False
1159144
function (login_id, session, data) {

	// acknowledge as 'logined'	
	l_loginID[login_id] = data.account;
	
	// init session
	session['_account'] = data.account;
	
	// TODO: needs to fix this, should read "groups" from DB
	session['_groups'] = data.groups;
	session['_permissions'] = data.permissions;
	session['lastStatus'] = data.lastStatus;
	
	// TODO: centralize handling of logined users?
	//SR.User.addGroup(user_data.account, ['user', 'admin']);
}
1366653
def connect_login(self):
        
        self.client.connect(self.options['server'], self.options['port'], self.options['username'],
                            self.options['password'])
        self.comm_chan = self.client.invoke_shell()
        time.sleep(1)  # Let the server take some time to get ready.
        while not self.comm_chan.recv_ready():
            time.sleep(0.5)
        login_response = self.comm_chan.recv(2048)
        if not login_response.endswith('$ '):
            raise AuthenticationFailed
        return login_response
406008
def authenticate(self, login, passcode):
        
        return login in self.store and self.store[login] == passcode
113578
public function login()
    {
        $this->defaultData();
        /** @var common_ext_ExtensionsManager $extensionManager */
        $extensionManager = $this->getServiceLocator()->get(common_ext_ExtensionsManager::SERVICE_ID);
        $extension = $extensionManager->getExtensionById('tao');
        $config = $extension->getConfig('login');

        $disableAutoComplete = !empty($config['disableAutocomplete']);
        $enablePasswordReveal = !empty($config['enablePasswordReveal']);

        $enableIframeProtection = !empty($config['block_iframe_usage']) && $config['block_iframe_usage'];
        if ($enableIframeProtection) {
            \oat\tao\model\security\IFrameBlocker::setHeader();
        }

        $params = array(
            'disableAutocomplete' => $disableAutoComplete,
            'enablePasswordReveal' => $enablePasswordReveal,
        );

        if ($this->hasRequestParameter('redirect')) {
            $redirectUrl = $_REQUEST['redirect'];

            if (substr($redirectUrl, 0,1) == '/' || substr($redirectUrl, 0, strlen(ROOT_URL)) == ROOT_URL) {
                $params['redirect'] = $redirectUrl;
            }
        }

        $container = new tao_actions_form_Login($params);
        $form = $container->getForm();

        if ($form->isSubmited()) {
            if ($form->isValid()) {

                /** @var UserLocks $userLocksService */
                $userLocksService = $this->getServiceLocator()->get(UserLocks::SERVICE_ID);
                /** @var EventManager $eventManager */
                $eventManager = $this->getServiceLocator()->get(EventManager::SERVICE_ID);

                try {
                    if ($userLocksService->isLocked($form->getValue('login'))) {
                        $this->logInfo("User '" . $form->getValue('login') . "' has been locked.");

                        $statusDetails = $userLocksService->getStatusDetails($form->getValue('login'));
                        if ($statusDetails['auto']) {
                            $msg = __('You have been locked due to too many failed login attempts. ');
                            if ($userLocksService->getOption(UserLocks::OPTION_USE_HARD_LOCKOUT)) {
                                $msg .= __('Please contact your administrator.');
                            } else {
                                /** @var DateInterval $remaining */
                                $remaining = $statusDetails['remaining'];

                                $reference = new DateTimeImmutable;
                                $endTime = $reference->add($remaining);

                                $diffInSeconds = $endTime->getTimestamp() - $reference->getTimestamp();

                                $msg .= __('Please try in %s.',
                                    $diffInSeconds > 60
                                        ? tao_helpers_Date::displayInterval($statusDetails['remaining'], tao_helpers_Date::FORMAT_INTERVAL_LONG)
                                        : $diffInSeconds . ' ' . ($diffInSeconds == 1 ? __('second') : __('seconds'))
                                );
                            }
                        } else {
                            $msg = __('Your account has been locked, please contact your administrator.');
                        }

                        $this->setData('errorMessage', $msg);
                    } else {
                        if (LoginService::login($form->getValue('login'), $form->getValue('password'))) {
                            $logins = $this->getSession()->getUser()->getPropertyValues(UserRdf::PROPERTY_LOGIN);

                            $eventManager->trigger(new LoginSucceedEvent(current($logins)));

                            $this->logInfo("Successful login of user '" . $form->getValue('login') . "'.");

                            if ($this->hasRequestParameter('redirect') && tao_models_classes_accessControl_AclProxy::hasAccessUrl($_REQUEST['redirect'])) {
                                $this->redirect($_REQUEST['redirect']);
                            } else {
                                $this->forward('entry');
                            }
                        } else {
                            $eventManager->trigger(new LoginFailedEvent($form->getValue('login')));

                            $this->logInfo("Unsuccessful login of user '" . $form->getValue('login') . "'.");

                            $msg = __('Invalid login or password. Please try again.');

                            if ($userLocksService->getOption(UserLocks::OPTION_USE_HARD_LOCKOUT)) {
                                $remainingAttempts = $userLocksService->getLockoutRemainingAttempts($form->getValue('login'));
                                if ($remainingAttempts !== false) {
                                    if ($remainingAttempts === 0) {
                                        $msg = __('Invalid login or password. Your account has been locked, please contact your administrator.');
                                    } else {
                                        $msg = $msg . ' ' .
                                            ($remainingAttempts === 1
                                                ? __('Last attempt before your account is locked.')
                                                : __('%d attempts left before your account is locked.', $remainingAttempts));
                                    }
                                }
                            }

                            $this->setData('errorMessage', $msg);
                        }
                    }
                } catch (core_kernel_users_Exception $e) {
                    $this->setData('errorMessage', __('Invalid login or password. Please try again.'));
                }
            } else {
                foreach ($form->getElements() as $formElement) {
                    $fieldError = $formElement->getError();
                    if ($fieldError) {
                        $this->setData('fieldMessages_' . $formElement->getName(), $fieldError);
                    }
                }
            }
        }

        $this->setData('title', __("TAO Login"));

        $this->setData('autocompleteDisabled', (int)$disableAutoComplete);
        $this->setData('passwordRevealEnabled', (int)$enablePasswordReveal);

        $entryPointService = $this->getServiceLocator()->get(EntryPointService::SERVICE_ID);
        $this->setData('entryPoints', $entryPointService->getEntryPoints(EntryPointService::OPTION_PRELOGIN));

        if ($this->hasRequestParameter('msg')) {
            $this->setData('msg', $this->getRequestParameter('msg'));
        }

        $this->setData('show_gdpr', !empty($config['show_gdpr']) && $config['show_gdpr']);

        $this->setData('content-template', array('blocks/login.tpl', 'tao'));

        $this->setView('layout.tpl', 'tao');
    }
497005
def _login(self, environ, start_response):
        """"""
        response = HTTPUnauthorized()
        response.www_authenticate = ('Basic', {'realm': self._realm})
        return response(environ, start_response)
1126082
def seamless_login
    login! unless logged_in?
    json = <<-EOF
      {
        "session": "#{@sugar_session_id}"
      }
    EOF
    json.gsub!(/^\s{6}/,'')
    response = send!(:seamless_login, json)
  end
354732
public function login()
    {

        //connect if not connected
        if(!$this->connected){

            $this->reconnect();
        }
        //calc the jid from uname+host
        $this->jid = $this->uname.'@'.substr($this->host, strpos($this->host, '//')+2);

        if($this->pass){

            $this->write("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>" . base64_encode("\x00" . $this->uname . "\x00" . $this->pass) . "</auth>");
        } else {
            $this->write("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='ANONYMOUS' />");
    }

        $buffer = $this->read();
        if(substr($buffer, 0, 5) == '<fail'){
            $this->onError(0, 'Cound not log in');
            return false;

        }

        $this->client_name = empty($this->client_name) ? __CLASS__ : $this->client_name;

        if(!$this->sendClientName()){
            return false;
        }

        $this->setStatus($this->status);

        $this->onAfterLogin();

        return true;

    }
1351262
def login(self):
        
        response = self._request('Login')
        parser = OneXLogin()
        parser.parse(response)

        self.session_id = response.cookies.get(self.session_id_cookie_name, '')

        if parser.headers.get('RETS-Version') is not None:
            self.version = str(parser.headers.get('RETS-Version'))
            self.client.headers['RETS-Version'] = self.version

        for k, v in parser.capabilities.items():
            self.add_capability(k, v)

        if self.capabilities.get('Action'):
            self._request('Action')
        return True
98759
public void login(Object userIdentifier) {
        session().put(config().sessionKeyUsername(), userIdentifier);
        app().eventBus().trigger(new LoginEvent(userIdentifier.toString()));
    }
1040914
def login(self):
        
        auth_data = dict()
        auth_data['apikey'] = self.api_key
        auth_data['username'] = self.username
        auth_data['userkey'] = self.account_identifier

        auth_resp = requests_util.run_request('post', self.API_BASE_URL + '/login', data=json.dumps(auth_data),
                                              headers=self.__get_header())

        if auth_resp.status_code == 200:
            auth_resp_data = self.parse_raw_response(auth_resp)
            self.__token = auth_resp_data['token']
            self.__auth_time = datetime.now()
            self.is_authenticated = True
        else:
            raise AuthenticationFailedException('Authentication failed!')
1107931
def login(self):
        """"""
        if self.__logged_in:
            return
        login = {'userId': self.__username, 'userPassword': self.__password}
        header = BASE_HEADERS.copy()
        request = requests.post(BASE_URL + 'login',
                                data=login,
                                headers=header,
                                timeout=10)

        try:
            result = request.json()
        except ValueError as error:
            raise Exception(
                "Not a valid result for login, " +
                "protocol error: " + request.status_code + ' - ' +
                request.reason + "(" + str(error) + ")")

        if 'error' in result.keys():
            raise Exception("Could not login: " + result['error'])

        if request.status_code != 200:
            raise Exception(
                "Could not login, HTTP code: " +
                str(request.status_code) + ' - ' + request.reason)

        if 'success' not in result.keys() or not result['success']:
            raise Exception("Could not login, no success")

        cookie = request.headers.get("set-cookie")
        if cookie is None:
            raise Exception("Could not login, no cookie set")

        self.__cookie = cookie
        self.__logged_in = True
        return self.__logged_in