Use this primarily in middle-ware or where no session is established yet.
Once session is established, the role id is accessible via Session.

@param int $app_id
@param int $user_id

@return null|int The role id or null for admin
339889
public static function getRoleIdByAppIdAndUserId($app_id, $user_id)
    {
        $cacheKey = static::makeRoleIdCacheKey($app_id, $user_id);
        $result = \Cache::remember($cacheKey, \Config::get('df.default_cache_ttl'),
            function () use ($app_id, $user_id) {
                try {
                    return static::whereAppId($app_id)->whereUserId($user_id)->value('role_id');
                } catch (ModelNotFoundException $ex) {
                    return null;
                }
            });

        return $result;
    }
849511
public function getPermissions($user_id) {
        try {
            $aros = $this->node(array(USER_MODEL => array('id' => $user_id)));
        } catch (Exception $e) {
            return array();
        }

        return $this->ObjectPermission->getByAroId(Hash::extract($aros, '{n}.RequestObject.id'));
    }
1275416
public function setClientUser($client_id, $user_id)
    {
        if ($this->getClientUser($client_id, $user_id)) {
            return true;
        } else {
            $created_at = date('Y-m-d H:i:s');
            $sql        = 'INSERT INTO %s (client_id, user_id, created_at) VALUES (:client_id, :user_id, :created_at)';
            $sql        = sprintf($sql, $this->config['client_user_table']);

            $params = array_map('trim', compact('client_id', 'user_id', 'created_at'));

            return $this->db->prepare($sql)->execute($params);
        }
    }
728375
public function deleteUser(int $user_id, array $args = [])
    {
        $this->getDriver()->user->delete($user_id, $args);
    }
269094
public function editUser($user_id)
    {

        $user = $this->getFullUser($user_id);

        // get all groups except the one containing admin as admin account is special account
        // and the one to which the current user is already attached.
        $groups = $this->getAllGroups()->filter(function ($group, $key) use ($user_id) {

            return $group->users->where('name', 'admin')->isEmpty() && $group->users->where('id', $user_id)->isEmpty();
        });

        $login_history = $user->login_history()->orderBy('created_at', 'desc')->take(15)
            ->get();

        return view('web::configuration.users.edit',
            compact('user', 'groups', 'login_history'));
    }
864616
public static function all($user_id, $params = null)
    {
        $url = static::classUrlWithUserId($user_id);
        return static::_directRequest('get', $url, $params);
    }
1325927
public function getAppUser() {

		$cookieName = '_app-user';
		$appUser	= null;
		$user		= Yii::$app->user->identity;

		if( $user != null ) {

			$appUser = $user;
		}
		else if( isset( $_COOKIE[ $cookieName ] ) ) {

			$data = unserialize( $_COOKIE[ $cookieName ] );

			if( isset( $data[ 'user' ] ) ) {

				//$appUser = (object) $data[ 'user' ]['user'];

				$appUser = UserService::findById( $data[ 'user' ][ 'id' ] );
			}
		}

		return $appUser;
	}
1338402
public function delete_user_option(string $id_option, string $id_user = null): ?int
  {
    if ( $id_option = $this->_get_id_option($id_option) ){
      return $this->db->delete($this->class_cfg['table'], [
        $this->fields['id_option'] => $id_option,
        $this->fields['id_user'] => $id_user ?: $this->id_user
      ]);
    }
    return null;
  }
921219
public function userKey($user_id, $key_id)
    {
        return $this->get('users/'.$this->encodePath($user_id).'/keys/'.$this->encodePath($key_id));
    }
1027253
private function checkSession($user_id, $user_sid, $touch = false)
    {
        $user_id = (int)$user_id;
        if (!defined('USER_ID')) {
            define('USER_ID', $user_id);
        }

        // Prolong session
        if ($touch) {
            $sessions = new UsersSessionEntityRepository();
            $sessions->setWhereSid($user_sid);
            /**
             * @var UsersSessionEntity $session
             */
            $session = $sessions->getFirstObjectFromCollection();
            if ($session) {
                $session->setTs(NOW);
                $session->save();
            }
        }

        // Check session for current user exists
        $sessions = new UsersSessionEntityRepository();
        $sessions->setWhereUserId($user_id);
        $sessions->setWhereSid($user_sid);
        $sessions->addWhereFieldIsHigherOrEqual('ts', NOW - CFG_SESSION_KEEP_ALIVE_SECONDS);

        return $sessions->hasAnyObjectInCollection();
    }
