Auth not logging in (CakePHP 2.7.5) - php

I have a CakePHP app that I am trying to upgrade from 1.3 to 2.7.5 and I can hit the log in page but when I go to log in, it doesn't do anything, no errors, just basically refreshes the page. I am really confused why this is happening and would greatly appreciate any help I could get. I did post another question about this but deleted it because it did not provide enough of the code to solve the problem. I have included the AppController as well as the Users controller below.
AppController.php
?php
class AppController extends Controller {
var $components = array('Auth', 'Session', 'RequestHandler');
var $uses = array('Tour');
function beforeFilter() {
$this->setLayout();
$this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'find_home');
$this->Auth->autoRedirect = false;
if ($this->Session->check('Auth.User.userid')) {
$tour = $this->Tour->findByUserid($this->Session->read('Auth.User.userid'));
$user = $this->Auth->user();
$tour = $this->Tour->findByUserid($user['User']['userid']);
$user['Tour'] = $tour['Tour'];
$this->set('user', $user);
}else if (isset($_GET['token'])) {
$tour = $this->Tour->read(null, $_GET['token']);
if ($tour) {
$tour['Tour']['sessionmodified'] = date('Y-m-d H:i:s');
$this->Tour->save($tour);
$this->set('user', $tour);
}
}
}
private function setLayout() {
if (array_key_exists('prefix', $this->params)) {
if ($this->params['prefix'] == 'admin') {
$this->layout = 'admin';
}else if ($this->params['prefix'] == 'teacher') {
$this->layout = 'teacher';
}
}
}
}
?>
UserController.php
function login() {
if (!empty($this->data) && $this->Auth->user()) {
// Delete all old tokens
$this->Tour->recursive = -1;
$this->Tour->deleteAll(array('Tour.userid' => $this->Auth->user('userid')));
// Create a new token
$this->Tour->create();
$this->Tour->save(array('token' => md5(rand()), 'userid' => $this->Auth->user('userid')));
// Update login count
$user = $this->User->read(null, $this->Auth->user('userid'));
$user['User']['logincount']++;
$this->User->saveField('logincount', $user['User']['logincount']);
// Update last login time
$this->User->saveField('lastlogin', date('Y-m-d h:m:s'));
$this->redirect($this->find_home());
}
}
function logout() {
if (!empty($this->data) && $this->Auth->user()) {
// Delete any tours
$this->Tour->recursive = -1;
$this->Tour->deleteAll(array('Tour.userid' => $this->Auth->user('userid')));
}
$this->redirect($this->Auth->logout());
}
function index() {
$this->layout = false;
$this->autoRender = false;
Configure::write('debug', 0);
ini_set('soap.wsdl_cache_enabled', '0');
$server = new SoapServer('http://' . $_SERVER['HTTP_HOST'] . $this->webroot . 'users/wsdl');
$server->setClass('User');
$server->handle();
}

Related

Yii2 custom login is not working

I am new in yii2, Right now i am working with custom login, i did all code for login but when i go in home page through index action i didn't get any session there, Here is my code
public function actionIndex()
{
$session = Yii::$app->session;
if ($session->isActive) {
echo 'sdsd'; die;
}
return $this->render('index');
}
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new User();
//if ($model->load(Yii::$app->request->post()) && $model->login()) {
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$userName = $_POST['User']['UserName'];
$password = $_POST['User']['Password'];
$condition = "UserName = '".$userName."' AND Password = '".md5($password)."' AND Status = '1' AND UserType = '1' ";
$loginData = User::find()->where($condition)->all();
if(count($loginData)>0) {
$username = $loginData[0]->UserName;
$userID = $loginData[0]->UserID;
$session = Yii::$app->session;
$session->set('userName',$username);
$session->set('userID',$userID);
$this->redirect('index');
} else {
Yii::$app->session->setFlash('error', 'Username or password is incorrect');
}
}
return $this->render('login', [
'model' => $model,
]);
}
Even after login it still consider me as guaest user, Yii::$app->user->isGuest what changes i need to do now ?
You don't login the user in Yii App
You don't need set the session you must assign the proper value to this function
return \Yii::$app->getUser()->login($yourUser, $yourRememberMe ? $this->module->rememberFor : 0);
see this doc for user and this for login

Cant write to database with cakePHP

