20 September 2010

How to make login system for CodeIgniter using OpenID. This example uses Google Accounts for login.

Basically we need library that communicates with CodeIgniter OpenID Googleoogle. Then we need to adjust CodeIgniter for it. Then we get unique url that is id for your user, or you can make it secondary value so primary autoincreased int is id.

Getting The Library

I personally like LightOpenID witch is released under MIT license. Then we need to copy openid.php form the arcive and place it in our libraries folder. Also change the file name to Openid.php and the file contains class that is called to LightOpenID, cange that to Openid aswell. You can also take a look at example-google.php, because that is what we are going to do, but in CodeIgniter.

Query Strings:

This library needs query strings, but for SEO reasons we want to keep pritty urls for our site. So we need a little hack. Go to your config/config.php file in application folder. Don't enable query strings, but change uri_protocol to PATH_INFO. Then you can use this line in your login controller to enable query strings only for that controller.
Source code viewer
  1. class Login extends Controller {
  2. function __construct() {#<-PHP5 - __construct(); PHP4 - class name()
  3. parent::Controller();
  4. #enable query strings for this class
  5. parse_str($_SERVER['QUERY_STRING'],$_GET);
  6. }
  7. ...
  8. }
Programming Language: PHP
CodeIgniter OpenID Google:
This is a function I made, based on example-google.php file from the archive. This function only validates user and gets unique user id, how you save the session is up to you. So basically, how you make the login is up to you. But here is the function:
Source code viewer
  1. function google_openid(){
  2. $this->load->library('openid');
  3. try {
  4. if(!isset($_GET['openid_mode'])) {
  5. $openid = new Openid;
  6. $openid->identity = 'https://www.google.com/accounts/o8/id';
  7. header('Location: ' . $openid->authUrl());
  8. }
  9. elseif($_GET['openid_mode'] == 'cancel')
  10. echo 'User has canceled authentication!';
  11. else {
  12. $openid = new Openid;
  13. if($openid->validate()){
  14. #Here goes the code that gets interpreted after successful login!!!
  15. }
  16. else echo 'User has not logged in.';
  17. }
  18. }
  19. catch(ErrorException $e) {
  20. echo $e->getMessage();
  21. }
  22. }
Programming Language: PHP