Rectangle 27 10

The Steps I took to get ION AUTH working with CodeIgniter + MX HMVC

Since, I didn't really see any exact info on this and the stuff I did see, had a bunch of things like routing and stuff that I couldn't get working the way they were done, I decided to share the what I did to accomplish this.

At first I was struggling with it, but then I had to sit back and think about what was going on.

After that, it was actually pretty straight forward, only a couple of gotchas

Install CodeIgnter (I actually used an existing project I was working on, so it wasn't a fresh clean install. I removed "index.php" and I had HMVC already installed the recommended way. This is about Ion Auth anyway.)

Get the latest version of Ion Auth.

Instead of installing Ion Auth in application/third_party, Unzip it, and rename the resulting directory to auth. Put it in application/modules which results in application/modules/auth.

application/config/autoload.php
$autoload['libraries'] = array('database','session');
  • In modules/auth/libraries/Ion_auth.php update the lines in __construct to: $this->ci->load->config('auth/ion_auth', TRUE); $this->ci->load->library('email'); $this->ci->load->library('session'); $this->ci->lang->load('auth/ion_auth'); $this->ci->load->model('auth/ion_auth_model')
  • In modules/auth/models/ion_auth_model.php update the lines in __construct to: $this->load->config('auth/ion_auth', TRUE); $this->load->helper('cookie'); $this->load->helper('date'); $this->load->library('session'); $this->lang->load('auth/ion_auth');
auth
modules/auth/controllers/auth.php
MX_Controller
CI_Controller

Now, in auth.php, make sure you change all $this->data to $data - (Make sure to read about this below!!).

Move the files and directories in modules/auth/views/auth to modules/auth/views resulting in modules/auth/views with no lower level auth dir - (Make sure to read about this below!!).

Add a routes.php file into modules/auth/config and add the following line:

$route['auth/(:any)'] = "auth/$1";

Now, go to http://yoursite/auth and everything should be good to go!

First off.. DO NOT AUTOLOAD THE LIBRARIES OR MODELS in the application/config/autoload.php file. Do them in the modules explicitly with $this->load->library("whatever"), etc

## Set up mod_rewrite
<IfModule mod_rewrite.c>
Options +MultiViews +FollowSymLinks
DirectoryIndex index.php index.html

# Enable Rewrite Engine
# ------------------------------
RewriteEngine On

# UPDATE THIS TO POINT TO where you installed this FROM YOUR DOC ROOT.
# If this is in the DOC ROOT, leave it as it is
#---------------------
RewriteBase /

# In case your hosting service doesn't add or remove 'www.' for you, you can
# do it here by uncommenting and updating the 'Rewrite*'s below.
#
# Add or remove 'www.'  Whichever you prefer.  
# This one removes the 'www.' which seems to be the favorable choice these days. 
# ------------------------------
#RewriteCond %{HTTP_HOST} ^www.<sitename>.com
#RewriteRule (.*) http://<sitename>.com/$1 [R=301,L]

# Redirect index.php Requests
# ------------------------------
RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteCond %{THE_REQUEST} !/system/.*
RewriteRule (.*?)index\.php/*(.*) $1$2 [R=301,L]

# Standard ExpressionEngine Rewrite
# ------------------------------
RewriteRule modules/(.+)/controllers/(.+)\.php$ /index.php?/$1/$2 [L,R=301]
RewriteRule controllers/(.+)\.php$ /index.php?/$1 [L,R=301]

RewriteCond $1 !\.(css|js|gif|jpe?g|png) [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

When I updated the modules/auth/controllers/auth.php to extend MX_Controller instead of CI_Controller, I was getting a series of errors after. The first of these errors was:

A PHP Error was encountered

    Severity: Notice

    Message: Undefined property: CI::$data

    Filename: MX/Controller.php

To resolve this error, I changed all $this->data to $data in the auth.php controller`.

After fixing this problem, when I would go to auth, I would get an error like this:

Unable to load the requested file: auth/login.php

Apparently, it can't find the view files in it's own views dir. Ahh. Not exactly true though after thinking about it. The reason is because it's trying to find module/file_to_view and the file_to_view should be in views! Not in auth/views/auth!! So, we need to move everyting up from the auth dir into the views dir!

After that, everything works fine! I can cross load models, libraries and controllers in other modules and I can do Modules::run() in views and everything else!

I hope this helps someone else. Good Luck!

I wrote a bash script to make this all even easier, I tried to paste it in here, but I guess it's too large. I'll see if it can be posted in it's own post, if not, if anyone is interested, let me know and I'll figure out somewhere to put it.

Step 10 is redundant, somehow... There is no need for adding ->ci-> member variable, i.e. leave $this->load->config('users/ion_auth', TRUE); as is

php - Using Ion Auth as a separate module in the HMVC structure - Stac...

php codeigniter hmvc
Rectangle 27 10

The Steps I took to get ION AUTH working with CodeIgniter + MX HMVC

Since, I didn't really see any exact info on this and the stuff I did see, had a bunch of things like routing and stuff that I couldn't get working the way they were done, I decided to share the what I did to accomplish this.

At first I was struggling with it, but then I had to sit back and think about what was going on.

After that, it was actually pretty straight forward, only a couple of gotchas

Install CodeIgnter (I actually used an existing project I was working on, so it wasn't a fresh clean install. I removed "index.php" and I had HMVC already installed the recommended way. This is about Ion Auth anyway.)

Get the latest version of Ion Auth.

Instead of installing Ion Auth in application/third_party, Unzip it, and rename the resulting directory to auth. Put it in application/modules which results in application/modules/auth.

application/config/autoload.php
$autoload['libraries'] = array('database','session');
  • In modules/auth/libraries/Ion_auth.php update the lines in __construct to: $this->ci->load->config('auth/ion_auth', TRUE); $this->ci->load->library('email'); $this->ci->load->library('session'); $this->ci->lang->load('auth/ion_auth'); $this->ci->load->model('auth/ion_auth_model')
  • In modules/auth/models/ion_auth_model.php update the lines in __construct to: $this->load->config('auth/ion_auth', TRUE); $this->load->helper('cookie'); $this->load->helper('date'); $this->load->library('session'); $this->lang->load('auth/ion_auth');
auth
modules/auth/controllers/auth.php
MX_Controller
CI_Controller

Now, in auth.php, make sure you change all $this->data to $data - (Make sure to read about this below!!).

Move the files and directories in modules/auth/views/auth to modules/auth/views resulting in modules/auth/views with no lower level auth dir - (Make sure to read about this below!!).

Add a routes.php file into modules/auth/config and add the following line:

$route['auth/(:any)'] = "auth/$1";

Now, go to http://yoursite/auth and everything should be good to go!

First off.. DO NOT AUTOLOAD THE LIBRARIES OR MODELS in the application/config/autoload.php file. Do them in the modules explicitly with $this->load->library("whatever"), etc

## Set up mod_rewrite
<IfModule mod_rewrite.c>
Options +MultiViews +FollowSymLinks
DirectoryIndex index.php index.html

# Enable Rewrite Engine
# ------------------------------
RewriteEngine On

# UPDATE THIS TO POINT TO where you installed this FROM YOUR DOC ROOT.
# If this is in the DOC ROOT, leave it as it is
#---------------------
RewriteBase /

# In case your hosting service doesn't add or remove 'www.' for you, you can
# do it here by uncommenting and updating the 'Rewrite*'s below.
#
# Add or remove 'www.'  Whichever you prefer.  
# This one removes the 'www.' which seems to be the favorable choice these days. 
# ------------------------------
#RewriteCond %{HTTP_HOST} ^www.<sitename>.com
#RewriteRule (.*) http://<sitename>.com/$1 [R=301,L]

# Redirect index.php Requests
# ------------------------------
RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteCond %{THE_REQUEST} !/system/.*
RewriteRule (.*?)index\.php/*(.*) $1$2 [R=301,L]

# Standard ExpressionEngine Rewrite
# ------------------------------
RewriteRule modules/(.+)/controllers/(.+)\.php$ /index.php?/$1/$2 [L,R=301]
RewriteRule controllers/(.+)\.php$ /index.php?/$1 [L,R=301]

RewriteCond $1 !\.(css|js|gif|jpe?g|png) [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

When I updated the modules/auth/controllers/auth.php to extend MX_Controller instead of CI_Controller, I was getting a series of errors after. The first of these errors was:

A PHP Error was encountered

    Severity: Notice

    Message: Undefined property: CI::$data

    Filename: MX/Controller.php

To resolve this error, I changed all $this->data to $data in the auth.php controller`.

After fixing this problem, when I would go to auth, I would get an error like this:

Unable to load the requested file: auth/login.php

Apparently, it can't find the view files in it's own views dir. Ahh. Not exactly true though after thinking about it. The reason is because it's trying to find module/file_to_view and the file_to_view should be in views! Not in auth/views/auth!! So, we need to move everyting up from the auth dir into the views dir!

After that, everything works fine! I can cross load models, libraries and controllers in other modules and I can do Modules::run() in views and everything else!

I hope this helps someone else. Good Luck!

I wrote a bash script to make this all even easier, I tried to paste it in here, but I guess it's too large. I'll see if it can be posted in it's own post, if not, if anyone is interested, let me know and I'll figure out somewhere to put it.

Step 10 is redundant, somehow... There is no need for adding ->ci-> member variable, i.e. leave $this->load->config('users/ion_auth', TRUE); as is

php - Using Ion Auth as a separate module in the HMVC structure - Stac...

php codeigniter hmvc
Rectangle 27 18

This problem occurs due to difference between timezones of user and webserver location e.g. I live in Pakistan which is 10 hours ahead of US timezone and my server is in US. I request the page at 17/10/2012 14:00 at Pakistan time. The time in US is 17/10/2012 4:00 since webserver is in US and session expiry is set to 2 hours the cookie sent by server is set to expire at 17/10/2012 6:00. Now browser interacts with your local pc time and it gets time 17/10/2012 14:00 therefore it deletes the cookie or your cookie always refreshed on your request. Therefore its best to set session expiry to 1 day because the largest timezone difference is 17 hours between new zealand and US (i am not sure about difference may be i am wrong). So your cookie will at least keep alive for 7 hours

Yes, its working now, by increasing expiry to one day... :) but how to manage it without this, do you try it? anyhow thanks.

this problem occurs when your timezone differs from the web host timezone therefore 1 day is safe.

@Shayanhusaini but when we are use localhost then why should face this problem

CodeIgniter session class not working in Chrome - Stack Overflow

codeigniter session google-chrome cookies
Rectangle 27 122

In order to use base_url(), you must first have the URL Helper loaded. This can be done either in application/config/autoload.php (on or around line 67):

$autoload['helper'] = array('url');
$this->load->helper('url');

Once it's loaded, be sure to keep in mind that base_url() doesn't implicitly print or echo out anything, rather it returns the value to be printed:

echo base_url();

Remember also that the value returned is the site's base url as provided in the config file. CodeIgniter will accomodate an empty value in the config file as well:

Guessing that an echo or something was missing? Otherwise this should not happen, autoload will choke if the helper was spelled wrong or doesn't exist. At least php would throw an error if the function was not defined. base_url() should always return something. Addendum: Note that in 2.0.2 the config value can be empty and will auto-detect the base url, so there's no chance of it being empty.

@Wesley I'm suspecting it's a missing call to echo as well.

@Jonathan Sampson: I have loaded the autoload helper as said. But still it doesn't seem to work. I have gone through codeigniter user guide and I think URL helper exists.

@SanksR Are you placing echo before the call or not? Please update your question with relevant code so that we can better assist you.

@Jonathan Sampson: Thank you man. Its working fine now using autoload helper. The thing is that I was declaring autoload thing for more than once.

php - base_url() function not working in codeigniter - Stack Overflow

php codeigniter
Rectangle 27 122

In order to use base_url(), you must first have the URL Helper loaded. This can be done either in application/config/autoload.php (on or around line 67):

$autoload['helper'] = array('url');
$this->load->helper('url');

Once it's loaded, be sure to keep in mind that base_url() doesn't implicitly print or echo out anything, rather it returns the value to be printed:

echo base_url();

Remember also that the value returned is the site's base url as provided in the config file. CodeIgniter will accomodate an empty value in the config file as well:

Guessing that an echo or something was missing? Otherwise this should not happen, autoload will choke if the helper was spelled wrong or doesn't exist. At least php would throw an error if the function was not defined. base_url() should always return something. Addendum: Note that in 2.0.2 the config value can be empty and will auto-detect the base url, so there's no chance of it being empty.

@Wesley I'm suspecting it's a missing call to echo as well.

@Jonathan Sampson: I have loaded the autoload helper as said. But still it doesn't seem to work. I have gone through codeigniter user guide and I think URL helper exists.

@Jonathan Sampson: Thank you man. Its working fine now using autoload helper. The thing is that I was declaring autoload thing for more than once.

php - base_url() function not working in codeigniter - Stack Overflow

php codeigniter
Rectangle 27 3

You can use CSRF protection and encrypt the cookies to strengthen the system against cookie manipulation.

If you are concerned about security, though, you absolutely should be using the db for sessions. Unless you have tons of users, the hit on the db will be negligible. If you do have tons of users, time to think about distributing the workload as the session lookup will be the least of your worries.

The client cookies are more for state. They can be used for things like "remember me" on login forms or for a page layout or something. They should not be used for securing your application.

You can not verify a session via cookie if you are not using db sessions as there is no where for the application to store the session id.

Codeigniter what is the point of storing session data in the cookie ON...

codeigniter session cookies
Rectangle 27 3

You can use CSRF protection and encrypt the cookies to strengthen the system against cookie manipulation.

If you are concerned about security, though, you absolutely should be using the db for sessions. Unless you have tons of users, the hit on the db will be negligible. If you do have tons of users, time to think about distributing the workload as the session lookup will be the least of your worries.

The client cookies are more for state. They can be used for things like "remember me" on login forms or for a page layout or something. They should not be used for securing your application.

You can not verify a session via cookie if you are not using db sessions as there is no where for the application to store the session id.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

Codeigniter what is the point of storing session data in the cookie ON...

codeigniter session cookies
Rectangle 27 2

Cookie based sessions provide a light-weight and fast mechanism for storing session information. They are also secure. Each cookie is encrypted using strong AES-256 encryption. However, cookies have a four kilobyte storage limit, so you may wish to use another driver if you are storing a lot of data in the session. The data is encrypted based off the hash in your config and CI also runs an update on the hash intermittently for more security. Storing the session in a cookie or in the database also is more ideal for server farms or clusters under high load. Many large corporations and other high traffic websites use this strategy for their sessions.

This being said I understand the concern to being limited to 4kb of data, having the data client side, and also having the data show up as a REQUEST on each page load. However, there is nothing keeping you from manually using the default PHP session or rolling your own session library.

Codeigniter what is the point of storing session data in the cookie ON...

codeigniter session cookies
Rectangle 27 2

Cookie based sessions provide a light-weight and fast mechanism for storing session information. They are also secure. Each cookie is encrypted using strong AES-256 encryption. However, cookies have a four kilobyte storage limit, so you may wish to use another driver if you are storing a lot of data in the session. The data is encrypted based off the hash in your config and CI also runs an update on the hash intermittently for more security. Storing the session in a cookie or in the database also is more ideal for server farms or clusters under high load. Many large corporations and other high traffic websites use this strategy for their sessions.

This being said I understand the concern to being limited to 4kb of data, having the data client side, and also having the data show up as a REQUEST on each page load. However, there is nothing keeping you from manually using the default PHP session or rolling your own session library.

Codeigniter what is the point of storing session data in the cookie ON...

codeigniter session cookies
Rectangle 27 5

use route inside codeigniter, so you can rerwrite new uri for each of them

$route['contact'] = 'welcome/contact';

and don't forget about htaccess file

RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

Why are functions not working in Codeigniter default controller? - Sta...

codeigniter
Rectangle 27 4

The "default controller" is only used when there are no URL segments. It only calls one method, and the default method of a controller is index().

Generally, the first part of your URL maps to a controller:

This would invoke the index method of the contact controller:

http://example.com/contact

This would invoke the hello method of the contact controller and pass world as the first argument:

http://example.com/contact/hello/world

You need a contact controller for this URL to work, or you can use routing.

Why are functions not working in Codeigniter default controller? - Sta...

codeigniter
Rectangle 27 2

Yes, is about the session id stored in the cookie. This is regenerated every 5 minutes. And when it's time to regenerate, first it will get current session data and than assign it to the new session id.

code from CI session library, function sess_update():

// Save the old session id so we know which record to
// update in the database if we need it
$old_sessid = $this->userdata['session_id'];
$new_sessid = '';
while (strlen($new_sessid) < 32)
{
    $new_sessid .= mt_rand(0, mt_getrandmax());
}

// To make the session ID even more secure we'll combine it with the user's IP
$new_sessid .= $this->CI->input->ip_address();

// Turn it into a hash
$new_sessid = md5(uniqid($new_sessid, TRUE));

// Update the session data in the session data array
$this->userdata['session_id'] = $new_sessid;
$this->userdata['last_activity'] = $this->now;

really thanks for this useful information, and SO for the love of programming.

php - How Sessions in Codeigniter Work - Stack Overflow

php codeigniter session cookies
Rectangle 27 2

Yes, is about the session id stored in the cookie. This is regenerated every 5 minutes. And when it's time to regenerate, first it will get current session data and than assign it to the new session id.

code from CI session library, function sess_update():

// Save the old session id so we know which record to
// update in the database if we need it
$old_sessid = $this->userdata['session_id'];
$new_sessid = '';
while (strlen($new_sessid) < 32)
{
    $new_sessid .= mt_rand(0, mt_getrandmax());
}

// To make the session ID even more secure we'll combine it with the user's IP
$new_sessid .= $this->CI->input->ip_address();

// Turn it into a hash
$new_sessid = md5(uniqid($new_sessid, TRUE));

// Update the session data in the session data array
$this->userdata['session_id'] = $new_sessid;
$this->userdata['last_activity'] = $this->now;

really thanks for this useful information, and SO for the love of programming.

php - How Sessions in Codeigniter Work - Stack Overflow

php codeigniter session cookies
Rectangle 27 4

base_url()
$autoload['helper'] = array('url');
  • Or by manually load in controller or in view $this->load->helper('url');

Then you can user base_url() anywhere in controller or view.

php - base_url() function not working in codeigniter - Stack Overflow

php codeigniter
Rectangle 27 4

base_url()
$autoload['helper'] = array('url');
  • Or by manually load in controller or in view $this->load->helper('url');

Then you can user base_url() anywhere in controller or view.

php - base_url() function not working in codeigniter - Stack Overflow

php codeigniter
Rectangle 27 2

Working with ion_auth.php library is pretty easy. You need to follow these steps. I assume you have followed ion_auth installation process.

First you need to create a MY_Controller class and put it in core

Class MY_Controller Extends CI_Controller{
    public function __construct(){
        parent::__construct();
        if (!$this->ion_auth->logged_in()) 
        {
            redirect(site_url('auth/login'));
        }
    }
}

Make sure you autoload the ion_auth library. The second important thing is that you need to extend your every controller with MY_Controller. (Note : if you dont want to extend with MY_Controller but want to use simple controllers that extend CI_Controller put the above condition in every controller's constructor) If user is not logged in and try to access any page he will be redirected to auth/login.

$user   =    $this->ion_auth->user()->row();

This will return the logged in user information.

php - How to use ion_aut library in codeigniter with MY_Controller - S...

php login codeigniter-2 ion-auth
Rectangle 27 18

Using CodeIgniter sessions with database is going to be fairly secure. You just don't have to trust the input that the user gives. Even if you are using AJAX, the CodeIgniter session will work just like any standard call, so the same security goes on.

What happens with the CodeIgniter session is that the server stores the cookie, and every time the user does an action that would change the content of the cookie, it is first compared to the previous cookie.

If the user changes the content of the session cookie in the browser, CodeIgniter will notice on the next server call, and create a new session for the user, basically logging him out.

CodeIgniter doesn't really need the data stored in the cookie in the user's browser, and as long as you're using

$this->session->userdata('userid');

you're going to get trusted server-side data. The user can't change that. Furthermore, the cookie can be encrypted, and you should have it encrypted. Just look in config.php of CodeIgniter.

There are several other protections around the session data: the short refresh timeout (usually 300 seconds), it checks if the IP changed, and if the browser changed. In other words, in the worst case scenario, the only way to spoof the session data is by having the same version of the browser, having the same IP, getting direct access to the computer to copy/paste the cookie, and getting this done within 5 minutes.

So, watch out for the guy sitting beside you!

Codeigniter session security - Stack Overflow

codeigniter session cookies
Rectangle 27 3

$this->db->set('description', $description);
$this->db->set('order_qty', $order_qty);
$this->db->set('no_of_panels', $no_of_panels);
$this->db->set('division', $division);
$this->db->set('job_number', $job_number);
$this->db->set('customer_group', $customer_group);
$this->db->set('sales_office', $sales_office);
$this->db->set('sales_group', $sales_group);
$this->db->set('project_name', $project_name);
$this->db->set('project_manager', $project_manager);
$this->db->set('net_value_myr', $net_value_myr);
$this->db->set('credit_status', $credit_status);
$this->db->set('so_delivery_date', $so_delivery_date);
$this->db->set('order_delivery_date', $order_delivery_date);
$this->db->insert('order_bank');

or if your data are stored in an array then you can do it simply running

$this->db->insert('order_bank', $data);

Please provide a code sample. If the link ever stops working the answer will still be useful.

@bottleboot check the updated answer.

Brilliant, much more usful! +1 I would never use the first way though second thing you do is cleaner.

php - Insert query not working in codeigniter - Stack Overflow

php mysql codeigniter
Rectangle 27 1

Perhaps it is because it needs two underscores, not 1 :)

function __construct(){
    parent::__construct();
    $this->is_logged_in();
}

Spot on mate! Thanks very much for the help

php - Cookie not working with Login System CodeIgniter - Stack Overflo...

php codeigniter session login session-cookies
Rectangle 27 1

Perhaps it is because it needs two underscores, not 1 :)

function __construct(){
    parent::__construct();
    $this->is_logged_in();
}

Spot on mate! Thanks very much for the help

php - Cookie not working with Login System CodeIgniter - Stack Overflo...

php codeigniter session login session-cookies