I am new to cakePHP and am just starting to use it for my new job.
I have created an edit_company action in my Orders Controller. I updated the acos table to allow this action. Now the problem is, I can't access any sort of 'edit' action. It says "You are not authorized to access that location" whenever I try to acccess any action that writes or updates database. edit,edit_products,edit_shipping, etc...
The view action works just fine.
This was not happening before.
Heres a bit of the code:
class OrdersController extends AppController{
public $uses = array('Order');
public $hideActions = array('campaign','customer','shipping','review_order','place_order','products','payment','confirmation','cancel','edit_status','edit_order_type','edit_products','edit_tax','add_product','cancel_shipping_label','track_label','view_label','reprint_label','edit_shipping','create_shipping_label');
public $components = array('Payflow','Printer');
public $actionMap = array(
'create' => array('add','create','campaign','customer','shipping','review_order','place_order','payment','products'),
'read'=> array('index', 'view', 'display','confirmation','track_label','search'),
'update' => array('edit','cancel','edit_status','edit_order_type','edit_products','edit_company','edit_tax','add_product','cancel_shipping_label','reprint_label','edit_shipping','create_shipping_label'),
'delete' => array('delete','back_orders_by_state')
);
public function beforeFilter(){
parent::beforeFilter();
$this->Auth->allow('permissions','gen_acos');
}
public function permissions(){
$this->Acl->allow('Admin','Controllers/Orders');
$this->Acl->allow("Sales","Controllers/Orders",'read');
$this->Acl->allow("Sales","Controllers/Orders",'create');
$this->Acl->allow("Sales","Controllers/Orders",'update');
$this->Acl->deny("Shipping","Controllers/Orders",'update');
$this->Session->setFlash("Permissions Updated.");
$this->redirect("/orders/");
}
public function edit_shipping($id){
$sm_conditions = array();
if(!$this->Acl->check(array('User' => array('UserID' => $this->Auth->user("UserID"))), 'Controllers/Orders','delete')){
$sm_conditions['Restricted'] = 1;
}
$shipping_method_ids = $this->Order->ShippingMethod->find("list",array("conditions"=>$sm_conditions,"fields"=>array("ShippingMethodID","ShippingMethodName")));
$order = $this->Order->read(null,$id);
$this->set("order",$order);
$this->set("shipping_method_ids",$shipping_method_ids);
if($this->request->is('put')){
if($this->Order->save($this->data,null,array("ShippingAddress","ShippingMethodID"))){
$this->Session->setFlash("Order Shipping Updated.");
$this->Order->Note->create();
$this->Order->Note->save(
array("Note"=>array('OrderID'=>$id,"UserID"=>$this->Auth->user("UserID"),"NoteBody"=>"Order Shipping Information updated.","CreatedDate"=>date("Y-m-d H:i:s")))
);
$this->redirect("/orders/view/$id");
}
}else{
$this->request->data = $order;
}
}
public function create_shipping_label($id){
$order = $this->Order->read(null,$id);
$this->set("order",$order);
if($this->request->is('put')){
$this->Order->save(array(
"Order"=>array(
"OrderID"=>$id,
"LabelPrinted"=>false,
"OrderStatusID"=>2,
"Notes"=>(!empty($this->data['Order']['Notes']))?$this->data['Order']['Notes']:null
)
));
$this->Session->setFlash("A new shipping label will be created momentarily.");
$this->Order->Note->create();
$this->Order->Note->save(
array("Note"=>array('OrderID'=>$id,"UserID"=>$this->Auth->user("UserID"),"NoteBody"=>"New shipping label will be created. ".((!empty($this->data['Order']['Notes']))?$this->data['Order']['Notes']:null),"CreatedDate"=>date("Y-m-d H:i:s")))
);
$this->redirect("view/".$id);
}else{
$this->request->data = $order;
}
}
public function cancel($id){
$order = $this->Order->read(null,$id);
if($this->request->is('post')){
//Check if note given
$this->Order->Note->data = $this->data;
if($this->Order->Note->validates()){
//Delete from Call table
$this->loadModel("Call");
$this->Call->deleteAll(array('Call.OrderID'=>$id));
//Add a note
$user_id = $this->Auth->user("UserID");
$this->Order->Note->create();
$this->Order->Note->save(
array("Note"=>array('OrderID'=>$id,"UserID"=>$user_id,"NoteBody"=>"Order Canceled. ","CreatedDate"=>date("Y-m-d H:i:s")))
);
$this->Order->Note->create();
$this->Order->Note->save(
array("Note"=>array('OrderID'=>$id,"UserID"=>$user_id,"NoteBody"=>"Reason For Cancellation: ".$this->data['Note']['NoteBody'],"CreatedDate"=>date("Y-m-d H:i:s")))
);
//Create a refund request if payment type is in TxType (1,2,3,7,11,9)
$txTypes = array(1,2,3,7,11,9);
$paid = 0;
foreach($txTypes as $txType){
$payments = Set::extract("/Payment[TransactionTypeID=$txType]/PaymentAmount",$order);
$paid += array_sum($payments);
}
if($paid>0){
$this->Order->refund($id,$paid);
}
//Change Status to Cancel (4) & LabelPrinted = 0
$this->Order->save(array("Order"=>array("OrderID"=>$id,"LabelPrinted"=>0,"OrderStatusID"=>4)));
//Update the total price
$this->Order->updateOrderTotal($id);
$this->Session->setFlash("Order was successfully canceled.");
$this->redirect("/orders/view/".$id);
}
}
$this->set("order",$order);
}
public function edit_products($id){
$order = $this->Order->read(null,$id);
$this->set("order",$order);
if($this->request->is("post")){
$error = false;
while($error==false && ($oe=array_shift($this->request->data['OrderEntry']))){
if(!$this->Order->OrderEntry->save(array("OrderEntry"=>$oe))){
$error = true;
}
}
if($error==false){
$this->Session->setFlash("Products Updated.");
$this->Order->updateOrderTotal($id);
$this->redirect("/orders/view/$id");
}
}
}
public function edit_company () {
}
public function edit ($id=null) {
$order = $this->Order->read(null,$id);
$this->set("order",$order);
if($this->request->is("post")){
$error = false;
while($error==false && ($oe=array_shift($this->request->data['OrderEntry']))){
if(!$this->Order->OrderEntry->save(array("OrderEntry"=>$oe))){
$error = true;
}
}
if($error==false){
$this->Session->setFlash("Products Updated.");
$this->Order->updateOrderTotal($id);
$this->redirect("/orders/view/$id");
}
}
}
Could anyone help me with this problem?
Thanks!
You are only giving non authenticaded users permission to access two actions:
public function beforeFilter(){
parent::beforeFilter();
$this->Auth->allow('permissions','gen_acos');
}
Add the new actions or log the user in before accesing the actions:
Giving permission to not authenticated users to your new actions:
public function beforeFilter(){
parent::beforeFilter();
$this->Auth->allow('permissions','gen_acos','edit_products','edit','cancel','create_shipping_label','edit_shipping');
}
If you don't want to grant access to non authenticated users to these actions login before trying to access them.
You can check more about Auth here
Also check this example that is part of the Blog Tutorial

Bad redirectUrl at login with CakePHP

This is what I did to reproduce my problem:
Login (redirection at page foo)
Click and go to page bar
Logout
Login again
The redirected page is bar (it should be foo)
This is what I did:
AppController.php
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'loginRedirect' => [
'controller' => 'Dashboard',
'action' => 'index'
]
]);
UsersController.php
public function login($reset = null) {
$this->layout = 'login';
$this->set('reset', $reset);
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
// IMPORTANT!
// Here I'm setting a different redirect url. The book says
// that $this->Auth->redirectUrl() will read the Auth.redirect
// session. I wanted my admin to login into a different page
if($session->read('Auth.User.role_id') === 3) {
$session->write('Auth.redirect', '/users/system_administrator_index');
}
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
} else {
$this->Flash->error('Oops', ['key' => 'auth']);
}
}
}
public function logout() {
return $this->redirect($this->Auth->logout());
}
I tried to use $session->destroy(); in order to clear everything related to my session but I noticed anything.
Each time I retry to login, the server redirect me to the last page I visited the last time I was connected.
I found a workaround. Instead of using return $this->redirect($this->Auth->redirectUrl());, I do a manual redirection.
public function login($reset = null) {
$this->layout = 'login';
$this->set('reset', $reset);
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
if($user['role_id'] === 3){
return $this->redirect('/users/system_administrator_index');
}
return $this->redirect('/dashboard');
} else {
$this->Flash->error('Oops', ['key' => 'auth']);
}
}
}

