2016-04-19 10 views
4

私は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); 
} 

を私はすでに検索の多くをやったが、私は、ユーザー情報やアクセストークンにアクセスする方法を見当もつかない、私はのためのリクエストヘッダを解析する必要がありますこの?

答えて

3

私はまたそれを探していました。私はそれについてのドキュメントは見つかりませんでした。しかし、答えは非常に単純です:

リソースクラスはgetIdentityというメソッドを既に持っていますZF\Rest\AbstractResourceListenerを継承しています。

/** 
* 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を使用することもできます。

私は最新のバージョンの忍耐を使用しています。

+0

ありがとうございました!私はそれを仕事にしました。私は最後に '$ this-> getIdentity() - > getRoleId()'でユーザIDを取得することもできました。 –

+0

ニース。私はそれに気付かなかった! –

3

最後に、ユーザーIDを取得するための短い方法を見つけました。完全性のために答えとして追加するだけです。
@ViníciusFagundesのようなidentityオブジェクトには$this->getIdentity()と記載されています。このIDオブジェクトには、ユーザの識別子を返す関数getRoleId()があります。

$user_id = $this->getIdentity()->getRoleId(); 
関連する問題