Cakephp $this->Auth->loggedIn() doesnt always work - cakephp-2.1

I am using cakephps Auth Component to login to my site. When I correctly enter in my username and password, it will log me in. Then when I use loggedIn() to check that I am logged in, it is very inconsistent in returning true.
This is my AppController where I set loggedIn() to a variable to use later:
<?php
App::uses('Controller', 'Controller');
App::uses('File', 'Utility');
App::uses('AuthComponent', 'Component');
class AppController extends Controller {
public $components = array(
'Session',
'Auth'=>array(
'loginRedirect'=> array('controller'=>'users', 'action'=>'index'),
'logoutRedirect'=> array('controller'=>'users', 'action'=>'index'),
'authError' =>"You can't access that page",
'authorize'=> array('Controller')
)
);
//determines what logged in users have access to
public function isAuthorized($user){
return true;
}
//determines what non-logged in users have access to
public function beforeFilter(){
$this->Auth->allow('index','view');
$this->set('logged_in', $this->Auth->loggedIn());
$this->set('current_user', $this->Auth->user());
}
}
And here is a bit of my code where I use 'logged_in'
<?php if($logged_in): ?> //this only returns true some of the time
Welcome <?php echo $current_user['username']; ?>. <?php echo $this->Html->link('Logout', array('controller'=>'users', 'action'=>'login')); ?>
<?php else: ?>
<?php echo $this->Html->link('Login', array('controller'=>'users', 'action'=>'logout')); ?>
<?php endif; ?>
And here is my login():
public function login(){
if($this->request->is('post')){
if($this->Auth->login()){ //this returns true every time
$this->redirect($this->Auth->redirect());
}else{
$this->Session->setFlash('Your username and/or password is incorrect');
}
}
}
I have tried calling $this->Auth->loggedIn() instead of using $logged_in but I get the error that the Auth Helper cannot be found.
Please let me know if there is any more information needed to answer my question.

Move these lines to beforeRender()
$this->set('logged_in', $this->Auth->loggedIn());
$this->set('current_user', $this->Auth->user());
Besides that, nothing seems wrong with your code.
The comment that Auth->login() would always return true only happens when you pass any argument to the login() method, which the code you show doesnt have though.

Related

Checking if Post author is equal to logged in user

A user can post a 'Tutorial', each tutorial is associated with its author via their 'user_id'.
My problem is I want to alter the view if the logged in user is viewing their own post (Tutorial).
CONTROLLER:
public function view($id = null)
{
$tutorial = $this->Tutorials->get($id, [
'contain' => ['Users','Courses', 'TutorialComments.Users']
]);
$tutorialComment = $this->Tutorials->TutorialComments->newEntity();
$this->set(compact('tutorial', 'tutorialComment'));
}
VIEW:
<? if (($tutorial->user->id) === ($this->request->session()->read('Auth.User.id'))): ?>
<p> hello </p>
<? endif; ?>
you should access the logged in the controller through the Auth component and pass the user to the view
controller
$logged_user_id = $this->Auth->user('id');
$this->set(compact('tutorial', 'tutorialComment', 'logged_user_id '));
view
if($tutorial->user->id == $logged_user_id) {
// your code here
}

Codeigniter - after submit form getting 404 error

I am new to Codeigniter and I am trying learn it by building simple admin panel.. but in the last days I got stuck on some error:
When I send/submit the login information I get 404 error. here is my controller code:
class Login extends CI_Controller {
public function index()
{
if($this->aauth->is_loggedin()){redirect('/dashboard');}
$this->sign_in();
}
public function sign_in()
{
$this->load->view('header');
$this->load->view('login');
$this->load->view('footer');
}
public function validate()
{
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if($this->form_validation->run() == FALSE){
//Field validation failed. User redirected to login page
$this->load->view('header');
$this->load->view('login');
$this->load->view('footer');
}else{
//Check for database and redirect to private area
redirect('/dashboard');
}
}
}
I've also shared my whole project on github, because its may related to some other file:
https://github.com/shaimoryosef/admin
Please try to help me find what is the problem..
Thanks
Shai
Two thing you need to change
first : in view/login.php
Login is link
`Login`
change to button
<button type="submit" class="btn btn-lg btn-success btn-block">Login</button>
And second put index.php in form_open()
<?php echo form_open('index.php/login/validate'); ?>
This link
Login
is wrong, that's why you are probably getting the 404 error, due to the href attribute which points to index.html.
If you want to submit the form just put a submit button and you will get to login/validate through the form action. My advice is to either use
<?php echo form_submit('mysubmit', 'Submit'); ?>
or
<?php echo echo form_button(array( 'type' => 'submit', 'content' => 'Login')); ?>
functions from form helper. Check the CI user guide and pick whichever suits you best.

Use a function in $this->set() with CakePHP 2.1

