Session views helper CakePHP3 - cakephp

This is my code in my view:
if($this->request->session->read('Auth.User')) {
echo $this->Html->link('Log Out', array('controller' => 'users','action' => 'logout'));
}
if(!$this->request->session->read('Auth.User')) {
echo $this->Html->link('Log Out', array('controller' => 'users','action' => 'logout'));
}
But I get this error:
Call to a member function read() on null
I'm connected but is dont work.

You can try another way for checking Authenticate User from your View
From your AppController you can set $AuthUser variable
Example:
public function initialize(){
parent::initialize();
$this->loadComponent('Auth', [
#All configurations for AuthComponent
]);
$this->set('AuthUser',$this->Auth->user()); #Set for all Views
}
Note : Now you can use $AuthUser variable to your View directly.

Related

Applying sessions in cakephp 3.2

Im using cakephp 3.2 to build an application. Im using the bookmarks tutorial as a basis for my project. in one of my bookmarks .ctp view files I would like to have a number of select boxes with data specific to the user loggged in. i have two tables namely users and bookmarks. My bookmarks table contains foreign key from users table user_id.
Here's my bookmark table with the fields i would like the dropdowns. id, user_id, title, systemregistration, systemroles, country, province, metropolitan.
Code for my appcontroller
namespace App\Controller;
use Cake\Controller\Controller;
use Cake\Event\Event;
/**
* Application Controller
*
* Add your application-wide methods in the class below, your controllers
* will inherit them.
*
* #link http://book.cakephp.org/3.0/en/controllers.html#the-app-controller
*/
class AppController extends Controller
{
/**
* Initialization hook method.
*
* Use this method to add common initialization code like loading components.
*
* e.g. `$this->loadComponent('Security');`
*
* #return void
*/
/*public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
}*/
public function initialize()
{
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
]
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
//'storage' => 'Session'
'Session'
]);
// Allow the display action so our pages controller
// continues to work.
$this->Auth->allow(['display']);
}
/*public function initialize()
{
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'loginRedirect' => [
'controller' => 'Bookmarks',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
]
]);
}
public function beforeFilter(Event $event)
{
$this->Auth->allow(['index', 'view', 'display']);
}*/
/**
* Before render callback.
*
* #param \Cake\Event\Event $event The beforeRender event.
* #return void
*/
public function beforeRender(Event $event)
{
if (!array_key_exists('_serialize', $this->viewVars) &&
in_array($this->response->type(), ['application/json', 'application/xml'])
) {
$this->set('_serialize', true);
}
}
}
//BookmarksController looks like this
namespace App\Controller;
use App\Controller\AppController;
/**
* Bookmarks Controller
*
* #property \App\Model\Table\BookmarksTable $Bookmarks
*/
class BookmarksController extends AppController
{
public function internalprotocol()
{
$bookmark = $this->Bookmarks->newEntity();
$users = $this->Bookmarks->Users->find('list', ['limit' => 200]);
$tags = $this->Bookmarks->Tags->find('list', ['limit' => 200]);
$this->set(compact('bookmark', 'users', 'tags'));
$this->set('_serialize', ['bookmark']);
$bookmarks = $this->paginate($this->Bookmarks);
$this->set(compact('bookmarks'));
$this->set('_serialize', ['bookmarks']);
}
}
//my internalprotocol.ctp looks like this
<div>
<?php echo $this->Form->input('user_id', ['options' => $bookmarks]); ?>
<?php echo $this->Form->input('title', ['options' => $bookmarks]); ?>
<?php echo $this->Form->input('systemregistration', ['options' => $bookmarks]); ?>
<?php echo $this->Form->input('systemroles', ['options' => $bookmarks]); ?>
<?php echo $this->Form->input('country', ['options' => $bookmarks]); ?>
</div>
I would like to populate each of the fields with data specific to the user logged in. Could you please help!
You don't need to do anything. If a login is successful you can access the logged in user details through the Auth component using $this->Auth->user();
If you need to add any more information to the session you can use the Session component like $this->Session->write('User.AscociatedData', $AscociatedData);
Easiest way to access this data in the view is to set authenticated user as a view variable in the controller:
$this->set('user',$this->Auth->user());
then you can accesses the users info in the view with $user e.g$user->fieldName
Not entirely sure what your asking but I hope one of my answers is relevant.
we only need to show bookmarks for the currently logged in user.
We can do that by updating the call to paginate().Make your index() action from Controller/BookmarksController.php look like:
public function index()
{
$this->paginate = [
'conditions' => [
'Bookmarks.user_id' => $this->Auth->user('id'),
]
];
$this->set('bookmarks', $this->paginate($this->Bookmarks));
$this->set('_serialize', ['bookmarks']);
}
We should also update the tags() action and the related finder method as we done for bookmarks above
Please read the tutorial
http://book.cakephp.org/3.0/en/tutorials-and-examples/bookmarks/part-two.html#fixing-list-view-and-forms

