Warning: Cannot use a scalar value as an array in /home/admin/public_html/forum/include/fm.class.php on line 757

Warning: Invalid argument supplied for foreach() in /home/admin/public_html/forum/include/fm.class.php on line 770

Warning: Invalid argument supplied for foreach() in /home/admin/public_html/forum/topic.php on line 737
Форумы портала PHP.SU :: RBAC в Yii2 привязка ролей к пользователю-почему нет доступа?

 PHP.SU

Программирование на PHP, MySQL и другие веб-технологии
PHP.SU Портал     На главную страницу форума Главная     Помощь Помощь     Поиск Поиск     Поиск Яндекс Поиск Яндекс     Вакансии  Пользователи Пользователи


 Страниц (1): [1]   

> Описание: yii2 advanced
Vladim
Отправлено: 13 Сентября, 2017 - 17:10:28
Post Id


Новичок


Покинул форум
Сообщений всего: 4
Дата рег-ции: Сент. 2017  


Помог: 0 раз(а)




Привет всем!

Не могу разобраться с RBAC

1.Почему-то во fronted у меня нет регистрации, и вкладка Signup не открывается-
только 'login' - но зарегистрироваться нельзя.
В backend -тоже - ошибка 404 и открывается ссылка http://admin[dot]site[dot]com/site/register[dot]html
т.е. значит сервер не нашел страницу, куда его послали. Очень странный путь: site/register.html , Как настроить урл менеджер, и где? на .html ?

Как сделать доступ к админке только для админа и контент-менеджера? А на fronted - регистрацию доступной для всех?

Какой экшен нужно создать и где?

Куда нужно добавить это исключение?
PHP:
скопировать код в буфер обмена
  1. 'except' => ['login','error','register'],

site\yii2\\backend\controllers\Site Controllers



PHP:
скопировать код в буфер обмена
  1.  
  2. <?PHP
  3. namespace backend\controllers;
  4.  
  5. use Yii;
  6. use yii\web\Controller;
  7. use yii\filters\VerbFilter;
  8. use yii\filters\AccessControl;
  9. use common\models\LoginForm;
  10. use yii\base\DynamicModel;
  11. use vova07\imperavi\Widget;
  12. use yii\base\Action;
  13. use yii\base\InvalidCallException;
  14. use yii\base\InvalidConfigException;
  15. use yii\helpers\FileHelper;
  16. use yii\web\BadRequestHttpException;
  17. use yii\web\Response;
  18. use yii\web\UploadedFile;
  19. use yii\helpers\Url;
  20. use yii\widgets\ActiveForm;
  21. use kartik\widgets\FileInput;
  22. use common\models\Person;
  23. use common\models\ImageManager;
  24.  
  25.  
  26.  
  27.  
  28. /**
  29.  * Site controller
  30.  */
  31. class SiteController extends Controller
  32. {
  33.     /**
  34.      * @inheritdoc
  35.      */
  36.     public function behaviors()
  37.     {
  38.         return [
  39.             'access' => [
  40.                 'class' => AccessControl::className(),
  41.                 'rules' => [
  42.  
  43.                     [
  44.                         'actions'=> ['index'],
  45.                         'allow' => true,
  46.                         'roles' => ['canAdmin','admin'],
  47.  
  48.                     ],
  49.                     [
  50.                         'actions' => ['login', 'error'],
  51.                         'allow' => true,
  52.                     ],
  53.                     [
  54.                       'actions' => ['logout','save-redactor-img','save-img'],
  55.                       'allow' => true,
  56.                       'roles' => ['@'],
  57.                         ],
  58.                     ],
  59.               ],
  60.             'verbs' => [
  61.                 'class' => VerbFilter::className(),
  62.                 'actions' => [
  63.                     'logout' => ['post'],
  64.                 ],
  65.             ],
  66.         ];
  67.     }
  68.  
  69.     /**
  70.      * @inheritdoc
  71.      */
  72.     public function actions()
  73.     {
  74.         return [
  75.             'error' => [
  76.                 'class' => 'yii\web\ErrorAction',
  77.             ],
  78.         ];
  79.     }
  80.  
  81.     /**
  82.      * Displays homepage.
  83.      *
  84.      * @return string
  85.      */
  86.     public function actionIndex()
  87.     {
  88.         return $this->render('index');
  89.     }
  90.  
  91.     /**
  92.      * Login action.
  93.      *
  94.      * @return string
  95.      */
  96.     public function actionLogin()
  97.     {
  98.         if (!Yii::$app->user->isGuest) {
  99.             return $this->goHome();
  100.         }
  101.  
  102.         $model = new LoginForm();
  103.         if ($model->load(Yii::$app->request->post()) && $model->login()) {
  104.             return $this->goBack();
  105.         } else {
  106.             return $this->render('login', [
  107.                 'model' => $model,
  108.             ]);
  109.         }
  110.     }
  111.  
  112.     /**
  113.      * Logout action.
  114.      *
  115.      * @return string
  116.      */
  117.     public function actionLogout()
  118.     {
  119.         Yii::$app->user->logout();
  120.  
  121.         return $this->goHome();
  122.     }
  123.  
  124.  
  125.  
  126. public function actionSaveRedactorImg ($sub='main')
  127.  {
  128.         $this -> enableCsrfValidation = false;
  129.         if (Yii::$app->request->isPost) {
  130.         $dir = Yii::getAlias ('@images') .'/'.$sub.'/';
  131.         if (!file_exists($dir)){
  132.             FileHelper::createDirectory($dir);
  133.         }
  134.  
  135.  
  136.         $result_link = str_replace('admin.','',Url::home(true)).'uploads/images/'.$sub.'/';
  137.         $file = UploadedFile::getInstanceByName('file');
  138.         $model = new DynamicModel (compact ('file'));
  139.         $model ->addRule ('file', 'image')->validate();
  140.  
  141.         if ($model->hasErrors()) {
  142.  
  143.             $result = [
  144.             'error' => $model -> getFirstError ('file')
  145.             ];
  146.         } else {
  147.               $model->file->name = strtotime('now').'_'.Yii::$app->getSecurity()->generateRandomString(6) . '.' . $model->file->extension;
  148.  
  149.             if ($model->file->saveAs ($dir . $model->file->name)) {
  150.               $imag = Yii::$app->image->load($dir . $model->file->name);
  151.                 $imag -> resize (800, NULL, Yii\image\drivers\Image::PRECISE)
  152.                 ->save($dir . $model->file->name, 85);
  153.  
  154.                 $result = [
  155.                 'filelink' => $result_link . $model->file->name,'filename'=>$model->file->name];
  156.  
  157.         } else {
  158.  
  159.             $result = [
  160.             'error' => Yii::t ('vova07/imperavi', 'ERROR_CAN_NOT_UPLOAD_FILE')
  161.             ];
  162.  
  163.         }
  164.        
  165.     }
  166.              Yii::$app->response->format = Response::FORMAT_JSON;
  167.  
  168.             return $result;
  169.              } else {
  170.                 throw new BadRequestHttpException ('Only Post is allowed');
  171.               }
  172.          }
  173.      
  174.  
  175.  
  176.  public function actionSaveImg ()
  177.      
  178.         {
  179.  
  180.         $this -> enableCsrfValidation = false;
  181.         if (Yii::$app->request->isPost) {
  182.             $post = Yii::$app->request->post();
  183.  
  184.         $dir = Yii::getAlias ('@images') .'/'.$post['ImageManager']['class'].'/';
  185.         if (!file_exists($dir)){
  186.             FileHelper::createDirectory($dir);
  187.         }
  188.  
  189.  
  190.         $result_link = str_replace('admin.','',Url::home(true)).'uploads/images/'.$post['class'].'/';
  191.         $file = UploadedFile::getInstanceByName('ImageManager[attachment]');
  192.         $model = new ImageManager();
  193.         $model->name = strtotime('now').'_'.Yii::$app->getSecurity()->generateRandomString(6) . '.' . $file->extension;
  194.         $model ->load($post);
  195.         $model->validate();
  196.  
  197.          if ($model->hasErrors()) {
  198.  
  199.             $result = [
  200.             'error' => $model -> getFirstError ('file')
  201.             ];
  202.         } else {
  203.            if ($file->saveAs($dir . $model->name)) {
  204.               $imag = Yii::$app->image->load($dir . $model->name);
  205.                 $imag -> resize (800, NULL, Yii\image\drivers\Image::PRECISE)
  206.                 ->save($dir . $model->name, 85);
  207.  
  208.                 $result = [
  209.                 'filelink' => $result_link . $model->name,'filename'=>$model->name];
  210.  
  211.         } else {
  212.  
  213.             $result = [
  214.             'error' => 'ошибка'
  215.             ];
  216.  
  217.         }
  218.  
  219.         $model->save();
  220.    
  221. }
  222.       Yii::$app->response->format = Response::FORMAT_JSON;
  223.  
  224.             return $result;
  225.              } else {
  226.                 throw new BadRequestHttpException ('Only Post is allowed');
  227.               }
  228.          }
  229.      }
  230.  
  231.  
  232.  





