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.
Related
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
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
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
]
]
]
I'm using Yii 2 and building a RESTful API inside a Yii 2 module called apiv1.
The file config.php for the module apiv1 looks like this:
// ...
urlManager' => [
// ...
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => [
'likes',
],
],
],
];
For instance, GET /apiv1/likes works, but I'd like to set up a route to handle GET /api/v1/likes. How can this be done either individually or for the entire module as a general route from api/v1 to apiv1?
You can use the prefix attribute to customize your rest/UrlRule routes.
E.g., for your case, you should be able to do:
[
'class' => 'yii\rest\UrlRule',
'controller' => 'likes',
'prefix' => 'api/v1',
]
For more info, you can see the REST routing guide and yii-rest-rule API docs - in particular, see the $patterns and $extraPatterns properties for additional configuration options.
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.