Makes sure there is a UserLogin on a session; designed to be called by code unrelated to the regular login logic (the
TemplateExceptionRenderer) to make sure there's at least an anonymous login session set up for that templater

@param session

@return
17735
public UserLogin ensureLoginOnSession(HttpSession session)
	{
		if (session.getAttribute(LOGIN_SESSION_ATTRIBUTE) == null)
			// Fall back on the anonymous user
			// Save in the "login" session attribute
			session.setAttribute(LOGIN_SESSION_ATTRIBUTE, new UserLoginImpl(null));

		return (UserLogin) session.getAttribute(LOGIN_SESSION_ATTRIBUTE);
	}
1039253
@Remoted
    public IPromise<Object[]> login(String user, String pw, String jwt) {
        Promise res = new Promise();
        ConnectionRegistry remoteConnection = connection.get();
        getCredentials(user,pw,jwt).then( (authres, err) -> {
            if ( err != null ) {
                res.reject(err);
            } else {
                String sessionId = remoteConnection != null ? remoteConnection.getSocketRef().getConnectionIdentifier() : null;
                getSession(user,sessionId, authres ).then( (sess,serr) -> {
                    if ( sess != null ) {
                        if ( sessionId != null && sessionStorage != null ) {
                            sessionStorage.putUserAtSessionId(sessionId,user);
                        }
                        res.resolve(new Object[]{sess,authres});
                    } else
                        res.complete(sess,serr);
                });
            }
        });
        return res;
    }
105441
def login_view(request):
    '''  '''
    ANONYMOUS_SESSION = request.session.get('ANONYMOUS_SESSION', False)
    page_name = "Login Page"
    redirect_to = request.GET.get('next', reverse('homepage'))
    if (request.user.is_authenticated() and not ANONYMOUS_SESSION) or (ANONYMOUS_SESSION and request.user.username != ANONYMOUS_USERNAME):
        return HttpResponseRedirect(redirect_to)
    form = LoginForm(request.POST or None)
    if form.is_valid():
        user = form.save()
        login(request, user)
        if ANONYMOUS_SESSION:
            request.session['ANONYMOUS_SESSION'] = True
        return HttpResponseRedirect(redirect_to)
    elif request.method == "POST":
        reset_url = request.build_absolute_uri(reverse('reset_pw'))
        messages.add_message(request, messages.INFO,
                             MESSAGES['RESET_MESSAGE'].format(reset_url=reset_url))

    return render_to_response('login.html', {
        'page_name': page_name,
        'form': form,
        'oauth_providers': _get_oauth_providers(),
        'redirect_to': redirect_to,
        }, context_instance=RequestContext(request))
507851
@Override
    public OptionalThing<USER_BEAN> getSavedUserBean() { // use covariant generic type
        final String key = getUserBeanKey();
        return OptionalThing.ofNullable(sessionManager.getAttribute(key, getUserBeanType()).orElse(null), () -> {
            throwLoginRequiredException("Not found the user in session by the key:" + key); // to login action
        });
    }
288516
@Override
    public IUserInstance getUserInstance(HttpServletRequest request) throws PortalException {
        try {
            request = this.portalRequestUtils.getOriginalPortalRequest(request);
        } catch (IllegalArgumentException iae) {
            // ignore, just means that this isn't a wrapped request
        }

        // Use request attributes first for the fastest possible retrieval
        IUserInstance userInstance = (IUserInstance) request.getAttribute(KEY);
        if (userInstance != null) {
            return userInstance;
        }

        final IPerson person;
        try {
            // Retrieve the person object that is associated with the request
            person = this.personManager.getPerson(request);
        } catch (Exception e) {
            logger.error("Exception while retrieving IPerson!", e);
            throw new PortalSecurityException("Could not retrieve IPerson", e);
        }

        if (person == null) {
            throw new PortalSecurityException(
                    "PersonManager returned null person for this request.  With no user, there's no UserInstance.  Is PersonManager misconfigured?  RDBMS access misconfigured?");
        }

        final HttpSession session = request.getSession();
        if (session == null) {
            throw new IllegalStateException(
                    "HttpServletRequest.getSession() returned a null session for request: "
                            + request);
        }

        // Return the UserInstance object if it's in the session
        UserInstanceHolder userInstanceHolder = getUserInstanceHolder(session);
        if (userInstanceHolder != null) {
            userInstance = userInstanceHolder.getUserInstance();

            if (userInstance != null) {
                return userInstance;
            }
        }

        // Create either a UserInstance or a GuestUserInstance
        final LocaleManager localeManager = this.getLocaleManager(request, person);
        final String userAgent = this.getUserAgent(request);
        final IUserProfile userProfile =
                this.getUserProfile(request, person, localeManager, userAgent);

        // Create the user layout manager and user instance object
        IUserLayoutManager userLayoutManager =
                userLayoutManagerFactory.getUserLayoutManager(person, userProfile);

        final UserPreferencesManager userPreferencesManager =
                new UserPreferencesManager(person, userProfile, userLayoutManager);
        userInstance = new UserInstance(person, userPreferencesManager, localeManager);

        // Ensure the newly created UserInstance is cached in the session
        if (userInstanceHolder == null) {
            userInstanceHolder = new UserInstanceHolder();
        }
        userInstanceHolder.setUserInstance(userInstance);
        session.setAttribute(KEY, userInstanceHolder);
        request.setAttribute(KEY, userInstance);

        // Return the new UserInstance
        return userInstance;
    }