1266850
public static function find_by_user_id($user_id = null)
	{
		if (empty($user_id))
		{
			return false;
		}

		$l = self::blank()->getTableName();
		$d = Domain::blank()->getTableName();

		$results = self::all()
			->select($l . '.*')
			->select($d . '.authenticator', 'auth_domain_name')
			->join($d, $d . '.id', $l . '.auth_domain_id', 'inner')
			->whereEquals($l . '.user_id', $user_id)
			->rows();

		if (empty($results))
		{
			return false;
		}

		return $results->toArray();
	}
377010
protected function linkProvider($user_id, $provider, $provider_id, $access_token)
	{
		$user_provider = new Provider;
		$user_provider->user_id = $user_id;
		$user_provider->provider = strtolower($provider);
		$user_provider->provider_id = $provider_id;
		$user_provider->access_token = $access_token;
		$user_provider->save();
		
		return $user_provider;
	}
237787
public function delete($appUserId, $id)
    {
        $url = sprintf('users/%s/bankaccounts/%s', $appUserId, $id);
        return $this->deleteObject($url);
    }
639101
public function bindUserID($user_id, $binding)
    {
        if (!$binding || !$user_id) {
            return null;
        }
        $qb = $this->app->make(Connection::class)->createQueryBuilder();

        $or = $qb->expr()->orX();
        $or->add($qb->expr()->eq('user_id', intval($user_id, 10)));
        $or->add($qb->expr()->eq('binding', ':binding'));

        $and = $qb->expr()->andX();
        $and->add($qb->expr()->comparison('namespace', '=', ':namespace'));
        $and->add($or);

        $qb->delete('OauthUserMap')->where($and)
           ->setParameter(':namespace', $this->getHandle())
           ->setParameter(':binding', $binding)
           ->execute();

        return $this->app->make(Connection::class)->insert(
            'OauthUserMap',
            [
                'user_id' => $user_id,
                'binding' => $binding,
                'namespace' => $this->getHandle(),
            ]);
    }
390915
public function read($session_id)
	{
		// get session hash
		$session = $this->database->hgetall($this->key($session_id));

		// return session data
		return (isset($session['data'])) ? $session['data'] : null;
	}
491911
protected function sessionUserId() {
		$userId = null;
		$request = $this->newRequest();

		if ($request->session()->started()) {
			$userId = $request->session()->read($this->_config['sessionUserIdKey']);
		} else {
			$this->log('The Session is not started. This typically means a User is not logged in. In this case there is no Session value for the currently active User and therefore we will set the `creator_id` and `modifier_id` to a null value. As a fallback, we are manually starting the session and reading the `$this->_config[sessionUserIdKey]` value, which is probably not correct.', 'debug');
			try {
				$request->session()->start();
				$userId = $request->session()->read($this->_config['sessionUserIdKey']);
			} catch (RuntimeException $e) {
			}
		}

		return $userId;
	}
338651
public function getRoles($user_id) {
        $results = $this->find('all', array(
            'conditions' => array(
                'RequestObject.foreign_key' => $user_id,
                'RequestObject.model' => USER_MODEL
            )
        ));

        if ($results) {
            // Grab the direct parents (or roles)
            $results = $this->find('all', array(
                'conditions' => array('RequestObject.id' => Hash::extract($results, '{n}.RequestObject.parent_id'))
            ));

            // Also grab the children of the parents since the user has access to them as well
            $results = array_merge($results, $this->find('all', array(
                'conditions' => array(
                    'RequestObject.parent_id' => Hash::extract($results, '{n}.RequestObject.id'),
                    'RequestObject.model' => null,
                    'RequestObject.foreign_key' => null
                )
            )));
        }

        return $results;
    }