CakePHP4 - How to create multiple user login with the Authentication plugin? - authentication

There are two types of users in the application I am developing. Users (table users.sql) for frontend users and AdminUsers (table admin_users.sql) for administration.
In CakePHP3, I solved this problem as follows with AuthComponent in AppController:
public function initialize()
{
parent::initialize();
// ...
//user login
if (!empty($this->request->params['prefix']) AND
$this->request->params['prefix'] == 'admin'
) {
$this->setAdminLogin();
}else{
$this->setUserLogin();
$this->Auth->allow();
}
// ...
}
//frontend users
public function setUserLogin()
{
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'loginRedirect' => [
'controller' => 'Users',
'action' => 'edit'
],
'logoutRedirect' => [
'controller' => 'Users',
'action' => 'login'
],
'authError' => false,
'authenticate' => [
'Xety/Cake3CookieAuth.Cookie' => [
'userModel' => 'Users',
'scope' => ['Users.active' => 1],
'fields' => ['username' => 'email','password' => 'password'],
],
'Form' => [
'userModel' => 'Users',
'scope' => ['Users.active' => 1],
'fields' => ['username' => 'email','password' => 'password'],
'passwordHasher' => [
'className' => 'Fallback',
'hashers' => ['Default']
]
],
],
'storage' => ['className' => 'Session', 'key' => 'Auth.User']
]);
}
//admin users
public function setAdminLogin()
{
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'loginAction' => [
'controller' => 'AdminUsers',
'action' => 'login',
],
'loginRedirect' => [
'controller' => 'AdminHelps',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'AdminUsers',
'action' => 'login'
],
'authError' => false,
'authenticate' => [
'Form' => [
'userModel' => 'AdminUsers',
'scope' => ['AdminUsers.active' => 1],
'fields' => ['username' => 'email','password' => 'password'],
'passwordHasher' => [
'className' => 'Fallback',
'hashers' => ['Default']
]
],
],
'storage' => ['className' => 'Session', 'key' => 'Auth.AdminUser']
]);
}
How can I do the same thing in CakePHP4 version with Authentication plugin? How can I create multiple user login?

Related

Uses a different AUTH cakephp

I have this auth in me appController
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'authenticate' > [
'Form' => [
'fields' => [
'username' => 'username',
'password' => 'password'
],
'finder' => 'auth'
]
],
'loginRedirect' => [
'controller' => 'Centros',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Users',
'action' => 'login',
'home'
]
]);
But i want use other auth in other login, i tried this but always return false but idk why.
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'authenticate' > [
'Form' => [
'userModel'=>'Personas',
'fields' => [
'username' => 'username',
'password' => 'password'
],
'finder' => 'auth'
]
],
'loginRedirect' => [
'controller' => 'Usuarios',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Personas',
'action' => 'login',
'home'
]
]);
In the latter case, if I change personas for user it works but not with personas.

Not added to data to table

I'm trying to validate the form.
I do not understand why form validation does not take place. Logically, it should work with the simple presence of symbols, but in fact, a simple test:
if (! $form->isValid()) {
echo 'not valid in check';
return ['form' => $form];
}
returned " echo 'not valid in check' "
What is the problem?
Input filter are very simple:
public function getInputFilter()
{
if ($this->inputFilter) {
return $this->inputFilter;
}
$inputFilter = new InputFilter();
$inputFilter->add([
'name' => 'id',
'required' => true,
'filters' => [
['name' => ToInt::class],
],
]);
$inputFilter->add([
'name' => 'text',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 1,
'max' => 1000,
],
],
],
]);
$inputFilter->add([
'name' => 'title',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
],
],
],
]);
$this->inputFilter = $inputFilter;
return $this->inputFilter;
}
Form? for added post:
class PostForm extends Form
{
public function __construct($name = null)
{
// We will ignore the name provided to the constructor
parent::__construct('post');
$this->add([
'name' => 'id',
'type' => 'hidden',
]);
$this->add([
'name' => 'title',
'type' => 'text',
'options' => [
'label' => 'Title',
],
]);
$this->add([
'name' => 'text',
'type' => 'textarea',
'options' => [
'label' => 'Text',
],
]);
$this->add([
'name' => 'submit',
'type' => 'submit',
'attributes' => [
'value' => 'Go',
'id' => 'submitbutton',
],
]);
}
}
Add action, if it need:
public function addAction()
{
$form = new PostForm();
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if (! $request->isPost()) {
return ['form' => $form];
}
// echo 'test';
$post = new Post();
$form->setInputFilter($post->getInputFilter());
$form->setData($request->getPost());
// echo 'before valid';
if (! $form->isValid()) {
echo 'not valid in check';
return ['form' => $form];
}
echo '\n';
echo 'valid';
$post->exchangeArray($form->getData());
$this->table->savePost($post);
return $this->redirect()->toRoute('post');
}
public function addAction()
{
---------------
if (!$form->isValid()) {
echo 'not valid in check';
return ['form' => $form];
}
---------
}
Validation:
public function getInputFilter()
{
if ($this->inputFilter) {
return $this->inputFilter;
}
$inputFilter = new InputFilter();
$inputFilter->add([
'name' => 'id',
'required' => true,
'filters' => [
['name' => ToInt::class],
],
]);
$inputFilter->add([
'name' => 'text',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 1,
'max' => 1000,
],
],
],
]);
$inputFilter->add([
'name' => 'title',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
],
],
],
]);
$inputFilter->add([
'name' => 'disc',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
],
],
],
]);
$this->inputFilter = $inputFilter;
return $this->inputFilter;
}

