normal login handler part //todo: consider using mostly the same code as in proxy part below
430613
@Override
  public boolean loginHandler(String target, HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (! isLoginTarget(target)) {
      return false;
    }

    if (isPageRequest(request)) {
      sendLoginForm(request, response);
    } else {
      ServletUtils.sendResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, "Access denied. Please login.");
    }
    return true;
  }
331923
async def login(
        self, username: str, password: str, timeout: DefaultNumType = _default
    ) -> SMTPResponse:
        
        await self._ehlo_or_helo_if_needed()

        if not self.supports_extension("auth"):
            raise SMTPException("SMTP AUTH extension not supported by server.")

        response = None  # type: Optional[SMTPResponse]
        exception = None  # type: Optional[SMTPAuthenticationError]
        for auth_name in self.supported_auth_methods:
            method_name = "auth_{}".format(auth_name.replace("-", ""))
            try:
                auth_method = getattr(self, method_name)
            except AttributeError:
                raise RuntimeError(
                    "Missing handler for auth method {}".format(auth_name)
                )
            try:
                response = await auth_method(username, password, timeout=timeout)
            except SMTPAuthenticationError as exc:
                exception = exc
            else:
                # No exception means we're good
                break

        if response is None:
            raise exception or SMTPException("No suitable authentication method found.")

        return response
455530
public boolean onLogin()
    {
        SStaticString sfStaticField = null;
        String strUserName = null;
        String strPassword = null;
        for (int i = 0; i < this.getSFieldCount(); i++)
        {
            ScreenField sField = this.getSField(i);
            if (sfStaticField == null)
                if (sField instanceof SStaticString)
                    sfStaticField = (SStaticString)sField;
            if (sField.getConverter() != null)
                if (DBParams.USER_NAME.equalsIgnoreCase(sField.getConverter().getFieldName()))
                    strUserName = sField.getConverter().getField().toString();
            if (sField.getConverter() != null)
                if (DBParams.PASSWORD.equalsIgnoreCase(sField.getConverter().getFieldName()))
                    strPassword = sField.getConverter().getField().toString();
        }
        if (strUserName == null)
            return false;
        
        App application = this.getTask().getApplication();
        int iErrorCode = application.login(this.getTask(), strUserName, strPassword, this.getProperty(DBParams.DOMAIN));
        
        if (iErrorCode == DBConstants.NORMAL_RETURN)
        {
            String strLastCommand = null;
            BasePanel parent = this.getParentScreen();
            int iUseSameWindow = ScreenConstants.USE_SAME_WINDOW | ScreenConstants.PUSH_TO_BROWSER;
            if (parent != null)
            {
                strLastCommand = parent.popHistory(1, false);
                iUseSameWindow = ScreenConstants.USE_SAME_WINDOW | ScreenConstants.DONT_PUSH_TO_BROWSER;
            }
            else
                strLastCommand = this.getScreenURL();
            
            this.handleCommand(strLastCommand, this, iUseSameWindow);     // Process the last command
        }
        else
        {
            String strError = this.getTask().getLastError(iErrorCode);
            if (strError != null)
                if (sfStaticField != null)
                    sfStaticField.setString(strError);
            try {
                Thread.sleep(3000);     // Wait 3 seconds if bad password
            } catch (InterruptedException ex) {
                ex.printStackTrace();   // Never
            }
        }

        return (iErrorCode == DBConstants.NORMAL_RETURN);    // Handled
    }
973423
def _processHandler(self, securityHandler, param_dict):
        """"""
        cj = None
        handler = None
        if securityHandler is None:
            cj = cookiejar.CookieJar()
        elif securityHandler.method.lower() == "token":
            param_dict['token'] = securityHandler.token
            if hasattr(securityHandler, 'cookiejar'):
                cj = securityHandler.cookiejar
            if hasattr(securityHandler, 'handler'):
                handler = securityHandler.handler
        elif securityHandler.method.lower() == "handler":
            handler = securityHandler.handler
            cj = securityHandler.cookiejar
        return param_dict, handler, cj