I'm just wondering how I can use/define my own function using the $this->set() method in CakePHP? I want to do something like this...
AppController.php
<?php
function checkSetup() {
if ($this->Auth->user('setup') == 'notcomplete') { return true; }
}
$this->set('isSetup', checkSetup());
?>
And then I will be able to access and call it in my view file:
<?php if ($isSetup): ?>
You haven't setup your profile yet!
<?php endif; ?>
I've tried that, but It clearly doesn't work as I get a massive fatal error. Any ideas/suggestions on how I can do this?
$this->set('isSetup', checkSetup());
That line needs to be inside some function in order to be called. Presumably you want it in the beforFilter of your app controller - something like this:
<?php
App::uses('Controller', 'Controller');
class AppController extends Controller {
function beforeFilter() {
$this->set('isSetup', checkSetup());
}
function checkSetup() {
if ($this->Auth->user('setup') == 'notcomplete') { return true; }
}
}
?>

user can't login using CodeIgniter with facebook php sdk

I am following the guide here to play around with the facebook php sdk, but my little app doesn't work. It keeps staying on the login page.
Here is the controller:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Facebook_connect extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper(array('form','url'));
$this->load->library('fb_connect');
}
function index()
{
}
function test()
{
$data['title'] = 'Facebook API Testing';
$data['user_id'] = $this->fb_connect->user_id;
if($data['user_id'])
{
$data['user_profile'] = $this->fb_connect->user;
}
if($data['user_id'])
{
$data['logout_url'] = $this->fb_connect->getLogoutUrl();;
}
else
{
$data['login_url'] = $this->fb_connect->getLoginUrl();
}
$this->template->load('template', 'facebook_connect/test', $data);
}
}
?>
Here is the view:
<h1>php-sdk</h1>
<?php if($user_id): ?>
Logout
<?php else: ?>
<div>
Login using OAuth 2.0 handled by the PHP SDK:
Login with Facebook
</div>
<?php endif ?>
<h3>PHP Session</h3>
<pre><?php print_r($_SESSION); ?></pre>
<?php if($user_id): ?>
<h3>Your Avata</h3>
<img src="https://graph.facebook.com/<?php echo $user_id; ?>/picture">
<h3>Your User Object (/me)</h3>
<pre><?php print_r($user_profile); ?></pre>
<?php else: ?>
<strong><em>You are not Connected.</em></strong>
<?php endif ?>
I get stuck at it and couldn't figure out why.
Use this example provided by facebook:
https://github.com/facebook/php-sdk/blob/master/examples/example.php
But keep your $this->load->library('fb_connect'); and make sure to add $this->fb_connect to any facebook library calls in that example.
It works 100%. Try to just put all the code in the controller to make sure it works, then distribute as needed. Not sure what your problem is, perhaps faulty return url.

Stumped by CodeIgniter controllers found but not found

OK, I admit it. I'm a CI newbie. I'm doing something really basic wrong and I've been at it for a couple of hours and can't find my error.
I have a controller called login. It's in the resources folder in my controllers folder. It loads a view called login_form. But for the life of me it will not load if I go to domain.com/resources/login or domain.com/resources/index. But I can get to it via a route:
$route['engineering-resources/login'] = "resources/login";
Even when I get to it this way, my form action isn't found. Here is my form:
<?php
echo form_open('resources/login/validate_credentials'); //folder/controller/method. I think this is where my problem is
echo form_input('username', 'Username');
echo form_password('password', 'Password');
echo form_submit('submit', 'Login');
echo anchor('login/signup', 'Create Account');
echo form_close();
?>
The path is my resources folder in my controllers folder, and the controller is the login controller using the validate_credentials method. Here is the pertinent part of my login controller:
class Login extends Controller {
function index()
{
$data['title'] = 'Engineering Resources | Login';
$data['main_content'] = 'resources/login_form';
$this->load->view('templates/main.php', $data);
}
function validate_credentials()
{
$this->load->model('login/membership_model');
$query = $this->membership_model->validate();
if($query) // if the user's credentials validated...
{
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('resources/members_area');
}
else // incorrect username or password
{
$this->index();
}
}
The index function works when I use the route, but not when I use the above domain.com paths. I assume that is why it cannot find the validate_credentials method. What am I doing wrong?
Here is main.php
<?php $this->load->view('includes/header.php'); ?>
<?php $this->load->view('includes/nav.php'); ?>
<?php $this->load->view($main_content); ?>
<?php $this->load->view('includes/footer.php'); ?>
$route['engineering-resources/login'] = "resources/login";
This does not route to engineering-resources/login/validate_credentials to resources/login/validate_credentials
You should have something like this:
// not tested
$route['engineering-resources/login/(\S*)'] = "resources/login/$1";
One more thing is that if you are using routes, you should use the routes from your views too..
echo form_open('engineering-resources/login/validate_credentials');

Resources