public function testAuthenticate() { // Test using user OR alias $tu = $this->users('testUser'); $ui = new UserIdentity($tu->username, 'password'); $this->assertEquals($tu->id, $ui->getUserModel()->id); $this->assertTrue($ui->authenticate()); $ui = new UserIdentity($tu->userAlias, 'password'); $this->assertEquals($tu->id, $ui->getUserModel()->id); $this->assertTrue($ui->authenticate()); $tu->status = User::STATUS_INACTIVE; // Test incorrect password: $ui = new UserIdentity($tu->username, 'notthepassword'); $this->assertFalse($ui->authenticate()); $this->assertEquals(UserIdentity::ERROR_PASSWORD_INVALID, $ui->errorCode); // Test incorrect username: $ui = new UserIdentity('nousernamethatexistsoreverwillexistintheusersfixture', 'passwor'); $this->assertFalse($ui->authenticate()); $this->assertEquals(UserIdentity::ERROR_USERNAME_INVALID, $ui->errorCode); // Test lockout: $tu->update(array('status')); $ui = new UserIdentity($tu->username, 'password'); $this->assertFalse($ui->authenticate()); $this->assertEquals(UserIdentity::ERROR_DISABLED, $ui->errorCode); }
/** * Logs a user in. * * If $rememberMe is set to `true`, the user will be logged in for the duration specified by the * [rememberedUserSessionDuration](http://craftcms.com/docs/config-settings#rememberedUserSessionDuration) * config setting. Otherwise it will last for the duration specified by the * [userSessionDuration](http://craftcms.com/docs/config-settings#userSessionDuration) * config setting. * * @param string $username The user’s username. * @param string $password The user’s submitted password. * @param bool $rememberMe Whether the user should be remembered. * * @throws Exception * @return bool Whether the user was logged in successfully. */ public function login($username, $password, $rememberMe = false) { // Require a userAgent string and an IP address to help prevent direct socket connections from trying to login. if (!craft()->request->userAgent || !$_SERVER['REMOTE_ADDR']) { Craft::log('Someone tried to login with loginName: ' . $username . ', without presenting an IP address or userAgent string.', LogLevel::Warning); $this->logout(true); $this->requireLogin(); } // Validate the username/password first. $usernameModel = new UsernameModel(); $passwordModel = new PasswordModel(); $usernameModel->username = $username; $passwordModel->password = $password; // Validate the models. if ($usernameModel->validate() && $passwordModel->validate()) { $this->_identity = new UserIdentity($username, $password); // Did we authenticate? if ($this->_identity->authenticate()) { return $this->loginByUserId($this->_identity->getUserModel()->id, $rememberMe, true); } } Craft::log($username . ' tried to log in unsuccessfully.', LogLevel::Warning); return false; }