Asyncronously attempt to log into user account
@param loginCreds Credentials used to login.
@return Response of the operation
339224
public Observable<BackendUser> loginASync(final LoginCredentials loginCreds){
        logger.debug("loginASync("+loginCreds+")");
        try{
            setLoginState(LOGGING_IN);

            return getWebService().getPublicKeyA().flatMap(new Func1<byte[], Observable<LoginCredentials>>() {
                @Override
                public Observable<LoginCredentials> call(byte[] bytes) {
                    try {
                        if (!loginCreds.isEncrypted()) {
                            PublicKey key = Crypto.pubKeyFromBytes(bytes);
                            loginCreds.encryptPassword(key);
                        }
                        return Observable.from(loginCreds);
                    } catch (Exception e) {
                        return Observable.error(e);
                    }
                }
            }).flatMap(new Func1<LoginCredentials, Observable<ValidCredentials>>() {
                @Override
                public Observable<ValidCredentials> call(LoginCredentials credentials) {
                    return getWebService().loginA(credentials);
                }
            }).map(new Func1<ValidCredentials, BackendUser>() {
                @Override
                public BackendUser call(ValidCredentials validCredentials) {
                    return setUser(validCredentials);
                }
            })
              .subscribeOn(Schedulers.io()).observeOn(config.observeOn());

        }catch (Exception e){
            logger.error("Failed to SignIn("+loginCreds.getEmailAddress()+")",e);
            setLoginState(LOGGED_OUT);
            return Observable.error(e);
        }
    }
616834
@NoAuth
    @RequestMapping(value = "/signin", method = RequestMethod.POST)
    @ResponseBody
    public JsonObjectBase signin(@Valid SigninForm signin, HttpServletRequest request) {

        LOG.info(signin.toString());

        // 验证
        authValidator.validateLogin(signin);

        // 数据库登录
        User user = signMgr.signin(signin.getName());

        // 过期时间
        int expireTime = LoginConstant.SESSION_EXPIRE_TIME;
        if (signin.getRemember().equals(1)) {
            expireTime = LoginConstant.SESSION_EXPIRE_TIME2;
        }

        // redis login
        redisLogin.login(request, user, expireTime);

        VisitorVo visitorVo = userMgr.getCurVisitor();

        return buildSuccess("visitor", visitorVo);
    }
1254041
function (error, result) {
    // If the login method returns its result but the connection is lost
    // before the data is in the local cache, it'll set an onReconnect (see
    // above). The onReconnect will try to log in using the token, and *it*
    // will call userCallback via its own version of this
    // loggedInAndDataReadyCallback. So we don't have to do anything here.
    if (reconnected)
      return;

    // Note that we need to call this even if _suppressLoggingIn is true,
    // because it could be matching a _setLoggingIn(true) from a
    // half-completed pre-reconnect login method.
    Accounts._setLoggingIn(false);
    if (error || !result) {
      error = error || new Error(
        "No result from call to " + options.methodName);
      onceUserCallback(error);
      return;
    }
    try {
      options.validateResult(result);
    } catch (e) {
      onceUserCallback(e);
      return;
    }

    // Make the client logged in. (The user data should already be loaded!)
    makeClientLoggedIn(result.id, result.token, result.tokenExpires);
    onceUserCallback();
  }
3080
public void login(AuthenticatedUser user) throws AuthenticationException
    {
        if (!user.isAnonymous() && !Auth.isExistingUser(user.getName()))
           throw new AuthenticationException(String.format("User %s doesn't exist - create it with CREATE USER query first",
                                                           user.getName()));
        this.user = user;
    }
390568
public String login(String loginName, String password) throws AuthException{
    String loginResult = null;
    try{
      Debug.logVerbose("[JdonFramework] --> enter login", module);

      TargetMetaDef targetMetaDef = new POJOTargetMetaDef("authenticator",
           "com.jdon.bussinessproxy.remote.auth.Authenticator");

      Authenticator authenticator = (Authenticator) getService(targetMetaDef);
      loginResult = authenticator.login(loginName, password);
    }catch(Exception e){
      throw new AuthException(e);
    }
    return loginResult;

  }