$this->auth->login() Not Working

Hello Everyone i'm trying to login after i have successfully add user data into database, but login is not working,I'm new to cakephp.Please Help me out.
here is the code
appcontroller:
class AppController extends Controller {
public $components = array(
'DebugKit.Toolbar' ,'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login')
)
);}
UsersController:
public function login(){
if ($this->request->is('Post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
}//$this->Flash->error(__('Invalid username or password, try again'));
}
}
login.ctp:
<?php
echo $this->Form->create('User');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('login');
?>
Add password hashing to your User model
User.php
App::uses('AppModel', 'Model');
class User extends AppModel {
public function beforeSave($options = array()) {
if(isset($this->data['User']['password'])) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
}
}
after that truncate your user table and save fresh user and then check again the login.

'Error: Call to a member function allow() on a non-object' in CakePHP 3 AuthComponent

Following the CakePHP which looks a bit confusing and not so straight forward, I have created a basic authentication logic, however, I cannot seem to load Auth component.
Here is the code part from the AppController.php:
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => ['Form' => ['fields' => ['username' => 'email', 'password' => 'password']]],
'loginAction' => ['controller' => 'Users', 'action' => 'login'],
'loginRedirect' => ['controller' => 'Groups', 'action' => 'index'],
'logoutRedirect' => ['controller' => 'Users', 'action' => 'login']
]);
}
//Allow basic views
public function beforeFilter(Event $event)
{
$this->Auth->allow(['index', 'view', 'display']);
}
Now no matter which controller or action I run, I always receive the following error:
Error: Call to a member function allow() on a non-object
that is referencing the following line:
$this->Auth->allow(['index', 'view', 'display']);
It has to be a straight forward thing, but I just cannot find it in the docummentation, therefore any help or guidance is much appreciated.
Check that your child controller's method initialize() is calling the parent method.
class MyController extends AppController
{
public function initialize() {
parent::initialize();
//rest of code
}
}
I've got this one when I had no Template/Users/login.ctp template created yet
managed to find out only after inspecting the stack-trace obtained by
$e = new \Exception('How did I got here anyway?');
debug($e->getTraceAsString());
yielding
#5 vendor/cakephp/cakephp/src/Error/ExceptionRenderer.php(318): Cake\Controller\Controller->render('missingTemplate')

debug AuthComponent in cakephp 2.4

