| Current Path : /var/www/html/csm/common/models/ |
| Current File : /var/www/html/csm/common/models/LoginThrottle.php |
<?php
namespace common\models;
use Yii;
/**
* This is the model class for table "login_throttle".
*
* @property int $id
* @property string $ip
* @property int $last_attempt_timestamp
*/
class LoginThrottle extends \yii\db\ActiveRecord
{
const MIN_COOLDOWN_TIME = 300;
const MAX_ATTEMPT = 3;
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'login_throttle';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['last_attempt_timestamp'], 'integer'],
[['ip'], 'string', 'max' => 16],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'ip' => Yii::t('app', 'Ip'),
'last_attempt_timestamp' => Yii::t('app', 'Last Attempt Timestamp'),
];
}
public static function login_throttle_save() {
$login_throttle = new self();
$login_throttle->ip = Yii::$app->request->userIP;
$login_throttle->last_attempt_timestamp = time();
if(!$login_throttle->save()) {
echo 'Failed to save throttle data';
}
}
/**
* [login_throttle_check Check login attempt from the same ip]
* @param int $cooldown Cooldown in second before user can try again
* @param int $max_attempt Max attempt before login is disable
* @return boolean
*/
public static function login_throttle_check($cooldown=null, $max_attempt=null) {
if(empty($cooldown)) {
$cooldown = self::MIN_COOLDOWN_TIME;
}
if(empty($max_attempt)) {
$max_attempt = self::MAX_ATTEMPT;
}
// var_dump(time() - $cooldown);
$query = 0;
$driver = Yii::$app->db->getDriverName();
/** check cooldown time */
$query = (new \yii\db\Query())
->select(['last_attempt_timestamp'])
->from('login_throttle')
->where(['>','last_attempt_timestamp', (time() - $cooldown)])
->andWhere(['ip' => Yii::$app->request->userIP])
->all();
if(count($query) > $max_attempt) {
return true;
}
return false;
}
}