Yii2 rest api with bearer auth - php

I created the api structure/config and it works but now i need to set it up with bearer authentication and every GET request i send to the api (with Authentication Bearer XXXXXXXXXXXX) gives me a 401 error:
{"name":"Unauthorized","message":"Your request was made with invalid credentials.","code":0,"status":401,"type":"yii\\web\\UnauthorizedHttpException"}
Sorry about the length of this question with all snippets but i tried several changes, read all what i found here about this with no success and im starting to lose control on this. What could i be missing?
My app uses the advanced template with the next folder structure (the same as in all howtos ive read):
> -api
> --config
> --main.php
> --params.php
> --modules
> --v1
> --controllers
> --OrdersController.php
> --models
> --Orders.php
> --Module.php
> --web
> --index.php
> -backend
> -common
> -frontend...
api/config/main.php
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php')
//require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-api',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'modules' => [
'v1' => [
'basePath' => '#app/modules/v1',
'class' => 'api\modules\v1\Module'
]
],
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => false,
'enableSession' => false,
'loginUrl' =>'',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'v1/countries',
'tokens' => [
'{id}' => '<id:\\w+>'
]
],
[
'class' => 'yii\rest\UrlRule',
'controller' => 'v1/orders',
'tokens' => [
'{id}' => '<id:\\w+>'
]
]
],
]
],
'params' => $params,
];
api/config/params.php
<?php
return [
'adminEmail' => 'admin#domain.com',
];
api/modules/v1/Module.php
<?php
namespace api\modules\v1;
class Module extends \yii\base\Module
{
public $controllerNamespace = 'api\modules\v1\controllers';
public function init()
{
parent::init();
\Yii::$app->user->enableSession = false;
}
}
api/modules/v1/controllers/OrdersController.php
<?php
namespace api\modules\v1\controllers;
use yii\rest\ActiveController;
use yii\web\Response;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBasicAuth;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;
class OrdersController extends ActiveController
{
public $modelClass = 'api\modules\v1\models\Orders';
public function actions() // Just read only rest api
{
$actions = parent::actions();
unset($actions['delete'], $actions['create'], $actions['update']);
return $actions;
}
public function behaviors() {
$behaviors = parent::behaviors();
$behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
$behaviors['authenticator'] = [
//'class' => HttpBasicAuth::className(),
'class' => HttpBearerAuth::className(),
//'class' => QueryParamAuth::className(),
];
return $behaviors;
}
}
common/models/User.php
<?php
namespace common\models;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
/**
* User model
*
* #property integer $id
* #property string $username
* #property string $password_hash
* #property string $password_reset_token
* #property string $email
* #property string $auth_key
* #property integer $status
* #property integer $created_at
* #property integer $updated_at
* #property string $password write-only password
*/
class User extends ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
/**
* #inheritdoc
*/
public static function tableName()
{
return '{{%user}}';
}
/**
* #inheritdoc
*/
public function behaviors()
{
return [
TimestampBehavior::className(),
];
}
/**
* #inheritdoc
*/
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
];
}
/**
* #inheritdoc
*/
public static function findIdentity($id)
{
return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
//throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
return static::findOne(['auth_key' => $token]);
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username)
{
return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
}
/**
* Finds user by password reset token
*
* #param string $token password reset token
* #return static|null
*/
public static function findByPasswordResetToken($token)
{
if (!static::isPasswordResetTokenValid($token)) {
return null;
}
return static::findOne([
'password_reset_token' => $token,
'status' => self::STATUS_ACTIVE,
]);
}
/**
* Finds out if password reset token is valid
*
* #param string $token password reset token
* #return boolean
*/
public static function isPasswordResetTokenValid($token)
{
if (empty($token)) {
return false;
}
$timestamp = (int) substr($token, strrpos($token, '_') + 1);
$expire = Yii::$app->params['user.passwordResetTokenExpire'];
return $timestamp + $expire >= time();
}
/**
* #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 Yii::$app->security->validatePassword($password, $this->password_hash);
}
/**
* Generates password hash from password and sets it to the model
*
* #param string $password
*/
public function setPassword($password)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
}
/**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
}
/**
* Generates new password reset token
*/
public function generatePasswordResetToken()
{
$this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
}
/**
* Removes password reset token
*/
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
}
Thank you in advance,

After checking this question i was able to find what was happening. Just added
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
to api/web/.htaccess and it works
Is this the best approach?

Related

Search Filtering users by FK in gridview

