Highly customizable and extensible user management, authentication, and authorization Yii2 extension
tonydspaniard on master
Add nl_NL Dutch translation. Mi… Improve translations Merge pull request #301 from sq… (compare)
maxxer on master
Fix password expire service #293 (compare)
Pls, help me. The problem with authorization through social network new user. Return 404 /user/registration/connect?code=FMwHPLCI*DJC
// Da\User\Controller\RegistrationController
public function actionConnect($code)
{
/** @var SocialNetworkAccount $account */
$account = $this->socialNetworkAccountQuery->whereCode($code)->one();
if ($account === null || $account->getIsConnected()) {
throw new NotFoundHttpException(); // !!!!!!!!!!!!!!!!!!!!!!!!!!!!! social_account not saved
}
...
}
// Da\User\Service\SocialNetworkAuthenticateService
protected function createAccount()
{
$data = $this->client->getUserAttributes();
/** @var SocialNetworkAccount $account */
$account = $this->controller->make(
SocialNetworkAccount::class,
[],
[
'provider' => $this->client->getId(),
'client_id' => $data['id'],
'data' => json_encode($data),
'username' => $this->client->getUserName(),
'email' => $this->client->getEmail(),
]
);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! User not found => social_account not save
if (($user = $this->getUser($account)) instanceof User) {
$account->user_id = $user->id;
$account->save(false);
}
return $account;
}
I tried all events. The problem is solved only this way, otherwise redirecting to 404
'security' => [
'class' => 'Da\User\Controller\SecurityController',
'layout' => '@app/views/layouts/main_with_container',
// beforeAuthenticate
// afterAuthenticate
// beforeConnect
// afterConnect
'on beforeAuthenticate' => function($event){
/** @var Da\User\Event\SocialNetworkAuthEvent $event */
/** @var Da\User\Model\User $user */
if(Da\User\Model\User::find()->where(['email' => $event->client->email])->exists()) return;
$user = Yii::createObject([
'class' => Da\User\Model\User::class,
'scenario' => 'create',
'email' => $event->client->email,
'username' => $event->client->username,
'password' => null
]);
$mailService = \Da\User\Factory\MailFactory::makeWelcomeMailerService($user);
$userCreateService = Yii::createObject([
'class' => \Da\User\Service\UserCreateService::class,
], [$user, $mailService]);
$userCreateService->run();
$event->account->user_id = $user->id;
$event->account->save();
Yii::$app->user->login($user);
}
],
Hello. I am trying to install the Usuario module in a fresh Yii2 Advanced Template instance. I have the baseline instance working (frontend and backend), but when I attempt to apply the migrations according to your instructions [here|https://yii2-usuario.readthedocs.io/en/latest/installation/advanced-application-template/] I get an error:
yii-adv-app>> php yii migrate
Yii Migration Tool (based on Yii v2.0.39.2)
Exception 'yii\base\InvalidArgumentException' with message 'Invalid path alias: @Da/User/Migration'
in /Users/xxxxxx/PhpstormProjects/wwwrootYii2Portals/yii-adv-app/vendor/yiisoft/yii2/BaseYii.php:154
Stack trace:
#0 /Users/xxxxxx/PhpstormProjects/wwwrootYii2Portals/yii-adv-app/vendor/yiisoft/yii2/console/controllers/BaseMigrateController.php(710): yii\BaseYii::getAlias('@Da/User/Migrat...')
#1 /Users/xxxxxx/PhpstormProjects/wwwrootYii2Portals/yii-adv-app/vendor/yiisoft/yii2/console/controllers/BaseMigrateController.php(890): yii\console\controllers\BaseMigrateController->getNamespacePath('Da\User\Migrati...')
Is there any reason why the Usuario code would generate this error? I'm at a loss why this is happening.
I see now what happened. The instructions show two methods for performing the migrations: the first method is from the command line, and the second requires modification of the console->config->main.php, specifically, adding a controllerMap configuration with a definition for migrationNamespace pointing to Da\User\Migration.
When the first method didn't work, I tried the second, but the instructions don't tell you what to do after making the changes to the configuration file. So I went back to the first method but forgot to remove my controllerMap changes to the console config file.
Once I removed the controllerMap settings from console->config->main.php, I was able to run the migration from the command line without the invalidArgumentException.
So, I removed the controllerMap settings and tried the command line version again.
I'm still getting the Invalid path alias from the first command:
yii-adv-app/> php yii migrate --migrationNamespaces=Da\User\Migration;
Yii Migration Tool (based on Yii v2.0.39.2)
Exception 'yii\base\InvalidArgumentException' with message 'Invalid path alias: @Da/User/Migration'
in /Users/jgoetz/PhpstormProjects/wwwrootYii2Portals/yii-adv-app/vendor/yiisoft/yii2/BaseYii.php:154
Stack trace:
#0 /Users/jgoetz/PhpstormProjects/wwwrootYii2Portals/yii-adv-app/vendor/yiisoft/yii2/console/controllers/BaseMigrateController.php(710): yii\BaseYii::getAlias('@Da/User/Migrat...')
#1 /Users/jgoetz/PhpstormProjects/wwwrootYii2Portals/yii-adv-app/vendor/yiisoft/yii2/console/controllers/BaseMigrateController.php(890): yii\console\controllers\BaseMigrateController->getNamespacePath('Da\User\Migrati...')
To correct the invalid path alias error, I added an alias in common->config->main.php:
return [
'aliases' => [
'@bower' => '@vendor/bower-asset',
'@npm' => '@vendor/npm-asset',
@Da' => '@vendor/2amigos/yii2-usuario/src'
],
'vendorPath' => dirname(dirname(DIR)) . '/vendor',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
My example console.php file:<?php
$params = require DIR . '/params.php';
$db = require DIR . '/db.php';
$config = [
'id' => 'basic-console',
'basePath' => dirname(DIR),
'bootstrap' => ['log'],
'controllerNamespace' => 'app\commands',
'aliases' => [
'@bower' => '@vendor/bower-asset',
'@npm' => '@vendor/npm-asset',
'@tests' => '@app/tests',
'@Da' => '@vendor/2amigos/yii2-usuario/src'
],
'modules' => [
'user' => [
'class' => Da\User\Module::class,
],
],
'components' => [
'authManager' => [
'class' => 'Da\User\Component\AuthDbManagerComponent',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'Da\User\Model\User',
'class' => 'Da\User\Model\User',
'enableAutoLogin' => true,
],
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
],
'params' => $params,
/
'controllerMap' => [
'fixture' => [ // Fixture generation command line.
'class' => 'yii\faker\FixtureController',
],
],
/
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
}
return $config;
My complete web.php configuration file:
<?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',
'@Da' => '@vendor/2amigos/yii2-usuario/src'
],
'modules' => [
'user' => [
'class' => Da\User\Module::class,
],
],
'components' => [
'authManager' => [
//'class' => 'yii\rbac\DbManager', // original setting
'class' => 'Da\User\Component\AuthDbManagerComponent',
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'M6Pdf__ZcD6xzjNa_nlUagM4rNZwhrSi',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'Da\User\Model\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
'urlManager' => [
'class' => 'yii\web\UrlManager',
// Disable index.php
'showScriptName' => false,
// Disable r= routes
'enablePrettyUrl' => true,
'rules' => array(
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
),
],
],
'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' => ['127.0.0.1', '::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;
My "administrator migration" file:
<?php
use yii\db\Migration;
/**
Class m201202_021321_add_admin_user_and_role
/
class m201202_021321_add_admin_user_and_role extends Migration
{
/*
{@inheritdoc}
*/
public function safeUp()
{
$auth = Yii::$app->authManager;
// create a role named "administrator"
$administratorRole = $auth->createRole('administrator');
$administratorRole->description = 'Administrator';
$auth->add($administratorRole);
// create permission for certain tasks
$permission = $auth->createPermission('user-management');
$permission->description = 'User Management';
$auth->add($permission);
// let administrators do user management
$auth->addChild($administratorRole, $auth->getPermission('user-management'));
// create user "admin" with password "verysecret"
$user = new \Da\User\Model\User([
'scenario' => 'create',
'email' => "email@example.com",
'username' => "admin",
'password' => "verysecret" // >6 characters!
]);
$user->confirmed_at = time();
$user->save();
// assign role to our admin-user
$auth->assign($administratorRole, $user->id);
}
/**
{@inheritdoc}
*/
public function safeDown()
{
$auth = Yii::$app->authManager;
// delete permission
$auth->remove($auth->getPermission('user-management'));
// delete admin-user and administrator role
$administratorRole = $auth->getRole("administrator");
$user = \Da\User\Model\User::findOne(['name'=>"admin"]);
$auth->revoke($administratorRole, $user->id);
$user->delete();
$auth->remove($administratorRole);
}
/*
// Use up()/down() to run migration code without a transaction.
public function up()
{
}
public function down()
{
echo "m201202_021321_add_admin_user_and_role cannot be reverted.\n";
return false;
}
*/
}
Trying to get property 'enableGdprCompliance' of non-object (/var/www/html/yii2-basic/vendor/2amigos/yii2-usuario/src/User/Model/User.php:167)
Hey guys!
Having an issue implementing the recaptcha on the Login side of things. Has anyone got this working yet? I just get the error: verification code is incorrect.
Hello!
I'm having trouble with propper install of yii2-usuario.
It seems like i did all all 3 steps in Getting Started instruction (composer require, migrations and config of user module).
But now my index page gives errow: Getting unknown property: Da\User\Module::isGuest
I also tryed to create the first Administrator during a migration (as on https://yii2-usuario.readthedocs.io/en/latest/helpful-guides/first-steps/)
This was giving error: Exception: Trying to get property 'enableGdprCompliance' of non-object (/home/akovaleva/Projects/my_portret/vendor/2amigos/yii2-usuario/src/User/Model/User.php:167)
Unfortunatly I don't undestend where things went wrong...
'authManager' => [
'class' => 'yii\rbac\DbManager',
// 'defaultRoles' => ['guest'],
],
'user' => [
'class' => Da\User\Module::class
],