1355185
protected void initLoginConfig(XmlParser.Node node)
    {
        XmlParser.Node method=node.get("auth-method");
        FormAuthenticator _formAuthenticator=null;
        if(method!=null)
        {
            Authenticator authenticator=null;
            String m=method.toString(false,true);
            if(SecurityConstraint.__FORM_AUTH.equals(m))
                authenticator=_formAuthenticator=new FormAuthenticator();
            else if(SecurityConstraint.__BASIC_AUTH.equals(m))
                authenticator=new BasicAuthenticator();
            else if(SecurityConstraint.__DIGEST_AUTH.equals(m))
                authenticator=new DigestAuthenticator();
            else if(SecurityConstraint.__CERT_AUTH.equals(m))
                authenticator=new ClientCertAuthenticator();
            else if(SecurityConstraint.__CERT_AUTH2.equals(m))
                authenticator=new ClientCertAuthenticator();
            else
                log.warn("UNKNOWN AUTH METHOD: "+m);
            getWebApplicationContext().setAuthenticator(authenticator);
        }
        XmlParser.Node name=node.get("realm-name");
        if(name!=null)
            getWebApplicationContext().setRealmName(name.toString(false,true));
        XmlParser.Node formConfig=node.get("form-login-config");
        if(formConfig!=null)
        {
            if(_formAuthenticator==null)
                log.warn("FORM Authentication miss-configured");
            else
            {
                XmlParser.Node loginPage=formConfig.get("form-login-page");
                if(loginPage!=null)
                    _formAuthenticator.setLoginPage(loginPage.toString(false,true));
                XmlParser.Node errorPage=formConfig.get("form-error-page");
                if(errorPage!=null)
                {
                    String ep=errorPage.toString(false,true);
                    _formAuthenticator.setErrorPage(ep);
                }
            }
        }
    }
1133246
def login_handler(self, config=None, prefix=None, **args):
        """"""
        params = {
            'response_type': 'code',
            'client_id': self.google_api_client_id,
            'redirect_uri': self.scheme_host_port_prefix(
                'http', config.host, config.port, prefix) + '/home',
            'scope': self.google_api_scope,
            'state': self.request_args_get('next', default=''),
        }
        url = self.google_oauth2_url + 'auth?' + urlencode(params)
        return self.login_handler_redirect(url)
740232
def conn_handler(self, session: ClientSession, proxy: str = None) -> ConnectionHandler:
        
        return ConnectionHandler("https", "wss", self.server, self.port, "", session, proxy)
189297
function loginpage_hook() {
        global $CFG, $SESSION;

        // HTTPS is potentially required
        //httpsrequired(); - this must be used before setting the URL, it is already done on the login/index.php

        if (($_SERVER['REQUEST_METHOD'] === 'GET'         // Only on initial GET of loginpage
             || ($_SERVER['REQUEST_METHOD'] === 'POST'
                 && (get_local_referer() != strip_querystring(qualified_me()))))
                                                          // Or when POSTed from another place
                                                          // See MDL-14071
            && !empty($this->config->ntlmsso_enabled)     // SSO enabled
            && !empty($this->config->ntlmsso_subnet)      // have a subnet to test for
            && empty($_GET['authldap_skipntlmsso'])       // haven't failed it yet
            && (isguestuser() || !isloggedin())           // guestuser or not-logged-in users
            && address_in_subnet(getremoteaddr(), $this->config->ntlmsso_subnet)) {

            // First, let's remember where we were trying to get to before we got here
            if (empty($SESSION->wantsurl)) {
                $SESSION->wantsurl = null;
                $referer = get_local_referer(false);
                if ($referer &&
                        $referer != $CFG->wwwroot &&
                        $referer != $CFG->wwwroot . '/' &&
                        $referer != $CFG->wwwroot . '/login/' &&
                        $referer != $CFG->wwwroot . '/login/index.php') {
                    $SESSION->wantsurl = $referer;
                }
            }

            // Now start the whole NTLM machinery.
            if($this->config->ntlmsso_ie_fastpath == AUTH_NTLM_FASTPATH_YESATTEMPT ||
                $this->config->ntlmsso_ie_fastpath == AUTH_NTLM_FASTPATH_YESFORM) {
                if (core_useragent::is_ie()) {
                    $sesskey = sesskey();
                    redirect($CFG->wwwroot.'/auth/ldap/ntlmsso_magic.php?sesskey='.$sesskey);
                } else if ($this->config->ntlmsso_ie_fastpath == AUTH_NTLM_FASTPATH_YESFORM) {
                    redirect($CFG->wwwroot.'/login/index.php?authldap_skipntlmsso=1');
                }
            }
            redirect($CFG->wwwroot.'/auth/ldap/ntlmsso_attempt.php');
        }

        // No NTLM SSO, Use the normal login page instead.

        // If $SESSION->wantsurl is empty and we have a 'Referer:' header, the login
        // page insists on redirecting us to that page after user validation. If
        // we clicked on the redirect link at the ntlmsso_finish.php page (instead
        // of waiting for the redirection to happen) then we have a 'Referer:' header
        // we don't want to use at all. As we can't get rid of it, just point
        // $SESSION->wantsurl to $CFG->wwwroot (after all, we came from there).
        if (empty($SESSION->wantsurl)
            && (get_local_referer() == $CFG->wwwroot.'/auth/ldap/ntlmsso_finish.php')) {

            $SESSION->wantsurl = $CFG->wwwroot;
        }
    }
