Overview

Source Codacy Badge

A simple, flexible authentication class that is easy to set up and understand.

Installation

Installation is easiest via composer.

1
$ composer require vespula/auth

Example Usage

 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
require '/your/autoloader.php'; // composer for example

use Vespula\Auth\Session\Session;
use Vespula\Auth\Auth;
use Vespula\Auth\Adapter\Text;

$session = new Session();

// Optionally pass a maximum idle time and a time until the session expires (in seconds)
$max_idle = 1200;
$expire = 3600;
$session = new Session($max_idle, $expire);

$adapter = new Text(...);

$auth = new Auth($adapter, $session);

// login condition could be if a $_POST['someval'] is true or whatever
if (login condition) {
    // filter/sanitize these first
    $credentials = [
        'username'=>$_POST['username'],
        'password'=>$_POST['password']
    ];

    // The credentials are passed as an array. This helps 'hide' them if an exception is thrown. Even in development environments.
    $auth->login($credentials);
    if ($auth->isValid()) {
        // Yay....
        echo "Welome " . $auth->getUsername();

        // Get userdata
        $userdata = $auth->getUserdata();
        echo $userdata['fullname'];

        // Shortcut to userdata
        echo $auth->getUserdata('fullname');
    } else {
        // Nay....
        // Wonder why? Any errors?
        $error = $adapter->getError(); // may be no errors. Just bad credentials
        echo "Please try again, if you dare";
    }
}

// Perform a log out. For example, if isset($_GET['logout'] && $_GET['logout'] == '1')
if (logout condition) {
    $auth->logout();
}

// Check if the user is valid (authenticated)
if ($auth->isValid()) {
    // Access some part of site
}

// Has the person been sitting idle too long?
if ($auth->isIdle()) {
    // Sitting around for too long
    // User is automatically logged out and status set to ANON
}

// Did the expire time get reached?
// Note that if the session actually expires, this won't show as being expired.
// This is because there is no status in a non-existent session.
if ($auth->isExpired()) {
    // Sitting around way too long!
    // User is automatically logged out and status set to ANON
}

// Access to user data
$username = $auth->getUsername();

$userdata = $auth->getUserdata(); // varies by adapter

// get a specific key from the $userdata array (assuming it exists in the array)
$email = $auth->getUserdata('email');

Adapters

  • Text: Authenticate against a text file (.htaccess) or array of users.
  • Sql: Authenticate against an SQL database table
  • LDAP: Authenticate against an LDAP/AD server.