1197142
public T authentication(String username, String password, boolean allowAnyHost) {
        if (StringUtils.isNotBlank(username)) {
            if (defaultHost == null || StringUtils.isBlank(defaultHost.getHostName())) {
                throw new IllegalStateException("Cannot configure authentication when host is not set.");
            }
            AuthScope authscope = allowAnyHost ?
                    new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM) :
                    new AuthScope(defaultHost.getHostName(), AuthScope.ANY_PORT, AuthScope.ANY_REALM);
            credsProvider.setCredentials(authscope, new UsernamePasswordCredentials(username, password));
        }
        return self();
    }
1293576
public function findFromSession(Session $session)
    {
        $this->addWhere('user_email', $session->get('email'));
        $this->addWhere('user_id',    (int) $session->get('id'));
        $this->addWhere('user_is_activated', 1);

        try {
            $user = $this->selectOne();
        } catch (ExceptionNoData $exception) {
            throw new LoginException('Login and / or password is incorrect!', 1000, $exception);
        }

        return $user;
    }
242156
public Session getSysSession(String schema, User user) {

        sysSession.currentSchema =
            sysSession.database.schemaManager.getSchemaHsqlName(schema);
        sysSession.isProcessingScript = false;
        sysSession.isProcessingLog    = false;

        sysSession.setUser(user);

        return sysSession;
    }
619967
public static Object getUser()
    {
        HttpSession session = WebContextFactory.get().getSession(true);
        return session.getAttribute(USER);
    }
290317
public String auth_getSession(String authToken)
    throws FacebookException, IOException {
    if (null != this._sessionKey) {
      return this._sessionKey;
    }
    JSONObject d = (JSONObject) this.callMethod(FacebookMethod.AUTH_GET_SESSION, 
                                                new Pair<String, CharSequence>("auth_token", authToken.toString()));
    this._sessionKey = (String) d.get("session_key");
    Object uid = d.get("uid");
    try {
      this._userId = ((Long) uid).intValue();
    } catch (ClassCastException cce) {
      this._userId = Integer.parseInt((String) uid);
    } 
    if (this.isDesktop()) {
      this._sessionSecret = (String) d.get("secret");
    }
    return this._sessionKey;
  }
265108
@SuppressWarnings("unchecked")
	public void sessionCreated(HttpSessionEvent se) {
		Descriptor<? extends Context> descriptor = container.contexts().get(Session.class);
		
		if (descriptor != null) {
			WebContext<HttpSession> context = (WebContext<HttpSession>) container.component(descriptor);
			context.associate(se.getSession());
		}
	}
390319
@Override
  public SessionHandle openSessionWithImpersonation(String username, String password, Map<String, String> configuration,
      String delegationToken) throws HiveSQLException {
    SessionHandle sessionHandle = sessionManager.openSession(SERVER_VERSION, username, password, null, configuration,
        true, delegationToken);
    LOG.debug(sessionHandle + ": openSession()");
    return sessionHandle;
  }
835270
public void sessionCreated(ISession session) {
        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, "sessionCreated", "sessionObservers.size()=" + _sessionObservers.size());
        }
        if (_sessionObservers == null || _sessionObservers.size() < 1) {
            return;
        }
        ISessionObserver sessionObserver = null;
        for (int i = 0; i < _sessionObservers.size(); i++) {
            sessionObserver = (ISessionObserver) _sessionObservers.get(i);
            sessionObserver.sessionCreated(session);
        }
    }
1179348
private Session getSession(boolean isSingleton) {
		final MailAccount mailAccount = this.mailAccount;
		Authenticator authenticator = null;
		if (mailAccount.isAuth()) {
			authenticator = new UserPassAuthenticator(mailAccount.getUser(), mailAccount.getPass());
		}

		return isSingleton ? Session.getDefaultInstance(mailAccount.getSmtpProps(), authenticator) //
				: Session.getInstance(mailAccount.getSmtpProps(), authenticator);
	}
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;
    }
1154438
private String isLoggedIn() throws RuntimeException {
        if(this.getUser() != null && this.getUser().getAuthToken() != null){
            return "CUSTOM " + this.getUser().getAuthToken();
        } else {
            throw new RuntimeException("User state error.");
        }
    }
195334
protected Session createSession(Connection connection) throws JMSException {
        if (connection instanceof QueueConnection) {
            return ((QueueConnection) connection).createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        }
        return connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    }