Laravel Multi Roles - laravel-6

I am just new in Laravel 6. I installed the default auth in Laravel. I want to have multiple user.
Admin - This user can monitor everything from the dashboard and other pages.
Maker - This user can create only a job.
Approver - This user can only approve the job but it can't create job.
Viewer - This user can only view all the pages of the application.
Other this I need to auto generate an OPGROUP ID for each companies. And I want to the user who is logged in only see what are the data that is save under their account.
Can you help me to achieve my goal please.

We have to follow the below steps
First, we have to create a table by using the below command in which we will store the roles
php artisan make: migration create_admins_table --create=admins
after creating the migration, we will add the columns
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken(); // I put this linke incase if it was missing
then we will run the migration
php artisan migrate
then we will run the below command
php artisan make: model Admin
do not forget to add the below code in the admin.php model if there aren't
protected $guard = 'admin';
protected $fillable = [
'name', 'email', 'password',
];
we have to set up our guard in the config/auth.php file
right after the guards, we should add the below code
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'admin-api' => [
'driver' => 'token',
'provider' => 'admins',
],
right after the provider, we should add the below code
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
let's create controller
php artisan make: controller AdminController
let's create a view called admin and route in the web.php
Route::get()'/admin',AdminController#index)
and add the below code in the admin controller
public function __construct()
{
$this->middleware('auth:admin');
}
You can insert user roles in the table (Admin, Maker, Approver, Viewer) and direct it to views that you want

Related

Cakephp 3 Authentication plugin, login URL did not match

I want to use the Authentication plugin for CakePHP 3.8 and I'm having problems that are not in documentation.
After follow Getting Started (https://book.cakephp.org/authentication/1/en/index.html) I have one question.
Originally $fields were specified to change username and password relation in real database, same that Auth component, and login URL is where login form si loaded.
First, in getting started or any part of documentation doesn't says about a login view (form), so, like old Auth Component I created this to Users/login.ctp
<div class="users form">
<?= $this->Flash->render('auth') ?>
<?= $this->Form->create() ?>
<fieldset>
<legend><?= __('Please enter your email and password') ?></legend>
<?= $this->Form->input('email') ?>
<?= $this->Form->input('password') ?>
</fieldset>
<?= $this->Form->button(__('Login')); ?>
<?= $this->Form->end() ?>
</div>
My code in Application.php includes this (with its respective uses and implements):
public function getAuthenticationService(ServerRequestInterface $request, ResponseInterface $response)
{
$service = new AuthenticationService();
$fields = [
'username' => 'email',
'password' => 'password'
];
// Load identifiers
$service->loadIdentifier('Authentication.Password', compact('fields'));
// Load the authenticators, you want session first
$service->loadAuthenticator('Authentication.Session');
$service->loadAuthenticator('Authentication.Form', [
'fields' => $fields,
'loginUrl' => '/users/login'
]);
return $service;
}
But when I try to login, I have this error, after var_dump in login.ctp I get this:
object(Authentication\Authenticator\Result)[124]
protected '_status' => string 'FAILURE_OTHER' (length=13)
protected '_data' => null
protected '_errors' =>
array (size=1)
0 => string 'Login URL `http://localhost/users/login` did not match `/users/login`.' (length=70)
If I comment 'loginUrl' => '/users/login' line, then login works fine.
Additional notes:
- I've tested with hashed and textplane passwords, same results.
- I've added $this->Authentication->allowUnauthenticated(['view', 'index', 'login', 'add']); in beforeFilter to access login.
- It's a clean cakephp 3.8 install, only database is the same for tests.
- I've added Crud only with cake console.
I would like to learn more about that loginURL, I should include some uses in UsersController? What causes this error?
Thank you
The error messages is currently a little misleading, as it doesn't show you the possible base directory, which is the actual issue that you are experiencing. I've proposed a fix for that, which may make into the next release.
When your application lives in a subdirectory, you need to make sure that your login URL configuration takes that into account, that is by either passing the URL including the base directory, which you could do either manually:
'loginUrl' => '/myapp/users/login'
or by using the router:
'loginUrl' => \Cake\Routing\Router::url('/users/login')
'loginUrl' => \Cake\Routing\Router::url([
'plugin' => null,
'prefix' => null,
'controller' => 'Users',
'action' => 'login'
])
Another option would be to use the routes based URL checker, which can be configured via the form authenticators urlChecker option, then you can define the login URL using URL arrays, without having to use the router:
'urlChecker' => 'Authentication.CakeRouter',
'loginUrl' => [
'plugin' => null,
'prefix' => null,
'controller' => 'Users',
'action' => 'login'
]
See also:
Authentication Cookbook > Authenticators > Form
Authentication Cookbook > URL Checkers

Two Yii2 applications Login conflict

I have two different Yii2 Basic template applications on the same hosting. When I login to the first Yii2 app and then go to login the secon Yii2 app, the first automatically logs out and vice versa. They use different cookieValidationKey in config. How to fix this.
I'm not sure if it fixes your problem but try to change configuration for identityCookie in one of the applications.
'components' => [
// ...
'user' => [
// ...
'identityCookie' => [
'name' => '_identity', // <-- change _identity to something else
'httpOnly' => true
]
]
]

Routing in module doesn't work Yii 2

I am new in Yii 2 and my problem is about routing inside a module.
I have a module in my app which is a profile cabinet both for users and admins. I created a CabinetController instead of DefaultController and also I created a AdminController and UserController.
What I want? I want this CabinetController received request and forward it to either AdminController or UserController after verify wether the user is admin or not.
In config file I set a default route for module as "cabinet"(as I understand this is a name for default controller). And in "rules" part of UrlManager I wrote following:
'modules' => [
'cabinet' => [
'class' => 'app\modules\cabinet\Module',
'defaultRoute' => 'cabinet'
],
'utility' => [
'class' => 'c006\utility\migration\Module',
],
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<_c:\w+>/' => '<_c>/',
'<_c:[\w\-]+>/<_a:\w+>' => '<_c>/<_a>',
'<_m:cabinet>/<_a:\w+>' => '<_a>',
],
],
If I go to "my-site.com/cabinet" it works fine and open "admin/index" because I made it to redirest this request to AdminController/actionIndex, but once I go to somewhere like "my-site.com/cabinet/users" it respond with 404 NotFound. I open the loger and see: exception 'yii\base\InvalidRouteException' with message 'Unable to resolve the request "cabinet/desktop"
This is my CabinetController and the way I forward requests to Admin/UserController:
public function init()
{
parent::init();
$this->user = $this->findModel();
$this->controllerToUse = $this->user->isAdmin() ? 'admin' : 'user';
}
public function actionIndex()
{
return $this->module->runAction($this->controllerToUse . '/' . $this->action->id);
}
If I change defaultAction in CabinetController it run this action normally as expected. Or if I go to "my-site.com/cabinet/admin/users" again it works good, because it found a controller in the url(as I think).
Routing can be a bit tricky in Yii2, it follows a few rules you need to understand which can be found here
But if i understand you correctly Admin/UserController is part of the Cabinet module? and you want Yii to route /cabinet/users to /cabinet/admin/users
You'll need to add some rules in your UrlManager see Rules
Example:
'rules' => [
'<module:cabinet>/<action:\w+>' => '<module>/admin/<action>',
],
Hope it helps