cakepphp 2.3: Authentication via custom BaseAuthenticate

I wrote a class AlephBaseAuthenticate that extents BaseAuthenticate which works fine:
<?php
// Authentication against Aleph X-Service
// user and password for x-service see aleph.ini
App::uses('BaseAuthenticate', 'Controller/Component/Auth');
App::uses('IniReader', 'Configure');
Configure::config('default', new IniReader());
class AlephAuthenticate extends BaseAuthenticate {
public function authenticate(CakeRequest $request, CakeResponse $response) {
// Do things for Aleph here.
// Return an array of user + group-id if they could authenticate the user,
// return false if not
// verification = empty works, so we have to check lenght of verification!
$configfile = Configure::read('configfile');
Configure::load($configfile, 'default');
$alephxurl = Configure::read('aleph.xurl');
$xlib = Configure::read('aleph.xlib');
$username = $request->data['Users']['username'];
$password = $request->data['Users']['password'];
$req = $alephxurl . 'library=' . $xlib . '&verification=' . $password . '&op=bor_info&bor_id=' . $username;
$userxml = file_get_contents($req);
$xml = simplexml_load_string($userxml);
$error = $xml->error;
if($error == 'Error retrieving Patron System Key' || strlen($password) == 0){
return FALSE;
} else {
$data['username'] = $xml->z303->{'z303-name'};
$data['group'] = $xml->z303->{'z303-profile-id'};
$data['id'] = $xml->z303->{'z303-id'};
return $data;
}
}
}
In my UserController I added
public $components = array(
'Session',
'Auth' => array(
'authenticate' => array(
'Aleph'
)
)
);
function beforeFilter(){
$this->Auth->allow('index', 'login', 'logout');
}
The problem is: Only in UsersController.php, action "login", I can access this->Auth->user('id'), and, $this->Auth->allow('index', 'login', 'logout') doesn't work at all. Access to every action after login throughs a "You are not authorized to access that location". Looks like authentication doesn't work at all.
Any idea whats wrong here?
Thanks,
Christoph

CakePHP remember me with Auth

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/

Categories