Bas van Stein Bas van Stein - 3 months ago 31
PHP Question

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.

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?

Answer

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.

/**
 * 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.

I'm using the latest version of apigility.