How to force include a field into AuthComponent's user?

I have a role field for my users that I really need to access. If a user is an admin, they would have extra available actions on many of my views.
So, in the beforeRender of my AppController I do this:
$this->set('loggedInUser', $this->Auth->user());
This way, I can use $loggedInUser to access the logged in user in all of my views.
The thing is that from the 10 fields that the table users has, the AuthComponent seems to fetch only these 4: id, username, verified and modified.
I cannot find anywhere in my code specifying those 4 fields as a whole.
What is causing AuthComponent to select randomly those specific fields? How can I force the fields I need?
Extra information in case it is needed:
All the fields of the users table are:
id
username
email
password
role
verification_hash
email_md5
verified
created
modified
The initialization of AuthComponent inside my AppController is the following:
$this->loadComponent(
'Auth',
[
'authorize' => 'Controller',
'authError' => 'You are not allowed to go there',
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'username',
'email' => 'email',
'password' => 'password'
]
]
],
'loginAction' => [
'controller' => 'Pages',
'action' => 'display',
'home'
]
]
);
The problem was with the accessible fields in my entity. I had left there some non-existent fields that I had forgotten to remove.
For some reason it seems that the AuthComponent did not like those non-existent fields and it fetched only 4 fields.
Removing from the accessible fields the ones that did not exist seems to fix the problem.

How to access logged in user data, in a layout. (CakePHP 3)

I have a web app programmed in cakephp 3.
I want to have a layout that shows logged in user first & last name. like something in facebook main page. that you can click and go to your page.
I want to have this feature in every page, so I decided to use layouts.
my Users table is like:
| id | username | password | email | first_name | last_name | created | modified |
I use Authentication Component like this:
$this->loadComponent('Auth', [
'loginRedirect' => [
'controller' => 'Pages',
'action' => 'display'
],
'logoutRedirect' => [
'controller' => 'Users',
'action' => 'login'
],
'authError' => 'Authentication Error'
]);
How can I load user first name and last name in a layout?
you can do it by using Session. like:
$user = "";
$loguser = $this->Session->read('Auth.User');
if(!empty($loguser)){
$user = $loguser['first_name']." ".$loguser['last_name'];
}
UPDATE (8/23/2015) :
as recently cakephp says that SessionHelper is deprecated, you should use request->session() instead.
$loguser = $this->request->session()->read('Auth.User');
if(!$loguser) {
$user = $loguser['first_name'].' '.$loguser['last_name'];
}
You can pass your variables through controller to views by:
$this->set('user','users_data');
and then pass this to the layout:
$this->assign('user',$user);
and show it in the layout by:
$this->fetch('user');
You need to pass the data from the controller to the view environment.
I've found the best way to do this globally is to put the set() statement in AppController::beforeRender-
// make logged in user's first name available to the view (mainly for menu)
$name="(none)";
if($this->Auth->user()) {
$name = $this->Auth->user("first_name");
}
$this->set("user_first_name", $name);
Just please make sure not to put any sensitive data there, eg password, as a bug at the template level could potentially expose it.