Simple authentication tutorial




The setup

So, now I'm going to show you how the SimpleAuth class works.

The idea behind it is to provide a simple authentication process when you don't need any bells and whistles! The SimpleAuth class can hold the following user information:

  • ID
  • Username
  • Password
  • Real name
  • E-mail
  • Level - that can be useful if you want users to have different access levels.
  • Appname - so that you can use the same database and table for multiple sites/applications/logins

This information is stored in a SQLite or MySQL database. You can either provide an existing DB object or let SimpleAuth create one for you.

To keep down the number of SQL executions you have to invoke the creation of the table it self manually, and while you'r at it you might as well add your self as an user. This is typically how you would do to create the table and add your self as a user:

11 lines of PHP
  1. <?php 
  2. require_once 'PLib.php'; 
  3. PLib::Import('Security.SimpleAuth'); 
  4.  
  5. //! If you have an existing DB-object that could be passed as the first
  6. //! argument instead of the connection string here.
  7. $auth = new SimpleAuth('sqlite:///path/to/db.sqlite', 'myapp'); 
  8. $auth->SetupTable(); 
  9. //! Username, Password, Real name, Email, Level
  10. $auth->AddUser('admin', 'password', 'Pontus Östlund', 'spam@poppa.se', 1); 
  11. ?>

When this is done you would probably want to remove the calls to SetupTable and AddUser.

One thing worth noticing is that the password is run through sha1() and salted with a standard salt that's defined in the class. You can replace the standard salt with your own by calling the static mehod SetSalt prior to calling AddUser.

3 lines of PHP
  1. $auth = new SimpleAuth('sqlite:///path/to/db.sqlite', 'myapp'); 
  2. SimpleAuth::SetSalt('my452Very123MysterI5322OUs892Sal65t'); 
  3. //! And the rest of the code

To verify that your newly created user is created you can call the method Inspect which will print out a table of all the users

2 lines of PHP
  1. $auth = new SimpleAuth('sqlite:///path/to/db.sqlite', 'myapp'); 
  2. $auth->Inspect();

Example 1 »

So that's the basic setup.

Now lets do some authentication »