Gentics Portal.Node PHP API
 All Classes Namespaces Functions Variables Pages
BadLoginAttemptsFilter.php
1 <?php
2 
3 /**
4  * Checks if user has ability to perform login
5  **/
6 class BadLoginAttemptsFilter extends CFilter
7 {
8  /**
9  * Controller var for storing flag described if attempts remains
10  *
11  * @public string
12  **/
13  public $blockedVar = 'attemptsEnded';
14 
15  /**
16  * Controller var for storing flag showing remained blocking time
17  *
18  * @public string
19  **/
20  public $timeRemainsVar = 'timeRemains';
21 
22  /**
23  * Number of login attempts
24  *
25  * @public int
26  **/
27  public $attemptsCount = 3;
28 
29  /**
30  * Time for blicking account
31  *
32  * @public string
33  **/
34  public $blockTime = 360;
35 
36  /**
37  * Performs the pre-action filtering.
38  * @param CFilterChain $filterChain the filter chain that the filter is on.
39  * @return boolean whether the filtering process should continue and the action
40  * should be executed.
41  */
42  protected function preFilter($filterChain)
43  {
44  if(Yii::app()->request->isPostRequest && Yii::app()->user->isGuest){
45  $record = LoginAttempt::model()->findByAttributes(array('ip' => Yii::app()->request->userHostAddress));
46  if($record){
47  //time eleapsed
48  $timeRemains = $this->blockTime - (time() - strtotime($record->updated));
49  $filterChain->controller->{$this->timeRemainsVar} = $timeRemains;
50  if( $timeRemains <= 0) {
51  $record->attempts = 0;
52  $record->save();
53  } elseif($record->attempts >= $this->attemptsCount){
54  //block
55  $filterChain->controller->{$this->blockedVar} = true;
56  }
57  }
58  }
59 
60  return true;
61  }
62 
63  /**
64  * If user is guest after login attepmt then it means that password was invalid.
65  * Increment counter in db by ip address
66  *
67  * @param CFilterChain $filterChain the filter chain that the filter is on.
68  */
69  protected function postFilter($filterChain)
70  {
71  //if access not blocked
72  if(Yii::app()->request->isPostRequest && Yii::app()->user->isGuest && $filterChain->controller->{$this->blockedVar} !== true){
73  $ip = Yii::app()->request->userHostAddress;
74  $record = LoginAttempt::model()->findByAttributes(array('ip' => $ip));
75  if($record){
76  if($record->attempts < $this->attemptsCount){
77  $record->attempts += 1;
78  $record->save();
79  }
80  } else {
81  $record = new LoginAttempt();
82  $record->ip = $ip;
83  $record->save();
84  }
85  }
86  }
87 }