If the proxy user name is provided then check privileges to substitute the user.
@param realUser
@param sessionConf
@param ipAddress
@return
@throws HiveSQLException
199419
private String getProxyUser(String realUser, Map<String, String> sessionConf,
      String ipAddress) throws HiveSQLException {
    String proxyUser = null;
    // Http transport mode.
    // We set the thread local proxy username, in ThriftHttpServlet.
    if (cliService.getHiveConf().getVar(
        ConfVars.HIVE_SERVER2_TRANSPORT_MODE).equalsIgnoreCase("http")) {
      proxyUser = SessionManager.getProxyUserName();
      LOG.debug("Proxy user from query string: " + proxyUser);
    }

    if (proxyUser == null && sessionConf != null && sessionConf.containsKey(HiveAuthFactory.HS2_PROXY_USER)) {
      String proxyUserFromThriftBody = sessionConf.get(HiveAuthFactory.HS2_PROXY_USER);
      LOG.debug("Proxy user from thrift body: " + proxyUserFromThriftBody);
      proxyUser = proxyUserFromThriftBody;
    }

    if (proxyUser == null) {
      return realUser;
    }

    // check whether substitution is allowed
    if (!hiveConf.getBoolVar(HiveConf.ConfVars.HIVE_SERVER2_ALLOW_USER_SUBSTITUTION)) {
      throw new HiveSQLException("Proxy user substitution is not allowed");
    }

    // If there's no authentication, then directly substitute the user
    if (HiveAuthFactory.AuthTypes.NONE.toString()
        .equalsIgnoreCase(hiveConf.getVar(ConfVars.HIVE_SERVER2_AUTHENTICATION))) {
      return proxyUser;
    }

    // Verify proxy user privilege of the realUser for the proxyUser
    HiveAuthFactory.verifyProxyAccess(realUser, proxyUser, ipAddress, hiveConf);
    LOG.debug("Verified proxy user: " + proxyUser);
    return proxyUser;
  }
1265079
public User get( Connection conn, int id) throws SQLException {
        ResultSetHandler<User> h = new BeanHandler<User>(User.class);
        String sql =
            "SELECT id,username,fullname,type,emailaddress,registered_ts,invited_by,enabled \n"+
            "FROM userbase \n"+
            "WHERE id=?";
        return run.query(conn, sql, h, id);
    }
1297695
function ProxyGuest ( options ) {
	// prepare
	var name;

	// connection with server
	this.active = false;

	/**
	 * proxy instance configuration
	 * @namespace
	 */
	this.config = {
		// node.js server address
		host: '127.0.0.1',

		// http server port
		port: 8800,

		// session name
		name: 'anonymous',

		// cached url for posting requests
		urlPost: '',

		// cached url for info collecting
		urlInfo: ''
	};

	// single ajax object for performance
	this.xhr = new XMLHttpRequest();

	// validate and iterate input
	if ( options && typeof options === 'object' ) {
		for ( name in options ) {
			// rewrite defaults
			if ( options.hasOwnProperty(name) ) {
				this.config[name] = options[name];
			}
		}
	}

	// there may be some special chars
	name = encodeURIComponent(this.config.name);

	// cache final request urls
	this.config.urlPost = 'http://' + this.config.host + ':' + this.config.port + '/' + name;
	this.config.urlInfo = 'http://' + this.config.host + ':' + this.config.port + '/info/' + name;

	// check initial connection status
	this.active = this.info().active;

	console.log('%c[core]\t%c%s\t%c0\t%cconnection to the host %c(%s:%s): %c%s',
		'color:grey',
		'color:purple', this.config.name,
		'color:grey',
		'color:black',
		'color:grey', this.config.host, this.config.port,
		'color:' + (this.active ? 'green' : 'red'), this.active ? 'available' : 'not available'
	);
}
1310219
private boolean isRedirectHostTheSameAsLocalHost(String exitPage, String logoutURLhost, String hostFullName, String shortName, String ipAddress) {
        String localHostIpAddress = "127.0.0.1";
        boolean acceptURL = false;
        if (logoutURLhost.equalsIgnoreCase("localhost") || logoutURLhost.equals(localHostIpAddress) ||
            (hostFullName != null && logoutURLhost.equalsIgnoreCase(hostFullName)) ||
            (shortName != null && logoutURLhost.equalsIgnoreCase(shortName)) ||
            (ipAddress != null && logoutURLhost.equals(ipAddress))) {

            acceptURL = true;
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, "exitPage points to this host: all ok");
        }
        return acceptURL;
    }
