I have 2 entities : User and Member to access different modules in my ZF2 application.
I have 2 different login forms to make the connection.
config of the Member dedicated module :
'doctrine' =>
[
'authenticationservice' =>
[
'platform' => true,
],
'authenticationstorage' =>
[
'platform' => true,
],
'authenticationadapter' =>
[
'platform' => true
],
'authentication' =>
[
'platform' =>
[
'storage' => 'Platform_Auth',
'objectManager' => EntityManager::class,
'identityClass' => Member::class,
'identityProperty' => 'login',
'credentialProperty' => 'password',
'credentialCallable' => function (Member $member, $password)
{
return ($member->getPassword() === md5($password));
}
],
]
],
And User dedicated module
'doctrine' =>
[
'authenticationservice' =>
[
'admin' => true,
],
'authenticationstorage' =>
[
'admin' => true,
],
'authenticationadapter' =>
[
'admin' => true
],
'authentication' =>
[
'admin' =>
[
'storage' => 'Admin_Auth',
'objectManager' => EntityManager::class,
'identityClass' => User::class,
'identityProperty' => 'login',
'credentialProperty' => 'password',
'credentialCallable' => function (User $user, $password)
{
return ($user->getPassword() === md5($password));
}
]
]
],
How can I use Doctrine authentication with 2 different configuration ?
Is there a way to achieve that ?
edit
I can use either one with a shared Authentication factory and extention (platform / admin) based on route ... But I don't know if it's a good idea ...
edit2
I have another error with the configured storage :
".... Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for Admin_Auth in ..."
Any help would be very appreciated
Related
Good morning,
I dont get any further in this Topic so i am writing a Question here.
First of all i created a DB Table with Data from the Tutorial: https://www.yiiframework.com/doc/guide/2.0/en/start-databases
Then i created a Rest Controller from that Tutorial with the Data above: https://www.yiiframework.com/doc/guide/2.0/en/rest-quick-start
The first example GET Request from the Tutorial works fine and gives me all of the data from the DB.
My Request URL: http://XX.X.X.12:XX90/country/
Now we come to my Error when trying to create a new Country in the DB via a POST Request.
When using the CURL Command from underneath the Tutorial with my Test-Data i get following error:
SQLSTATE[HY000]: General error: 1364 Field 'code' doesn't have a default value**strong text**
(
[0] => HY000
[1] => 1364
[2] => Field 'code' doesn't have a default value
)
My standard logging from rest api says that the POST Var is empty, but why?
I also tested sending POST Request via a Tool (Postman) but i get the same error.
$_GET = []
$_POST = []
$_FILES = []
$_COOKIE = []
$_SERVER = [....]
My Model:
<?php
namespace app\models;
use yii\db\ActiveRecord;
class Country extends ActiveRecord
{
}
My Controller:
<?php
namespace app\controllers;
use yii\rest\ActiveController;
class CountryController extends ActiveController
{
public $modelClass = 'app\models\Country';
}
My CURL Request:
curl -i -H "Accept:application/json" -H "Content-Type:application/json" \
-XPOST "http://XX.X.X.12:XX90/countries/" \
-d '{"code": "TEST", "name": "TestCountry", "population": 01}'
My web.php Config:
<?php
$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'aliases' => [
'#bower' => '#vendor/bower-asset',
'#npm' => '#vendor/npm-asset',
],
'name' => 'Yii2-ExtJS Rest API',
'modules' => [
'user' => [
'class' => Da\User\Module::class,
// ...other configs from here: [Configuration Options](installation/configuration-options.md), e.g.
'administrators' => ['admin'], // this is required for accessing administrative actions
// 'generatePasswords' => true,
// 'switchIdentitySessionKey' => 'myown_usuario_admin_user_key',
],
'debug' => [
'class' => 'yii\debug\Module',
'allowedIPs' => ['XX.X.X.XXX', 'XX.XXX.XXX.XXX', '127.0.0.1', '::1']
],
],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'XXXXXXXXXXXXXXXX',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => \yii\symfonymailer\Mailer::class,
'viewPath' => '#app/mail',
// send all mails to a file by default.
'useFileTransport' => true,
],
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
// 'levels' => ['error', 'warning', 'trace', 'info'],
],
],
],
'db' => $db,
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => false,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule',
'controller' => 'country'],
],
],
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
'allowedIPs' => ['XX.X.X.XX', '::1'],
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
//'allowedIPs' => ['127.0.0.1', '::1'],
];
}
return $config;
Suggestions?
You need to declare validation rules for working with the Rest API
Thanks to #Bizley
My Country Model now:
<?php
namespace app\models;
use yii\db\ActiveRecord;
class Country extends ActiveRecord
{
public function rules()
{
return [
[['code', 'name', 'population'], 'required']
];
}
}
I'm using Yii2-usuario for my user module.
I ran the migrations found in "first step" under the section "Creating the first Administrator during a migration", and only changed from new \Da\User\Model\User() to new \app\models\user\Model\User() like this
$user = new \app\models\user\Model\User([
'scenario' => 'create',
'email' => "admin#admin.com",
'firstname' => 'first',
'lastname' => 'last',
'password' => "verysecret" // >6 characters!
]);
it populated my tables correctly. But when i login to backend and try to view https://localhost/bla/backend/web/user/admin/index, i get a 403 forbidden error
in my backend main.php i have this
'components' => [
....
'authManager' => [
'class' => 'Da\User\Component\AuthDbManagerComponent',
'defaultRoles' => ['guest'],
],
],
'modules' => [
'user' => [
'class' => Da\User\Module::class,
'enableEmailConfirmation' => true,
'enableRegistration' => false,
'maxPasswordAge' => 90,
'enableGdprCompliance' => false,
'classMap' => [
'User' => 'app\models\user\Model\User',
],
'viewPath' => '#app/views/user',
'controllerMap' => [
//disable for backend
'profile' => [
'class' => Da\User\Controller\ProfileController::class,
'as access' => [
'class' => yii\filters\AccessControl::class,
'rules' => [['allow' => false]],
],
],
'recovery' => [
'class' => Da\User\Controller\RecoveryController::class,
'as access' => [
'class' => yii\filters\AccessControl::class,
'rules' => [['allow' => false]],
],
],
'Registration' => [
'class' => Da\User\Controller\RegistrationController::class,
'as access' => [
'class' => yii\filters\AccessControl::class,
'rules' => [['allow' => false]],
],
],
'Settings' => [
'class' => Da\User\Controller\SettingsController::class,
'as access' => [
'class' => yii\filters\AccessControl::class,
'rules' => [['allow' => false]],
],
],
'migrate' => [
'class' => \yii\console\controllers\MigrateController::class,
'migrationNamespaces' => [
'Da\User\Migration',
],
'migrationPath' => [
'#app/migrations',
'#yii/rbac/migrations',
],
],
],
],
my User model in backend\models\user\Model looks like this
use Da\User\Model\User as BaseUser;
class User extends BaseUser
{
public static function tableName()
{
return '{{%admin}}';
}
...
...
..
}
the list of RBAC and admin action don't work. i get a 403.
any idea what I'm missing here or did wrong? Thanks.
In the link which was provided for the first step with migration code, next is written
After installing the extension and having configured everything, you
need setup your application with the all the user related stuff, e.g.
You need to run this migration only after you did all installation steps mentioned here. But still it won't work because default user table will be populated, which was created from initial migration. This package creates its own user table and moreover in installation steps there is a Note
Note: If you are using Yii2's Advanced Application Template, before
starting to work with database, please ensure you have deleted
m130524_201442_init.php migration file which comes from the default
installation. It's located at
%PROJECT_DIR%/console/migrations/m130524_201442_init.php path.
Step 1
In your case i would do yii migrate/down 2, which will revert last 2 migrations(init migration contain user table description). Only in case if you didn't add more migrations :)
Total 2 migrations to be reverted:
m190124_110200_add_verification_token_column_to_user_table
m130524_201442_init
In case migration fail, you can run few SQL queries
drop table user;
delete from migration where version='m130524_201442_init';
and then delete m130524_201442_init.php and m190124_110200_add_verification_token_column_to_user_table.php(second one is optional but its your call) files
Step 2
After that according to docs, you need to run rbac + Yii 2 Usuario migrations all together as stated in this note
Note: You will still have to apply Yii 2 RBAC migrations by executing
./yii migrate --migrationPath=#yii/rbac/migrations. Remember that you
have to configure the AuthManager component first. Also, namespaced
migrations were introduced in Yii 2.0.10, so before using them
consider updating your framework installation version. If you are
using a Yii 2 version prior to 2.0.10, you'll have to copy the
migrations located on vendor/2amigos/yii2-usuario/src/User/Migration,
remove its namespaces and add it to your #app/migrations folder.
But before that, you need to move code below from backend/config/main.php to %PROJECT_DIR%/console/config/main.php
'controllerMap' => [
'migrate' => [
'class' => \yii\console\controllers\MigrateController::class,
'migrationNamespaces' => [
'Da\User\Migration',
],
'migrationPath' => [
'#app/migrations',
'#yii/rbac/migrations',
],
],
]
and add authManager into console config for rbac also
'authManager' => [
'class' => 'Da\User\Component\AuthDbManagerComponent',
],
in final your console/config/main.php should be similar to this
return [
// ....
'controllerMap' => [
// ...
'migrate' => [
'class' => \yii\console\controllers\MigrateController::class,
'migrationPath' => [
'#app/migrations',
'#yii/rbac/migrations', // Just in case you forgot to run it on console (see next note)
],
'migrationNamespaces' => [
'Da\User\Migration',
],
],
],
'components' => [
'authManager' => [
'class' => 'Da\User\Component\AuthDbManagerComponent',
],
// ...
],
// ...
];
Step 3
Run the migration from note
./yii migrate --migrationPath=#yii/rbac/migrations
Total 13 new migrations to be applied:
Da\User\Migration\m000000_000001_create_user_table
Da\User\Migration\m000000_000002_create_profile_table
Da\User\Migration\m000000_000003_create_social_account_table
Da\User\Migration\m000000_000004_create_token_table
Da\User\Migration\m000000_000005_add_last_login_at
Da\User\Migration\m000000_000006_add_two_factor_fields
Da\User\Migration\m000000_000007_enable_password_expiration
Da\User\Migration\m000000_000008_add_last_login_ip
Da\User\Migration\m000000_000009_add_gdpr_consent_fields
m140506_102106_rbac_init
m170907_052038_rbac_add_index_on_auth_assignment_user_id
m180523_151638_rbac_updates_indexes_without_prefix
m200409_110543_rbac_update_mssql_trigger
Step 4
Create and run migration from first steps without changing model in example.
Step 5
Remove user config from both backend/config/main.php and frontend/config/main.php
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true],
],
Apply authManager and user module with proper administrators option to respective config files. This array should contain same role name as in migration which you did in step 4.
'modules' => [
'user' => [
'class' => Da\User\Module::class,
'administrators' => ['admin']
],
],
'authManager' => [
'class' => 'Da\User\Component\AuthDbManagerComponent',
],
In the final your frontend and backend config files should be similar to this
return [
// ...
'modules' => [
'user' => [
'class' => Da\User\Module::class,
'administrators' => ['admin']
],
],
'components' => [
'authManager' => [
'class' => 'Da\User\Component\AuthDbManagerComponent',
],
// ....
]
// ...
];
Step 6
My favorite step :)
http://yourapp/index.php?r=user/admin visit and enter your creds from migration. Enjoy!
i wanna ask about redirect any page to login page after session timeout in yii2, i try to do this
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => false,
'returnUrl' => 'index.php?r=site/login',
'identityCookie' => [
'name' => '_backendIdentity',
],
],
'session' => [
'name' => 'BACKENDSESSID',
'savePath' => __DIR__ . '/../runtime',
],
but it return to login page when i'm at index.php page, if i go to another action and the session timeout it will return
PHP Notice – yii\base\ErrorException
Trying to get property of non-object
1. in /var/www/html/spmoa/backend/controllers/StaffController.php at line 174
165166167168169170171172173174175176177178179180181182183
public function actionMyProfile() {
error here -> $id = Yii::$app->user->identity->staff->id;
$model = $this->findModel($id);
Please help me
Try with behaviors
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['youraction'],
'allow' => true,
'roles' => ['#'], // you can use matchCallback to create more powerful check
],
],
],
];`enter code here`
}
Please use session and timeout as below in your config/main.php file:
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'authTimeout' => 3600*4, // auth expire 4 hours
],
'session' => [
'class' => 'yii\web\Session',
'cookieParams' => ['httponly' => true, 'lifetime' => 3600*4],
'timeout' => 3600*4, //session expire 4 hours
'useCookies' => true,
],
],
//and in this beforeRequest give actions that can be accessed by guest user.
'as beforeRequest' => [
'class' => 'yii\filters\AccessControl',
'rules' => [
[
'allow' => true,
'actions' => ['login', 'error', 'forgotpassword', 'resetpassword'],
],
[
'allow' => true,
'roles' => ['#'],
],
],
],
You can check condition Before action : If user is logged in or not :
public function beforeAction($action){
if (Yii::$app->user->isGuest){
return $this->redirect(['site/login'])->send(); // login path
}
}
I am trying to run a console controller from the terminal, but i am getting this errors every time
Error: Getting unknown property: yii\console\Application::user
here is the controller
class TestController extends \yii\console\Controller {
public function actionIndex() {
echo 'this is console action';
} }
and this is the concole config
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'modules' => [],
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
],
'params' => $params];
I tried running it using these commands with no luck
php yii test/index
php yii test
php ./yii test
can anyone help please?
Console application does not have Yii->$app->user. So, you need to configure user component in config\console.php.
like as,
config\console.php
'components' => [
.........
......
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\models\User',
//'enableAutoLogin' => true,
],
'session' => [ // for use session in console application
'class' => 'yii\web\Session'
],
.......
]
More info about your problem see this : Link
OR
Visit following link :
Yii2 isGuest giving exception in console application
Note : There's no session in console application.
Set in \console\config\main.php
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\models\Credential',// class that implements IdentityInterface
//'enableAutoLogin' => true,
],
],
'params' => $params,
];
now in your \console\controller\AbcController.php add init method
public function init() {
parent::init();
Yii::$app->user->setIdentity(Credential::findOne(['id'=><cronloginid>]));
}
create a cron login and pass that login id in variable with this config your Blameable Behavior of yii2 will work
As #GAMITG said, you must config user component in config file, but unfortunately, you couldn't access session in console, that's because session is not available in console. Maybe you could solve the problem like this:
$user_id = isset(Yii::$app->user->id) ? Yii::$app->user->id : 0;
I have one table whose name is admins. Its contains username and password fields. My sales user use admins table for the sales login. I want to login sales using AuthComponent. I have write code for this as below.
AppController
public $components = [
'Auth' => [
'loginAction' => [
'controller' => '',
'action' => 'login'
],
'logoutRedirect' => [
'controller' => '',
'action' => 'login'
],
'loginRedirect' => [
'controller' => '',
'action' => 'deshboard'
],
'className' => 'MyAuth'
]]
public function beforeFilter() {
$this->Auth->authenticate = [
'Form' => ['userModel' => 'admin', "fields" => ["username" => "username",
"password" => "password"]
]];
}
SalesController
function login() {
$post = $this->request->data('Admin');
if ($this->request->is('post') && !empty($post)) {
//var_dump($this->Auth->login());exit;
if ($this->Auth->login()) {
return $this->Auth->redirect($this->Auth->redirectUrl());
}
// perform login throttling (failure and block) if Sales or Admin portal
// set an appropriate failure message
}
}
When I have print the return value of auth->login() function. Its always return false.
I have search a lots for this issue but I am unable to find any proper answer.
Thanks in advance for helping me.
I have find the solution for my above issue.
This issue is because of passwordHaser. I use difference password in the add or update password so we have to define the passwordHaser in the component configuration, if we don’t use simple encription.
'Auth' => [
'className' => 'MyAuth',
'authenticate' => [
'Form' => [
'userModel' => 'Admin',
'fields' => [
'username' => 'username',
'password' => 'password'
],
'passwordHasher' => [
'className' => 'Simple'
]
]
],
],