PHP . SU
Программирование на PHP, MySQL и другие веб-технологии
Описание: yii2 advanced
Поиск в теме | Версия для печати
Vladim
Отправлено: 13 Сентября, 2017 - 17:10:28
Новичок
Покинул форум
Сообщений всего: 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 - регистрацию доступной для всех?
Какой экшен нужно создать и где?
Куда нужно добавить это исключение?
site\yii2\\backend\controllers\Site Controllers
PHP:
скопировать код в буфер обмена
<?PHP
namespace backend\controllers;
use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use yii\base\DynamicModel;
use vova07\imperavi\Widget;
use yii\base\Action;
use yii\base\InvalidCallException;
use yii\base\InvalidConfigException;
use yii\helpers\FileHelper;
use yii\web\BadRequestHttpException;
use yii\web\Response;
use yii\web\UploadedFile;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
use kartik\widgets\FileInput;
use common\models\Person;
use common\models\ImageManager;
/**
* Site controller
*/
class SiteController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors( )
{
return [
'access' => [
'class' => AccessControl:: className ( ) ,
'rules' => [
[
'actions' => [ 'index' ] ,
'allow' => true ,
'roles' => [ 'canAdmin' , 'admin' ] ,
] ,
[
'actions' => [ 'login' , 'error' ] ,
'allow' => true ,
] ,
[
'actions' => [ 'logout' , 'save-redactor-img' , 'save-img' ] ,
'allow' => true ,
'roles' => [ '@' ] ,
] ,
] ,
] ,
'verbs' => [
'class' => VerbFilter:: className ( ) ,
'actions' => [
'logout' => [ 'post' ] ,
] ,
] ,
] ;
}
/**
* @inheritdoc
*/
public function actions( )
{
return [
'error' => [
'class' => 'yii\web\ErrorAction' ,
] ,
] ;
}
/**
* Displays homepage.
*
* @return string
*/
public function actionIndex( )
{
return $this -> render ( 'index' ) ;
}
/**
* Login action.
*
* @return string
*/
public function actionLogin( )
{
if ( ! Yii:: $app -> user -> isGuest ) {
return $this -> goHome ( ) ;
}
$model = new LoginForm( ) ;
if ( $model -> load ( Yii:: $app -> request -> post ( ) ) && $model -> login ( ) ) {
return $this -> goBack ( ) ;
} else {
return $this -> render ( 'login' , [
'model' => $model ,
] ) ;
}
}
/**
* Logout action.
*
* @return string
*/
public function actionLogout( )
{
Yii:: $app -> user -> logout ( ) ;
return $this -> goHome ( ) ;
}
public function actionSaveRedactorImg ( $sub = 'main' )
{
$this -> enableCsrfValidation = false ;
if ( Yii:: $app -> request -> isPost ) {
$dir = Yii:: getAlias ( '@images' ) . '/' . $sub . '/' ;
FileHelper:: createDirectory ( $dir ) ;
}
$result_link = str_replace ( 'admin.' , '' , Url
:: home ( true ) ) . 'uploads/images/' . $sub . '/' ; $file = UploadedFile:: getInstanceByName ( 'file' ) ;
$model = new DynamicModel
( compact ( 'file' ) ) ; $model -> addRule ( 'file' , 'image' ) -> validate ( ) ;
if ( $model -> hasErrors ( ) ) {
$result = [
'error' => $model -> getFirstError ( 'file' )
] ;
} else {
$model -> file -> name = strtotime ( 'now' ) . '_' . Yii
:: $app -> getSecurity ( ) -> generateRandomString ( 6 ) . '.' . $model -> file -> extension ;
if ( $model -> file -> saveAs ( $dir . $model -> file -> name ) ) {
$imag = Yii:: $app -> image -> load ( $dir . $model -> file -> name ) ;
$imag -> resize ( 800, NULL , Yii\image\drivers\Image:: PRECISE )
-> save ( $dir . $model -> file -> name , 85) ;
$result = [
'filelink' => $result_link . $model -> file -> name , 'filename' => $model -> file -> name ] ;
} else {
$result = [
'error' => Yii:: t ( 'vova07/imperavi' , 'ERROR_CAN_NOT_UPLOAD_FILE' )
] ;
}
}
Yii:: $app -> response -> format = Response:: FORMAT_JSON ;
return $result ;
} else {
throw new BadRequestHttpException ( 'Only Post is allowed' ) ;
}
}
public function actionSaveImg ( )
{
$this -> enableCsrfValidation = false ;
if ( Yii:: $app -> request -> isPost ) {
$post = Yii:: $app -> request -> post ( ) ;
$dir = Yii:: getAlias ( '@images' ) . '/' . $post [ 'ImageManager' ] [ 'class' ] . '/' ;
FileHelper:: createDirectory ( $dir ) ;
}
$result_link = str_replace ( 'admin.' , '' , Url
:: home ( true ) ) . 'uploads/images/' . $post [ 'class' ] . '/' ; $file = UploadedFile:: getInstanceByName ( 'ImageManager[attachment]' ) ;
$model = new ImageManager( ) ;
$model -> name = strtotime ( 'now' ) . '_' . Yii
:: $app -> getSecurity ( ) -> generateRandomString ( 6 ) . '.' . $file -> extension ; $model -> load ( $post ) ;
$model -> validate ( ) ;
if ( $model -> hasErrors ( ) ) {
$result = [
'error' => $model -> getFirstError ( 'file' )
] ;
} else {
if ( $file -> saveAs ( $dir . $model -> name ) ) {
$imag = Yii:: $app -> image -> load ( $dir . $model -> name ) ;
$imag -> resize ( 800, NULL , Yii\image\drivers\Image:: PRECISE )
-> save ( $dir . $model -> name , 85) ;
$result = [
'filelink' => $result_link . $model -> name , 'filename' => $model -> name ] ;
} else {
$result = [
'error' => 'ошибка'
] ;
}
$model -> save ( ) ;
}
Yii:: $app -> response -> format = Response:: FORMAT_JSON ;
return $result ;
} else {
throw new BadRequestHttpException ( 'Only Post is allowed' ) ;
}
}
}
site\yii2\common\config\main.pgp
PHP:
скопировать код в буфер обмена
<?PHP
return [
'timeZone' => 'Europe/Moscow' ,
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache' ,
/* 'robotEmail' => '',*/
/*'robotName' => 'Robot'*/
] ,
'image' => [
'class' => 'yii\image\ImageDriver' ,
'driver' => 'GD' , //GD or Imagick
] ,
'authManager' => [
'class' => 'yii\rbac\DbManager' ,
'cache' => 'cache'
] ,
] ,
'on beforeAction' => function ( $event ) { //цепляемся за событие перед запуском экшена
Yii:: $app -> controller -> attachBehavior ( '' , [ //цепляем к текущему контролеру поведение
'class' => \yii\filters\AccessControl:: className ( ) , //указываем класс поведения
'except' => [ 'login' , 'error' ] , //исключим из правила экшены login и error, так как они должны быть доступны всем
'rules' => [
[
'allow' => true , //разрешаем доступ
'roles' => [ 'admin' ] , //'@' только зарегистрированным пользователям или замените на 'admin', что бы только админам позволить
] ,
] ,
] ) ;
} ,
] ;
В main.php добавлен такой менеджер:
Пользователи и таблицы с миграциями создались, настройку ролей и permission сделана в TagController (yii2\backend\controllers)
PHP:
скопировать код в буфер обмена
<?PHP
namespace backend\controllers;
use Yii;
use common\models\Tag;
use common\models\TagSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
/**
* TagController implements the CRUD actions for Tag model.
*/
class TagController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors( )
{
return [
'access' => [
'class' => AccessControl:: className ( ) ,
'rules' => [
[
'allow' => true ,
'roles' => [ 'admin' ] ,
] ,
] ,
] ,
] ;
}
/* public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}*/
/**
* Lists all Tag models.
* @return mixed
*/
public function actionIndex( )
{
$searchModel = new TagSearch( ) ;
$dataProvider = $searchModel -> search ( Yii:: $app -> request -> queryParams ) ;
return $this -> render ( 'index' , [
'searchModel' => $searchModel ,
'dataProvider' => $dataProvider ,
] ) ;
}
/**
* Displays a single Tag model.
* @param integer $id
* @return mixed
*/
public function actionView( $id )
{
return $this -> render ( 'view' , [
'model' => $this -> findModel ( $id ) ,
] ) ;
}
/**
* Creates a new Tag model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate( )
{
$model = new Tag( ) ;
if ( $model -> load ( Yii:: $app -> request -> post ( ) ) && $model -> save ( ) ) {
return $this -> redirect ( [ 'view' , 'id' => $model -> id ] ) ;
} else {
return $this -> render ( 'create' , [
'model' => $model ,
] ) ;
}
}
/**
* Updates an existing Tag 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 -> id ] ) ;
} else {
return $this -> render ( 'update' , [
'model' => $model ,
] ) ;
}
}
/**
* Deletes an existing Tag 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 Tag model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Tag the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel( $id )
{
if ( ( $model = Tag:: findOne ( $id ) ) !== null ) {
return $model ;
} else {
throw new NotFoundHttpException( 'The requested page does not exist.' ) ;
}
}
public function actionRole( ) {
/* $admin = Yii::$app->authManager->createRole ('admin');
$admin->description = 'Администратор';
Yii::$app->authManager ->add ($admin);
$content = Yii::$app->authManager->createRole ('content');
$content ->description = 'Контент менеджер';
Yii::$app->authManager->add ($content);
$user = Yii::$app->authManager->createRole ('user');
$user ->description = 'Пользователь';
Yii::$app->authManager ->add($user);
$ban = Yii::$app->authManager->createRole ('banned');
$ban ->description ='Tварь';
Yii::$app->authManager->add($ban);*/
/* $permit = Yii::$app->authManager->createPermission('canAdmin');
$permit ->description = 'Право входа в админку';
Yii::$app->authManager ->add ($permit);*/
/* $role_a = Yii::$app->authManager->getRole ('admin');
$role_c = Yii::$app->authManager->getRole ('content');
$permit = Yii:: $app->authManager ->getPermission ('canAdmin');
Yii::$app->authManager->addChild ($role_a, $permit);
Yii::$app->authManager->addChild ($role_c, $permit);*/
$userRole = Yii:: $app -> authManager -> getRole ( 'admin' ) ;
Yii:: $app -> authManager -> assign ( $userRole , 1) ;
return 12345 ;
}
}
Прикреплено изображение (Нажмите для увеличения) (Отредактировано автором: 13 Сентября, 2017 - 17:50:10)
andrewkard
Отправлено: 14 Сентября, 2017 - 11:17:05
Участник
Покинул форум
Сообщений всего: 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/
Vladim
Отправлено: 14 Сентября, 2017 - 17:56:37
Новичок
Покинул форум
Сообщений всего: 4
Дата рег-ции: Сент. 2017
Помог: 0 раз(а)
Цитата: Во frontend/controllers нужен контроллер SiteController.php c методом actionSignup и в папке frontend/views/site нужно представление signup.php
(Добавле
Так у меня во fronted уже есть такой метод и представление sign.up
SiteController (fronted)
PHP:
скопировать код в буфер обмена
<?PHP
namespace frontend\controllers;
use medeyacom\blog\models\Blog;
use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
/**
* Site controller
*/
class SiteController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors( )
{
return [
'access' => [
'class' => AccessControl:: className ( ) ,
'only' => [ 'logout' , 'signup' ] ,
'rules' => [
[
'actions' => [ 'signup' ] ,
'allow' => true ,
'roles' => [ '?' ] ,
] ,
[
'actions' => [ 'logout' ] ,
'allow' => true ,
'roles' => [ '@' ] ,
] ,
] ,
] ,
'verbs' => [
'class' => VerbFilter:: className ( ) ,
'actions' => [
'logout' => [ 'post' ] ,
] ,
] ,
] ;
}
/**
* @inheritdoc
*/
public function actions( )
{
return [
'error' => [
'class' => 'yii\web\ErrorAction' ,
] ,
'captcha' => [
'class' => 'yii\captcha\CaptchaAction' ,
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null ,
] ,
] ;
}
/**
* Displays homepage.
*
* @return mixed
*/
public function actionIndex( )
{
#$blogs = Blog::find()->where(['status_id'=>1])->orderBy(['id' => SORT_DESC])->all();
$blogs = Blog:: find ( ) -> andWhere ( [ 'status_id' => 1 ] ) -> orderBy ( 'sort' ) -> all ( ) ;
#$blogs = Blog::find()->where(['status_id'=>1])->orderBy(['id' => SORT_ASC])->all();
return $this -> render ( 'index' , [ 'blogs' => $blogs ] ) ;
}
/**
* Logs in a user.
*
* @return mixed
*/
public function actionLogin( )
{
if ( ! Yii:: $app -> user -> isGuest ) {
return $this -> goHome ( ) ;
}
$model = new LoginForm( ) ;
if ( $model -> load ( Yii:: $app -> request -> post ( ) ) && $model -> login ( ) ) {
return $this -> goBack ( ) ;
} else {
return $this -> render ( 'login' , [
'model' => $model ,
] ) ;
}
}
/**
* Logs out the current user.
*
* @return mixed
*/
public function actionLogout( )
{
Yii:: $app -> user -> logout ( ) ;
return $this -> goHome ( ) ;
}
/**
* Displays contact page.
*
* @return mixed
*/
public function actionContact( )
{
$model = new ContactForm( ) ;
if ( $model -> load ( Yii:: $app -> request -> post ( ) ) && $model -> validate ( ) ) {
if ( $model -> sendEmail ( Yii:: $app -> params [ 'adminEmail' ] ) ) {
Yii:: $app -> session -> setFlash ( 'success' , 'Thank you for contacting us. We will respond to you as soon as possible.' ) ;
} else {
Yii:: $app -> session -> setFlash ( 'error' , 'There was an error sending your message.' ) ;
}
return $this -> refresh ( ) ;
} else {
return $this -> render ( 'contact' , [
'model' => $model ,
] ) ;
}
}
/**
* Displays about page.
*
* @return mixed
*/
public function actionAbout( )
{
return $this -> render ( 'about' ) ;
}
/**
* Signs user up.
*
* @return mixed
*/
public function actionSignup( )
{
$model = new SignupForm( ) ;
if ( $model -> load ( Yii:: $app -> request -> post ( ) ) ) {
if ( $user = $model -> signup ( ) ) {
if ( Yii:: $app -> getUser ( ) -> login ( $user ) ) {
return $this -> goHome ( ) ;
}
}
}
return $this -> render ( 'signup' , [
'model' => $model ,
] ) ;
}
/**
* Requests password reset.
*
* @return mixed
*/
public function actionRequestPasswordReset( )
{
$model = new PasswordResetRequestForm( ) ;
if ( $model -> load ( Yii:: $app -> request -> post ( ) ) && $model -> validate ( ) ) {
if ( $model -> sendEmail ( ) ) {
Yii:: $app -> session -> setFlash ( 'success' , 'Check your email for further instructions.' ) ;
return $this -> goHome ( ) ;
} else {
Yii:: $app -> session -> setFlash ( 'error' , 'Sorry, we are unable to reset password for the provided email address.' ) ;
}
}
return $this -> render ( 'requestPasswordResetToken' , [
'model' => $model ,
] ) ;
}
/**
* Resets password.
*
* @param string $token
* @return mixed
* @throws BadRequestHttpException
*/
public function actionResetPassword( $token )
{
try {
$model = new ResetPasswordForm( $token ) ;
} catch ( InvalidParamException $e ) {
throw new BadRequestHttpException( $e -> getMessage ( ) ) ;
}
if ( $model -> load ( Yii:: $app -> request -> post ( ) ) && $model -> validate ( ) && $model -> resetPassword ( ) ) {
Yii:: $app -> session -> setFlash ( 'success' , 'New password saved.' ) ;
return $this -> goHome ( ) ;
}
return $this -> render ( 'resetPassword' , [
'model' => $model ,
] ) ;
}
}
signup (fronted)
PHP:
скопировать код в буфер обмена
<?PHP
/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \frontend\models\SignupForm */
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
$this -> title = 'Signup' ;
$this -> params [ 'breadcrumbs' ] [ ] = $this -> title ;
?>
<div class="site-signup">
<h1><?= Html:: encode ( $this -> title ) ?> </h1>
<p>Пожалуйста, заполните следующие поля для регистрации.:</p>
<div class="row">
<div class="col-lg-5">
<?PHP $form = ActiveForm:: begin ( [ 'id' => 'form-signup' ] ) ; ?>
<?= $form -> field ( $model , 'username' ) -> textInput ( [ 'autofocus' => true ] ) ?>
<?= $form -> field ( $model , 'email' ) ?>
<?= $form -> field ( $model , 'password' ) -> passwordInput ( ) ?>
<div class="form-group">
<?= Html:: submitButton ( 'Signup' , [ 'class' => 'btn btn-primary' , 'name' => 'signup-button' ] ) ?>
</div>
<?PHP ActiveForm
:: end ( ) ; ?> </div>
</div>
</div>
(Добавление)
Цитата:
если нужно, то аналогично SiteController actionRegister
т.е. нужен файл Register.php в yii2\fronted\views\site ? и что в нем должно быть?
Ссылка 404 /register.html' - куда я попадаю, чтобы работала, значит надо сделать экшен Register в SiteController (backend) и сделать к нему ссылку? И как сделать ссылку?
site\yii2\common\config\main.pgp есть исключение :
Его добавление открывает доступ всем пользователям к экшену 'register' в контролере. Другой вопрос: как привести туда пользователя? И ошибка (на скрине) именно об этом говорит. "unable to resolve request"
Поэтому, получается разница между site/register и site/register.html куда я пытаюсь попасть. Ошибка, как я понимаю, не в отсутствии прав доступа, а в том, что yii не знает в какой контролер и какой экшен я пытаюсь попасть(Прикреплено изображение (Нажмите для увеличения) (Отредактировано автором: 14 Сентября, 2017 - 18:17:00)
andrewkard
Отправлено: 15 Сентября, 2017 - 16:37:10
Участник
Покинул форум
Сообщений всего: 1372
Дата рег-ции: Нояб. 2014
Помог: 30 раз(а)
Vladim пишет: Ссылка 404 /register.html' - куда я попадаю, чтобы работала, значит надо сделать экшен Register в SiteController (backend) и сделать к нему ссылку? И как сделать ссылку?
/site/register
в котроллере SiteController метод actionRegister,
в нем обработка поста и рендер register
а в register - нужная форма
Vladim
Отправлено: 15 Сентября, 2017 - 18:34:55
Новичок
Покинул форум
Сообщений всего: 4
Дата рег-ции: Сент. 2017
Помог: 0 раз(а)
Цитата:
в котроллере SiteController метод actionRegister,
Пробовал разные варианты, но что здесь не так?
Вот SiteController (backend)
PHP:
скопировать код в буфер обмена
<?PHP
namespace backend\controllers;
use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use yii\base\DynamicModel;
use vova07\imperavi\Widget;
use yii\base\Action;
use yii\base\InvalidCallException;
use yii\base\InvalidConfigException;
use yii\helpers\FileHelper;
use yii\web\BadRequestHttpException;
use yii\web\Response;
use yii\web\UploadedFile;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
use kartik\widgets\FileInput;
use common\models\Person;
use common\models\ImageManager;
/**
* Site controller
*/
class SiteController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors( )
{
return [
'access' => [
'class' => AccessControl:: className ( ) ,
'rules' => [
[
'actions' => [ 'index' ] ,
'allow' => true ,
'roles' => [ 'canAdmin' ] ,
] ,
[
'actions' => [ 'login' , 'error' ] ,
'allow' => true ,
] ,
[
'actions' => [ 'logout' , 'save-redactor-img' , 'save-img' ] ,
'allow' => true ,
'roles' => [ '@' ] ,
] ,
] ,
] ,
'verbs' => [
'class' => VerbFilter:: className ( ) ,
'actions' => [
'logout' => [ 'post' ] ,
] ,
] ,
] ;
}
/**
* @inheritdoc
*/
public function actions( )
{
return [
'error' => [
'class' => 'yii\web\ErrorAction' ,
] ,
] ;
}
/**
* Displays homepage.
*
* @return string
*/
public function actionIndex( )
{
return $this -> render ( 'index' ) ;
}
/**
* Login action.
*
* @return string
*/
public function actionLogin( )
{
if ( ! Yii:: $app -> user -> isGuest ) {
return $this -> goHome ( ) ;
}
$model = new LoginForm( ) ;
if ( $model -> load ( Yii:: $app -> request -> post ( ) ) && $model -> login ( ) ) {
return $this -> goBack ( ) ;
} else {
return $this -> render ( 'login' , [
'model' => $model ,
] ) ;
}
}
/**
* Logout action.
*
* @return string
*/
public function actionLogout( )
{
Yii:: $app -> user -> logout ( ) ;
return $this -> goHome ( ) ;
}
public function actionRegister( )
{
$model = new RegisterForm;
if ( ! empty ( $_POST [ 'RegisterForm' ] ) ) {
$model -> attributes = $_POST [ 'RegisterForm' ] ;
if ( $model -> validate ( ) && $model -> register ( ) )
$this -> redirect ( $this -> createUrl ( 'site/index' ) ) ;
}
$this -> render ( 'register' , array ( 'model' => $model ) ) ; }
/*public function actionRegister() {
$model = new RegisterForm;
if(isset($_POST['RegisterForm']))
{
$model->attributes=$_POST['RegisterForm'];
if($model->validate()){
//send mail here ... then redirect
$this->redirect(Yii::app()->user->returnUrl);
}
}
$this->render('register',array('model'=>$model));
}*/
/*public function actionRegister() {
$model = new RegisterForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax'] === 'register-form')
{
echo CActiveForm::validate($model);
app()->end();
}
}*/
public function actionSaveRedactorImg ( $sub = 'main' )
{
$this -> enableCsrfValidation = false ;
if ( Yii:: $app -> request -> isPost ) {
$dir = Yii:: getAlias ( '@images' ) . '/' . $sub . '/' ;
FileHelper:: createDirectory ( $dir ) ;
}
$result_link = str_replace ( 'admin.' , '' , Url
:: home ( true ) ) . 'uploads/images/' . $sub . '/' ; $file = UploadedFile:: getInstanceByName ( 'file' ) ;
$model = new DynamicModel
( compact ( 'file' ) ) ; $model -> addRule ( 'file' , 'image' ) -> validate ( ) ;
if ( $model -> hasErrors ( ) ) {
$result = [
'error' => $model -> getFirstError ( 'file' )
] ;
} else {
$model -> file -> name = strtotime ( 'now' ) . '_' . Yii
:: $app -> getSecurity ( ) -> generateRandomString ( 6 ) . '.' . $model -> file -> extension ;
if ( $model -> file -> saveAs ( $dir . $model -> file -> name ) ) {
$imag = Yii:: $app -> image -> load ( $dir . $model -> file -> name ) ;
$imag -> resize ( 800, NULL , Yii\image\drivers\Image:: PRECISE )
-> save ( $dir . $model -> file -> name , 85) ;
$result = [
'filelink' => $result_link . $model -> file -> name , 'filename' => $model -> file -> name ] ;
} else {
$result = [
'error' => Yii:: t ( 'vova07/imperavi' , 'ERROR_CAN_NOT_UPLOAD_FILE' )
] ;
}
}
Yii:: $app -> response -> format = Response:: FORMAT_JSON ;
return $result ;
} else {
throw new BadRequestHttpException ( 'Only Post is allowed' ) ;
}
}
public function actionSaveImg ( )
{
$this -> enableCsrfValidation = false ;
if ( Yii:: $app -> request -> isPost ) {
$post = Yii:: $app -> request -> post ( ) ;
$dir = Yii:: getAlias ( '@images' ) . '/' . $post [ 'ImageManager' ] [ 'class' ] . '/' ;
FileHelper:: createDirectory ( $dir ) ;
}
$result_link = str_replace ( 'admin.' , '' , Url
:: home ( true ) ) . 'uploads/images/' . $post [ 'class' ] . '/' ; $file = UploadedFile:: getInstanceByName ( 'ImageManager[attachment]' ) ;
$model = new ImageManager( ) ;
$model -> name = strtotime ( 'now' ) . '_' . Yii
:: $app -> getSecurity ( ) -> generateRandomString ( 6 ) . '.' . $file -> extension ; $model -> load ( $post ) ;
$model -> validate ( ) ;
if ( $model -> hasErrors ( ) ) {
$result = [
'error' => $model -> getFirstError ( 'file' )
] ;
} else {
if ( $file -> saveAs ( $dir . $model -> name ) ) {
$imag = Yii:: $app -> image -> load ( $dir . $model -> name ) ;
$imag -> resize ( 800, NULL , Yii\image\drivers\Image:: PRECISE )
-> save ( $dir . $model -> name , 85) ;
$result = [
'filelink' => $result_link . $model -> name , 'filename' => $model -> name ] ;
} else {
$result = [
'error' => 'ошибка'
] ;
}
$model -> save ( ) ;
}
Yii:: $app -> response -> format = Response:: FORMAT_JSON ;
return $result ;
} else {
throw new BadRequestHttpException ( 'Only Post is allowed' ) ;
}
}
}
RegistrForm (common/models)
PHP:
скопировать код в буфер обмена
<?PHP
namespace common\models;
use yii\base\Model;
use common\models\User;
/**
* Signup form
*/
class SignupForm extends Model
{
public $username ;
public $email ;
public $password ;
/**
* @inheritdoc
*/
public function rules( )
{
array ( 'email' , 'password' , 'required' , 'message' => 'Поле обязательно для заполнения' ) , array ( 'email' , 'email' , 'message' => 'Неверный формат Email' ) , array ( 'password' , 'compare' , 'compareAttribute' => 'password2' , 'message' => 'Пароли не совпадают' ) , ) ;
}
/* public function rules()
{
return [
['username', 'trim'],
['username', 'required'],
['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
['username', 'string', 'min' => 2, 'max' => 255],
['email', 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'string', 'max' => 255],
['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],
['password', 'required'],
['password', 'string', 'min' => 6],
];
}
*/
/**
* Signs user up.
*
* @return User|null the saved model or null if saving fails
*/
public function attributeLabels ( ) {
return [
'username' => 'Логин' ,
'password' => 'Пароль' ,
'email' => 'email' ,
] ;
}
public function register( )
{
if ( ! $this -> hasError ( ) )
{
//Добавляем в бд
$model = new User;
$model -> user_email = $this -> email ;
$model -> user_password = CPasswordHelper:: hashPassword ( $this -> password ) ;
$model -> save ( ) ;
}
else
return false ;
}
}
/* public function register()
{
if (!$this->validate()) {
return null;
}
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
return $user->save() ? $user : null;
}
}*/
registr.php (backend\views-site)
PHP:
скопировать код в буфер обмена
<?PHP
/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \common\models\RegistrForm */
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
$this -> title = 'Регистрация' ;
$this -> params [ 'breadcrumbs' ] [ ] = $this -> title ;
?>
<div class="site-registr">
<h1><?= Html:: encode ( $this -> title ) ?> </h1>
<p>Пожалуйста, заполните следующие поля для регистрации.:</p>
<div class="row">
<div class="col-lg-5">
<?PHP $form = ActiveForm:: begin ( [ 'id' => 'form-registr' ] ) ; ?>
<?= $form -> field ( $model , 'username' ) -> textInput ( [ 'autofocus' => true ] ) ?>
<?= $form -> field ( $model , 'email' ) ?>
<?= $form -> field ( $model , 'password' ) -> passwordInput ( ) ?>
<div class="form-group">
<?= Html:: submitButton ( 'Регистрация' , [ 'class' => 'btn btn-primary' , 'name' => 'signup-button' ] ) ?>
</div>
<?PHP ActiveForm
:: end ( ) ; ?> </div>
</div>
</div>
И во fronted вкладка регистрации не открывается, вместо неё http://site[dot]com/site/login
а залогиниться через неё может только админ.Прикреплено изображение (Нажмите для увеличения) (Отредактировано автором: 15 Сентября, 2017 - 18:39:04)
Vladim
Отправлено: 15 Сентября, 2017 - 19:25:11
Новичок
Покинул форум
Сообщений всего: 4
Дата рег-ции: Сент. 2017
Помог: 0 раз(а)
andrewkard пишет: раз поставили
'access' => [
'class' => AccessControl::className(),
то пропишите нужное правило для регистрации
а что там нужно прописывать? там же вроде бы указаны rules?
PHP:
скопировать код в буфер обмена
return [
'access' => [
'class' => AccessControl:: className ( ) ,
'rules' => [
[
'actions' => [ 'index' ] ,
'allow' => true ,
'roles' => [ 'canAdmin' ] ,
] ,
[
'actions' => [ 'login' , 'error' ] ,
'allow' => true ,
] ,
[
'actions' => [ 'logout' , 'save-redactor-img' , 'save-img' ] ,
'allow' => true ,
'roles' => [ '@' ] ,
] ,
] ,
] ,
andrewkard
Отправлено: 19 Сентября, 2017 - 14:18:31
Участник
Покинул форум
Сообщений всего: 1372
Дата рег-ции: Нояб. 2014
Помог: 30 раз(а)
Vladim пишет: а что там нужно прописывать? там же вроде бы указаны rules?
не вижу правила для register
Поиск в теме | Версия для печати
Страниц (1): [1]
Сейчас эту тему просматривают: 0 (гостей: 0, зарегистрированных: 0)
« CMS и фреймворки »
Все гости форума могут просматривать этот раздел. Только зарегистрированные пользователи могут создавать новые темы в этом разделе. Только зарегистрированные пользователи могут отвечать на сообщения в этом разделе.
Powered by ExBB FM 1.0 RC1. InvisionExBB