in yii2 : why my default language is en

how to change default language from en to another language
$config = [
'on beforeAction' => function ($event)
{
Yii::$app->language = 'fa';
},
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'language' => '/fa',
'components' => [
'jdate' => [
'class' => 'jDate\DateTime'
],
'mycomponent' => [
'class' => 'app\components\MyComponent',
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => '******',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'urlManager' => [
'class' => 'codemix\localeurls\UrlManager',
// Disable index.php
'languages' => ['fa', 'en'], // List all supported languages here
'showScriptName' => true,
// Disable r= routes
'enablePrettyUrl' => true,
'rules' => array(
// '' => 'site/index/fa',
// '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
// '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
),
],
'user' => [
'identityClass' => 'app\models\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' => require(__DIR__ . '/db.php'),
/*
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
*/
],
'params' => $params,
];
this is my $config in web.php
i want set default to 'fa' in root site !
my site automatic change lang to 'en' in first time in any browser!
i try to change lang with
'on beforeAction' => function ($event)
{
Yii::$app->language = 'fa';
},
but that is dosent correct work!
Remove this ridiculous 'on beforeAction' thing and just set
'language' => 'fa', // NOT '/fa'!
سلام
ویدئو های آقای صیف زاده رو مشاهده کردین؟
لینک زیر آموزش های ویدئویی ایشون هست . در شماره های 17 و 18 و 19
این موضوع رو آموزش دادن.
https://drive.google.com/drive/folders/0B4ZlNlar4Ij6XzJrbVZOejRCcGM

Creating new user role in Laravel 5.2

I am trying to create a new role originating_point_user in Laravel 5.2, besides user and admin. For that I have created a directory called OriginatingPointAuth within which there are two files AuthController.php and PasswordController.php. Also modified the kernal.php as below :
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
'origination_point_user' => \App\Http\Middleware\RedirectIfNotOriginationpointUser::class,
];
And auth.php as
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
'originating_point_users' => [
'driver' => 'eloquent',
'model' => App\OriginatingPointUser::class,
]
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
but when I tried to visit a route using originating_point_user middleware, it shows
ReflectionException in Container.php line 734: Class
originating_point_user does not exist
Route :
Route::group(['prefix'=>'originating-point-user'], function() {
Route::group(['prefix'=>'loading-details'], function() {
Route::get('/add', [
'as' => 'opu.loading_details.create',
'middleware' => ['originating_point_user'],
'uses' => 'OrdersController#add_loading_details'
]);
});
});
Also , it does not redirect to mentioned page defined in AuthController.php
In your kernel file you have registered your middleware as origination_point_user instead of originating_point_user . And when when calling the middleware you are calling with originating_point_user.
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
//change here originating_point_user
'originating_point_user' => \App\Http\Middleware\RedirectIfNotOriginationpointUser::class,
];

CakePHP 3.2: Prevent authError showing when user is not logged in

Even when user is not logged in and tries to open homepage, after being redirected to login page, authError is displayed.Is there an elegant way to prevent this, without modifying Auth component? This is how I load Auth component(I am using TinyAuth as authorization adapter):
$this->loadComponent('Auth', [
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'loginRedirect' => [
'controller' => 'Home',
'action' => 'index'
],
'authError' => 'You dont have permissions for that action',
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
],
'scope' => ['Users.active' => true],
'contain' => ['Roles']
]
],
'authorize' => [
'TinyAuth.Tiny' => [
'roleColumn' => 'role_id',
'rolesTable' => 'Roles',
'multiRole' => true,
'pivotTable' => 'roles_users',
'superAdminRole' => null,
'authorizeByPrefix' => false,
'prefixes' => [],
'allowUser' => false,
'adminPrefix' => null,
'autoClearCache' => true
]
]
]
);
According to CakePHP's documentation you can prevent the error message from being shown by setting authError to false.
Sometimes, you want to display the authorization error only after the
user has already logged-in. You can suppress this message by setting
its value to boolean false.
This should disable the error message:
if (!$this->Auth->user()) {
$this->Auth->config('authError', false);
}