Advertisement
Guest User

UserIdentity Yii1 to Yii2

a guest
Apr 23rd, 2018
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 9.28 KB | None | 0 0
  1. <?php
  2.  
  3. namespace app\components;
  4.  
  5. /**
  6.  * UserIdentity represents the data needed to identity a user.
  7.  * It contains the authentication method that checks if the provided
  8.  * data can identity the user.
  9.  */
  10. use yii\base\Exception;
  11. use yii\web\HttpException;
  12. use yii\web\IdentityInterface;
  13. use Yii;
  14.  
  15. class UserIdentity extends \yii\web\User implements \yii\web\IdentityInterface
  16. //class UserIdentity implements \yii\web\IdentityInterface
  17. {
  18.     const ERROR_NONE=0;
  19.     const ERROR_USERNAME_INVALID=1;
  20.     const ERROR_PASSWORD_INVALID=2;
  21.     const ERROR_CAN_NOT_VOTE = 3;
  22.     const ERROR_ALREADY_VOTED = 4;
  23.     const ERROR_USERNAME_BANNED = 5;
  24.     const ERROR_USERNAME_DEACTIVATED = 6;
  25.     const ERROR_UNKNOWN_IDENTITY=100;
  26.     private $_id;
  27.     public $id;
  28.     public $username;
  29.     public $errorCode;
  30.  
  31.     // #REFACTORING# Unused vars below, would need to refactor and use these that are accessed using session[]
  32.     // WARNING, THIS LINE EXISTS IN \yii\web\User and will cause an exception, don't use it here, leaving as reference
  33. //    public $isGuest;
  34.     public $totalVote;
  35.     public $currentVote;
  36.     public $returnUrl;
  37.  
  38.  
  39.     function init()
  40.     {
  41.         parent::init();
  42.         // Hacky way of fixing the login problem when ENV != 'debug', by fetching the user_id in the
  43.         // session instead of the user class. No idea why Yii::$app->user->id would return NULL when user is logged
  44.         $this->id = Yii::$app->session->get('id');
  45.     }
  46.  
  47.  
  48.     public function setUsername($username)
  49.     {
  50.         $this->username=$username;
  51. //        $this->id=$username;
  52. //        $this->_id=$username;
  53.     }
  54.  
  55.     // Old obsolete method from Yii1, will just save in the session AND the UserIdentity
  56.     // Unused anywhere at the moment, also failed attempt to fix the ENV login problem in conjuncture with __get()
  57.     public function setState($key, $value)
  58.     {
  59. //        $this->{$key} = $value;
  60.         Yii::$app->session->set($key, $value);
  61.     }
  62.  
  63.  
  64. /* This is a failed attempt to clean up the class and fix the ENV login problem, keeping it jsut in case
  65.     // Get the user identity's value and set it, if we have it
  66.     public function __get($key)
  67.     {
  68. //        if (isset($this->{$key}))
  69. ////        if (property_exists($this, $key))
  70. //            return $this->{$key};
  71.  
  72.         if (Yii::$app->session->has($key))
  73.             return Yii::$app->session->get($key, '');
  74.         else
  75.             return parent::__get($key);
  76.  
  77. //        // While we're here, set it in the user identity at the same time
  78. //        $this->{$key} = Yii::$app->session->get($key, '');
  79. //
  80. //        return $this->{$key};
  81.     }
  82. //*/
  83.  
  84.  
  85.     // This looks like it's never being called
  86.     public function setId($_id)
  87.     {
  88.         $this->_id=$_id;
  89.         $this->id=$_id;
  90.     }
  91.  
  92.    
  93.     /**
  94.      * Authenticates a user.
  95.      * The example implementation makes sure if the username and password
  96.      * are both 'demo'.
  97.      * In practical applications, this should be changed to authenticate
  98.      * against some persistent user identity storage (e.g. database).
  99.      * @return boolean whether authentication succeeds.
  100.      */
  101.     public function authenticate()
  102.     {
  103.         $clean=preg_replace('/[^0-9]/','',$this->username);
  104.         // $year=substr($clean,0,4);
  105.         // $month=substr($clean,4,2);
  106.         // $day=substr($clean,6,2);
  107.  
  108.         //$date=date('Ymd', strtotime($year.'-'.$month.'-'.$day));
  109.  
  110.         if(!isset($this->username) || $this->username==''){
  111.             $this->errorCode=self::ERROR_USERNAME_INVALID;
  112.         }else if(strlen($clean) < 3){
  113.             // LEss than 7 digits: invalid
  114.             $this->errorCode=self::ERROR_USERNAME_INVALID;
  115. #        }else if($year<1899 || $year>2015){
  116. #            // Member ids look like dates
  117. #           $this->errorCode=self::ERROR_USERNAME_INVALID;
  118. #        }else if($date!=$year.$month.$day){
  119. #            // Member ids look like dates
  120. #           $this->errorCode=self::ERROR_USERNAME_INVALID;
  121.        }else{
  122.             $member=\app\models\Member::find()->where(['matricule'=>$clean])->one();
  123.  
  124.             if($member){
  125.                 if($member->voted){
  126.                     $this->errorCode=self::ERROR_ALREADY_VOTED;
  127.                 }else if($member::model()->getBlocked($member->id) ){
  128.                     if(isset($member->deactivated) && $member->deactivated){
  129.                         $this->errorCode=self::ERROR_USERNAME_DEACTIVATED;
  130.                     }else{
  131.                         $this->errorCode=self::ERROR_USERNAME_BANNED;
  132.                     }
  133.                 }else{
  134.                     $this->_id = $member->id;
  135.                     $this->id = $member->id;
  136.  
  137.                     $this->errorCode=self::ERROR_NONE;
  138.                      // on peut garder ceci en state
  139.                     Yii::$app->session->set('id',$member->id);
  140. //                    Yii::$app->user->setState('id',$member->id);
  141.                     Yii::$app->session->open(); // Not sure this is needed, or even valid anymore with Yii2
  142.                     // session pour les infos secretes qui ne doivent PAS etre stockées cote client
  143.                     Yii::$app->session['error_nip']=0;
  144.                     Yii::$app->session['error_verif']=0;
  145.                     Yii::$app->session['error_vote']=0;
  146.  
  147.                     try {
  148.                         Yii::$app->session['nip'] = Yii::$app->getSecurity()->generatePasswordHash($member->nip);
  149.                     } catch (Exception $e) {
  150.                         // #REFACTORING# Check if this exception will work in case a hash cannot be created
  151.                         throw new HttpException(403, Yii::t('vote', 'Failed to get password hash.'));
  152.                     }
  153. //                    Yii::$app->session['nip']=CPasswordHelper::hashPassword($member->nip);
  154.  
  155.                     // Note: verification was removed. If needed again, check out branch yii1_untouched and port
  156.                     // the code to Yii2
  157.                     Yii::$app->session['verif_field']=$member->getVerifField();
  158.                     Yii::$app->session['verif']=$member->{$member->getVerifField()};
  159.  
  160.                     Yii::$app->session['ok_nip']=false; // Set to false so we can ask for nip next
  161.                     Yii::$app->session['ok_verif']=false;
  162.                     Yii::$app->session['is_voting']=false;
  163.                     Yii::$app->session['code_ul'] = $member->code_ul;
  164.                 }
  165.             }else{
  166.                 $this->errorCode=self::ERROR_USERNAME_INVALID;
  167.             }
  168.         }
  169.         return !$this->errorCode;
  170.     }
  171.  
  172.     /**
  173.      * Finds an identity by the given token.
  174.      * @param mixed $token the token to be looked for
  175.      * @param mixed $type the type of the token. The value of this parameter depends on the implementation.
  176.      * For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
  177.      * @return IdentityInterface the identity object that matches the given token.
  178.      * Null should be returned if such an identity cannot be found
  179.      * or the identity is not in an active state (disabled, deleted, etc.)
  180.      */
  181.     public static function findIdentityByAccessToken($token, $type = null)
  182.     {
  183.         // Never called
  184.         exit('findIdentityByAccessToken');
  185.         // TODO: Implement findIdentityByAccessToken() method.
  186.     }
  187.  
  188.     /**
  189.      * Returns an ID that can uniquely identify a user identity.
  190.      * @return string|int an ID that uniquely identifies a user identity.
  191.      */
  192.     public function getId()
  193.     {
  194.         return $this->id;
  195. //        return $this->_id;
  196.         // TODO: Implement getId() method.
  197.     }
  198.  
  199.     /**
  200.      * Returns a key that can be used to check the validity of a given identity ID.
  201.      *
  202.      * The key should be unique for each individual user, and should be persistent
  203.      * so that it can be used to check the validity of the user identity.
  204.      *
  205.      * The space of such keys should be big enough to defeat potential identity attacks.
  206.      *
  207.      * This is required if [[User::enableAutoLogin]] is enabled.
  208.      * @return string a key that is used to check the validity of a given identity ID.
  209.      * @see validateAuthKey()
  210.      */
  211.     public function getAuthKey()
  212.     {
  213.         // Never called
  214.         exit('getAuthKey');
  215.         // TODO: Implement getAuthKey() method.
  216.     }
  217.  
  218.     /**
  219.      * Validates the given auth key.
  220.      *
  221.      * This is required if [[User::enableAutoLogin]] is enabled.
  222.      * @param string $authKey the given auth key
  223.      * @return bool whether the given auth key is valid.
  224.      * @see getAuthKey()
  225.      */
  226.     public function validateAuthKey($authKey)
  227.     {
  228.         // Never called
  229.         exit('validateAuthKey');
  230.         // TODO: Implement validateAuthKey() method.
  231.     }
  232.  
  233.     /**
  234.      * Finds an identity by the given ID.
  235.      * @param string|int $id the ID to be looked for
  236.      * @return IdentityInterface the identity object that matches the given ID.
  237.      * Null should be returned if such an identity cannot be found
  238.      * or the identity is not in an active state (disabled, deleted, etc.)
  239.      */
  240.     public static function findIdentity($id)
  241.     {
  242.         // This was an attempt to make the login work in the beginning. Ugly so I'm commenting this
  243.         // If login stops working, could be because of this
  244. //        Yii::$app->user->id = $id;
  245. //        Yii::$app->user->setId($id);
  246.  
  247.         return Yii::$app->user;
  248.     }
  249. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement