默认情况下 yii2基本,用户可以使用user, user
和admin,admin
登录。
但是,我需要应用程序可以使用我的 sql数据库中的用户名和密码进行访问。在我的数据库中,我有一个名为ùser
的表,其中包含用户名,密码等。我正在尝试遵循this建议。
但是,它会给出这样的错误获取只写属性:app \ models \ User :: password
这是我的代码:
<?php
namespace app\models;
use Yii;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;
/**
* This is the model class for table "user".
*
* @property integer $id
* @property string $username
* @property string $email
* @property string $password_hash
* @property string $auth_key
*/
class User extends \yii\db\ActiveRecord implements IdentityInterface {
/**
* @inheritdoc
*/
public static function tableName() {
return 'user';
}
/**
* @inheritdoc
*/
public function rules() {
return [
[['username', 'email'], 'required'],
[['username', 'name', 'company'], 'string', 'max' => 100],
[['email'], 'string', 'max' => 250],
[['password_hash'], 'string', 'max' => 60],
[['auth_key'], 'string', 'max' => 32],
];
}
/**
* @inheritdoc
*/
public function attributeLabels() {
return [
'id' => 'ID',
'username' => 'Username',
'email' => 'Email',
'password_hash' => 'Password Hash',
'auth_key' => 'Auth Key',
];
}
/** INCLUDE USER LOGIN VALIDATION FUNCTIONS* */
/**
* @inheritdoc
*/
public static function findIdentity($id) {
return static::findOne($id);
}
/**
* @inheritdoc
*/
/* modified */
public static function findIdentityByAccessToken($token, $type = null) {
return static::findOne(['access_token' => $token]);
}
/* removed
public static function findIdentityByAccessToken($token)
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
*/
/**
* Finds user by username
*
* @param string $username
* @return static|null
*/
public static function findByUsername($username) {
return static::findOne(['username' => $username]);
}
/**
* Finds user by password reset token
*
* @param string $token password reset token
* @return static|null
*/
public static function findByPasswordResetToken($token) {
$expire = \Yii::$app->params['user.passwordResetTokenExpire'];
$parts = explode('_', $token);
$timestamp = (int) end($parts);
if ($timestamp + $expire < time()) {
// token expired
return null;
}
return static::findOne([
'password_reset_token' => $token
]);
}
/**
* @inheritdoc
*/
public function getId() {
return $this->getPrimaryKey();
}
/**
* @inheritdoc
*/
public function getAuthKey() {
return $this->auth_key;
}
/**
* @inheritdoc
*/
public function validateAuthKey($authKey) {
return $this->getAuthKey() === $authKey;
}
/**
* Validates password
*
* @param string $password password to validate
* @return boolean if password provided is valid for current user
*/
public function validatePassword($password) {
return $this->password === sha1($password);
}
/**
* Generates password hash from password and sets it to the model
*
* @param string $password
*/
public function setPassword($password) {
$this->password_hash = Security::generatePasswordHash($password);
}
/**
* Generates "remember me" authentication key
*/
public function generateAuthKey() {
$this->auth_key = Security::generateRandomKey();
}
/**
* Generates new password reset token
*/
public function generatePasswordResetToken() {
$this->password_reset_token = Security::generateRandomKey() . '_' . time();
}
/**
* Removes password reset token
*/
public function removePasswordResetToken() {
$this->password_reset_token = null;
}
}
<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
class SiteController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* @inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
/**
* Displays homepage.
*
* @return string
*/
public function actionIndex()
{
return $this->render('index');
}
/**
* Login action.
*
* @return string
*/
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
}
return $this->render('login', [
'model' => $model,
]);
}
/**
* Logout action.
*
* @return string
*/
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
/**
* Displays contact page.
*
* @return string
*/
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('contactFormSubmitted');
return $this->refresh();
}
return $this->render('contact', [
'model' => $model,
]);
}
/**
* Displays about page.
*
* @return string
*/
public function actionAbout()
{
return $this->render('about');
}
}
<?php
namespace app\models;
use Yii;
use yii\base\Model;
/**
* LoginForm is the model behind the login form.
*
* @property User|null $user This property is read-only.
*
*/
class LoginForm extends Model
{
public $username;
public $password;
public $rememberMe = true;
private $_user = false;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}
/**
* Logs in a user using the provided username and password.
* @return bool whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
}
return false;
}
/**
* Finds user by [[username]]
*
* @return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findByUsername($this->username);
}
return $this->_user;
}
}
这是我根据建议添加的配置
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
任何帮助将不胜感激。谢谢
答案 0 :(得分:1)
这是因为这种方法:
public function validatePassword($password) {
return $this->password === sha1($password);
}
这是什么?这绝对是错的。它应该是:
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->password_hash);
}
编辑:并且setPassword方法应该是:
public function setPassword($password)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
}
答案 1 :(得分:0)
你有一个密码设置器,但没有getter,尝试为User类添加一个getter。
编辑(试试这个):
public function getPassword() {
return $this->password_hash;
}