6272
private String getUserFromToken(HiveAuthFactory authFactory, String tokenStr) throws HiveSQLException {
    return authFactory.getUserFromToken(tokenStr);
  }
214466
@SuppressWarnings("unchecked")
	public <S extends IPAddressPartConfiguredString<T, P>> SQLStringMatcher<T, P, S> getNetworkStringMatcher(boolean isEntireAddress, IPAddressSQLTranslator translator) {
		return new SQLStringMatcher<T, P, S>((S) this, isEntireAddress, translator);
	}
1220476
public void sessionUserNameSet(ISession session, String oldUserName, String newUserName) {
        // ArrayList sessionStateObservers = null;

        /*
         * Check to see if there is a non-empty list of sessionStateObservers.
         */
        if (_sessionStateObservers == null || _sessionStateObservers.size() < 1) {
            return;
        }

        // synchronized(_sessionStateObservers) {
        // sessionStateObservers = (ArrayList)_sessionStateObservers.clone();
        // }

        ISessionStateObserver sessionStateObserver = null;
        for (int i = 0; i < _sessionStateObservers.size(); i++) {
            sessionStateObserver = (ISessionStateObserver) _sessionStateObservers.get(i);
            sessionStateObserver.sessionUserNameSet(session, oldUserName, newUserName);
        }
    }
337839
private static URLConnection getConnection(String url, final ProxyConfig proxy) throws IOException {
        URLConnection conn = null;

        if (proxy != null && proxy.getProxyUser() != null) {
            Authenticator.setDefault(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(proxy.getProxyUser(), proxy.getProxyPassword().toCharArray());
                }

            });
        }

        if (proxy != null) {
            Proxy thisProxy = new Proxy(proxy.getProxyType(), new InetSocketAddress(proxy.getProxyHost(), proxy.getProxyPort()));
            conn = new URL(url).openConnection(thisProxy);
        } else {
            conn = new URL(url).openConnection();
        }

        return conn;
    }
1215807
public static void loginFromKeytab(HiveConf hiveConf) throws IOException {
    String principal = hiveConf.getVar(ConfVars.HIVE_SERVER2_KERBEROS_PRINCIPAL);
    String keyTabFile = hiveConf.getVar(ConfVars.HIVE_SERVER2_KERBEROS_KEYTAB);
    if (principal.isEmpty() || keyTabFile.isEmpty()) {
      throw new IOException("HiveServer2 Kerberos principal or keytab is not correctly configured");
    } else {
      UserGroupInformation.loginUserFromKeytab(SecurityUtil.getServerPrincipal(principal, "0.0.0.0"), keyTabFile);
    }
  }
942602
public void sessionUserNameSet(ISession session, String oldUserName, String newUserName) {
        _sessionStateEventDispatcher.sessionUserNameSet(session, oldUserName, newUserName);

    }
393769
public N1qlQueryResult query(final String usernameAttribute, final String usernameValue) throws GeneralSecurityException {
        val theBucket = getBucket();
        val statement = Select.select("*")
            .from(Expression.i(theBucket.name()))
            .where(Expression.x(usernameAttribute).eq('\'' + usernameValue + '\''));

        LOGGER.debug("Running query [{}] on bucket [{}]", statement.toString(), theBucket.name());

        val query = N1qlQuery.simple(statement);
        val result = theBucket.query(query, timeout, TimeUnit.MILLISECONDS);
        if (!result.finalSuccess()) {
            LOGGER.error("Couchbase query failed with [{}]", result.errors()
                .stream()
                .map(JsonObject::toString)
                .collect(Collectors.joining(",")));
            throw new GeneralSecurityException("Could not locate account for user " + usernameValue);
        }
        return result;
    }
329678
@Builder(builderClassName = "ProxiedFileSystemFromToken", builderMethodName = "fromToken")
  private static FileSystem getProxiedFileSystemUsingToken(@NonNull String userNameToProxyAs, Token<?> userNameToken,
      URI fsURI, Configuration conf, FileSystem referenceFS) throws IOException, ExecutionException {
    Preconditions.checkNotNull(userNameToProxyAs, "Must provide a user name to proxy as.");
    Preconditions.checkNotNull(userNameToken, "Must provide token for user to proxy.");
    URI actualURI = resolveUri(fsURI, conf, referenceFS);
    Configuration actualConfiguration = resolveConfiguration(conf, referenceFS);

    return USER_NAME_TO_FILESYSTEM_CACHE.get(getFileSystemKey(actualURI, userNameToProxyAs, referenceFS),
        new CreateProxiedFileSystemFromToken(userNameToProxyAs, userNameToken, actualURI, actualConfiguration,
            referenceFS));
  }