I have users table containing : PK - id, username, password.
i have three tables ( laptop, display, phone) - id - FK, series, model
I have userequipmentmapping table containing : id - PK , user_id - FK( id from users table), laptop_id - FK (id from laptop table), phone_id - FK (id from phone table), display_id(id from dislpay table), start_date, end_date.
I want to search by user in my gridview from UserEquipmentMapping, but don't know where should i implement the search model, considering the username is passed from the users table by foreign key.
If you have any suggestions are appreciated. Thank You in advance !
Controller :
<?php
namespace app\controllers;
use Yii;
use app\models\UserEquipmentMapping;
use app\models\UserequipmentmappingSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\models\User;
use app\models\Laptop;
use app\models\Phone;
use app\models\Display;
/**
* UserequipmentmappingController implements the CRUD actions for UserEquipmentMapping model.
*/
class UserequipmentmappingController extends Controller
{
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all UserEquipmentMapping models.
* #return mixed
*/
public function actionIndex()
{
$usermodel = new UserEquipmentMapping();
$userquery = $usermodel->getUsers();
$displaymodel = new UserEquipmentMapping();
$displayquery = $displaymodel->getDisplays();
$phonemodel = new UserEquipmentMapping();
$phonequery = $phonemodel->getPhones();
$laptopmodel = new UserEquipmentMapping();
$laptopquery = $laptopmodel->getLaptops();
#foreach($query as $q)
# print_r($q);
#
# die;
$searchModel = new UserequipmentmappingSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'userquery' => $userquery,
'displayquery' => $displayquery,
'laptopquery'=> $laptopquery,
'phonequery'=> $phonequery,
]);
}
/**
* Displays a single UserEquipmentMapping model.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new UserEquipmentMapping model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new UserEquipmentMapping();
$usermodel = User::find()->all();
$laptopmodel = Laptop::find()->all();
$phonemodel = Phone::find()->all();
$displaymodel = Display::find()->all();
#print_r(Yii::$app->request->post()); die;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
'usermodel' => $usermodel,
'laptopmodel' => $laptopmodel,
'phonemodel' => $phonemodel,
'displaymodel' => $displaymodel,
]);
}
/**
* Updates an existing UserEquipmentMapping model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
$usermodel = User::find()->all();
$laptopmodel = Laptop::find()->all();
$phonemodel = Phone::find()->all();
$displaymodel = Display::find()->all();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
'usermodel' => $usermodel,
'laptopmodel' => $laptopmodel,
'phonemodel' => $phonemodel,
'displaymodel' => $displaymodel,
]);
}
/**
* Deletes an existing UserEquipmentMapping model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the UserEquipmentMapping model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return UserEquipmentMapping the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = UserEquipmentMapping::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
}
Model :
<?php
namespace app\models;
use Yii;
use app\models\User;
use app\models\UserQuery;
use yii\db\ActiveQuery;
/**
* This is the model class for table "user_equipment_mapping".
*
* #property int $id
* #property int $user_id
* #property int|null $laptop_id
* #property int|null $phone_id
* #property int|null $display_id
* #property string|null $start_date
* #property string|null $stop_date
*
* #property Display $display
* #property Laptop $laptop
* #property Phone $phone
* #property User $user
*/
class UserEquipmentMapping extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'user_equipment_mapping';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['user_id'], 'required'],
[['user_id', 'laptop_id', 'phone_id', 'display_id'], 'integer'],
[['start_date', 'stop_date'], 'safe'],
[['display_id'], 'exist', 'skipOnError' => true, 'targetClass' => Display::className(), 'targetAttribute' => ['display_id' => 'id']],
[['laptop_id'], 'exist', 'skipOnError' => true, 'targetClass' => Laptop::className(), 'targetAttribute' => ['laptop_id' => 'id']],
[['phone_id'], 'exist', 'skipOnError' => true, 'targetClass' => Phone::className(), 'targetAttribute' => ['phone_id' => 'id']],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'user_id' => 'User ID',
'laptop_id' => 'Laptop ID',
'phone_id' => 'Phone ID',
'display_id' => 'Display ID',
'start_date' => 'Start Date',
'stop_date' => 'Stop Date',
];
}
/**
* Gets query for [[Display]].
*
* #return \yii\db\ActiveQuery|DisplayQuery
*/
public function getDisplay()
{
return $this->hasOne(Display::className(), ['id' => 'display_id']);
}
/**
* Gets query for [[Laptop]].
*
* #return \yii\db\ActiveQuery|LaptopQuery
*/
public function getLaptop()
{
return $this->hasOne(Laptop::className(), ['id' => 'laptop_id']);
}
/**
* Gets query for [[Phone]].
*
* #return \yii\db\ActiveQuery|PhoneQuery
*/
public function getPhone()
{
return $this->hasOne(Phone::className(), ['id' => 'phone_id']);
}
/**
* Gets query for [[User]].
*
* #return \yii\db\ActiveQuery|UserQuery
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
public function getUsers()
{
return $this->hasMany(User::className(),['user_id', 'id']);
}
public function getLaptops()
{
return $this->hasMany(Laptop::className(),['laptop_id', 'id']);
}
public function getDisplays()
{
return $this->hasMany(Display::className(),['dislpay_id', 'id']);
}
public function getPhones()
{
return $this->hasMany(Phone::className(),['phone_id', 'id']);
}
/**
* {#inheritdoc}
* #return UserEquipmentMappingQuery the active query used by this AR class.
*/
public static function find()
{
return new UserEquipmentMappingQuery(get_called_class());
}
}
ModelSearch :
<?php
namespace app\models;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\UserEquipmentMapping;
/**
* UserequipmentmappingSearch represents the model behind the search form of `app\models\UserEquipmentMapping`.
*/
class UserequipmentmappingSearch extends UserEquipmentMapping
{
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['id', 'user_id', 'laptop_id', 'phone_id', 'display_id'], 'integer'],
[['start_date', 'stop_date'], 'safe'],
];
}
/**
* {#inheritdoc}
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$query = UserEquipmentMapping::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'user_id' => $this->user_id,
'laptop_id' => $this->laptop_id,
'phone_id' => $this->phone_id,
'display_id' => $this->display_id,
'start_date' => $this->start_date,
'stop_date' => $this->stop_date,
]);
return $dataProvider;
}
}
Index :
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $searchModel app\models\UserequipmentmappingSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'User Equipment Mappings';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="user-equipment-mapping-index">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Create User Equipment Mapping', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'formatter' => [
'class' => 'yii\i18n\Formatter',
'nullDisplay' => '-',],
'columns' => [
['class' => 'yii\grid\SerialColumn'],
#'id',
'user.username',
#'laptop.laptop_model',
'laptop.laptop_series',
#'laptop_id',
#'phone.phone_model',
'phone.phone_series',
#'phone_id',
#'display.display_model',
'display.display_series',
#'display_id',
'start_date',
'stop_date',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
Uncomment in your index view _search view. There are all fields from UserequipmentmappingSearch model. You can replace input fields with select fields for user, laptop and etc. Search model will do the other thing, all is in search function that fills your dataprovider

Show Related Data in View Yii 2

I'm new in Yii 2, and I'm creating an inventory system for the library of my school, but I had a problem.
First, I have a relation like this:
I want to show all the adqs (a unique number for each book - that way we don't need to capture the book again for every copy) of a book in his view, but only the adqs related to the book id obviously at the bottom.
My View:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $model app\models\Libros */
/* #var $searchModel app\models\LibrosSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = $model->lib_titulo;
$this->params['breadcrumbs'][] = ['label' => 'Libros', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="libros-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Modificar', ['update', 'id' => $model->lib_id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Borrar', ['delete', 'id' => $model->lib_id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<div class="row" align="center">
<?php
if ($model->lib_image_web_filename!='') {
echo '<br /><p><img width="500" src="'.Url::to('#web/', true). '/uploads/libros/'.$model->lib_image_web_filename.'"></p>';
}
?>
</div>
<div class="row" style="
text-align: center;
font: normal normal bold 15px/1 'lato';
color: rgba(7,7,7,1);
text-align: center;
">
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'lib_id',
'lib_titulo',
'lib_autor',
//'lib_edicion',
'editorialNombre',
'ubicacionNombre',
'lib_isbn',
'lib_clasificacion',
'lib_seccion',
//'lib_image_src_filename',
//'lib_image_web_filename',
],
]) ?>
</div>
</div>
My Controller (LibrosController):
<?php
namespace backend\controllers;
use Yii;
use app\models\Libros;
use app\models\LibrosSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
/**
* LibrosController implements the CRUD actions for Libros model.
*/
class LibrosController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Libros models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new LibrosSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Libros model.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionCreate()
{
$model = new Libros();
if ($model->load(Yii::$app->request->post())) {
$image = UploadedFile::getInstance($model, 'image');
if (!is_null($image)) {
$model->lib_image_src_filename = $image->name;
$ext = end((explode(".", $image->name)));
// generate a unique file name to prevent duplicate filenames
$model->lib_image_web_filename = Yii::$app->security->generateRandomString().".{$ext}";
// the path to save file, you can set an uploadPath
// in Yii::$app->params (as used in example below)
Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/web/uploads/libros/';
$path = Yii::$app->params['uploadPath'] . $model->lib_image_web_filename;
$image->saveAs($path);
}
if ($model->save()) {
return $this->redirect(['view', 'id' => $model->lib_id]);
} else {
var_dump ($model->getErrors()); die();
}
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing Libros model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())) {
$image = UploadedFile::getInstance($model, 'image');
if (!is_null($image)) {
$model->lib_image_src_filename = $image->name;
$ext = explode(".", $image->name);
$ext_final = end($ext);
// generate a unique file name to prevent duplicate filenames
$model->lib_image_web_filename = Yii::$app->security->generateRandomString().".{$ext_final}";
// the path to save file, you can set an uploadPath
// in Yii::$app->params (as used in example below)
Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/web/uploads/libros/';
$path = Yii::$app->params['uploadPath'] . $model->lib_image_web_filename;
$image->saveAs($path);
}
if ($model->save()) {
return $this->redirect(['view', 'id' => $model->lib_id]);
} else {
var_dump ($model->getErrors()); die();
}
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Deletes an existing Libros model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Libros model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Libros the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Libros::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
}
My Model (Libros.php):
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "libros".
*
* #property int $lib_id
* #property string $lib_titulo
* #property string $lib_autor
* #property string $lib_edicion
* #property int $lib_ubi
* #property int $lib_editorial_id
* #property string $lib_isbn
* #property string $lib_clasificacion
* #property string $lib_seccion
* #property string $lib_image_src_filename
* #property string $lib_image_web_filename
*
* #property Adq[] $adqs
* #property Editorial $libEditorial
* #property Ubicacion $libUbi
* #property LibrosCarreras[] $librosCarreras
* #property Carreras[] $licCarreras
*/
class Libros extends \yii\db\ActiveRecord
{
const PERMISSIONS_PRIVATE = 10;
const PERMISSIONS_PUBLIC = 20;
public $image;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'libros';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['lib_titulo', 'lib_autor', 'lib_ubi', 'lib_isbn', 'lib_clasificacion', 'lib_seccion', 'lib_image_src_filename', 'lib_image_web_filename'], 'required'],
[['lib_ubi', 'lib_editorial_id'], 'integer'],
[['lib_titulo'], 'string', 'max' => 120],
[['lib_autor', 'lib_clasificacion'], 'string', 'max' => 64],
//[['lib_edicion'], 'string', 'max' => 3],
[['lib_isbn'], 'string', 'max' => 32],
[['lib_seccion'], 'string', 'max' => 2],
[['lib_editorial_id'], 'exist', 'skipOnError' => true, 'targetClass' => Editorial::className(), 'targetAttribute' => ['lib_editorial_id' => 'edi_id']],
[['lib_ubi'], 'exist', 'skipOnError' => true, 'targetClass' => Ubicacion::className(), 'targetAttribute' => ['lib_ubi' => 'ubil_id']],
[['lib_image_src_filename', 'lib_image_web_filename'], 'string', 'max' => 100],
[['image'], 'safe'],
[['image'], 'file', 'extensions'=>'jpg, gif, png'],
[['image'], 'file', 'maxSize'=>'1000000'],
[['lib_image_src_filename', 'lib_image_web_filename'], 'string', 'max' => 255], ];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'lib_id' => 'ID',
'lib_titulo' => 'Titulo',
'lib_autor' => 'Autor',
//'lib_edicion' => 'Edicion',
'lib_editorial_id' => 'Editorial',
'lib_isbn' => 'ISBN',
'lib_clasificacion' => 'Clasificacion',
'lib_ubi' => 'Ubicacion',
'lib_seccion' => 'Seccion',
'image' => 'Captura',
'lib_image_src_filename' => Yii::t('app', 'Nombre de Archivo'),
'lib_image_web_filename' => Yii::t('app', 'Nombre del Directorio'),
'editorialNombre' => 'Editorial',
'ubicacionNombre' => 'Ubicacion',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getAdqs()
{
return $this->hasMany(Adq::className(), ['adq_libro_id' => 'lib_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
/**
* #return \yii\db\ActiveQuery
*/
public function getLibrosCarreras()
{
return $this->hasMany(LibrosCarreras::className(), ['lic_libros_id' => 'lib_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getEditorial0()
{
return $this->hasOne(Editorial::className(), ['edi_id' => 'lib_editorial_id']);
}
public function getEditorialNombre()
{
return $this->editorial0->edi_nombre;
}
public function getLibUbi()
{
return $this->hasOne(Ubicacion::className(), ['ubil_id' => 'lib_ubi']);
}
public function getUbicacionNombre()
{
return $this->libUbi->ubil_nombre; }
}
My Search Model (LibrosSearch.php):
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Libros;
/**
* LibrosSearch represents the model behind the search form of `app\models\Libros`.
*/
class LibrosSearch extends Libros
{
public $editorialNombre;
public $ubicacionNombre;
/**
* #inheritdoc
*/
public function rules()
{
return [
[['lib_id', 'lib_ubi', 'lib_editorial_id'], 'integer'],
[['lib_titulo', 'lib_autor', 'lib_isbn', 'lib_clasificacion', 'lib_seccion', 'lib_image_src_filename', 'lib_image_web_filename'], 'safe'],
[['editorialNombre'],'safe'],
[['ubicacionNombre'],'safe'],
];
}
/**
* #inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$query = Libros::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->setSort([
'attributes'=>[
'editorialNombre'=>[
'asc'=>['editorial.edi_nombre'=>SORT_ASC],
'desc'=>['editorial.edi_nombre'=>SORT_DESC],
'label'=>'Editorial Nombre'
]
]
]);
$dataProvider->setSort([
'attributes'=>[
'ubicacionNombre'=>[
'asc'=>['ubicacion.ubil_nombre'=>SORT_ASC],
'desc'=>['ubicacion.ubil_nombre'=>SORT_DESC],
'label'=>'Ubicacion Nombre'
]
]
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'lib_id' => $this->lib_id,
'lib_ubi' => $this->lib_ubi,
'lib_editorial_id' => $this->lib_editorial_id,
]);
$query->andFilterWhere(['like', 'lib_titulo', $this->lib_titulo])
->andFilterWhere(['like', 'lib_autor', $this->lib_autor])
//->andFilterWhere(['like', 'lib_edicion', $this->lib_edicion])
->andFilterWhere(['like', 'lib_isbn', $this->lib_isbn])
->andFilterWhere(['like', 'lib_clasificacion', $this->lib_clasificacion])
->andFilterWhere(['like', 'lib_seccion', $this->lib_seccion])
->andFilterWhere(['like', 'lib_image_src_filename', $this->lib_image_src_filename])
->andFilterWhere(['like', 'lib_image_web_filename', $this->lib_image_web_filename]);
$query->joinWith(['editorial0'=>function($q)//creamos un nuevo filtro
{
$q->where('editorial.edi_nombre LIKE "%' . $this->editorialNombre . '%"');
}]);
$query->joinWith(['libUbi'=>function($q)//creamos un nuevo filtro
{
$q->where('ubicacion.ubil_nombre LIKE "%' . $this->ubicacionNombre . '%"');
}]);
return $dataProvider;
}
}
How can I accomplish this task?
[
'attribute' => 'adq_libro_id',
'value' => implode(', ', \yii\helpers\ArrayHelper::map($model->Adqs, 'id',
function ( $model )
{
return $model['adq'];
}
)),
'format' => 'raw'
],
try like this. Check the right name of attributes
In your model Libros.php you have this function.
public function getAdqs()
{
return $this->hasMany(Adq::className(), ['adq_libro_id' => 'lib_id']);
}
This means you can access the relations of Libros like:
// where $model is an instance of Libros
$model->adqs->property_name
Or as a function
$model->getAdqs();

issue with Yii 2 framework

I was trying to make a blog with YII2, my framework is confusing to call data from database.
For example when I call "username" from "user" table,
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'user.fullname', --->> Yii2 is thinking that this is a category and not a user table
'title',
'description',
'content:html',
'count_view',
'status',
'created_at',
],
]) ?>
I am getting this error: -->> unknown property: app\models\Category::fullname
please could you help me to solve this issue, where I did make a mistake?
and here is my post model contains:
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "post".
*
* #property integer $id
* #property integer $user_id
* #property string $title
* #property string $description
* #property string $content
* #property integer $count_view
* #property string $status
* #property string $created_at
*
* #property User $user
* #property TagAssign[] $tagAssigns
*/
class Post extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'post';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['user_id', 'count_view','category_id'], 'integer'],
[['content', 'status'], 'string'],
[['created_at'], 'safe'],
[['count_view'], 'default','value'=>0],
[['user_id'], 'default','value'=>Yii::$app->user->id],
[['title', 'description'], 'string', 'max' => 255],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'user_id' => 'User ID',
'title' => 'Title',
'description' => 'Description',
'content' => 'Content',
'category' => 'Category',
'count_view' => 'Count View',
'status' => 'Status',
'created_at' => 'Created At',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(Category::className(), ['id' => 'user_id']);
}
public function getCategory()
{
return $this->hasOne(User::className(), ['id' => 'category_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getTagAssigns()
{
return $this->hasMany(TagAssign::className(), ['post_id' => 'id']);
}
}
and here user Model:
<?php
namespace app\models;
use Yii;
use yii\web\IdentityInterface;
/**
* This is the model class for table "user".
*
* #property integer $id
* #property string $username
* #property string $password
* #property string $fullname
* #property string $status
* #property string $role
* #property string $created_At
*
* #property Post[] $posts
*/
class User extends \yii\db\ActiveRecord implements IdentityInterface
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'user';
}
public $current_password;
public $new_password;
public $confirm_password;
public $authKey;
/**
* #inheritdoc
*/
public function rules()
{
return [
[['status', 'role'], 'string'],
[['created_At'], 'safe'],
[['username', 'password', 'fullname'], 'string', 'max' => 45],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'username' => 'username',
'password' => 'password',
'fullname' => 'fullname',
'status' => 'Status',
'role' => 'Role',
'created_At' => 'Created At',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getPosts()
{
return $this->hasMany(Post::className(), ['user_id' => 'id']);
}
public static function findIdentity($id)
{
return static::findOne($id);
}
public static function findIdentityByAccessToken($token,$type=null)
{
return static::findOne(['access_token'=>$token]);
}
public function getId()
{
return $this->id;
}
public function getAuthKey()
{
return $this->authKey;
}
public function validateAuthKey($authKey)
{
return $this->authKey == $authKey;
}
public static function findByUsername($username)
{
return static::findOne(['username'=>$username]);
}
public function validatePassword($password)
{
if(Yii::$app->security->validatePassword($password,$this->password))
{
return true;
} else {
return false;
}
}
}
Change to this in Post model.
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'category_id']);
}
public function getCategory()
{
return $this->hasOne(Category::className(), ['id' => 'user_id']);
}

How to get session data and put in a dropDownList in Yii 2?

I'm new in StackOverflow and also new using the framework Yii 2, and I need to get session data and put in a create and update form using the _form.php from a view called Planficacion, but when I try to use this line of code in the form:
<?= $form->field($model, 'rutProfesor')->dropDownList(ArrayHelper::getvalue(Yii::$app->user->identity->rutProfesor,'nombreProfesor')) ?>
Return this error: PHP Warning – yii\base\ErrorException. Invalid argument supplied for foreach()
I need to get the value of 'nombreProfesor' from a model called Profesor, and the relation of both Planificacion and Profesor is 'rutProfesor' and I want to show in the dropDownList only the 'nombreProfesor' of the actual session.
There are the codes from:
Profesor Model (Profesor.php)
<?php
namespace common\models;
use Yii;
class Profesor extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'profesor';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['rutProfesor'], 'required'],
[['nombreProfesor', 'apellidoProfesor', 'escuelaProfesor'], 'string', 'max' => 45],
[['rutProfesor', 'claveProfesor'], 'string', 'max' => 15],
[['rol'], 'string', 'max' => 2],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'nombreProfesor' => 'Nombre Profesor',
'apellidoProfesor' => 'Apellido Profesor',
'escuelaProfesor' => 'Escuela',
'rutProfesor' => 'Rut',
'claveProfesor' => 'Clave Profesor',
'rol' => 'Rol',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getPlanificacions()
{
return $this->hasMany(Planificacion::className(), ['rutProfesor' => 'rutProfesor']);
}
}
Planificacion Model (planificacion.php)
<?php
namespace common\models;
use Yii;
class Planificacion extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'planificacion';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['fecha', 'fechaRevision', 'fechaPlanificacion'], 'safe'],
[['objetivosPlanificacion', 'actividad1', 'actividad2', 'actividad3', 'actividad4', 'obsActividad1', 'obsActividad2', 'obsActividad3', 'obsActividad4', 'contenidoActividad1', 'contenidoActividad2', 'contenidoActividad3', 'contenidoActividad4'], 'string'],
[['rutProfesor'], 'string', 'max' => 15],
[['nombreSesion', 'recursosUtilizadosPlanificacion', 'estadoActividad1', 'estadoActividad2', 'estadoActividad3', 'estadoActividad4', 'evalActividad1', 'evalActividad2', 'evalActividad3', 'evalActividad4', 'nombreSupervisor', 'asistencia'], 'string', 'max' => 255],
[['estado', 'rutSupervisor'], 'string', 'max' => 30],
[['rutProfesor'], 'exist', 'skipOnError' => true, 'targetClass' => Profesor::className(), 'targetAttribute' => ['rutProfesor' => 'rutProfesor']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'idPlanificacion' => 'Id Planificacion',
'rutProfesor' => 'Nombre Profesor',
'fecha' => 'Fecha',
'nombreSesion' => 'Nombre Sesion',
'objetivosPlanificacion' => 'Objetivos Planificacion',
'recursosUtilizadosPlanificacion' => 'Recursos Utilizados Planificacion',
'actividad1' => 'Actividad1',
'actividad2' => 'Actividad2',
'actividad3' => 'Actividad3',
'actividad4' => 'Actividad4',
'estadoActividad1' => 'Estado Actividad1',
'estadoActividad2' => 'Estado Actividad2',
'estadoActividad3' => 'Estado Actividad3',
'estadoActividad4' => 'Estado Actividad4',
'obsActividad1' => 'Obs Actividad1',
'obsActividad2' => 'Obs Actividad2',
'obsActividad3' => 'Obs Actividad3',
'obsActividad4' => 'Obs Actividad4',
'contenidoActividad1' => 'Contenido Actividad1',
'contenidoActividad2' => 'Contenido Actividad2',
'contenidoActividad3' => 'Contenido Actividad3',
'contenidoActividad4' => 'Contenido Actividad4',
'evalActividad1' => 'Eval Actividad1',
'evalActividad2' => 'Eval Actividad2',
'evalActividad3' => 'Eval Actividad3',
'evalActividad4' => 'Eval Actividad4',
'estado' => 'Estado',
'fechaRevision' => 'Fecha Revision',
'rutSupervisor' => 'Rut Supervisor',
'fechaPlanificacion' => 'Fecha Planificacion',
'nombreSupervisor' => 'Nombre Supervisor',
'asistencia' => 'Asistencia',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getAsistencias()
{
return $this->hasMany(Asistencia::className(), ['idPlanificacion' => 'idPlanificacion']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getRutProfesor0()
{
return $this->hasOne(Profesor::className(), ['rutProfesor' => 'rutProfesor']);
}
}
User Model (User.php)
<?php
namespace common\models;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;
class User extends ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
const ROLE_SUPERVISOR = 1;
const ROL_PROFESOR = 2;
public $authKey;
/** #inheritdoc
/**
*/
public static function tableName()
{
return 'profesor';
}
/**
* #inheritdoc
*/
public function behaviors()
{
return [
TimestampBehavior::className(),
];
}
/**
* #inheritdoc
*/
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
];
}
/**
* #inheritdoc
*/
public static function findIdentity($rutProfesor)
{
return static::findOne(['rutProfesor' => $rutProfesor]);
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($rutProfesor)
{
return static::findOne(['rutProfesor' => $rutProfesor]);
}
/**
* Finds user by password reset token
*
* #param string $token password reset token
* #return static|null
*/
public static function findByPasswordResetToken($token)
{
if (!static::isPasswordResetTokenValid($token)) {
return null;
}
return static::findOne([
'password_reset_token' => $token,
'status' => self::STATUS_ACTIVE,
]);
}
/**
* Finds out if password reset token is valid
*
* #param string $token password reset token
* #return bool
*/
public static function isPasswordResetTokenValid($token)
{
if (empty($token)) {
return false;
}
$timestamp = (int) substr($token, strrpos($token, '_') + 1);
$expire = Yii::$app->params['user.passwordResetTokenExpire'];
return $timestamp + $expire >= time();
}
/**
* #inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}
/**
* #inheritdoc
*/
public function getAuthKey()
{
return $this->authKey;
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
/**
* Validates password
*
* #param string $password password to validate
* #return bool if password provided is valid for current user
*/
public function validatePassword($claveProfesor)
{
return $this->claveProfesor === $claveProfesor;
}
/**
* Generates password hash from password and sets it to the model
*
* #param string $password
*/
public function setPassword($password)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
}
/**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
}
/**
* Generates new password reset token
*/
public function generatePasswordResetToken()
{
$this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
}
/**
* Removes password reset token
*/
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
public function isUserSimple($rutProfesor)
{
if(static::findOne(['rutProfesor' => $rutProfesor, 'rol' => 2]))
{
return true;
} else {
return false;
}
}
public function isUserAdmin($rutProfesor)
{
if(static::findOne(['rutProfesor' => $rutProfesor, 'rol' => 1]))
{
return true;
} else {
return false;
}
}
}
Planificacion Controller (planificacionController.php)
<?php
namespace frontend\controllers;
use Yii;
use common\models\Planificacion;
use common\models\PlanificacionSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* PlanificacionController implements the CRUD actions for Planificacion model.
*/
class PlanificacionController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Planificacion models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new PlanificacionSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Planificacion model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Planificacion model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Planificacion();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->idPlanificacion]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Planificacion model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->idPlanificacion]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Planificacion model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Planificacion model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Planificacion the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Planificacion::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
First, why you getting the error, is because ArrayHelper::getValue() require an array as first parameter, as it's purpose is to
Retrieves the value of an array element or object property with the
given key or property name.
And Yii::$app->user->identity->rutProfesor wouldn't yield an array, no, it would yield an single string, which is current rutProfessor in the session.
Then, on how you create the dropDownList you wanted, i suggest using an ArrayHelper::map() which is more straightfoward.
<?= $form->field($model, 'rutProfesor')->dropDownList(ArrayHelper::map(Profesor::find()->where([
'rutProfesor' => Yii::$app->user->identity->rutProfesor
])->all(), 'rutProfesor', 'nombreProfesor'); ?>
I beleive that code will do you good.
Happy coding. :)

