| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127 |
- <?php
- namespace common\models;
- use Yii;
- use yii\web\IdentityInterface;
- use Firebase\JWT\JWT;
- use Kreait\Firebase\Factory;
- use Kreait\Firebase\Exception\AuthException;
- use Kreait\Firebase\Exception\FirebaseException;
- class Usuario implements IdentityInterface {
-
- public $uid;
- public $correo;
- public $nombre;
- protected static function firebase() {
- $params = \Yii::$app->params;
- $firebase = (new Factory())
- ->withServiceAccount($params['firebaseKey'])
- ->createAuth();
- return $firebase;
- }
- /**
- * Finds an identity by the given id.
- *
- * @param string|int $id the id to be looked for
- * @return IdentityInterface|null the identity object that matches the given id.
- */
- public static function findIdentity($uid) {
- $firebase = self::firebase();
- try {
- $fUsuario = $firebase->getUser($uid);
- if ($fUsuario->disabled === true) {
- return null;
- }
- $usuario = new static();
- $usuario->uid = $uid;
- $usuario->nombre = "";
- if($fUsuario->displayName) {
- $usuario->nombre = $fUsuario->displayName;
- }
- $usuario->correo = $fUsuario->email;
- return $usuario;
- } catch (AuthException $e) {
- return null;
- } catch (FirebaseException $e) {
- return null;
- }
- }
- /**
- * Finds an identity by the given token.
- *
- * @param string $token the token to be looked for
- * @return IdentityInterface|null the identity object that matches the given token.
- */
- public static function findIdentityByAccessToken($token, $type = null) {
- $firebase = self::firebase();
- try {
- $verifiedIdToken = $firebase->verifyIdToken($token);
- $uid = $verifiedIdToken->claims()->get('sub');
- $fUsuario = $firebase->getUser($uid);
- if ($fUsuario->disabled === true) {
- return null;
- }
- $usuario = new static();
- $usuario->uid = $uid;
- $usuario->nombre = "";
- if($fUsuario->displayName) {
- $usuario->nombre = $fUsuario->displayName;
- }
- $usuario->correo = $fUsuario->email;
- return $usuario;
- } catch (AuthException $e) {
- return null;
- } catch (FirebaseException $e) {
- return null;
- }
- }
- /**
- * @return int|string current user ID
- */
- public function getId() {
- return $this->uid;
- }
- /**
- * @return string current user auth key
- */
- public function getAuthKey() {
- $key = Yii::$app->params['jwt.key'];
- $token = [
- "id" => $this->id,
- "pass" => $this->clave
- ];
- $jwt = JWT::encode($token, $key);
- return $jwt;
- }
- /**
- * @param string $authKey
- * @return bool if auth key is valid for current user
- */
- public function validateAuthKey($authKey) {
- $key = Yii::$app->params['jwt.key'];
- $jwt = JWT::decode($authKey, $key);
- if(!isset($jwt["id"])) {
- return false;
- }
- return $jwt["id"] == $this->id;
- }
- }
|