User Authentication in CodeIgniter - codeigniter

Securing a CodeIgniter Site
I am trying to use the authentication method suggested on the Tuts+ site at http://code.tutsplus.com/tutorials/easy-authentication-with-codeigniter--net-20248.
After validating the user I create a session variable as follows:
$_SESSION['username'] = $this->input->post('email_address');
Tuts+ then suggests the following be placed in all controllers:
public function __construct() {
session_start();
parent::__construct();
if(!ISSET($_SESSION['username'])){
redirect('admin_controller');
}
}
This works without any problems when I place it in my main_controller, but when I add the code to other controllers I get:
A PHP Error was encountered
Severity: Warning
Message: session_start() [function.session-start]: Cannot send session cache limiter - > > headers already sent (output started at /………….../application/controllers> /contact_controller.php:146)
This is probably a really dumb question but how do I check for the session variable in the other controllers?

This is not about session it's about redirect function; it must be called without any output before it, please check the file /contact_controller.php at line 146 if it's echoing anything before redirect.
Further information about header.

Related

Laravel 8: 302 Redirection when POST/PUT methods called

I've newly installed Laravel 8, and setup my api resources.
But when I try to create/update a record, it's redirect me with 302to the home page...
Here is my api.php:
Route::apiResource('addresses', AddressController::class);
In my AddressController.php, my store method:
public function store(CreateAddressRequest $request)
{
return response()->json(Address::create($request->validated()));
}
Need help (to understand), please.
Please set the header in postman - Accept: application/json.
When you create through store() method, you have CreateAddressRequest class which validates your input. When the validation fails it redirects to the previous page and it could redirects to the homepage if there is no previous page.
For API, this behavior is not desirable since you want to return error message (in JSON) instead of redirection.
Example of using validator to return the error. REST API in Laravel when validating the request

Check Laravel 5.7 login from external script

I have a Laravel app and I need to check if a user is logged and who from a external script. I'm using the following lines to load Laravel and try to check it.
require_once __DIR__.'/../../../vendor/autoload.php';
$app = require_once __DIR__.'/../../../bootstrap/app.php';
$app->make('Illuminate\Contracts\Http\Kernel')
->handle(Illuminate\Http\Request::capture());
/*if (Cookie::get(config('session.cookie')) != "") {
$id = Cookie::get(config('session.cookie'));
Session::driver()->setId($pericod);
Session::driver()->start();
}*/
$isAuthorized = Auth::check();
if(!$isAuthorized){
echo "NO AUTORIZADO";
exit();
}
With this lines I can access any Laravel function and I can check the login if I made GET request to the external scripts, but when the request is POST it always fails. I'm unable to check the login and I see that the session changes because can't get the existing session.
I have made many tests and I think that somethings of Laravel are not working fine, like routes or middlewares. I can made it work if I disable all encryption of the cookies and the session, but I want to use this security functions.
I'm using updated Laravel 5.7 and I had this code working in Laravel 5.4
Thank you for your help.
I discovered the problem,
The trick is that the route is external to laravel so laravel's route resolver identifies the current route as /.
It was working on GET requests because in my routes file I have the / route only as get. If I set the / route as any, everything works.
I wasn't seeing the problem because I was not terminating Laravel's execution. If I change the logged user verification to this, it shows the error:
$isAuthorized = Auth::check();
if(!$isAuthorized){
echo "NO AUTORIZADO";
$response->send();
$kernel->terminate($request, $response);
exit();
}
This two lines ends laravel execution and returns the error "405 Method Not Allowed".
$response->send();
$kernel->terminate($request, $response);
Thank you for your help.

Yii2 $session->setId() not working

I'm using Ajax to log in a user from subdomain. The Yii2 app is on another subdomain. Both subdomains are configured to use same cookie and session domains and save paths. I'm including session ID with Ajax call to write the user information to the same session used by non-app subdomain like this:
$session = Yii::$app->session;
$session->open();
$session->setId($post["session"]);
$session["user.id"] = $user->id;
echo $session->id; // This does not return the same ID originating from post!
Unfortunately the user information IS NOT written to the session already existing, but a new one. Is there a session involved somewhere in the middle of login process or why isn't it working? I've also tried session_id($post["session"]), but nothing.
This was actually working on previous domain, so I must be missing something. All of the AJAX posted info is correct and checked, the user is logged in properly (checked the logs) but into wrong session.
Thanks in advance!
yii\web\Session::setId() is a wrapper for session_id(), you should read PHP documentation about this function :
string session_id([ string $id ])
If id is specified, it will replace the current session id. session_id() needs to be called before session_start() for that purpose.
So you should simply try :
$session = Yii::$app->session;
$session->setId($customId);
$session->open();
I Don't think you are following the correct way to SET & GET session.
Try This:
$session = Yii::$app->session;
$session->open();
$session->set('id', $post["session"]);
echo $session->get('id');
For more info, please click Session Management - Yii2

CakePHP redirect method not redirecting

I am trying to redirect to a new page using CakePHP redirect method but for some reason the redirect is not working. The code I am using to redirect is
public function update_sticky_postition_in_db()
{
$this->autoRender = false;
... // Save info to database
$this->redirect(array('action' => 'tool'));
}
Where tool is the name of the view I am tring to redirect to. To try and speed the process of finding the problem I have checked few things and think I have found the cause of the problem. Basically I am trying to redirect to the view that is currently active which I think is part of the reason why it is not redirecting. I have read that it might have something to do with caching of the page but I am not sure how to solve that issue.
Also when using firebug I can see the redirect is sending a GET request but after that nothing is happening. Do I have to do something with the GET request or should Cake handle that for me. Also I have checked the URL of the GET and it is correct.
It is located within the controller with the correct name as I can view the original tool page.
Also the update_sticky_postition_in_db() method does not have a view (hence why the auto render is set to false), its intended purpose is to update a row in the database from an ajax call.
From your post it seems you're firing the update_sticky_postition_in_db() using ajax call, so that the redirection will not work.
You can do redirection using JavaScript within ajax success method.
In order to do that, you may send some json_encode() message from you above method and checking that status within ajax success method you can do a redirect using window.location.

CodeIgniter only allow access to certain controllers when logged in

I have some CodeIgniter controllers which should only be accessed by users who have logged in (i.e. where $this->session->userdata('username') is not null). If a non-authenticated person attempts to access said controllers they should receive:
header('location: /auth/login');
There has got to be a better way to do this than to put a
if (!$this->session->userdata('username'))
header('location: /auth/login');
else
{
[rest of function]
}
in front of every function in the controller...
I know DX_Auth has a similar functionality, but I am not using an authentication plugin and I am not open to doing so.
Thanks!
Mala
Do the user login check when the class is created, so it doesn't matter what function the user is accessing it will check for the session variable and redirect to the login page on failure:
function className()
{
parent::Controller();
if(!$this->session->userdata('username')) header('location: /auth/login');
}
That's the way of calling the __constructor or it's equivalent in codeigniter when you create controllers/models, or at least that's what I understood!

Resources