230931
def init(base_url, username=None, password=None, verify=True):
    """"""
    handler = RequestHandler(base_url, username, password, verify)
    set_default_request_handler(handler)
    return handler
761697
async def login(
        host: str,
        password: str,
        websession: ClientSession,
        *,
        port: int = 8080,
        ssl: bool = True,
        request_timeout: int = DEFAULT_TIMEOUT) -> Controller:
    """"""
    print('regenmaschine.client.login() is deprecated; see documentation!')
    client = Client(websession, request_timeout)
    await client.load_local(host, password, port, ssl)
    return next(iter(client.controllers.values()))
675902
def get_session(session, baseurl, config):
    
    # Read proxy for firefox
    if environ.get("HTTP_PROXY"):
        myProxy = environ.get("HTTP_PROXY")
        proxy = Proxy({
            'proxyType': ProxyType.MANUAL,
            'httpProxy': myProxy,
            'ftpProxy': myProxy,
            'sslProxy': myProxy,
            'noProxy': ''  # set this value as desired
        })
    else:
        proxy = None

    if 'login' in config['DEFAULT']:
        login, password = credentials(config['DEFAULT']['login'])
    else:
        login, password = credentials()

    browser = webdriver.Firefox(proxy=proxy)
    browser.get(baseurl)
    browser.find_element_by_name('login').send_keys(login)
    browser.find_element_by_name('passwd').send_keys(password)

    cookie = {'PHPSESSID': browser.get_cookie('PHPSESSID')['value']}
    prof_session.cookies = requests.utils.cookiejar_from_dict(cookie)
    print("Please log using firefox")
    while True:
        try:
            browser.find_element_by_css_selector("select")
            break
        except:
            sleep(0.5)
    browser.close()
    set_sessid(cookie['PHPSESSID'])
    if not verify_session(session, baseurl):
        print("Cannot get a valid session, retry")
        get_session(session, baseurl, {'DEFAULT': {}})
83837
private void loginUser(final String userId, final String password, final BooleanCallback callback) {
		LoginRequest request = new LoginRequest();
		request.setLogin(userId);
		request.setPassword(password);
		GwtCommand command = new GwtCommand(loginCommandName);
		command.setCommandRequest(request);
		GwtCommandDispatcher.getInstance().execute(command, new AbstractCommandCallback<LoginResponse>() {

			public void execute(LoginResponse loginResponse) {
				if (loginResponse.getToken() == null) {
					if (callback != null) {
						callback.execute(false);
					}
					manager.fireEvent(new LoginFailureEvent(loginResponse.getErrorMessages()));
				} else {
					userToken = loginResponse.getToken();
					Authentication.this.userId = userId;
					UserDetail userDetail = GwtCommandDispatcher.getInstance().getUserDetail();
					userDetail.setUserId(loginResponse.getUserId());
					userDetail.setUserName(loginResponse.getUserName());
					userDetail.setUserOrganization(loginResponse.getUserOrganization());
					userDetail.setUserDivision(loginResponse.getUserDivision());
					userDetail.setUserLocale(loginResponse.getUserLocale());
					if (callback != null) {
						callback.execute(true);
					}
					manager.fireEvent(new LoginSuccessEvent(userToken));
				}
			}
		});
	}
145712
def _processHandler(self, securityHandler, param_dict):
        """"""
        cj = None
        handler = None
        if securityHandler is None:
            cj = cookiejar.CookieJar()
        elif securityHandler.method.lower() == "token" or \
             securityHandler.method.lower() == "oauth":
            param_dict['token'] = securityHandler.token
            if hasattr(securityHandler, 'cookiejar'):
                cj = securityHandler.cookiejar
            if hasattr(securityHandler, 'handler'):
                handler = securityHandler.handler
        elif securityHandler.method.lower() == "handler":
            handler = securityHandler.handler
            cj = securityHandler.cookiejar
        if len(param_dict) > 0:
            for k,v in param_dict.items():
                if isinstance(v, bool):
                    param_dict[k] = json.dumps(v)
        return param_dict, handler, cj
