Cake is not saving the cookie, at least not that I can see, and when I revisit the page I am not auto logged in.i actually want to implement the 'remember me functionality '.i am using this component
https://github.com/ceeram/Authenticate/wiki/Set-Cookie
here is my code
login.ctp
echo $this->form->create();
echo $this->form->input('email');
echo $this->form->input('password');
<?php echo $this->Form->checkbox('remember_me', array('hiddenField' => false,'name' => 'remember_me'));?>
echo $this->form->end('submit');
?>
UserController
<?php
class UsersController extends AppController {
public $components = array('Cookie');
public function beforeFilter() {
parent::beforeFilter();
$this->Cookie->type('rijndael');
$this->Security->requireSecure('login');// for security
$this->Auth->authenticate = array(
'Authenticate.MultiColumn' => array(
'fields' => array(
'username' => 'email',
'password' => 'password'
),
'columns' => array('email', 'mobileNo'),
'userModel' => 'User',
)
);
}
public function index(){
}
public function login() {
$this->layout='userdefault';
if ($this->request->is('post')) {
//$this->Auth->logout();
$cookie = $this->Cookie->read('Auth.User');
debug($cookie);
if ($this->Auth->login()) {
$this->_setCookie($this->Auth->user('id'));
$this->redirect('/users/controlpanel');
} else {
$this->Session->setFlash('Incorrect Email/Password Combination');
}
}
}
protected function _setCookie($id) {
if (!$this->request->data('User.remember_me')) {
return false;
}
$data = array(
'username' => $this->request->data('User.email'),
'password' => $this->request->data('User.password')
);
$this->Cookie->write('User', $data, true, '+1 week');
return true;
}
public function logout() {
$this->redirect($this->Auth->logout());
}
public function controlpanel(){
$this->layout='controlpaneldefault';
}
}
?>
and also tell me how can i check or debug the cookie to check that whether my cookie saving or not or if debugging is not possible then tell me how can i set the name of the cookie so i go in the browser cookies and search the cookie with name
insert exit(); after debug($cookie); for check cookie data.
Related
I have already check and when I create users and passwords and then I try to login and is successful, however if for example I install on other device my project and set up my DB I enter to my system how can I access for first time if I dont have users created?
1) I tried to create user and password on my database but it cant recognize the password due to hashing methods.
How can i access for the first time and then create users as normal?
My login access controller:
public function login() {
//if already logged-in, redirect
if($this->Session->check('Auth.User')){
$this->redirect(array('action' => 'index'));
}
// if we get the post information, try to authenticate
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->Session->setFlash(__('Bienvenido, '. $this->Auth->user('username')));
$this->redirect($this->Auth->redirectUrl());
} else {
$this->Session->setFlash(__('Usuario o password invalidos'));
}
}
$this->layout = 'login';
}
appcontroller:
class AppController extends Controller {
//public $components = array('DebugKit.Toolbar');
public $components = array(
//'DebugKit.Toolbar',
'Session',
'Auth' => array(
'authorize' => 'Controller',
'actionPath' => 'controllers/',
'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
'authError' => 'You must be logged in to view this page.',
'loginError' => 'Invalid Username or Password entered, please try again.'
),
);
// only allow the login controllers only
public function beforeFilter() {
$this->Auth->allow('login','view','index','logout','getData');
}
public function isAuthorized($user) {
// Here is where we should verify the role and give access based on role
if (isset($user['role']) && $user['role'] === 'adm') {
return true;
}
if (in_array($this->action, array('add','getData','getDataArticulos','addDetFac','descargar','getNit'))) {
if (isset($user['role']) && $user['role'] === 'vend')
return true;
else
return $this->Session->setFlash(__('Acceso denegado.'), 'error');
}
return $this->Session->setFlash(__('Acceso denegado.'), 'error');
}
}
At first allow add method.
public function beforeFilter() {
$this->Auth->allow('login','view','index','logout','getData','add');
}
Then create a user, write in your browser URL your_project_path/users/add
After add 1st user remove add from Auth allow.
I've created a module to authenticate a user. Now, after login I go to the index action and the system tells me that the authentication is all working fine. But What I want is to print some more user details from the Users table. When I try:
print_r($this->getServiceLocator()->get('AuthService')->getAdapter()->getResultRowObject());
I get no result. What am I doing wrong?
Thanks for your help.
In my module.php I've the following code(snippet):
public function getServiceConfig()
{
return array(
'abstract_factories' => array(),
'aliases' => array(),
'factories' => array(
// Some more code here but removed for simplicity
// Autentication
'AuthService' => function ($sm) {
$adapter = $sm->get('master_db');
$dbAuthAdapter = new DbAuthAdapter ( $adapter, 'Users', 'email', 'password' );
$auth = new AuthenticationService();
$auth->setAdapter ( $dbAuthAdapter );
return $auth;
},
// Some more code here but removed for simplicity
}
In my IndexController.php I've the following (snippets):
public function indexAction()
{
if(!$this->getServiceLocator()->get('AuthService')->hasIdentity()){
return $this->redirect()->toUrl('login');
}
echo "hello, it works!";
exit;
}
public function loginAction(){
$form = $this->getServiceLocator()->get('LoginForm');
$viewModel = new ViewModel(array('form' =>
$form));
return $viewModel;
}
public function processAction(){
// Lots of code here
if($bcrypt->verify($loginData['password'], $userData->password))
{
$this->getAuthService()
->getAdapter()
->setIdentity($loginData['email'])
->setCredential($userData->password);
$result = $this->getAuthService()->authenticate();
}
// Lots of code here where I check if $result->isValid and route to the
// correct action
}
public function getAuthService() {
if(!isset($this->authservice)) {
$this->authservice = $this->getServiceLocator()->get('AuthService');
}
return $this->authservice;
}
Instead of refering to the authentication result object (which properly only exists in the authentication request) you can simply store user details in the authentication identity (#see http://framework.zend.com/manual/2.1/en/modules/zend.authentication.intro.html).
For your case you could also store user specific details right after the validation of the authentication result in the authentication storage:
if ($result->isValid()) {
//authentication success
$resultRow = $this->authService->getAdapter()->getResultRowObject();
$this->authService->getStorage()->write(array(
'id' => $resultRow->id,
'user_agent' => $request->getServer('HTTP_USER_AGENT'))
);
}
(This information was taken from this authentication tutorial http://samsonasik.wordpress.com/2013/05/29/zend-framework-2-working-with-authenticationservice-and-db-session-save-handler/)
I have successfully used Auth, but unfortunately, it seems that it does work only with Session. I want that if user checks "Remember Me" checkbox, I would use Cookie and he would be logged in for 2 weeks. I can't find anything in official book and in Google I found just few and not great blog posts. Is there any way to implement this without rewriting the core?
In your user controller:
public function beforeFilter() {
$this->Auth->allow(array('login', 'register'));
parent::beforeFilter();
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
// did they select the remember me checkbox?
if ($this->request->data['User']['remember_me'] == 1) {
// remove "remember me checkbox"
unset($this->request->data['User']['remember_me']);
// hash the user's password
$this->request->data['User']['password'] = $this->Auth->password($this->request->data['User']['password']);
// write the cookie
$this->Cookie->write('remember_me_cookie', $this->request->data['User'], true, '2 weeks');
}
return $this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Username or password is incorrect.'));
}
}
$this->set(array(
'title_for_layout' => 'Login'
));
}
public function logout() {
// clear the cookie (if it exists) when logging out
$this->Cookie->delete('remember_me_cookie');
return $this->redirect($this->Auth->logout());
}
In the login view:
<h1>Login</h1>
<?php echo $this->Form->create('User'); ?>
<?php echo $this->Form->input('username'); ?>
<?php echo $this->Form->input('password'); ?>
<?php echo $this->Form->checkbox('remember_me'); ?> Remember Me
<?php echo $this->Form->end('Login'); ?>
In your AppController:
public $components = array(
'Session',
'Auth',
'Cookie'
);
public $uses = array('User');
public function beforeFilter() {
// set cookie options
$this->Cookie->key = 'qSI232qs*&sXOw!adre#34SAv!#*(XSL#$%)asGb$#11~_+!##HKis~#^';
$this->Cookie->httpOnly = true;
if (!$this->Auth->loggedIn() && $this->Cookie->read('remember_me_cookie')) {
$cookie = $this->Cookie->read('remember_me_cookie');
$user = $this->User->find('first', array(
'conditions' => array(
'User.username' => $cookie['username'],
'User.password' => $cookie['password']
)
));
if ($user && !$this->Auth->login($user['User'])) {
$this->redirect('/users/logout'); // destroy session & cookie
}
}
}
See this URL i think it is very help full to you.
http://lecterror.com/articles/view/cakephp-and-the-infamous-remember-me-cookie
Or Try this
function login() {
if ($this->Auth->user()) {
if (!empty($this->data) && $this->data['User']['remember_me']) {
$cookie = array();
$cookie['username'] = $this->data['User']['username'];
$cookie['password'] = $this->data['User']['password'];
$this->Cookie->write('Auth.User', $cookie, true, COOKIE_EXPIRE);
unset($this->data['User']['remember_me']);
}
$this->LogDetail->Write('activity','has logged IN');
$this->redirect($this->Auth->redirect());
}
if (empty($this->data)) {
$cookie = $this->Cookie->read('Auth.User');
if (!is_null($cookie)) {
if ($this->Auth->login($cookie)) {
$this->Session->destroy('Message.Auth'); # clear auth message, just in case we use it.
$this->LogDetail->Write('activity','has been authenticated via cookie and is now logged IN');
$this->redirect($this->Auth->redirect());
} else {
$this->LogDetail->Write('activity','attempted to gain access with an invalid cookie');
$this->Cookie->destroy('Auth.User'); # delete invalid cookie
$this->Session->setFlash('Invalid cookie');
$this->redirect('login');
}
}
}
}
use CookeAuthenticate adapter:
https://github.com/ceeram/Authenticate/blob/master/Controller/Component/Auth/CookieAuthenticate.php
here more info:
https://github.com/ceeram/Authenticate/wiki/Set-Cookie
Remember me is nothing else but session identified with a cookie, but cookie lifetime set to infinity. Look at Config/core.php for session cookie lifetime.
I think you need to know about CakePHP Security levels. Try to lower the security of your cakePHP. CakePHP's Config variables documentation. I had written a blog about it also a long ago.
you can try this
if ($this->Auth->login())
{
if (!empty($this->data['User']['remember']))
{
$cookie = array();
$cookie['login'] = $this->data['User']['login'];
$cookie['password'] = $this->data['User']['password'];
$cookie['language'] =$this->data['User']['language'];
$this->Cookie->write('Auth.projectname', $cookie, true, '+1 years');
unset($this->data['User']['remember']);
public function admin_login() {
$this->layout = 'admin_login';
if (count($this->Session->read("Auth.User"))) {
$usr = $this->Session->read("Auth.User");
if ($usr['role'] == 'A' || $usr['role'] == 'RA' || $usr['role'] == 'MAfA' || $usr['role'] == 'Af' || $usr['role'] == 'FAA')
return $this->redirect(array('controller' => 'dashboard', 'action' => 'view'));
}
if ($this->request->is('post')) {
if ($this->request->data['User']['remember_me']=="1") {
// pr($this->request->data);
// die('sdd');
$this->Cookie->write('username', $this->request->data['User']['username'], true, '1 year');
$this->Cookie->write('password', $this->request->data['User']['password'], true, '1 year');
} else {
$this->Cookie->destroy();
}
/*
* Check if email or username is passed in form
*/
$uname = $this->request->data['User']['username'];
//login via email
if (filter_var($uname, FILTER_VALIDATE_EMAIL)) {
$u = $this->User->findByemail($uname);
} else { //login via username
$u = $this->User->findByusername($uname);
}
if ($u) {
$this->request->data['User']['username'] = $u['User']['username'];
/* * *
* Error if user is not active
*/
if ($u['User']['user_status'] != 'active') {
$this->Session->setFlash(__('Sorry! Your account is not active.'), 'default', array('class' => 'alert alert-danger'));
} elseif ($this->Auth->login()) { //if logged in
$user_caps = $this->fetchCapabilitiesByRole($u['User']['role']);
$this->Session->write("Auth.User.privileges", array('capabilities' => $user_caps['capabilities'], 'geo_areas' => array()));
if ($u['User']['role'] == 'A' || $u['User']['role'] == 'RA' || $u['User']['role'] == 'Af' || $u['User']['role'] == 'MAfA' || $u['User']['role'] == 'FAA')
return $this->redirect(array('controller' => 'dashboard', 'action' => 'view'));
return $this->redirect($this->Auth->redirect());
}else { //if invalid
$this->Session->setFlash(__('Invalid username or password.'), 'default', array('class' => 'alert alert-danger'));
}
} else {//if user does not exists
$this->Session->setFlash(__('User does not exists.'), 'default', array('class' => 'alert alert-danger'));
}
}
}
It's been a while since the question was answered but hopefully this can help to ones that come after me.
I've written short walkthrough on how to setup 'remember me' functionality using Auhenticate Plugin from Ceeram
More info here: http://mirkoborivojevic.com/posts/2013/08/10/setup-remember-me-functionality-in-cakephp/
I have made a a basic login form with three fields, they're "company", "employee", and "password" I tried using the default Auth component:
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
}
but as this parses the default "username", and "password" fields I can't log in. How can I change the Auth function to validate my three fields and log me in?
Sorry if this is a noob question, I had a read through http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html but nothing on there helped.
Try the following:
public function beforeFilter() {
$this->Auth->authenticate = array(
'Form' => array(
'fields' => array(
'username' => 'employee',
),
),
);
}
public function login() {
if ($this->request->is('post')) {
$this->Auth->authenticate['Form']['scope'] = array(
'User.company_id' => $this->request->data['User']['company_id'],
// or however this condition needs to be setup as
);
if ($this->Auth->login()) {
// login success
} else {
// login fail
}
}
}
Basically, add the third condition as a scope.
I'm currently trying to change my cakephp login from using the username field to using the email field.
When using the username field, the login works fine, here's the code for the login with username:
login.ctp
<?php
echo $this->Form->create('User');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end(__('Login'));
?>
UsersController.php
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add', 'login'); // Letting users register themselves
$this->Auth->fields = array('username' => 'username', 'password' => 'password');
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->Session->setFlash(__('worked'));
} else {
debug($this->data);
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
}
AppController
public $components = array('Session', 'Auth');
So this all works fine, I can login with test details.
So to change this to using an email, all I have done is:
Change the input in login.ctp from username to email
echo $this->Form->input('email');
Change the fields array in userscontroller from username to email
$this->Auth->fields = array('username' => 'email', 'password' => 'password');
Change the database field from username to email
I then try to login using the same test details and it tells me they are incorrect.
Does anyone have any idea why this wouldn't work?
In Cake 2.x it's a little different
$this->Auth->authenticate = array(
'Form' => array(
'fields' => array('username' => 'email', 'password' => 'password'),
),
);