site\yii2\common\config\main.pgp

PHP:
скопировать код в буфер обмена
  1. <?PHP
  2. return [
  3.     'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
  4.     'timeZone' => 'Europe/Moscow',
  5.     'components' => [
  6.         'cache' => [
  7.             'class' => 'yii\caching\FileCache',
  8.             /* 'robotEmail' => '',*/
  9.             /*'robotName' => 'Robot'*/
  10.         ],
  11.            
  12.          'image' => [
  13.                         'class' => 'yii\image\ImageDriver',
  14.                         'driver' => 'GD',  //GD or Imagick
  15.                         ],
  16.                
  17.         'authManager' => [
  18.             'class' => 'yii\rbac\DbManager',
  19.             'cache' => 'cache'
  20.         ],
  21.    
  22.     ],
  23.     'on beforeAction' => function($event){ //цепляемся за событие перед запуском экшена
  24.       Yii::$app->controller->attachBehavior('',[ //цепляем к текущему контролеру поведение
  25.           'class' => \yii\filters\AccessControl::className(), //указываем класс поведения
  26.           'except' => ['login','error'], //исключим из правила экшены login и error, так как они должны быть доступны всем
  27.           'rules' => [
  28.               [
  29.                   'allow' => true, //разрешаем доступ
  30.                   'roles' => ['admin'], //'@' только зарегистрированным пользователям или замените на 'admin',  что бы только админам позволить
  31.               ],
  32.           ],
  33.       ]);
  34.     },
  35. ];


В main.php добавлен такой менеджер:
PHP:
скопировать код в буфер обмена
  1. 'authManager' => [
  2.             'class' => 'yii\rbac\DbManager',
  3.             'cache' => 'cache'
  4.         ],


Пользователи и таблицы с миграциями создались, настройку ролей и permission сделана в TagController (yii2\backend\controllers)