776642
private void doFormLogin(FormAuthInfo authInfo) {
        logger.info("FORM authentication for: {}", authInfo.getLoginTarget());
        String fullUri =
                authInfo.getProtocol() + "://" + authInfo.getHost() + ":" + authInfo.getPort() +
                        authInfo.getLoginTarget();
        HttpPost httpPost = new HttpPost(fullUri);
        List<NameValuePair> formParams = new ArrayList<>();
        formParams.add(
                new BasicNameValuePair(authInfo.getUsernameFormStr(), authInfo.getUsername()));
        formParams.add(
                new BasicNameValuePair(authInfo.getPasswordFormStr(), authInfo.getPassword()));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8);
        httpPost.setEntity(entity);

        try {
            httpClient.execute(httpPost);
            logger.debug("Successfully request to login in with user: {} to: {}", authInfo.getUsername(),
                    authInfo.getHost());
        } catch (ClientProtocolException e) {
            logger.error("While trying to login to: {} - Client protocol not supported",
                    authInfo.getHost(), e);
        } catch (IOException e) {
            logger.error("While trying to login to: {} - Error making request", authInfo.getHost(),
                    e);
        }
    }
1316046
@Override
    public ProxyHandler createProxyHandler() {
        final HttpProxyHandler handler;

        // For reasons that are not immediately clear, HttpProxyHandler doesn't allow null usernames/passwords if
        // specified. If we want them to be null, we have to use the constructor that doesn't take a username/password
        // at all.
        if (this.username != null && this.password != null) {
            handler = new HttpProxyHandler(this.proxyAddress, this.username, this.password);
        } else {
            handler = new HttpProxyHandler(this.proxyAddress);
        }

        return handler;
    }
352243
function trustableAuthHandler(//{{{
    authHandler,
    pathSpec,
    ext,
    method,
    ac,
    req,
    actualRes,
    actualNext
) {

    // Provide fake http environment:
    var httpDone = false;
    var res = Object.create(actualRes);
    res.send = function newSend(){
        actualRes.send.apply(actualRes, arguments);
        httpDone = true;
    };
    function next(){
        actualNext.apply(this, arguments);
        httpDone = true;
    };

    // Call actual authentication handler:
    var auth = authHandler(
        pathSpec,
        ext,
        method,
        ac,
        req,
        res,
        next
    );

    // Ensure http handshake is fully handled:
    if (! httpDone && typeof auth != "object") {
        var msg = (typeof auth == "string")
            ? auth
            : "Access denied."
        ;
        Util.sendStatusMessage(actualRes, "forbidden", msg);
        httpDone = true;
    };
    if (httpDone) auth = false; // Any response handling in authHandler is also an access reject.


    // Ensure consistent auth interface.
    if (auth) {
        auth.filter || (auth.filter = defaultResponse.filter);
        auth.userData || (auth.userData = defaultResponse.userData);
        auth.privileges || (auth.privileges = defaultResponse.privileges);
        if (
            (typeof auth.filter != "function")
            || (typeof auth.userData != "object")
            || (typeof auth.privileges != "function")
        ) {
            console.error("Wrong auth object", auth);
            Util.sendStatusMessage(actualRes, "error", "Internal Server Error");
                // With httpDone = true we were never got here ;-)
        };
    };

    // Return trusted auth data.
    return auth;

}
681767
def do_login():
    

    dt_filter = lambda x: x >= datetime.utcnow() - timedelta(seconds=60)
    app.config['AUTH_ATTEMPTS'] = filter(dt_filter, app.config['AUTH_ATTEMPTS'])

    if len(app.config['AUTH_ATTEMPTS']) > app.config['AUTH_RATE_LIMIT']:
        return redirect(url_for('login',
                                alert="Rate limit exceeded. Try again in 60 seconds."))

    if request.form.get('password') == app.config['APP_PASSWORD']:
        login_user(SingleAuthUser)
        return redirect('/')

    app.config['AUTH_ATTEMPTS'].append(datetime.utcnow())
    return redirect(url_for('login', alert="Incorrect password."))