I baked a cakephp application with a users table, and I'm trying to get authentication to work using the Blowfish hash. My password field is a varchar(255), so it should be long enough to store the hash. Everything in the app is the default baked output, expect for what follows.
This issue is that I can't log in after creating a user; I always get "Access Denied". What's the best way of troubleshooting this?
AppController.php
App::uses('Controller', 'Controller');
class AppController extends Controller {
public function beforeFilter(){
$this->Auth->allow('index', 'view');
}
public $components = array(
'Session',
'Auth' => array(
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email'),
'passwordHasher' => 'Blowfish'
)
),
'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'index'),
'authError' => "Access Denied",
'authorize' => array('Controller'),
)
);
public function isAuthorized($user){
return true;
}
}
User.php (model)
App::uses('AppModel', 'Model');
App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');
public function beforeSave($options = array()) {
if (!empty($this->data['User']['password'])) {
$passwordHasher = new BlowfishPasswordHasher();
$this->data['User']['password'] = $passwordHasher->hash($this->data['User']['password']);
}
return true;
}
UsersController.php
public function login(){
if ($this->request->is('post')) {
if($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
}
else {
$this->Session->setFlash('Access Denied');
}
}
}
login.ctp
echo $this->Form->create('user');
echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->button('Log In', array('type' => 'submit');
echo $this->Form->end();
'debug($this->request); die;' in login function gives the following output. should password be * or should it be the hashed version of the input?
data => array(
'user' => array(
'password' => '*****',
'email' => 'test#test.com'
)
)
1)listen to #waspinator echo $this->Form->create('User');
2)
App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');
remove it ad put it in AppController and it should be
App::uses('AuthComponent', 'Controller/Component');
3)comment this lines
//public function beforeFilter(){
// $this->Auth->allow('index', 'view');
//}
//public function isAuthorized($user){
// return true;
//}
4) for first time put this on top of user controller so you can save your password
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('edit', 'index', 'view);
}
echo $this->Form->create('user');
should be
echo $this->Form->create('User');

Cakephp auth login problem?

In my database I have users table,and one record - user ,password for this is hashed with md5.
Problem is every time I try to login with right admin/pass I get bad user/pass login msg.
Here is my controller :
class UsersController extends AppController {
var $name = 'Users';
function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow(array('*'));
}
function login() {
//debug($this->data);
if ($this->Session->read('Auth.User')) {
$this->Session->setFlash('You are logged in!');
}
}
function logout() {
$this->redirect($this->Auth->logout());
}
}
and from appControler
class AppController extends Controller {
var $components = array('Auth', 'Session');
function beforeFilter() {
//debug($this->data);
//Security::setHash('md5');
$this->Auth->allow('admin_index', 'index', 'login', 'logout');
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'index');
$this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'logout');
$this->Auth->loginRedirect = array('controller' => 'posts', 'action' => 'index');
}
}
login.ctp :
<div class="login">
<?
$session->flash('auth');
echo $form->create('User', array('action' => 'login'));
echo $form->inputs(array('legend' => __('Login', true), 'username', 'password'));
echo $form->end('Login');
?>
</div>
here are debug msg from app_controller
Array
(
[User] => Array
(
[username] => admin
[password] => pass
)
)
and debug msg from users controller :
Array
(
[User] => Array
(
[username] => admin
[password] => 8e2665a3fe6983fa38464685ac4a3d9c93a3d301
//this is not empty anymore but it is not same as in database
)
)
here is sql code,that is good,but user pass hashed is wrong.
SELECT `User`.`id`, `User`.`username`, `User`.`password`, `User`.`email`, `User`.`created` FROM `users` AS `User` WHERE `User`.`username` = 'admin' AND `User`.`password` = '09b98f2308740bf305ce1e1097d02ded' LIMIT 1
What could be the problem?I'm new in cakephp.
Tnx in advance
user303832,
you have to add the login, logout to your set of allowed actions via $this->Auth->allow( .
Edit0:
Another frequent point of failure is that the password confirmation field is omitted, causing the hash of the earlier password being hashed again and persisted in the database.
As the password is now double-hashed, a user can no longer log in. It is so common, that it has its own name (ninjahash) Ü.
Edit1:
My deep apologies: Please change your line back to:
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
and
$this->Auth->logoutRedirect = array('controller' => 'users','action' => 'login');
In addition, make sure that your database table is configured to take a char(40) as a password(#haprax: this is what the book suggests even for sha1).
Don't try use any other format of hashing because cakephp has not mention any particular format of hashing. According to me Cakephp convert it according to security.Salt value and decipher value that we change in cofig file of cakephp.
So, Solution is create a use after implementing auth component and then Cake php will create password in its own format and then try to login.

Resources