Как сохраняется id пользователя в таблицу?

Всё про контроль доступа пользователей: фильтры, RBAC, проверки
Ответить
alexnew2000
Сообщения: 104
Зарегистрирован: 2015.10.04, 09:47

Как сохраняется id пользователя в таблицу?

Сообщение alexnew2000 »

Здравствуйте .
Настроил rbac по инструкции http://krivochenko.ru/blog/post/rbac-in-yii2-users

Проблема в том что поле author_id - не заполняется после сохранения. Но если вручную через phpmyadmin занести Id в таблицу - то правила brac работают. А от этого и не могу делать Update записи.

О пользователе которым тестил- зарегистрировал вручную и через панель пользователей добавил роль аuthor

Таблица
id int(11)
name varchar(255)
text text
id_tezis int(11)
url varchar(255)
author_id
модель

Код: Выделить всё

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "reshenie".
 *
 * @property integer $id
 * @property string $name
 * @property string $text
 * @property integer $id_tezis
 */
class Reshenie extends \yii\db\ActiveRecord
{
    
     public $image;
    public $gallery;
    
        public function behaviors()
    {
        return [
            'image' => [
                'class' => 'rico\yii2images\behaviors\ImageBehave',
            ]
        ];
    }
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'reshenie';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'id_tezis'], 'required'],
            [['text' ], 'string'],
            [['id_tezis' , 'author_id'], 'integer'],
            [['name' ,'url'], 'string', 'max' => 255],
             [['image'], 'file', 'extensions' => 'png, jpg'],
            [['gallery'], 'file', 'extensions' => 'png, jpg', 'maxFiles' => 4],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Название',
            'text' => 'Текст',
            'id_tezis' => 'Id Tezis',
            'url' => 'Ссылка',
            'image' => 'Фото',
            'gallery' => 'Галерея',
        ];
    }
        public function upload(){
        if($this->validate()){
            $path = 'upload/store/' . $this->image->baseName . '.' . $this->image->extension;
            $this->image->saveAs($path);
            $this->attachImage($path, true);
            @unlink($path);
            return true;
        }else{
            return false;
        }
    }

    public function uploadGallery(){
        if($this->validate()){
            foreach($this->gallery as $file){
                $path = 'upload/store/' . $file->baseName . '.' . $file->extension;
                $file->saveAs($path);
                $this->attachImage($path);
                @unlink($path);
            }
            return true;
        }else{
            return false;
        }
    }
}
Контроллер

Код: Выделить всё

namespace app\controllers;

use Yii;
use app\models\Reshenie;
use app\models\ReshenieSearch;
use app\models\Resheniestat;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\data\ActiveDataProvider;
use yii\web\UploadedFile;
use yii\helpers\Url;
//это для brak
use yii\filters\AccessControl;

/**
 * ReshenieController implements the CRUD actions for Reshenie model.
 */
class ReshenieController extends Controller
{
     private $_model = false;
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        
     return [
        'access' => [
            'class' => AccessControl::className(),
            'only' => ['index', 'create', 'view', 'update', 'delete'],
            'rules' => [
                [
                    'allow' => true,
                    'actions' => ['index'],
                    'roles' => ['articleRead'],
                ],
                [
                    'allow' => true,
                    'actions' => ['create'],
                    'roles' => ['articleCreate'],
                ],
                [
                    'allow' => true,
                    'actions' => ['view'],
                    'roles' => ['articleRead'],
                ],
                [
                    'allow' => true,
                    'actions' => ['update'],
                    'matchCallback' => function ($rule, $action) {
                        return Yii::$app->user->can('articleUpdate', ['article' => $this->findModel(Yii::$app->request->get('id'))]);
                    }
                ],
                [
                    'allow' => true,
                    'actions' => ['delete'],
                    'matchCallback' => function ($rule, $action) {
                        return Yii::$app->user->can('articleDelete', ['article' => $this->findModel(Yii::$app->request->get('id'))]);
                    }
                ],
            ],
        ],
    ];    
      /*  return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ]; */
    }

    /**
     * Lists all Reshenie models.
     * @return mixed
     */
    public function actionIndex($id_tezis)
    {
    //    echo 111; die();
        
        $searchModel = new ReshenieSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams, $id_tezis);

    /*    $query = ReshenieSearch::find()->where(['id_tezis' => $id_tezis]);
        $dataProvider = new ActiveDataProvider([
            'query' => $query
        ]); */
        
       return $this->renderAjax('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]); 
         /*return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);*/ 
    }

    /**
     * Displays a single Reshenie model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->renderAjax('view', [
            'model' => $this->findModel($id),
        ]);
    }


    /**
     * Updates an existing Reshenie 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()) {           
            
              $model->image = UploadedFile::getInstance($model, 'image');

            if( $model->image ){
                $model->upload();
            }
            unset($model->image);
            $model->gallery = UploadedFile::getInstances($model, 'gallery');
            $model->uploadGallery();
            Yii::$app->session->setFlash('success', "Решение обновлено");      
            //$success=true;
           // return json_encode($success);
        } 
        
        if( Yii::$app->request->isAjax ){
            return $this->renderAjax('update', [
            'model' => $model,
            ]);    
        }else{
             return $this->render('update', [
            'model' => $model,
            ]);
        }
           
        
    }

 

....
 
    
     protected function findModel($id)
    {
        if ($this->_model === false) {
            $this->_model = Reshenie::findOne($id);
        }
        if ($this->_model !== null) {
            return $this->_model;
        }
        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
файл isAuthorRule

Код: Выделить всё

namespace app\rbac;
use yii\rbac\Rule;
use Yii;
class IsAuthorRule extends Rule
{
    public $name = 'isAuthorRule';
    public function execute($user, $item, $params)
    {
        if (!isset($params['article'])) {
            return false;
        }
        return ($params['article']->author_id == $user);
    }
} 
alexnew2000
Сообщения: 104
Зарегистрирован: 2015.10.04, 09:47

Re: Как сохраняется id пользователя в таблицу?

Сообщение alexnew2000 »

Добавил в контроллер id пользователя похоже на костыл, но вроде работает.

Код: Выделить всё

    
 public function actionCreate()
    {
        $model = new Reshenie();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $model->author_id=\Yii::$app->user->identity->id;
            $model->save();
 
Loveorigami
Сообщения: 977
Зарегистрирован: 2014.08.27, 21:54

Re: Как сохраняется id пользователя в таблицу?

Сообщение Loveorigami »

Если нужен author_id - используйте поведение Blameable из коробки
http://www.yiiframework.com/doc-2.0/yii ... avior.html
alexnew2000
Сообщения: 104
Зарегистрирован: 2015.10.04, 09:47

Re: Как сохраняется id пользователя в таблицу?

Сообщение alexnew2000 »

Loveorigami писал(а):Если нужен author_id - используйте поведение Blameable из коробки
http://www.yiiframework.com/doc-2.0/yii ... avior.html
Спасибо!! Это решение получше моего будет!
Drugpunker
Сообщения: 187
Зарегистрирован: 2014.08.13, 19:44

Re: Как сохраняется id пользователя в таблицу?

Сообщение Drugpunker »

Loveorigami писал(а): 2016.11.27, 21:20 Если нужен author_id - используйте поведение Blameable из коробки
http://www.yiiframework.com/doc-2.0/yii ... avior.html
Вчера ночью сидел писал поведение на основе TimestampBehavior, с мыслью "Почему не реализовано тоже самое для user udated и created at из коробки" :)
Случайно наткнулся на эту тему сегодня.
Сравнил варианты.
Стало радостно, что они совпадают.
Стало грустно, что решение уже существовало. :)
Ответить