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

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.

Related

After a successful login, I want to be redirected to the screen I was on before I logged in. getLoginRedirect() does not work

Suppose you were in the user list screen. From there you will go to the login screen to log in. There, you will enter your email and password and enter the submit button.
You have successfully logged in.
If the login is successful, we want to be redirected to the user list screen.
If you were in the user details screen, you will be redirected to the user details screen by
If the user was on the edit screen, the user editing screen
I have read the AuthenticationPlugin documentation at book.cakephp.org.
There I learned to use getLoginRedirect() to achieve this functionality.
I am aware that what I want to do will happen once I set up in the steps below.
However, getLoginRedirect() returns null.
What do I need to do?
What am I missing?
What's wrong?
// in Application.php
public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
{
$path = $request->getPath();
$authenticationService = new AuthenticationService([
'unauthenticatedRedirect' => '/',
'queryParam' => 'redirect', // <- I believe this is the only one that matters.
]);
// Abbreviated below....
}
// in UsersController
public function login()
{
$this->request->allowMethod(['get', 'post']);
if ($this->request->is('post')) {
$result = $this->Authentication->getResult();
$requestData = $this->request->getData();
if ($result->isValid()) {
// I want to get the original url. But null is passed.
$redirect = $this->Authentication->getLoginRedirect() ?? '/';
return $this->redirect($redirect);
}
if ($this->request->is('post') && !$result->isValid()) {
$this->Flash->error(__('メールアドレス、またはパスワードが間違っています。'));
}
}
}
I think I've disclosed everything related to getLoginRedirect(). If there is something missing or something you are curious about, please feel free to let me know.
Please help me. Please help me...
The login redirect functionality provided by the plugin only works automatically when you are being redirected to the login URL after accessing a URL that requires authentication while not being logged in. In that case the authentication middleware will set the redirect query string variable with the current URL, so that the component can pick it up after the redirect to the login URL.
If you manually visit the login URL, then you'd also need to manually set the redirect query string variable, ie in your menu where you build the link that takes you to the login, add the current URL to the query string, something along the lines of this:
$service = $this->request->getAttribute('authentication');
// here `$queryParam` would by default be `redirect`
$queryParam = $service->getConfig('queryParam');
echo $this->Html->link('Login', [
'plugin' => null,
'prefix' => false,
'controller' => 'Users',
'action' => 'login',
'?' => [
$queryParam => $this->request->getRequestTarget(),
],
]);
So if you're on /users/show, the login link's URL would look something like:
/login?redirect=/users/show
and the form helper that builds your login form should pick up that exact URL, so that after submitting the form, the authentication component can read the redirect URL from the current URL accordingly.
See also
Cookbook > Views > Helpers > Html > Creating Links

Laravel Multi Roles

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

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
]
]
]

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 remove auth from the pages controller in CakePHP?

I'm using CakePHP's Auth component and it's in my app_controller.php.
Now I want to allow specific views from the pages controller. How do I do that?
Copy the pages_controller.php file in cake/libs/controllers to your app/controllers/ dir. Then you can modify it to do anything you want. With the auth component, the typical way to allow specific access is like this:
class PagesController extends AppController {
...
function beforeFilter() {
$this->Auth->allow( 'action1', 'allowedAction2' );
}
...
I recommend highly copying the file to your controllers dir, rather than editing it in place, because it will make upgrading cake much easier, and less likely that you accidentally overwrite some stuff.
You could add the following to your app_controller.
function beforeFilter() {
if ($this->params['controller'] == 'pages') {
$this->Auth->allow('*'); // or ('page1', 'page2', ..., 'pageN')
}
}
Then you don't have to make a copy the pages controller.
I haven't tried the other ways but this is also the right way to allow access to all those static pages as display is that common action.
In app_controller:
//for all actions
$this->Auth->allow(array('controller' => 'pages', 'action' => 'display'));
//for particular actions
$this->Auth->allow(array('controller' => 'pages', 'action' => 'display', 'home'));
$this->Auth->allow(array('controller' => 'pages', 'action' => 'display', 'aboutus'));