CakePHP: Get loggedin user data - cakephp

What I did
I used this part of the Cookbook to create my authentication: Link
After i was finished, i changed the fields to email and password (in AppController.php):
public function beforeFilter() {
$this->Auth->allow('index');
$this->Auth->fields = array('username' => 'email', 'password' => 'password');
}
What happened
The login form always said that my password/email combination was not correct.
After a while searching and trying stuff, i added "$this->request->data" to the Auth->login() parameter in the login() function of the UsersController:
public function login(){
$this->layout = 'login';
if ($this->request->is('post')){
if ($this->Auth->login($this->request->data)){
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Ongeldig email adres of wachtwoord. Probeer het AUB opnieuw'));
}
}
}
This worked, but now i can't use "$user['id']" to get the loggedin users id. It says that it doesn't know the $user variable.
What I expected to happen
In the first place, it should have logged the user in without me adding the parameter. And second, it should have printed the loggedin user's id.
I hope someone can help me with the problem.
Thanks in advance!

fields is now in the authenticate array:
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email', ...)
)
)
see
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#configuring-authentication-handlers
either with
$this->Auth->authenticate = ...
or
public $components = array(
'Auth' => array(
'authenticate' => ...
)
);
but, as PHP freelancer stated, this is well documented.
what cookbook version did you use? the 2.x one?

Related

User Login in CakePHP

I am using CakePHP 2.3.6. I have several plugins in a project. I want to implement the login system in the UsersController. For that, I have this code in my AppController :
public $components=array('Session','Auth');
public function beforeFilter(){
if($this->Auth->user('role')=='admin'){
$this->Auth->loginRedirect(array('plugin'=>'admins_panel','controller'=>'admins','action'=>'index'));
$this->Auth->logoutRedirect(array('plugin'=>'admins_panel','controller'=>'admins','action'=>'index'));
}
}
So, it means, it'll redirect me to the Admin Panel plugin after I login. In my Users controller :
public $components=array('Auth');
public function beforeFilter(){
parent::beforeFilter();
$this->Auth->allow();
}
public function login(){
if($this->request->is('post')){
if($this->Auth->login()){
$this->Session->setFlash('Welcome '.AuthComponent::user('name'));
$this->redirect($this->Auth->redirectUrl());
}else{
$this->Session->setFlash('Invalid username or password, please try again');
$this->set('title_for_layout','Error - Login');
}
}else
$this->set('title_for_layout','Login');
}
In the User model :
public $validate=array(
'email'=>array(
'rule'=>'isUnique',
'message'=>'This email address has already been taken. Use another one.'
),
'username'=>array(
'rule'=>'isUnique',
'message'=>'This username has already been taken.'
)
);
public function beforeSave($options=array()){
if(isset($this->data[$this->alias]['password']))
$this->data[$this->alias]['password']=AuthComponent::password($this->data[$this->alias]['password']);
return true;
}
My View file is :
<?php echo $this->Form->create('User');?>
echo $this->Form->input('username',array('type'=>'email'));?>
echo $this->Form->input('password',array('type'=>'password'));?>
echo $this->Form->submit('Login');
echo $this->Form->end();
?>
So, I thought it'd work, but its not working. When I try to login, it says "Invalid username or password, please try again.", as I set in the "login" function.
So, what should do here ? Please help me.
Thanks
Define authentication fields in your auth component:
public $Components = array(
'Session',
'Auth' => array(
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'username', 'password' => 'password'),
)
)
)
)
If you want to use the email for your authentication then use:
'fields' => array('username' => 'email', 'password' => 'password')

CakePHP 1.3: getting authError message on successful login

I'm trying to implement a login feature where a user can use his username or email address. I've worked out the login with both, but when the user logs in successfully with his email address, the authError still flashes (user is logged in). I've put a comment "HERE" down in the login action, and I'm not sure what happens after that with the redirect.
Here are the relevant bits of my code:
App Controoler:
public $components = array(
'Auth' => array(
'authorize' => 'controller',
'loginRedirect' => array(
'controller' => 'users',
'action' => 'welcome_page'
),
'loginError' => 'Invalid user name/password',
'authError' => 'You don\'t have permission'
),
'Session',
);
User Controller:
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add');
}
public function login() {
// At this point, the Auth Component is unable to log in user, so check with email.
if (!empty($this->data) &&
!empty($this->Auth->data['User']['username']) &&
!empty($this->Auth->data['User']['password'])) {
// Look for user with email address using the entered username
$user = $this->User->find('first', array(
'conditions' => array(
'User.email' => $this->Auth->data['User']['username'],
'User.password' => $this->Auth->data['User']['password']
),
'recursive' => -1
));
// Check if a matching user is found and that if login was succesfull
if (!empty($user) && $this->Auth->login($user)) {
if ($this->Auth->autoRedirect) {
// NOTE: user trying to log in with email reaches HERE
$this->redirect($this->Auth->redirect()); // this is the default authentication redirect defined in App Controller
}
} else {
$this->Session->setFlash($this->Auth->loginError, $this->Auth->flashElement, array(), 'auth');
}
}
}
I edited your original post to delete the messages from the session variables.
<?php
$this->Session->delete('Message.flash');
$this->Session->delete('Message.auth');
?>
Hope this helps!
-Andrew

can't change auth authenticate method

