在 Apigility Resource 中获取当前用户信息

Get current user information in Apigility Resource

我刚开始使用 Apigility 和 oAuth2,我想知道在从数据库中获取信息时是否可以获取当前经过身份验证的 "loggedin" 用户。

我目前有以下代码:

/**
 * Fetch all or a subset of resources
 *
 * @param  array $params
 * @return mixed
 */
public function fetchAll($params = array())
{
    var_dump($params);
    // Using Zend\Db's SQL abstraction 
    $sql = new \Zend\Db\Sql\Sql($this->db); 
    //I would like to get the currently logged in user here... but how?
    $select = $sql->select('projects')->where(array('userid' => 1));; 

    // This provides paginated results for the given Select instance 
    $paged  = new \Zend\Paginator\Adapter\DbSelect($select, $this->db); 

    // which we then pass to our collection 
    return new ProjectsCollection($paged);  
}

我已经做了很多搜索,但我不知道如何访问用户信息或访问令牌,我需要为此解析请求 header 吗?

我也在找。我没有找到任何相关文件。但答案很简单:

资源 类 继承 ZF\Rest\AbstractResourceListener 已经有一个方法 getIdentity.

/**
 * Fetch all or a subset of resources
 *
 * @param  array $params
 * @return mixed
 */
public function fetchAll($params = array())
{
    // if user isn't authenticated return nothing
    if(!$this->getIdentity() instanceof ZF\MvcAuth\Identity\AuthenticatedIdentity) {
        return [];
    }

    // this array returyour query here using $userIdns the authentication info
    // in this case we need the 'user_id' 
    $identityArray= $this->getIdentity()->getAuthenticationIdentity();

    // note, by default user_id is the email (username column in oauth_users table)
    $userId = $identityArray['user_id'];

    // fetch all using $userId
}

您还可以在 RPC 服务中使用 getIdentity

我使用的是最新版本的 apigility。

最后我找到了一种获取用户 ID 的较短方法,为了完整起见,将其添加为答案。
您可以获得像@ViníciusFagundes 提到的 identity 对象 $this->getIdentity() 并且此身份对象具有函数 getRoleId() 其中 returns 用户的标识符。

$user_id = $this->getIdentity()->getRoleId();