Skip to content

Commit 2491ef3

Browse files
the model to log the login attempt
1 parent e62faf9 commit 2491ef3

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

src/models/LoginAttempt.php

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
<?php
2+
3+
namespace ZakharovAndrew\user\models;
4+
5+
use Yii;
6+
use yii\db\ActiveRecord;
7+
use ZakharovAndrew\user\Module;
8+
9+
class LoginAttempt extends ActiveRecord
10+
{
11+
const MAX_ATTEMPT = 3;
12+
13+
public static function tableName()
14+
{
15+
return 'login_attempts';
16+
}
17+
18+
/**
19+
* {@inheritdoc}
20+
*/
21+
public function rules()
22+
{
23+
return [
24+
[['username', 'ip_address'], 'required'],
25+
[['attempt_time'], 'safe'],
26+
[['successful'], 'boolean'],
27+
[['username'], 'string', 'max' => 255],
28+
[['ip_address'], 'string', 'max' => 45], // Sufficient length for IPv6
29+
];
30+
}
31+
32+
/**
33+
* {@inheritdoc}
34+
*/
35+
public function attributeLabels()
36+
{
37+
return [
38+
'id' => 'ID',
39+
'username' => Module::t('Username'),
40+
'ip_address' => Module::t('IP Address'),
41+
'attempt_time' => Module::t('Attempt Time'),
42+
'successful' => Module::t('Successful Attempt'),
43+
];
44+
}
45+
46+
/**
47+
* Method to check if the IP address is blocked
48+
* @param string $ipAddress
49+
* @return boolean
50+
*/
51+
public static function isBlockedByIp($ipAddress)
52+
{
53+
$count = static::find()
54+
->where(['ip_address' => $ipAddress, 'successful' => false])
55+
->andWhere(['>', 'attempt_time', new \yii\db\Expression('NOW() - INTERVAL 1 HOUR')])
56+
->count();
57+
58+
return $count >= static::MAX_ATTEMPT; // Block after 3 unsuccessful attempts
59+
}
60+
61+
/**
62+
* Method to log the login attempt
63+
* @param string $username
64+
* @param string $ipAddress
65+
* @param boolean $successful
66+
* @return boolean
67+
*/
68+
public static function logLoginAttempt($username, $ipAddress, $successful)
69+
{
70+
$loginAttempt = new self();
71+
$loginAttempt->username = $username;
72+
$loginAttempt->ip_address = $ipAddress;
73+
$loginAttempt->attempt_time = date('Y-m-d H:i:s');
74+
$loginAttempt->successful = $successful;
75+
76+
return $loginAttempt->save(); // Save the login attempt to the database
77+
}
78+
}

0 commit comments

Comments
 (0)