Usuario.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace common\models;
  3. use Yii;
  4. use yii\web\IdentityInterface;
  5. use Firebase\JWT\JWT;
  6. class Usuario extends \app\models\Usuario implements IdentityInterface {
  7. /**
  8. * Finds an identity by the given id.
  9. *
  10. * @param string|int $id the id to be looked for
  11. * @return IdentityInterface|null the identity object that matches the given id.
  12. */
  13. public static function findIdentity($id) {
  14. return static::findOne($id);
  15. }
  16. /**
  17. * Finds an identity by the given token.
  18. *
  19. * @param string $token the token to be looked for
  20. * @return IdentityInterface|null the identity object that matches the given token.
  21. */
  22. public static function findIdentityByAccessToken($token, $type = null) {
  23. $key = Yii::$app->params['jwt.key'];
  24. $jwt = JWT::decode($token, $key, ['HS256']);
  25. if(!isset($jwt->id)) {
  26. return null;
  27. }
  28. return static::findOne($jwt->id);
  29. }
  30. /**
  31. * @return int|string current user ID
  32. */
  33. public function getId() {
  34. return $this->id;
  35. }
  36. /**
  37. * @return string current user auth key
  38. */
  39. public function getAuthKey() {
  40. $key = Yii::$app->params['jwt.key'];
  41. $token = [
  42. "id" => $this->id,
  43. "pass" => $this->clave
  44. ];
  45. $jwt = JWT::encode($token, $key);
  46. return $jwt;
  47. }
  48. /**
  49. * @param string $authKey
  50. * @return bool if auth key is valid for current user
  51. */
  52. public function validateAuthKey($authKey) {
  53. $key = Yii::$app->params['jwt.key'];
  54. $jwt = JWT::decode($authKey, $key);
  55. if(!isset($jwt["id"])) {
  56. return false;
  57. }
  58. return $jwt["id"] == $this->id;
  59. }
  60. }