I have 2 authenticate method for Auth component. Default and Special.
First method is for all users, and Special for my friends...
I want to change authenticate method to Special when posted role is equal to 2..
So I put this in my UsersController login method:
if($this->request->data['role'] == 2){
$this->Auth->authenticate = 'Special';
echo 'Method changed!';
}
if($this->Auth->login()){
......
}
and if AppController, where I set $components:
public $components = array('RequestHandler', 'Session',
'Auth' => array('authenticate' => 'Default'));
but, when I send a form with role=2, it prints Method changed but won't change the authenticate method and use Default method..
Have I made a mistake?
I've a simplier solution :
In your controller, define your new authenticate array :
$this->Auth->authenticate = array('Form' => array(
'userModel' => 'User',
'fields' => array('username' => 'login', 'password' => 'password'),
));
Then to make your changes effective in your application, simply write :
$this->Auth->constructAuthenticate();
That's all :)
I've had a similar problem and I solved it by defining the same variable in the beforeFilter action of the AppController:
function beforeFilter() {
parent::beforeFilter();
// Pass settings in
$this->Auth->authenticate = array('Form' => array(
'fields' => array('username' => 'email')
));
...
}
So in your case I would do the following in the AppController:
function beforeFilter() {
parent::beforeFilter();
if($this->request->data['role'] == 2){
$this->Auth->authenticate = 'Special';
echo 'Method changed!';
} else {
$this->Auth->authenticate = 'Default';
}
...
}
... and in the components declaration only write:
public $components = array('RequestHandler', 'Session', 'Auth');

Auth Component not working on CakePHP 2.0

I have tried most if not all tutorials for CakePHP 1.3 on their Auth method and non seem to work on CakePHP 2.0.
I can add users, hash the passwords, but the login feature does not work. It just refreshes the page when I click on login. No errors, no nothing.
I would appreciate some tips please and thank you for reading my question.
This my code
public function login()
{
if ($this->request->is('post') )
{
if( $this->Auth->login() )
{
// the redirect() function in the Auth class redirects us
// to the url we set up in the AppController.
return $this->redirect( $this->Auth->redirect());
}
else
{
$this->Session->setFlash(__('Email or password is incorrect',true));
}
}
}
Thanks,
Mahadeva Prasad
First of all check how you have hash the password.Also check the field length in database.
Preferred - varchar(255)
The password will be hash as follows.
class User extends AppModel {
public function beforeSave($options = array()) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
return true;
}
}
Also as you are using FormAuthenticate try using this when declaring component.
public $components = array(
'Auth' => array(
'loginAction' => array(
'controller' => 'users',
'action' => 'login',
),
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'username')
)
)
)
);
For more information refer http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html

CakePHP $this->Auth->login() not working

The web app is working great except for auth manual calls. I've been struggling with this for days. In my sample code I have temporarily rewritten the cookie to narrow down the cause. Here is my app controller snip:
App::import('Sanitize');
//uses('sanitize');
class AppController extends Controller {
var $components = array('Clean','Acl', 'Auth', 'Session', 'RequestHandler', 'Cookie', /* 'DebugKit.Toolbar' */);
var $helpers = array('uiNav','Flash','Html', 'Form', 'Session','Javascript','Ajax','Js' => array('Jquery'), 'Time','Js');
function beforeFilter() {
//Configure AuthComponent
$this->Auth->authorize = 'actions';
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
$this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');
$this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'view');
$this->Auth->actionPath = 'controllers/';
$this->Auth->autoRedirect = false;
$this->Auth->allowedActions = array('display');
if(!$this->Auth->user()){
//$cookie = $this->Cookie->read('Auth.User');
$cookie = array('username' => 'chris22', 'password' => 'stuff');
if (!is_null($cookie)) {
$this->set('checking_cookie',$cookie);
if ($this->Auth->login($cookie)) {
$this->set('cookie_message','cookie validates!');
// Clear auth message, just in case we use it.
$this->Session->delete('Message.auth');
/* $this->redirect($this->Auth->redirect()); */
}
}
}
}
}
As you can see I'm just plugging the user name and password into $this->Auth->login and it's not working!!
I don't know if my user controller is relevent, but here is the login function for that too:
function login() {
if ($this->Auth->user()) {
if (!empty($this->data) && $this->data['User']['remember_me'] && isset($this->data['User']['password'])) {
$cookie = array();
$cookie['username'] = $this->data['User']['username'];
$cookie['password'] = $this->data['User']['password'];
$this->Cookie->write('Auth.User', $cookie, true, '+1 month');
//unset($this->data['User']['remember_me']);
$this->set('cookie-00', 'setting cookie.');
}else{ $this->set('cookie_message', 'not setting cookie.');}
$this->redirect($this->Auth->redirect());
}
}
Thanks!
EDIT - 1 - I think I know why this is not working for you.
Reason 1: $this->Auth->login takes data in the form of
array(
'User'=>array(
'username'=>'myusername',
'password'=>'mypassword'
)
)
Reason 2: $this->Auth->login does NOT hash the password.
You must send the password exactly as it appears in the database.
EVERYTHING BELOW THIS LINE IS POSSIBLE BUT NOT LIKELY IN THIS CASE:
Are you sure that when you originally created the username and password, the hashes were setup?
To check that your hashes match look at your users table with phpmyadmin or mysql workbench and find the password field for the user chris22
Compare that entry to your current hashing. To check your current hash, put the code below somewhere in a controller function (index) and navigate there.
debug(Security::hash('stuff'));
exit;
I hope this helps!
Make sure the fields are correctly assigned in the Auth component.
if you use different field names than username & password to connect, you must declare them in your controller like this way :
'Auth' => array(
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email', 'password' => 'mot_de_passe')
)
)
)

Resources