1414use dektrium \user \Finder ;
1515use dektrium \user \helpers \Password ;
1616use dektrium \user \traits \ModuleTrait ;
17+ use yii \base \DynamicModel ;
1718use yii \helpers \ArrayHelper ;
1819use yii \helpers \Html ;
1920use Yii ;
2021use yii \base \Model ;
22+ use yii \validators \IpValidator ;
2123
2224/**
2325 * LoginForm get user's login and password, validates them and logs the user in. If user has been blocked, it adds
@@ -53,7 +55,7 @@ public function __construct(Finder $finder, $config = [])
5355 $ this ->finder = $ finder ;
5456 parent ::__construct ($ config );
5557 }
56-
58+
5759 /**
5860 * Gets all users to generate the dropdown list when in debug mode.
5961 *
@@ -145,6 +147,30 @@ public function login()
145147 }
146148
147149
150+ /**
151+ * Validates if an administrator is coming from the correct IP adress.
152+ *
153+ * @see Module $allowedIpConfiguration
154+ * @see http://www.yiiframework.com/doc-2.0/guide-tutorial-core-validators.html#ip
155+ * @see http://www.yiiframework.com/doc-2.0/yii-validators-ipvalidator.html
156+ * @return mixed true if the check is correct, an array with the errors otherwise
157+ */
158+ public function checkValidIpAddresses ()
159+ {
160+ $ config = $ this ->module ->allowedIpConfiguration ;
161+
162+ if (!$ this ->user ->isAdmin || !$ config ) {
163+ return true ;
164+ }
165+
166+ $ rules = ArrayHelper::merge (['login ' , 'ip ' ], $ config );
167+
168+ $ model = DynamicModel::validateData (['login ' => Yii::$ app ->request ->userIP ], [$ rules ]);
169+
170+ return $ model ->hasErrors () ? $ model ->getErrors () : true ;
171+ }
172+
173+
148174 /** @inheritdoc */
149175 public function formName ()
150176 {
@@ -157,6 +183,14 @@ public function beforeValidate()
157183 if (parent ::beforeValidate ()) {
158184 $ this ->user = $ this ->finder ->findUserByUsernameOrEmail (trim ($ this ->login ));
159185
186+ $ valid = $ this ->checkValidIpAddresses ();
187+
188+ if ($ valid !== true ) {
189+ foreach ($ valid as $ error ) {
190+ $ this ->addError ('login ' , $ error );
191+ }
192+ }
193+
160194 return true ;
161195 } else {
162196 return false ;
0 commit comments