919470
@Override
    public boolean login() throws LoginException {
        try{
            Object[] userPass= getCallBackAuth();
            if (null == userPass || userPass.length < 2) {
                setAuthenticated(false);
                throw new FailedLoginException();
            }
            String name = (String) userPass[0];
            Object pass = userPass[1];
            boolean authenticated = authenticate(name, pass);
            setAuthenticated(authenticated);

            if (!isAuthenticated()) {
                throw new FailedLoginException();
            }
            return isAuthenticated();
        } catch (UnsupportedCallbackException e) {
            throw new LoginException("Error obtaining callback information.");
        } catch (IOException e) {
            if (_debug) {
                e.printStackTrace();
            }
            throw new LoginException("IO Error performing login.");
        }
    }
804115
function doLogin() {
	// Request the login page.
	let res = http.get(baseURL + "/user/login");
	check(res, {
		"title is correct": (res) => res.html("title").text() == "User account | David li commerce-test",
	});

	// TODO: Add attr() to k6/html!
	// Extract hidden input fields.
	let formBuildID = res.body.match('name="form_build_id" value="(.*)"')[1];

	group("login", function() {
		// Pick a random set of credentials.
		let creds = credentials[Math.floor(Math.random()*credentials.length)];

		// Create login request.
		let formdata = {
			name: creds.username,
			pass: creds.password,
			form_build_id: formBuildID,
			form_id: "user_login",
			op: "Log in",
		};
		let headers = { "Content-Type": "application/x-www-form-urlencoded" };
		// Send login request
		let res = http.post(baseURL + "/user/login", formdata, { headers: headers });
		// Verify that we ended up on the user page
		check(res, {
			"login succeeded": (res) => res.url == `${baseURL}/users/${creds.username}`,
		}) || fail("login failed");
	});
}
1328535
public static UserAuthentication checkIfActive(UserAuthentication userAuth, User user, boolean throwException) {
		if (userAuth == null || user == null || user.getIdentifier() == null) {
			if (throwException) {
				throw new BadCredentialsException("Bad credentials.");
			} else {
				logger.debug("Bad credentials. {}", userAuth);
				return null;
			}
		} else if (!user.getActive()) {
			if (throwException) {
				throw new LockedException("Account " + user.getId() + " (" + user.getAppid() + "/" +
						user.getIdentifier() + ") is locked.");
			} else {
				logger.warn("Account {} ({}/{}) is locked.", user.getId(), user.getAppid(), user.getIdentifier());
				return null;
			}
		}
		return userAuth;
	}
341785
@Override
    public HttpResponse loginFailed(ServiceRequestContext ctx, AggregatedHttpMessage req,
                                    @Nullable MessageContext<Response> message, Throwable cause) {
        return HttpResponse.of(HttpStatus.UNAUTHORIZED, MediaType.HTML_UTF_8,
                               "<html><body>Login failed.</body></html>");
    }
366169
public User get(String loginname, String password) {
        Connection conn = null;
        User user = null;
        if (loginname == null || password == null) return null;
        String cryptpassword = MD5.encodeString(password,null);
        try {
            conn = ConnectionUtils.getConnection();
            user = userDAO.get(conn,loginname,cryptpassword);
        } catch(SQLException e) {
            logger.error(e.getMessage());
        } finally {
            DbUtils.closeQuietly(conn);
        }
        return user;
    }
1048536
public User login(Credentials credentials) throws AuthenticationException {
		//if a user wants to log in, we assume he's not surprised if
		//  his session was expired (hence the 'true')
		User user = getSession(true).login(credentials);
		entryPoint.onSessionUpdate(this, session);
		return user;
	}
47845
public Session login() throws RepositoryException {
        assertStateAfterOrEqual(State.CREATED);
        final Session session;
        if (username != null && password != null) {
            session = getRepository().login(new SimpleCredentials(username, password.toCharArray()));
            userSessions.put(username, session);
        } else if (anonSession == null) {
            anonSession = getRepository().login();
            session = anonSession;
        } else {
            session = anonSession;
        }
        return session;
    }
806957
def cr_login(self, response):
        
        self._state_params['auth'] = response['auth']
        self._user_data = response['user']
        if not self.logged_in:
            raise ApiLoginFailure(response)
