简体   繁体   English

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

[英]Get current user information in Apigility Resource

I just started with Apigility and oAuth2, and I was wondering if it is possible to get the currently authenticated "loggedin" user when fetching information from a database. 我刚开始使用Apigility和oAuth2,我想知道从数据库中获取信息时是否有可能获得当前经过身份验证的“登录”用户。

I currently have the following code: 我目前有以下代码:

/**
 * 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);  
}

I did a lot of searching already but I have no clue how to access the user information or the access token, do I need to parse the request header for this? 我已经做了很多搜索,但我不知道如何访问用户信息或访问令牌,我是否需要为此解析请求标头?

I was also looking for it. 我也在寻找它。 I didn't found any documentation about that. 我没有找到任何关于这方面的文件。 But the answer is quite simple: 但答案很简单:

Resource classes inherits ZF\\Rest\\AbstractResourceListener which already has a method getIdentity . 资源类继承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
}

You can also use getIdentity in RPC services. 您还可以在RPC服务中使用getIdentity

I'm using the latest version of apigility. 我正在使用最新版本的apigility。

I found in the end a shorter way to get the userid, just adding it as answer for the sake of completeness. 我最终找到了获取用户标识的简短方法,只是为了完整性而将其添加为答案。
You can get the identity object like @ViníciusFagundes mentioned $this->getIdentity() and this identity object has the function getRoleId() which returns the identifier of the user. 你可以像@ViníciusFagundes那样提到identity对象$this->getIdentity() ,这个身份对象有getRoleId()函数,它返回用户的标识符。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM