I'm not sure if it's the best pattern for CI 3 but I check for a login flag (boolean) in most of the controllers' constructors and redirect the user to a login page before loading anything else. If anyone can suggest a better way then I would be grateful.
Code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Admin extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('session');
// If the user is not logged in then get out of here!
if(!$this->session->login)
{
redirect('/user/index');
}
$this->load->model('admin_model');
$this->load->model('another_model');
}
function some_other_method()
{
}
}
While we are here, I'll add this warning for anyone struggling with Stripe Checkout or similar payment providers. Please be aware that if you have a route set up as an endpoint for a POST response from some external service (e.g. a
Stripe Checkout's success_url) this technique will return a
302 error to their API, so use an endpoint method in a different Controller that doesn't check the logged-in state.
Also, to get around the $_GET variable issues with Codeigniter, I specified my
success_url as this:
Code:
'success_url' => 'https://example.com/success/{CHECKOUT_SESSION_ID}',
rather than the example in Stripe's excellent documentation:
Code:
'success_url' => 'https://example.com/success?session_id={CHECKOUT_SESSION_ID}',
and the following route works as a normal Codeigniter endpoint without having to play around with URL config settings or htaccess.
Code:
$route['success/(:any)'] = 'subscription/checkout_success/$1';
And finally, my checkout_success method looks like this:
Code:
function checkout_success($session_id)
{
// Redirect to a Success page or
// do something else with the $session_id
// returned to you in the correctly formatted URL
// you specified in the 'Create Request' code.
}
Have fun.