Sql Adapter

Authenticate against a database table where users' passwords are stored using PHP's bcrypt hashing and the PASSWORD_DEFAULT algorithm. Under the hood, it uses password_verify().

1
2
3
4
5
6
// user table //
+----------+-------------+------------+---------------------+
| username | fullname    | email      | bcryptpass          |
|----------+-------------+------------+---------------------|
| juser    | Joe User    | juser@...  | $2y$.............   |
+----------+-------------+------------+---------------------+
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php

use Vespula\Auth\Session\Session;
use Vespula\Auth\Auth;
use Vespula\Auth\Adapter\Sql;

$session = new Session();
$dsn = 'mysql:dbname=mydatabase;host=localhost';
$pdo = new \PDO($dsn, 'dbuser', '********');

// $cols array must have a 'username' and 'password' element. You can use an alias if needed. See below.
// This data (except username and password) will populate the `getUserdata()` array
$cols = [
    'username',
    'bcryptpass'=>'password', // alias
    'fullname'=>'full_name' // alias
    'email'
];
$from = 'user';
$where = 'active=1'; // optional

$adapter = new Sql($pdo, $from, $cols, $where);
$auth = new Auth($adapter, $session);

if ('login button pushed logic') {
    $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
    $password = filter_input(INPUT_POST, 'password', FILTER_DEFAULT);
    $credentials = [
        'username'=>$username,
        'password'=>$password
    ];
    $auth->login($credentials);
    if ($auth->isValid()) {
        // display message, redirect, etc.
        $userdata = $auth->getUserdata();
        echo 'Hello, ' . $auth->getUsername();
        echo 'Your fullname is ' . $userdata['full_name']; // note the use of the alias (not fullname)
        // Or...
        echo 'Your fullname is ' . $auth->getUserdata('fullname');
    } else {
        // no luck, bad password or username
    }
}

if ('logout link clicked') {
    $auth->logout();
    // bye bye
    // $auth->isAnon() should return true
}