563576
public base_response perform_operation(nitro_service service)  throws Exception
	{
		if (!service.isLogin() && !get_object_type().equals("login"))
			service.login();
		base_response response = post_request(service, null);
		return response;
	}
410944
public base_response login() throws Exception
	{
		login login = new login(this.user_name, this.password, this.timeout);
		base_response result = login.perform_operation(this);
		if (result.errorcode == 0 || result.errorcode == 1034)
			this.sessionid = result.sessionid;

		return result;
	}
124789
private boolean loginInternal(String nic, String password, int timeInSec) throws IOException {
		// Due to per IP login rate limiting, we synchronize this part of the code.
		// if multiple IP available, it can be sync on public IP based token
		synchronized (ApiOvhCore.class) {
			String oldCK = config.getConsumerKey(nic);
			if (oldCK != null && _consumerKey != null && !oldCK.equals(_consumerKey)) {
				// a new CK is available try it first.
				_consumerKey = oldCK;
				return true;
			}
			OvhCredential token = requestToken(null);
			log.info("Generating a new ConsumerKey as appKey: {} for account {} valid for {} sec, validationUrl:{}",
					this.config.getApplicationKey(), nic, timeInSec, token.validationUrl);

			Document doc = Jsoup.connect(token.validationUrl).get();
			String html = doc.toString();
			if (html.contains("Too much requests"))
				return false;
			// <input type="hidden" name="sT" id="sT" value="XXXXX">
			Element st = doc.getElementById("sT");
			FormElement form = null;
			// get Parent Form
			for (Element elm : st.parents()) {
				// "form".equalsIgnoreCase(elm.tagName())
				if (elm instanceof FormElement) {
					form = (FormElement) elm;
					break;
				}
			}
			Elements inputs = form.select("input");
			Connection validForm = Jsoup.connect(token.validationUrl);
			validForm.followRedirects(false);
			// fill user and password field
			for (Element e : inputs) {
				String name = e.attr("name");
				String value = e.attr("value");
				String type = e.attr("type");
				if ("text".equals(type))
					value = nic;
				else if ("password".equals(type))
					value = password;
				validForm.data(name, value);
			}
			// set Expiration Date
			validForm.data("duration", Integer.toString(timeInSec));
			Document doc2 = validForm.post();
			Elements p = doc2.select("p");
			String pText = p.text();
			if ("The document has moved here.".equals(pText)) {
				log.info("a new consumerKey had been issued for {}", nic);
				this.setCK(nic, token.consumerKey);
				return true;
			}
			if ("Your token is now valid, you can use it in your application".equals(pText)) {
				log.info("a new consumerKey had been issued for {}", nic);
				this.setCK(nic, token.consumerKey);
				return true;
			}
			String error = doc2.select("div.error").text();
			if (error != null && error.length() > 0)
				log.error("Login {} Error:{}", nic, error);
			else {
				String body = doc2.toString();
				if (body.contains("Too much requests. Please retry in 3 seconds. ")) {
					log.error("Too much requests, block all connexion for 3sec, Retry later to connect {}", nic);
					ApiOvhUtils.sleep(3000);
				} else {
					log.error("Unknown Error connecting to {} in body:{}", nic, body);
				}
			}
			return false;
		}
	}
1228611
@Override
    void doLogin(String authUrl, final Callback<TokenInfo, Throwable> callback) {
        if (window != null && window.isOpen()) {
            callback.onFailure(new IllegalStateException("Authentication in progress"));
        } else {
            window = openWindow(authUrl, height, width);
            if (window == null) {
                callback.onFailure(new RuntimeException(
                        "The authentication popup window appears to have been blocked"));
            }
            // Workaround to check if the user has closed the auth window,
            // since neither the onclose and onunload events work the expected way in this scenario
            window.setFinished(false);
            new Timer() {
                @Override
                public void run() {
                    if (window.hasFinished())
                        cancel();
                    if (!window.isOpen()) {
                        window.setFinished(true);
                        callback.onFailure(new RuntimeException("User has closed the authentication window."));
                        cancel();
                    }
                }
            }.scheduleRepeating(300);
        }
    }