hakopako

Full-stack Engineer's blog

Auth with Sentinel + SQLite3 + PHP7

日本語 | English

Sentinel is an authorization and authentication package.
I tried it out on a prototype product, but constructing MySQL or PostgreSQL is too much...
Then I found out to use sqlite3.

Install Sentinel

As the official page says, install Sentinel and Illuminate with composer. I won't write the detail of how to install packages with composer, but composer.json would be like below.

# composer.json
~~~ ... ~~~
    "require": {
        "cartalyst/sentinel": "2.0.*", 
        "illuminate/database": "~5.1",
        "illuminate/events": "^5.2",
        "illuminate/http": "~5.0"
    },
~~~ ... ~~~
$ php composer.phar install

Configure DB connection of Sentinel

For the details, visit official page: https://cartalyst.com/manual/sentinel/2.0#configuration

// Import the necessary classes
use Cartalyst\Sentinel\Native\Facades\Sentinel;
use Illuminate\Database\Capsule\Manager as Capsule;

// Include the composer autoload file
require 'vendor/autoload.php';

// Setup a new Eloquent Capsule instance
$capsule = new Capsule;

$capsule->addConnection([
    'driver'    => 'sqlite',
    'database'  => '/path/to/database.sqlite',
    'charset'   => 'utf8'
]);

$capsule->bootEloquent();

These 2 lines are changed.

  • 'driver' => 'sqlite',
  • 'database' => '/path/to/database.sqlite',

Create User Tables

Sentinel supports migrate function of Laravel Framework.
As long as you work with Sentinel on Laravel and the database is such as MySQL, user tables are created automatically with prepared migration command.
For here, I'm going to use sqlite3 instead of MySQL, so creating user tables will be manual.

I wrote a SQL Schema file which is translated from MySQL Schema*1 into SQLite Schema.
Execute this SQL on your sqlite3 database to create user tables which Sentinel access to.

This is the SQLite Schema for Sentinel.

Check the behavior

Write and run functions as the way official page says, you'll see it works.
This is an example usage script.

// Register a new user
Sentinel::register([
    'email'    => 'test@example.com',
    'password' => 'foobar',
]);


// Authenticate
$credentials = [
    'email'    => 'test@example.com',
    'password' => 'foobar',
];

echo Sentinel::authenticate($credentials);

That's all.