Reputation: 21
I had tried a lot to make a user login through my module. But always failed. Neither it shows a error nor it logged in to the application. So far i have tried this.
My module/moduleName/moduleName.php
init function is
public function init()
{
parent::init();
// custom initialization code goes here
Yii::$app->set('user', [
'class' => 'yii\web\User',
'identityClass' => 'app\module\modulesName\models\UserTable',
'enableAutoLogin' => false,
'loginUrl' => ['moduleName/default/login'],
'identityCookie' => ['name' => 'module', 'httpOnly' => true],
'idParam' => 'id', //this is important !
]);
Yii::$app->set('session', [
'class' => 'yii\web\Session',
'name' => '_adminSessionId',
]);
}
Now my Loginform
in app\module\moduleName\models\LoginForm
is
<?php
namespace app\modules\moduleName\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 = UserTable::findByUsername($this->username);
}
return $this->_user;
}
}
Finally my model for login in app\module\moduleName\models\UserTable
is
<?php
namespace app\modules\moduleName\models;
use Yii;
/**
* @property integer $id
* @property string $fullName
* @property string $email
* @property string $password
* @property string $authkey
* @property string $accessToken
* @property integer $authStatus
*/
class UserTable extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'usertable';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['fullName', 'email', 'password'], 'required'],
[['authStatus'], 'integer'],
[['fullName', 'email', 'password'], 'string', 'max' => 50],
[['authkey', 'accessToken'], 'string', 'max' => 75],
// [['fullName', 'password'], 'unique', 'targetAttribute' => ['fullName', 'password'], 'message' => 'The combination of Full Name and Password has already been taken.'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'fullName' => 'Full Name',
'email' => 'Email',
'password' => 'Password',
'authkey' => 'Authkey',
'accessToken' => 'Access Token',
'authStatus' => 'Auth Status',
];
}
/**
* @return \yii\db\ActiveQuery
*/
// User login Codes
public function getId()
{
return $this->id;
}
/**
* @inheritdoc
*/
public function getAuthKey()
{
return $this->authKey;
}
/**
* @inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->authKey === $authKey;
}
/**
* Validates password
*
* @param string $password password to validate
* @return bool if password provided is valid for current user
*/
public function validatePassword($password)
{
return $this->password ===($password);
}
public static function findIdentity($id)
{
return static::findOne($id);
}
public static function findIdentityByAccessToken($token,$type=null)
{
return $this->accessToken;
}
public static function findbyUsername($uname)
{
return self::find()->where(['email' => $uname])->one();
}
}
At the end my defaultcontroller in module is
public function actionIndex()
{
if (!Yii::$app->user->isGuest){
var_dump('a');
exit();
return $this->render('index');
} else {
return $this->redirect(['login']);
}
}
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) ) {
return $this->redirect(['index']);
}
return $this->render('login', [
'model' => $model,
]);
}
I do not know how the app is not logged in. I had tried for 3 days now and i did not get any solution on this problem. It neither shows me error nor it get logged in ? How can I log in to different user instance in yii2 ?
Upvotes: 2
Views: 192
Reputation: 465
Create seperate config.php in your module directory, then add It into inject it into your app. Here is code. Just confugure config.php as you want
return [
'id' => 'api',
'basePath' => dirname(__DIR__),
//....
'components' => [
//..
'user' => [
//....
]
],
];
In your module class just do like that.
public function init()
{
parent::init();
\Yii::configure($this, require __DIR__ . '/config.php');
}
Thats all.
Upvotes: 1