Yii2 AccessControl

I am new in Yii2 and I try to make AccessControl and success
but the problem is after I success for login and redirect to other page
my Identity _attributes always are null.So if I check with Yii::$app->user->isGuest the return value is always true
this is my LoginHandler.php
<?php
namespace app\models;
use Yii;
use yii\base\Model;
/**
* Login form
*/
class LoginHandler extends Model
{
public $user_name;
public $user_password;
public $rememberMe = true;
private $_user;
/**
* #inheritdoc
*/
public function rules()
{
return [
[['user_name', 'user_password'], 'required'],
[['user_name', 'user_password'], 'string', 'max' => 100],
['user_password','authenticate'],
];
}
public function authenticate($attribute, $params){
// return true;
}
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
} else {
return false;
}
}
protected function getUser()
{
if ($this->_user === null) {
$this->_user = User::findByUsername($this->user_name);
}
return $this->_user;
}
}
LoginController
<?php
namespace backend\controllers;
use Yii;
use app\models\user;
use app\models\LoginHandler;
class LoginController extends \yii\web\Controller
{
public function actionIndex()
{
return $this->render('index');
}
public function actionSignin(){
$user = User::findByUsername('admin');
$model = new LoginHandler();
if(Yii::$app->request->post()){
$data = Yii::$app->request->post();
$model->attributes = $data;
if ($model->login()) {
return $this->redirect(['/user/test']);
}else{
die('test');
}
}
return $this->render('login');
}
}
My User.php as model
namespace app\models;
use Yii;
/**
* This is the model class for table "user".
*
* #property integer $user_id
* #property string $user_name
* #property string $user_password
*/
class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface{
public $id;
public $authKey;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'user';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['user_name', 'user_password'], 'required'],
[['user_name', 'user_password'], 'string', 'max' => 100]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'user_id' => 'User ID',
'user_name' => 'User Name',
'user_password' => 'User Password',
];
}
public static function findIdentity($id)
{
return static::findOne($id);
}
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['access_token' => $token]);
}
public function getId()
{
return $this->id;
}
public function getAuthKey()
{
return $this->authKey;
}
public function validateAuthKey($authKey)
{
return $this->authKey === $authKey;
}
public static function findByUsername($username){
return static::findOne(['user_name' => $username]);
}
}
and the last is my configuration main.php
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-backend',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'backend\controllers',
'bootstrap' => ['log'],
'modules' => [],
'components' => [
'user' => [
'identityClass' => 'backend\models\User',
'loginUrl' => ['login/signin'],
'enableAutoLogin' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
],
'params' => $params,
];
Thanks in advance.
You mentioned AccessControl in your question. In Yii2 AccessControl is the special behavior class to manage access rules inside controller:
http://www.yiiframework.com/doc-2.0/yii-filters-accesscontrol.html
and I don't see AccessControl in you code.
Anyway.
Most probably the problem is in your implementation of User class.
Looking at your code I can imagine that the table structure is: user_id (PK), user_name, user_password.
If so, then the method getId() returns variable
($this->id) which is never initialized. But this method is used by Yii to store current user in session. In your case it should return $this->user_id.
And if you wish to make remember me working, you should implement correctly getAuthKey and validateAuthKey too.
Here is details:
http://www.yiiframework.com/doc-2.0/guide-security-authentication.html
If this not helps, then show your table structure and code of view which pass authentication data to LoginController
It looks you should check for
Yii::$app->user->identity

Categories