1051867
public void setProxy(String proxyHost, int proxyPort, String username, String password) {
        setProxy(proxyHost, proxyPort);
        proxyAuth = true;
        proxyUser = username;
        proxyPassword = password;
    }
392005
protected <T> T createProxy(Class<T> interfaceClass, Session session) throws Exception {
        return configBean.getConfig().getStoredProcedureProxyFactory().getProxy(interfaceClass, session);
    }
744635
@SuppressWarnings("unchecked")
    @Override
    public String execute() {
        User sfsUser = CommandUtil.getSfsUser(username, api);
        return (sfsUser == null) ? "" : sfsUser.getIpAddress();
    }
858601
@Override
  public void set(final String name, final UserCredentials hostUser) throws IOException {

    assert this.proxyUGI == null;
    assert hostUser instanceof YarnProxyUser;

    LOG.log(Level.FINE, "UGI: user {0} copy from: {1}", new Object[] {name, hostUser});

    final UserGroupInformation hostUGI = ((YarnProxyUser) hostUser).get();
    final Collection<Token<? extends TokenIdentifier>> tokens = hostUGI.getCredentials().getAllTokens();

    this.set(name, hostUGI, tokens.toArray(new Token[tokens.size()]));
  }
1347496
@Override
    public ProducerSession createSystemProducerSession(SIDestinationAddress destAddress,
                                                       String discriminator,
                                                       DestinationType destFilter,
                                                       OrderingContext context,
                                                       String alternateUser,
                                                       boolean clearPubSubFingerprints)
                    throws SIConnectionUnavailableException, SIConnectionDroppedException,
                    SIResourceException, SIConnectionLostException, SILimitExceededException,
                    SIErrorException,
                    SINotAuthorizedException,
                    SINotPossibleInCurrentConfigurationException,
                    SIIncorrectCallException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "createSystemProducerSession",
                        new Object[] { destAddress, discriminator, destFilter, context, alternateUser, clearPubSubFingerprints });

        // See if this connection has been closed
        checkNotClosed();

        checkProducerSessionNullParameters(destAddress);

        if (!destAddress.getDestinationName().startsWith(SIMPConstants.SYSTEM_DESTINATION_PREFIX))
        {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                SibTr.exit(tc, "createSystemProducerSession", "SIIncorrectCallException");
            throw new SIIncorrectCallException(
                            nls.getFormattedMessage(
                                                    "SYSTEM_DESTINATION_USAGE_ERROR_CWSIP0024",
                                                    new Object[] { destAddress.getDestinationName(),
                                                                  _messageProcessor.getMessagingEngineName() },
                                                    null));
        }

        SecurityContext secContext = null;
        // If security is enabled then we need to set up a security context
        if (_isBusSecure)
        {
            // Feature 219101: Add the alternate user string to the security context
            secContext = new SecurityContext(this._subject,
                            alternateUser,
                            null,
                            _messageProcessor.getAuthorisationUtils());
        }

        //create a producer session
        ProducerSession session = null;
        try
        {
            session =
                            internalCreateProducerSession(
                                                          destAddress,
                                                          destFilter,
                                                          true,
                                                          secContext,
                                                          false, // keepSecurityUserid
                                                          false, // fixedQueuePoint
                                                          true, // preferLocal
                                                          clearPubSubFingerprints,
                                                          null);
        } catch (SITemporaryDestinationNotFoundException e)
        {
            // Temporary destination not found should not happen for a System destination
            // FFDC
            FFDCFilter.processException(
                                        e,
                                        "com.ibm.ws.sib.processor.impl.ConnectionImpl.createSystemProducerSession",
                                        "1:4590:1.347.1.25",
                                        this);

            SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0002",
                        new Object[] {
                                      "com.ibm.ws.sib.processor.impl.ConnectionImpl",
                                      "1:4596:1.347.1.25",
                                      e });

            SibTr.exception(tc, e);

            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                SibTr.exit(tc, "createSystemProducerSession", "SIErrorException");

            throw new SIErrorException(nls.getFormattedMessage(
                                                               "INTERNAL_MESSAGING_ERROR_CWSIP0002",
                                                               new Object[] { "ConnectionImpl",
                                                                             "1:4607:1.347.1.25",
                                                                             e },
                                                               null),
                            e);
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "createSystemProducerSession", session);
        return session;
    }