Я использую расширение пользователя и прав Yii, я хочу дать Authenticated
роль пользователю, который успешно зарегистрировался. Но это не работает.
Ниже приведен мой регистрационный код контроллера
Класс RegistrationController расширяет контроллер
{
public $ defaultAction = ‘registration’;
/**
* Declares class-based actions.
*/
public function actions()
{
return array(
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
);
}
/**
* Registration user
*/
public function actionRegistration() {
$model = new RegistrationForm;
$profile=new Profile;
$profile->regMode = true;
// ajax validator
if(isset($_POST['ajax']) && $_POST['ajax']==='registration-form')
{
echo UActiveForm::validate(array($model,$profile));
Yii::app()->end();
}
if (Yii::app()->user->id) {
$this->redirect(Yii::app()->controller->module->profileUrl);
} else {
if(isset($_POST['RegistrationForm'])) {
$rnd = rand(0, 9999); // generate random number between 0-9999
$model->attributes = $_POST['RegistrationForm'];
$uploadedFile = CUploadedFile::getInstance($profile, 'picture');
$fileName = "{$rnd}-{$uploadedFile}"; // random number + file name
$profile->picture = $fileName;
if(!empty($uploadedFile)) // check if uploaded file is set or not
{
//$uploadedFile->saveAs(Yii::getPathOfAlias('webroot')."/img".$filename);
$uploadedFile->saveAs(Yii::app()->basePath . '/../img/' . $fileName);
$image = Yii::app()->image->load(Yii::app()->basePath . '/../img/' . $fileName);
$image->resize(70, 70);
$image->save(Yii::app()->basePath . '/../img/' . $fileName);
}
$profile->attributes=((isset($_POST['Profile'])?$_POST['Profile']:array()));
if($model->validate()&&$profile->validate())
{
$soucePassword = $model->password;
$model->activkey=UserModule::encrypting(microtime().$model->password);
$model->password=UserModule::encrypting($model->password);
$model->verifyPassword=UserModule::encrypting($model->verifyPassword);
$model->superuser=0;
$model->status=((Yii::app()->controller->module->activeAfterRegister)?User::STATUS_ACTIVE:User::STATUS_NOACTIVE);
if ($model->save()) {
$profile->user_id=$model->id;
$profile->picture = $fileName;
$profile->insert();
if (Yii::app()->controller->module->sendActivationMail) {
$activation_url = $this->createAbsoluteUrl('/user/activation/activation',array("activkey" => $model->activkey, "email" => $model->email));
// here
UserModule::sendMail($model->email,UserModule::t("You registered from {site_name}",array('{site_name}'=>Yii::app()->name)),UserModule::t("Please activate you account go to {activation_url}",array('{activation_url}'=>$activation_url)));
}
if ((Yii::app()->controller->module->loginNotActiv||(Yii::app()->controller->module->activeAfterRegister&&Yii::app()->controller->module->sendActivationMail==false))&&Yii::app()->controller->module->autoLogin) {
$identity=new UserIdentity($model->username,$soucePassword);
$identity->authenticate();
Yii::app()->user->login($identity,0);
$this->redirect(Yii::app()->controller->module->returnUrl);
} else {
if (!Yii::app()->controller->module->activeAfterRegister&&!Yii::app()->controller->module->sendActivationMail) {
Yii::app()->user->setFlash('registration',UserModule::t("Thank you for your registration. Contact Admin to activate your account."));
} elseif(Yii::app()->controller->module->activeAfterRegister&&Yii::app()->controller->module->sendActivationMail==false) {
Yii::app()->user->setFlash('registration',UserModule::t("Thank you for your registration. Please {{login}}.",array('{{login}}'=>CHtml::link(UserModule::t('Login'),Yii::app()->controller->module->loginUrl))));
} elseif(Yii::app()->controller->module->loginNotActiv) {
Yii::app()->user->setFlash('registration',UserModule::t("Thank you for your registration. Please check your email or login."));
} else {
Yii::app()->user->setFlash('registration',UserModule::t("Thank you for your registration. Please check your email."));
}
$this->refresh();
}
}
} else $profile->validate();
}
$this->render('/user/registration',array('model'=>$model,'profile'=>$profile));
}
}
}
Мой main.config
<?php
// uncomment the following to define a path alias
// Yii::setPathOfAlias('local','path/to/local-folder');
// This is the main Web application configuration. Any writable
// CWebApplication properties can be configured here.
return array(
'theme' => 'bootstrap',
'basePath' => dirname(__FILE__) . DIRECTORY_SEPARATOR . '..',
'name' => 'My Web Application',
// preloading 'log' component
'preload' => array('log'),
'aliases' => array(
'bootstrap' => 'ext.bootstrap'),
// autoloading model and component classes
'import' => array(
'application.models.*',
'application.components.*',
'bootstrap.behaviors.*',
'bootstrap.helpers.*',
'bootstrap.widgets.*',
'application.modules.user.models.*',
'application.modules.user.components.*',
'application.modules.rights.*',
'application.modules.rights.components.*',
'ext.select2.Select2',
'application.extensions.*',
'application.helpers.*',//adding these lines to for yii user nd rights
),
'modules' => array(
// uncomment the following to enable the Gii tool
'gii' => array(
'class' => 'system.gii.GiiModule',
'password' => 'centangle',
'generatorPaths' => array('bootstrap.gii',),
// If removed, Gii defaults to localhost only. Edit carefully to taste.
'ipFilters' => array('127.0.0.1', '::1'),
),
'user' => array(
'tableUsers' => 'user',
'tableProfiles' => 'profiles',
'tableProfileFields' => 'profiles_fields',
),
'rights' => array(
'install' => false,
'superuserName' => 'Admin', // Name of the role with super user privileges.
'authenticatedName' => 'Authenticated', // Name of the authenticated user role.
'userIdColumn' => 'id', // Name of the user id column in the database.
'userNameColumn' => 'username', // Name of the user name column in the database.
//'enableBizRule'=>true, // Whether to enable authorization item business rules.
//'enableBizRuleData'=>true, // Whether to enable data for business rules.
//'displayDescription'=>true, // Whether to use item description instead of name.
'flashSuccessKey' => 'RightsSuccess', // Key to use for setting success flash messages.
'flashErrorKey' => 'RightsError', // Key to use for setting error flash messages.
// 'baseUrl'=>'/rights', // Base URL for Rights. Change if module is nested.
'layout' => 'rights.views.layouts.main', // Layout to use for displaying Rights.
'appLayout' => 'application.views.layouts.main', // Application layout.
'cssFile' => 'rights.css', // Style sheet file to use for Rights.
'install' => false, // Whether to enable installer.
'debug' => false,
),
'notifyii',
),
// application components
'components' => array(
'image'=>array(
'class'=>'application.extensions.image.CImageComponent',
// GD or ImageMagick
'driver'=>'GD',
// ImageMagick setup path
'params'=>array('directory'=>'/opt/local/bin'),
),
'user' => array(
'class' => 'RWebUser',
// enable cookie-based authentication
'allowAutoLogin' => true,
'loginUrl' => array('/user/login'),
),
'authManager' => array(
'class' => 'RDbAuthManager',
'connectionID' => 'db',
'defaultRoles' => array('Authenticated', 'Guest'),
'itemTable' => 'authitem',
'itemChildTable' => 'authitemchild',
'assignmentTable' => 'authassignment',
'rightsTable' => 'rights',
),
'bootstrap' => array(
'class' => 'bootstrap.components.BsApi',),
// uncomment the following to enable URLs in path-format
'urlManager' => array(
'urlFormat' => 'path',
'showScriptName' => false,
'rules' =>array(// REST patterns
//Packages
array('packages/list', 'pattern'=>'packages/<model:\w+>', 'verb'=>'GET'),
array('packages/view', 'pattern'=>'packages/<model:\w+>/<id:\d+>', 'verb'=>'GET'),
array('packages/update', 'pattern'=>'packages/<model:\w+>/<id:\d+>', 'verb'=>'PUT'),
array('packages/delete', 'pattern'=>'packages/<model:\w+>/<id:\d+>', 'verb'=>'DELETE'),
array('packages/create', 'pattern'=>'packages/<model:\w+>', 'verb'=>'POST'),
//Businesses
array('businesses/list', 'pattern'=>'businesses/<model:\w+>', 'verb'=>'GET'),
array('businesses/view', 'pattern'=>'businesses/<model:\w+>/<id:\d+>', 'verb'=>'GET'),
array('businesses/update', 'pattern'=>'businesses/<model:\w+>/<id:\d+>', 'verb'=>'PUT'),
array('businesses/delete', 'pattern'=>'businesses/<model:\w+>/<id:\d+>', 'verb'=>'DELETE'),
array('businesses/create', 'pattern'=>'businesses/<model:\w+>', 'verb'=>'POST'),
//Addresses
array('addresses/list', 'pattern'=>'addresses/<model:\w+>', 'verb'=>'GET'),
array('addresses/view', 'pattern'=>'addresses/<model:\w+>/<id:\d+>', 'verb'=>'GET'),
array('addresses/update', 'pattern'=>'addresses/<model:\w+>/<id:\d+>', 'verb'=>'PUT'),
array('addresses/delete', 'pattern'=>'addresses/<model:\w+>/<id:\d+>', 'verb'=>'DELETE'),
array('addresses/create', 'pattern'=>'addresses/<model:\w+>', 'verb'=>'POST'),
//Categories
array('categories/list', 'pattern'=>'categories/<model:\w+>', 'verb'=>'GET'),
array('categories/view', 'pattern'=>'categories/<model:\w+>/<id:\d+>', 'verb'=>'GET'),
array('categories/update', 'pattern'=>'categories/<model:\w+>/<id:\d+>', 'verb'=>'PUT'),
array('categories/delete', 'pattern'=>'categories/<model:\w+>/<id:\d+>', 'verb'=>'DELETE'),
array('categories/create', 'pattern'=>'categories/<model:\w+>', 'verb'=>'POST'),
//ReviewBusinesses
array('reviewbusinesses/list', 'pattern'=>'reviewbusinesses/<model:\w+>', 'verb'=>'GET'),
array('reviewbusinesses/view', 'pattern'=>'reviewbusinesses/<model:\w+>/<id:\d+>', 'verb'=>'GET'),
array('reviewbusinesses/businesspage', 'pattern'=>'businesspage/<model:\w+>/<id:\d+>', 'verb'=>'GET'),
array('reviewbusinesses/update', 'pattern'=>'reviewbusinesses/<model:\w+>/<id:\d+>', 'verb'=>'PUT'),
array('reviewbusinesses/delete', 'pattern'=>'reviewbusinesses/<model:\w+>/<id:\d+>', 'verb'=>'DELETE'),
array('reviewbusinesses/create', 'pattern'=>'reviewbusinesses/<model:\w+>', 'verb'=>'POST'),
//SubCategories
array('subcategories/list', 'pattern'=>'subcategories/<model:\w+>', 'verb'=>'GET'),
array('subcategories/view', 'pattern'=>'subcategories/<model:\w+>/<id:\d+>', 'verb'=>'GET'),
array('subcategories/update', 'pattern'=>'subcategories/<model:\w+>/<id:\d+>', 'verb'=>'PUT'),
array('subcategories/delete', 'pattern'=>'subcategories/<model:\w+>/<id:\d+>', 'verb'=>'DELETE'),
array('subcategories/create', 'pattern'=>'subcategories/<model:\w+>', 'verb'=>'POST'),
//SubCategoryBusinesses
array('subcategorybusinesses/list', 'pattern'=>'subcategorybusinesses/<model:\w+>', 'verb'=>'GET'),
array('subcategorybusinesses/view', 'pattern'=>'subcategorybusinesses/<model:\w+>/<id:\d+>', 'verb'=>'GET'),
array('subcategorybusinesses/businessname', 'pattern'=>'businesslist/<model:\w+>/<id:\d+>', 'verb'=>'GET'),
array('subcategorybusinesses/update', 'pattern'=>'subcategorybusinesses/<model:\w+>/<id:\d+>', 'verb'=>'PUT'),
array('subcategorybusinesses/delete', 'pattern'=>'subcategorybusinesses/<model:\w+>/<id:\d+>', 'verb'=>'DELETE'),
array('subcategorybusinesses/create', 'pattern'=>'subcategorybusinesses/<model:\w+>', 'verb'=>'POST'),
//Users
array('users/list', 'pattern'=>'users/<model:\w+>', 'verb'=>'GET'),
array('users/view', 'pattern'=>'users/<model:\w+>/<id:\d+>', 'verb'=>'GET'),
array('users/update', 'pattern'=>'users/<model:\w+>/<id:\d+>', 'verb'=>'PUT'),
array('users/delete', 'pattern'=>'users/<model:\w+>/<id:\d+>', 'verb'=>'DELETE'),
array('users/create', 'pattern'=>'users/<model:\w+>', 'verb'=>'POST'),
//ItemsReview
array('itemsreview/list', 'pattern'=>'itemsreview/<model:\w+>', 'verb'=>'GET'),
array('itemsreview/view', 'pattern'=>'itemsreview/<model:\w+>/<id:\d+>', 'verb'=>'GET'),
array('itemsreview/update', 'pattern'=>'itemsreview/<model:\w+>/<id:\d+>', 'verb'=>'PUT'),
array('itemsreview/delete', 'pattern'=>'itemsreview/<model:\w+>/<id:\d+>', 'verb'=>'DELETE'),
array('itemsreview/create', 'pattern'=>'itemsreview/<model:\w+>', 'verb'=>'POST'),
//ItemsController
array('item/list', 'pattern'=>'item/<model:\w+>', 'verb'=>'GET'),
array('item/view', 'pattern'=>'item/<model:\w+>/<id:\d+>', 'verb'=>'GET'),
array('item/update', 'pattern'=>'item/<model:\w+>/<id:\d+>', 'verb'=>'PUT'),
array('item/delete', 'pattern'=>'item/<model:\w+>/<id:\d+>', 'verb'=>'DELETE'),
array('item/create', 'pattern'=>'item/<model:\w+>', 'verb'=>'POST'),
//PackagesItems
array('packagesitems/list', 'pattern'=>'packagesitems/<model:\w+>', 'verb'=>'GET'),
array('packagesitems/view', 'pattern'=>'packagesitems/<model:\w+>/<id:\d+>', 'verb'=>'GET'),
array('packagesitems/update', 'pattern'=>'packagesitems/<model:\w+>/<id:\d+>', 'verb'=>'PUT'),
array('packagesitems/delete', 'pattern'=>'packagesitems/<model:\w+>/<id:\d+>', 'verb'=>'DELETE'),
array('packagesitems/create', 'pattern'=>'packagesitems/<model:\w+>', 'verb'=>'POST'),
// Other controllers
'user/registration/<id:\w+>' => 'user/registration',
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
),
),
/* 'db'=>array(
'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
), */
// uncomment the following to use a MySQL database
'db' => array(
'connectionString' => 'mysql:host=localhost;dbname=businessadvisor',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
),
'errorHandler' => array(
// use 'site/error' action to display errors
'errorAction' => 'site/error',
),
'log' => array(
'class' => 'CLogRouter',
'routes' => array(
array(
'class' => 'CFileLogRoute',
'levels' => 'error, warning',
),
// uncomment the following to show log messages on web pages
array(
'class'=>'CWebLogRoute',
),
),
),
),
// application-level parameters that can be accessed
// using Yii::app()->params['paramName']
'params' => array(
// this is used in contact page
'adminEmail' => '[email protected]',
),
);
Не могли бы вы добавить больше информации?
Обновить
Я думаю, что вы находитесь на правильном пути с авторизатором, но перед тем, как назначить роль пользователю, вы проверяете, являются ли роли пустыми. В вашем конфигурационном файле вы назначаете роли по умолчанию для пользователей.
'defaultRoles' => array('Authenticated', 'Guest'),
Метод assign () уже проверяет, назначена ли роль пользователю, см. # 50 (https://bitbucket.org/crisu83/yii-rights/src/02326a61da3171f5f81f12e49543a7c78a151bf0/components/RDbAuthManager.php?at=default&FileViewer = файл вид по умолчанию # RDbAuthManager.php-47)
так что, вероятно, должно быть что-то вроде этого
//...
if ($model->save()) {
$authorizer = Yii::app()->getModule("rights")->getAuthorizer();
$authorizer->authManager->assign('Authenticated', $model->id);
//...
Других решений пока нет …