PHP:
скопировать код в буфер обмена
  1. <?PHP
  2.  
  3. namespace backend\controllers;
  4.  
  5. use Yii;
  6. use common\models\Tag;
  7. use common\models\TagSearch;
  8. use yii\web\Controller;
  9. use yii\web\NotFoundHttpException;
  10. use yii\filters\VerbFilter;
  11. use yii\filters\AccessControl;
  12.  
  13. /**
  14.  * TagController implements the CRUD actions for Tag model.
  15.  */
  16. class TagController extends Controller
  17. {
  18.     /**
  19.      * @inheritdoc
  20.      */
  21.    public function behaviors()
  22.     {
  23.         return [
  24.             'access' => [
  25.                 'class' => AccessControl::className(),
  26.                 'rules' => [
  27.                     [
  28.                         'allow' => true,
  29.                         'roles' => ['admin'],
  30.                     ],
  31.                 ],
  32.             ],
  33.         ];
  34.     }
  35.  
  36.     /* public function behaviors()
  37.     {
  38.         return [
  39.             'verbs' => [
  40.                 'class' => VerbFilter::className(),
  41.                 'actions' => [
  42.                     'delete' => ['POST'],
  43.                 ],
  44.             ],
  45.         ];
  46.     }*/
  47.  
  48.                        
  49.                 /**
  50.      * Lists all Tag models.
  51.      * @return mixed
  52.      */
  53.     public function actionIndex()
  54.     {
  55.         $searchModel = new TagSearch();
  56.         $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
  57.  
  58.         return $this->render('index', [
  59.             'searchModel' => $searchModel,
  60.             'dataProvider' => $dataProvider,
  61.         ]);
  62.     }
  63.  
  64.     /**
  65.      * Displays a single Tag model.
  66.      * @param integer $id
  67.      * @return mixed
  68.      */
  69.     public function actionView($id)
  70.     {
  71.         return $this->render('view', [
  72.             'model' => $this->findModel($id),
  73.         ]);
  74.     }
  75.  
  76.     /**
  77.      * Creates a new Tag model.
  78.      * If creation is successful, the browser will be redirected to the 'view' page.
  79.      * @return mixed
  80.      */
  81.     public function actionCreate()
  82.     {
  83.         $model = new Tag();
  84.  
  85.         if ($model->load(Yii::$app->request->post()) && $model->save()) {
  86.             return $this->redirect(['view', 'id' => $model->id]);
  87.         } else {
  88.             return $this->render('create', [
  89.                 'model' => $model,
  90.             ]);
  91.         }
  92.     }
  93.  
  94.     /**
  95.      * Updates an existing Tag model.
  96.      * If update is successful, the browser will be redirected to the 'view' page.
  97.      * @param integer $id
  98.      * @return mixed
  99.      */
  100.     public function actionUpdate($id)
  101.     {
  102.         $model = $this->findModel($id);
  103.  
  104.         if ($model->load(Yii::$app->request->post()) && $model->save()) {
  105.             return $this->redirect(['view', 'id' => $model->id]);
  106.         } else {
  107.             return $this->render('update', [
  108.                 'model' => $model,
  109.             ]);
  110.         }
  111.     }
  112.  
  113.     /**
  114.      * Deletes an existing Tag model.
  115.      * If deletion is successful, the browser will be redirected to the 'index' page.
  116.      * @param integer $id
  117.      * @return mixed
  118.      */
  119.     public function actionDelete($id)
  120.     {
  121.         $this->findModel($id)->delete();
  122.  
  123.         return $this->redirect(['index']);
  124.     }
  125.  
  126.     /**
  127.      * Finds the Tag model based on its primary key value.
  128.      * If the model is not found, a 404 HTTP exception will be thrown.
  129.      * @param integer $id
  130.      * @return Tag the loaded model
  131.      * @throws NotFoundHttpException if the model cannot be found
  132.      */
  133.     protected function findModel($id)
  134.     {
  135.         if (($model = Tag::findOne($id)) !== null) {
  136.             return $model;
  137.         } else {
  138.             throw new NotFoundHttpException('The requested page does not exist.');
  139.         }
  140.     }
  141.  
  142.  
  143.     public function actionRole() {
  144.  
  145.       /*  $admin = Yii::$app->authManager->createRole ('admin');
  146.         $admin->description = 'Администратор';
  147.         Yii::$app->authManager ->add ($admin);
  148.  
  149.         $content = Yii::$app->authManager->createRole ('content');
  150.         $content ->description = 'Контент менеджер';
  151.         Yii::$app->authManager->add ($content);
  152.  
  153.         $user = Yii::$app->authManager->createRole ('user');
  154.         $user ->description = 'Пользователь';
  155.         Yii::$app->authManager ->add($user);
  156.        
  157.         $ban = Yii::$app->authManager->createRole ('banned');
  158.         $ban ->description ='Tварь';
  159.         Yii::$app->authManager->add($ban);*/
  160.      
  161.        /* $permit = Yii::$app->authManager->createPermission('canAdmin');
  162.         $permit ->description = 'Право входа в админку';
  163.          Yii::$app->authManager ->add ($permit);*/
  164.  
  165.        /* $role_a = Yii::$app->authManager->getRole ('admin');
  166.         $role_c = Yii::$app->authManager->getRole ('content');
  167.         $permit = Yii:: $app->authManager ->getPermission ('canAdmin');
  168.         Yii::$app->authManager->addChild ($role_a, $permit);
  169.         Yii::$app->authManager->addChild ($role_c, $permit);*/
  170.        
  171.         $userRole = Yii::$app->authManager->getRole('admin');
  172.         Yii::$app->authManager->assign($userRole, 1);
  173.  
  174.         return 12345;
  175.  
  176.      }
  177. }
  178.  

Прикреплено изображение (Нажмите для увеличения)
auau.jpg

(Отредактировано автором: 13 Сентября, 2017 - 17:50:10)

 
 Top
andrewkard
Отправлено: 14 Сентября, 2017 - 11:17:05
Post Id


Участник


Покинул форум
Сообщений всего: 1372
Дата рег-ции: Нояб. 2014  


Помог: 30 раз(а)




Vladim пишет:
1.Почему-то во fronted у меня нет регистрации, и вкладка Signup не открывается-
только 'login' - но зарегистрироваться нельзя.

Во frontend/controllers нужен контроллер SiteController.php c методом actionSignup и в папке frontend/views/site нужно представление signup.php
(Добавление)
Vladim пишет:
В backend -тоже - ошибка 404 и открывается ссылка http://admin[dot]site[dot]com/site/register[dot]html
т.е. значит сервер не нашел страницу, куда его послали. Очень странный путь: site/register.html

если нужно, то аналогично SiteController actionRegister
(Добавление)
Vladim пишет:
Как сделать доступ к админке только для админа и контент-менеджера? А на fronted - регистрацию доступной для всех?

https://habrahabr[dot]ru/post/235485/
(Добавление)
https://yiiframework[dot]com[dot]ua/ru/d[dot][dot][dot]y-authorization/
 
 Top
Vladim
Отправлено: 14 Сентября, 2017 - 17:56:37
Post Id


Новичок


Покинул форум
Сообщений всего: 4
Дата рег-ции: Сент. 2017  


Помог: 0 раз(а)




Цитата:
Во frontend/controllers нужен контроллер SiteController.php c методом actionSignup и в папке frontend/views/site нужно представление signup.php
(Добавле


Так у меня во fronted уже есть такой метод и представление sign.up

SiteController (fronted)

PHP:
скопировать код в буфер обмена
  1. <?PHP
  2. namespace frontend\controllers;
  3.  
  4. use medeyacom\blog\models\Blog;
  5. use Yii;
  6. use yii\base\InvalidParamException;
  7. use yii\web\BadRequestHttpException;
  8. use yii\web\Controller;
  9. use yii\filters\VerbFilter;
  10. use yii\filters\AccessControl;
  11. use common\models\LoginForm;
  12. use frontend\models\PasswordResetRequestForm;
  13. use frontend\models\ResetPasswordForm;
  14. use frontend\models\SignupForm;
  15. use frontend\models\ContactForm;
  16.  
  17. /**
  18.  * Site controller
  19.  */
  20. class SiteController extends Controller
  21. {
  22.     /**
  23.      * @inheritdoc
  24.      */
  25.     public function behaviors()
  26.     {
  27.         return [
  28.             'access' => [
  29.                 'class' => AccessControl::className(),
  30.                 'only' => ['logout', 'signup'],
  31.                 'rules' => [
  32.                     [
  33.                         'actions' => ['signup'],
  34.                         'allow' => true,
  35.                         'roles' => ['?'],
  36.                     ],
  37.                     [
  38.                         'actions' => ['logout'],
  39.                         'allow' => true,
  40.                         'roles' => ['@'],
  41.                     ],
  42.                 ],
  43.             ],
  44.             'verbs' => [
  45.                 'class' => VerbFilter::className(),
  46.                 'actions' => [
  47.                     'logout' => ['post'],
  48.                 ],
  49.             ],
  50.         ];
  51.     }
  52.  
  53.     /**
  54.      * @inheritdoc
  55.      */
  56.     public function actions()
  57.     {
  58.         return [
  59.             'error' => [
  60.                 'class' => 'yii\web\ErrorAction',
  61.             ],
  62.             'captcha' => [
  63.                 'class' => 'yii\captcha\CaptchaAction',
  64.                 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
  65.             ],
  66.         ];
  67.     }
  68.  
  69.     /**
  70.      * Displays homepage.
  71.      *
  72.      * @return mixed
  73.      */
  74.     public function actionIndex()
  75.     {
  76.         #$blogs = Blog::find()->where(['status_id'=>1])->orderBy(['id' => SORT_DESC])->all();
  77.  
  78.        $blogs = Blog::find()->andWhere(['status_id'=>1])->orderBy('sort')->all();
  79.         #$blogs = Blog::find()->where(['status_id'=>1])->orderBy(['id' => SORT_ASC])->all();
  80.  
  81.  
  82.         return $this->render('index',['blogs'=>$blogs]);
  83.     }
  84.  
  85.     /**
  86.      * Logs in a user.
  87.      *
  88.      * @return mixed
  89.      */
  90.     public function actionLogin()
  91.     {
  92.         if (!Yii::$app->user->isGuest) {
  93.             return $this->goHome();
  94.         }
  95.  
  96.         $model = new LoginForm();
  97.         if ($model->load(Yii::$app->request->post()) && $model->login()) {
  98.             return $this->goBack();
  99.         } else {
  100.             return $this->render('login', [
  101.                 'model' => $model,
  102.             ]);
  103.         }
  104.     }
  105.  
  106.     /**
  107.      * Logs out the current user.
  108.      *
  109.      * @return mixed
  110.      */
  111.     public function actionLogout()
  112.     {
  113.         Yii::$app->user->logout();
  114.  
  115.         return $this->goHome();
  116.     }
  117.  
  118.     /**
  119.      * Displays contact page.
  120.      *
  121.      * @return mixed
  122.      */
  123.     public function actionContact()
  124.     {
  125.         $model = new ContactForm();
  126.         if ($model->load(Yii::$app->request->post()) && $model->validate()) {
  127.             if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
  128.                 Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
  129.             } else {
  130.                 Yii::$app->session->setFlash('error', 'There was an error sending your message.');
  131.             }
  132.  
  133.             return $this->refresh();
  134.         } else {
  135.             return $this->render('contact', [
  136.                 'model' => $model,
  137.             ]);
  138.         }
  139.     }
  140.  
  141.     /**
  142.      * Displays about page.
  143.      *
  144.      * @return mixed
  145.      */
  146.     public function actionAbout()
  147.     {
  148.         return $this->render('about');
  149.     }
  150.  
  151.     /**
  152.      * Signs user up.
  153.      *
  154.      * @return mixed
  155.      */
  156.     public function actionSignup()
  157.     {
  158.         $model = new SignupForm();
  159.         if ($model->load(Yii::$app->request->post())) {
  160.             if ($user = $model->signup()) {
  161.                 if (Yii::$app->getUser()->login($user)) {
  162.                     return $this->goHome();
  163.                 }
  164.             }
  165.         }
  166.  
  167.         return $this->render('signup', [
  168.             'model' => $model,
  169.         ]);
  170.     }
  171.  
  172.     /**
  173.      * Requests password reset.
  174.      *
  175.      * @return mixed
  176.      */
  177.     public function actionRequestPasswordReset()
  178.     {
  179.         $model = new PasswordResetRequestForm();
  180.         if ($model->load(Yii::$app->request->post()) && $model->validate()) {
  181.             if ($model->sendEmail()) {
  182.                 Yii::$app->session->setFlash('success', 'Check your email for further instructions.');
  183.  
  184.                 return $this->goHome();
  185.             } else {
  186.                 Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for the provided email address.');
  187.             }
  188.         }
  189.  
  190.         return $this->render('requestPasswordResetToken', [
  191.             'model' => $model,
  192.         ]);
  193.     }
  194.  
  195.     /**
  196.      * Resets password.
  197.      *
  198.      * @param string $token
  199.      * @return mixed
  200.      * @throws BadRequestHttpException
  201.      */
  202.     public function actionResetPassword($token)
  203.     {
  204.         try {
  205.             $model = new ResetPasswordForm($token);
  206.         } catch (InvalidParamException $e) {
  207.             throw new BadRequestHttpException($e->getMessage());
  208.         }
  209.  
  210.         if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
  211.             Yii::$app->session->setFlash('success', 'New password saved.');
  212.  
  213.             return $this->goHome();
  214.         }
  215.  
  216.         return $this->render('resetPassword', [
  217.             'model' => $model,
  218.         ]);
  219.     }
  220. }
  221.  


signup (fronted)


PHP:
скопировать код в буфер обмена
  1. <?PHP
  2.  
  3. /* @var $this yii\web\View */
  4. /* @var $form yii\bootstrap\ActiveForm */
  5. /* @var $model \frontend\models\SignupForm */
  6.  
  7. use yii\helpers\Html;
  8. use yii\bootstrap\ActiveForm;
  9.  
  10. $this->title = 'Signup';
  11. $this->params['breadcrumbs'][] = $this->title;
  12. ?>
  13. <div class="site-signup">
  14.     <h1><?= Html::encode($this->title) ?></h1>
  15.  
  16.     <p>Пожалуйста, заполните следующие поля для регистрации.:</p>
  17.  
  18.     <div class="row">
  19.         <div class="col-lg-5">
  20.             <?PHP $form = ActiveForm::begin(['id' => 'form-signup']); ?>
  21.  
  22.                 <?= $form->field($model, 'username')->textInput(['autofocus' => true]) ?>
  23.  
  24.                 <?= $form->field($model, 'email') ?>
  25.  
  26.                 <?= $form->field($model, 'password')->passwordInput() ?>
  27.  
  28.                 <div class="form-group">
  29.                     <?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
  30.                 </div>
  31.  
  32.             <?PHP ActiveForm::end(); ?>
  33.         </div>
  34.     </div>
  35. </div>
  36.  

(Добавление)
Цитата:

если нужно, то аналогично SiteController actionRegister


т.е. нужен файл Register.php в yii2\fronted\views\site ? и что в нем должно быть?

Ссылка 404 /register.html' - куда я попадаю, чтобы работала, значит надо сделать экшен Register в SiteController (backend) и сделать к нему ссылку? И как сделать ссылку?

site\yii2\common\config\main.pgp есть исключение :
PHP:
скопировать код в буфер обмена
  1. 'except' => ['login','error','register']


Его добавление открывает доступ всем пользователям к экшену 'register' в контролере. Другой вопрос: как привести туда пользователя? И ошибка (на скрине) именно об этом говорит. "unable to resolve request"
Поэтому, получается разница между site/register и site/register.html куда я пытаюсь попасть. Ошибка, как я понимаю, не в отсутствии прав доступа, а в том, что yii не знает в какой контролер и какой экшен я пытаюсь попасть(
Прикреплено изображение (Нажмите для увеличения)
au9.jpg

(Отредактировано автором: 14 Сентября, 2017 - 18:17:00)

 
 Top
andrewkard
Отправлено: 15 Сентября, 2017 - 16:37:10
Post Id


Участник


Покинул форум
Сообщений всего: 1372
Дата рег-ции: Нояб. 2014  


Помог: 30 раз(а)




Vladim пишет:
Ссылка 404 /register.html' - куда я попадаю, чтобы работала, значит надо сделать экшен Register в SiteController (backend) и сделать к нему ссылку? И как сделать ссылку?


/site/register

в котроллере SiteController метод actionRegister,
в нем обработка поста и рендер register
а в register - нужная форма
 
 Top
Vladim
Отправлено: 15 Сентября, 2017 - 18:34:55
Post Id


Новичок


Покинул форум
Сообщений всего: 4
Дата рег-ции: Сент. 2017  


Помог: 0 раз(а)




Цитата:

в котроллере SiteController метод actionRegister,


Пробовал разные варианты, но что здесь не так?

Вот SiteController (backend)

PHP:
скопировать код в буфер обмена
  1. <?PHP
  2. namespace backend\controllers;
  3.  
  4. use Yii;
  5. use yii\web\Controller;
  6. use yii\filters\VerbFilter;
  7. use yii\filters\AccessControl;
  8. use common\models\LoginForm;
  9. use yii\base\DynamicModel;
  10. use vova07\imperavi\Widget;
  11. use yii\base\Action;
  12. use yii\base\InvalidCallException;
  13. use yii\base\InvalidConfigException;
  14. use yii\helpers\FileHelper;
  15. use yii\web\BadRequestHttpException;
  16. use yii\web\Response;
  17. use yii\web\UploadedFile;
  18. use yii\helpers\Url;
  19. use yii\widgets\ActiveForm;
  20. use kartik\widgets\FileInput;
  21. use common\models\Person;
  22. use common\models\ImageManager;
  23.  
  24.  
  25.  
  26.  
  27. /**
  28.  * Site controller
  29.  */
  30. class SiteController extends Controller
  31. {
  32.     /**
  33.      * @inheritdoc
  34.      */
  35.     public function behaviors()
  36.     {
  37.         return [
  38.             'access' => [
  39.                 'class' => AccessControl::className(),
  40.                 'rules' => [
  41.  
  42.                     [
  43.                         'actions'=> ['index'],
  44.                         'allow' => true,
  45.                         'roles' => ['canAdmin'],
  46.  
  47.  
  48.                     ],
  49.                     [
  50.                         'actions' => ['login', 'error'],
  51.                         'allow' => true,
  52.                        
  53.                     ],
  54.                     [
  55.                       'actions' => ['logout','save-redactor-img','save-img'],
  56.                       'allow' => true,
  57.                       'roles' => ['@'],
  58.                         ],
  59.                     ],
  60.               ],
  61.             'verbs' => [
  62.                 'class' => VerbFilter::className(),
  63.                 'actions' => [
  64.                     'logout' => ['post'],
  65.                 ],
  66.             ],
  67.         ];
  68.     }
  69.  
  70.     /**
  71.      * @inheritdoc
  72.      */
  73.     public function actions()
  74.     {
  75.         return [
  76.             'error' => [
  77.                 'class' => 'yii\web\ErrorAction',
  78.             ],
  79.         ];
  80.     }
  81.  
  82.     /**
  83.      * Displays homepage.
  84.      *
  85.      * @return string
  86.      */
  87.     public function actionIndex()
  88.     {
  89.         return $this->render('index');
  90.     }
  91.  
  92.     /**
  93.      * Login action.
  94.      *
  95.      * @return string
  96.      */
  97.     public function actionLogin()
  98.     {
  99.         if (!Yii::$app->user->isGuest) {
  100.             return $this->goHome();
  101.         }
  102.  
  103.         $model = new LoginForm();
  104.         if ($model->load(Yii::$app->request->post()) && $model->login()) {
  105.             return $this->goBack();
  106.         } else {
  107.             return $this->render('login', [
  108.                 'model' => $model,
  109.             ]);
  110.         }
  111.     }
  112.  
  113.     /**
  114.      * Logout action.
  115.      *
  116.      * @return string
  117.      */
  118.     public function actionLogout()
  119.     {
  120.         Yii::$app->user->logout();
  121.  
  122.         return $this->goHome();
  123.     }
  124.  
  125.  
  126.  
  127.  
  128.     public function actionRegister()
  129.     {
  130.         $model = new RegisterForm;
  131.        
  132.         if(!empty($_POST['RegisterForm']))
  133.         {
  134.             $model->attributes = $_POST['RegisterForm'];
  135.            
  136.             if($model->validate() && $model->register())
  137.                 $this->redirect($this->createUrl('site/index'));
  138.                
  139.         }
  140.        
  141.         $this->render('register', array('model'=>$model));
  142.     }
  143.    
  144.  
  145.  
  146.  
  147. /*public function actionRegister() {
  148.     $model = new RegisterForm;
  149.  
  150.  
  151. if(isset($_POST['RegisterForm']))
  152.     {
  153.         $model->attributes=$_POST['RegisterForm'];
  154.        
  155.         if($model->validate()){
  156.                     //send mail here ... then redirect
  157.  
  158.             $this->redirect(Yii::app()->user->returnUrl);
  159.              }
  160.  
  161.     }
  162.  
  163. $this->render('register',array('model'=>$model));
  164. }*/
  165.  
  166.  
  167.  /*public function actionRegister() {
  168.     $model = new RegisterForm;
  169.  
  170.     // if it is ajax validation request
  171.     if(isset($_POST['ajax']) && $_POST['ajax'] === 'register-form')
  172.     {
  173.         echo CActiveForm::validate($model);
  174.         app()->end();
  175.     }
  176.    
  177. }*/
  178.  
  179.  
  180. public function actionSaveRedactorImg ($sub='main')
  181.  {
  182.         $this -> enableCsrfValidation = false;
  183.         if (Yii::$app->request->isPost) {
  184.         $dir = Yii::getAlias ('@images') .'/'.$sub.'/';
  185.         if (!file_exists($dir)){
  186.             FileHelper::createDirectory($dir);
  187.         }
  188.  
  189.  
  190.         $result_link = str_replace('admin.','',Url::home(true)).'uploads/images/'.$sub.'/';
  191.         $file = UploadedFile::getInstanceByName('file');
  192.         $model = new DynamicModel (compact ('file'));
  193.         $model ->addRule ('file', 'image')->validate();
  194.  
  195.         if ($model->hasErrors()) {
  196.  
  197.             $result = [
  198.             'error' => $model -> getFirstError ('file')
  199.             ];
  200.         } else {
  201.               $model->file->name = strtotime('now').'_'.Yii::$app->getSecurity()->generateRandomString(6) . '.' . $model->file->extension;
  202.  
  203.             if ($model->file->saveAs ($dir . $model->file->name)) {
  204.               $imag = Yii::$app->image->load($dir . $model->file->name);
  205.                 $imag -> resize (800, NULL, Yii\image\drivers\Image::PRECISE)
  206.                 ->save($dir . $model->file->name, 85);
  207.  
  208.                 $result = [
  209.                 'filelink' => $result_link . $model->file->name,'filename'=>$model->file->name];
  210.  
  211.         } else {
  212.  
  213.             $result = [
  214.             'error' => Yii::t ('vova07/imperavi', 'ERROR_CAN_NOT_UPLOAD_FILE')
  215.             ];
  216.  
  217.         }
  218.        
  219.     }
  220.              Yii::$app->response->format = Response::FORMAT_JSON;
  221.  
  222.             return $result;
  223.              } else {
  224.                 throw new BadRequestHttpException ('Only Post is allowed');
  225.               }
  226.          }
  227.      
  228.  
  229.  
  230.  public function actionSaveImg ()
  231.      
  232.         {
  233.  
  234.         $this -> enableCsrfValidation = false;
  235.         if (Yii::$app->request->isPost) {
  236.             $post = Yii::$app->request->post();
  237.  
  238.         $dir = Yii::getAlias ('@images') .'/'.$post['ImageManager']['class'].'/';
  239.         if (!file_exists($dir)){
  240.             FileHelper::createDirectory($dir);
  241.         }
  242.  
  243.  
  244.         $result_link = str_replace('admin.','',Url::home(true)).'uploads/images/'.$post['class'].'/';
  245.         $file = UploadedFile::getInstanceByName('ImageManager[attachment]');
  246.         $model = new ImageManager();
  247.         $model->name = strtotime('now').'_'.Yii::$app->getSecurity()->generateRandomString(6) . '.' . $file->extension;
  248.         $model ->load($post);
  249.         $model->validate();
  250.  
  251.          if ($model->hasErrors()) {
  252.  
  253.             $result = [
  254.             'error' => $model -> getFirstError ('file')
  255.             ];
  256.         } else {
  257.            if ($file->saveAs($dir . $model->name)) {
  258.               $imag = Yii::$app->image->load($dir . $model->name);
  259.                 $imag -> resize (800, NULL, Yii\image\drivers\Image::PRECISE)
  260.                 ->save($dir . $model->name, 85);
  261.  
  262.                 $result = [
  263.                 'filelink' => $result_link . $model->name,'filename'=>$model->name];
  264.  
  265.         } else {
  266.  
  267.             $result = [
  268.             'error' => 'ошибка'
  269.             ];
  270.  
  271.         }
  272.  
  273.         $model->save();
  274.    
  275. }
  276.       Yii::$app->response->format = Response::FORMAT_JSON;
  277.  
  278.             return $result;
  279.              } else {
  280.                 throw new BadRequestHttpException ('Only Post is allowed');
  281.               }
  282.          }
  283.      }
  284.  
  285.  



RegistrForm (common/models)

PHP:
скопировать код в буфер обмена
  1.  
  2. <?PHP
  3. namespace common\models;
  4.  
  5. use yii\base\Model;
  6. use common\models\User;
  7.  
  8. /**
  9.  * Signup form
  10.  */
  11. class SignupForm extends Model
  12. {
  13.     public $username;
  14.     public $email;
  15.     public $password;
  16.  
  17.  
  18.     /**
  19.      * @inheritdoc
  20.      */
  21.  
  22.   public function rules()
  23.     {
  24.         return array(
  25.             array('email', 'password', 'required', 'message'=>'Поле обязательно для заполнения'),
  26.             array('email', 'email', 'message'=>'Неверный формат Email'),
  27.             array('password', 'compare', 'compareAttribute'=>'password2', 'message'=>'Пароли не совпадают'),
  28.         );
  29.     }
  30.  
  31.  
  32.    /* public function rules()
  33.     {
  34.         return [
  35.             ['username', 'trim'],
  36.             ['username', 'required'],
  37.             ['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
  38.             ['username', 'string', 'min' => 2, 'max' => 255],
  39.  
  40.             ['email', 'trim'],
  41.             ['email', 'required'],
  42.             ['email', 'email'],
  43.             ['email', 'string', 'max' => 255],
  44.             ['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],
  45.  
  46.             ['password', 'required'],
  47.             ['password', 'string', 'min' => 6],
  48.         ];
  49.     }
  50. */
  51.     /**
  52.      * Signs user up.
  53.      *
  54.      * @return User|null the saved model or null if saving fails
  55.      */
  56.  
  57.     public function attributeLabels () {
  58.         return [
  59.         'username' => 'Логин',
  60.         'password' => 'Пароль',
  61.         'email' => 'email',
  62.         ];
  63. }
  64.  
  65.  
  66.  
  67.   public function register()
  68.     {
  69.         if(!$this->hasError())
  70.         {
  71.            
  72.             //Добавляем в бд
  73.             $model = new User;
  74.             $model->user_email = $this->email;
  75.             $model->user_password = CPasswordHelper::hashPassword($this->password);
  76.             $model->save();
  77.            
  78.         }
  79.         else
  80.             return false;
  81.     }
  82. }
  83.  
  84.   /*  public function register()
  85.     {
  86.         if (!$this->validate()) {
  87.             return null;
  88.         }
  89.        
  90.         $user = new User();
  91.         $user->username = $this->username;
  92.         $user->email = $this->email;
  93.         $user->setPassword($this->password);
  94.         $user->generateAuthKey();
  95.        
  96.         return $user->save() ? $user : null;
  97.     }
  98. }*/
  99.  
  100.  
  101.  
  102.  
  103.  


registr.php (backend\views-site)

PHP:
скопировать код в буфер обмена
  1. <?PHP
  2.  
  3. /* @var $this yii\web\View */
  4. /* @var $form yii\bootstrap\ActiveForm */
  5. /* @var $model \common\models\RegistrForm */
  6.  
  7. use yii\helpers\Html;
  8. use yii\bootstrap\ActiveForm;
  9.  
  10. $this->title = 'Регистрация';
  11. $this->params['breadcrumbs'][] = $this->title;
  12. ?>
  13. <div class="site-registr">
  14.     <h1><?= Html::encode($this->title) ?></h1>
  15.  
  16.     <p>Пожалуйста, заполните следующие поля для регистрации.:</p>
  17.  
  18.     <div class="row">
  19.         <div class="col-lg-5">
  20.             <?PHP $form = ActiveForm::begin(['id' => 'form-registr']); ?>
  21.  
  22.                 <?= $form->field($model, 'username')->textInput(['autofocus' => true]) ?>
  23.  
  24.                 <?= $form->field($model, 'email') ?>
  25.  
  26.                 <?= $form->field($model, 'password')->passwordInput() ?>
  27.  
  28.                 <div class="form-group">
  29.                     <?= Html::submitButton('Регистрация', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
  30.                 </div>
  31.  
  32.             <?PHP ActiveForm::end(); ?>
  33.         </div>
  34.     </div>
  35. </div>
  36.  



И во fronted вкладка регистрации не открывается, вместо неё http://site[dot]com/site/login
а залогиниться через неё может только админ.
Прикреплено изображение (Нажмите для увеличения)
au1.jpg

(Отредактировано автором: 15 Сентября, 2017 - 18:39:04)

 
 Top
andrewkard
Отправлено: 15 Сентября, 2017 - 18:39:02
Post Id


Участник


Покинул форум
Сообщений всего: 1372
Дата рег-ции: Нояб. 2014  


Помог: 30 раз(а)




раз поставили
'access' => [
'class' => AccessControl::className(),
то пропишите нужное правило для регистрации
 
 Top
Vladim
Отправлено: 15 Сентября, 2017 - 19:25:11
Post Id


Новичок


Покинул форум
Сообщений всего: 4
Дата рег-ции: Сент. 2017  


Помог: 0 раз(а)




andrewkard пишет:
раз поставили
'access' => [
'class' => AccessControl::className(),
то пропишите нужное правило для регистрации


а что там нужно прописывать? там же вроде бы указаны rules?

PHP:
скопировать код в буфер обмена
  1.  return [
  2.             'access' => [
  3.                 'class' => AccessControl::className(),
  4.                 'rules' => [
  5.  
  6.                     [
  7.                         'actions'=> ['index'],
  8.                         'allow' => true,
  9.                         'roles' => ['canAdmin'],
  10.  
  11.  
  12.                     ],
  13.                     [
  14.                         'actions' => ['login', 'error'],
  15.                         'allow' => true,
  16.                        
  17.                     ],
  18.                     [
  19.                       'actions' => ['logout','save-redactor-img','save-img'],
  20.                       'allow' => true,
  21.                       'roles' => ['@'],
  22.                         ],
  23.                     ],
  24.               ],
 
 Top
andrewkard
Отправлено: 19 Сентября, 2017 - 14:18:31
Post Id


Участник


Покинул форум
Сообщений всего: 1372
Дата рег-ции: Нояб. 2014  


Помог: 30 раз(а)




Vladim пишет:
а что там нужно прописывать? там же вроде бы указаны rules?

не вижу правила для register
 
 Top
Страниц (1): [1]
Сейчас эту тему просматривают: 0 (гостей: 0, зарегистрированных: 0)
« CMS и фреймворки »


Все гости форума могут просматривать этот раздел.
Только зарегистрированные пользователи могут создавать новые темы в этом разделе.
Только зарегистрированные пользователи могут отвечать на сообщения в этом разделе.
 



Powered by PHP  Powered By MySQL  Powered by Nginx  Valid CSS  RSS

 
Powered by ExBB FM 1.0 RC1. InvisionExBB