codeandpixel/userclass

There is no license information available for the latest version (dev-master) of this package.

Userclass designed to make it all simple

dev-master 2017-03-03 19:06 UTC

This package is auto-updated.

Last update: 2024-04-15 03:08:40 UTC


README

A badass user management class that uses the (SimplePDO)[https://github.com/bennettstone/SimplePDO] database wrapper for prepared queries.

Provides simple integration and support for RapidPHP projects, and can fairly easily be adapted to other uses (the only thing to do is replace calls to $this->database->[dothing] with your preferred method).

Comes with built in standard registration, as well as facebook and google authentication via the (PHP Oauth API)[http://www.phpclasses.org/package/7700-PHP-Authorize-and-access-APIs-using-OAuth.html] by Manuel Lemos, and uses PHP's password hashing algorithms with the password_compatibility library for older versions of php.

The database schema used is provided in the /db_schemas/users.sql folder.

Functions and Usage

Initialize the class

The class assumes an existing database connection, so it must be initialized with a database instance and any params needed...

require_once( 'classes/userClass.php' );
$users = new userClass( SimplePDO::getInstance(), $options );

Set the class options

This class has quite a few options that may be set to control paths, oauth keys, and users table names...

$options = array(

    //require email conf. for normal reg?
    'confirm_users' => false,
    
    //require email conf. for social media auth?
    'confirm_social_users' => false, 
    
    //database table name to use for users
    'users_table' => 'users',  
    
    //Force header() location redirect?           
    'header_redirect' => false,
    
    //Reg with email OR username/email
    'email_only' => true,
    
    //Trailing slash IS important!
    'url' => 'http://yoururl.com/',
    
    //Use PHP 5 >= 5.5.0, PHP 7 password_hash algos
    'use_pwd_hash' => true, 
    
    //Multiplier for password hashing
    'hash_cost_factor' => 10,

    //2 weeks for secure cookie
    'cookie_runtime' => 1209600, 
    
    // important: always put a dot in front of the domain, like ".mydomain.com" see http://stackoverflow.com/q/9618217/1114320
    'cookie_domain' => '.127.0.0.1', 
    
    //Name of cookie to set
    'cookie_name' => 'remember_me', 
    
    //Outbound email "from" email
    'from_email' => 'noreply@yoursite.com', 
    
    //Outbound email "from" name
    'from_name' => 'yoursite', 
    
    //Full URI to where you plan on having the activate_account function
    'email_verification_url' => 'login/verify', 
    
    //Subject line for account activation emails
    'email_verification_subject' => 'account activation for project xy', 
    
    //Password reset URI where verify_pass_reset() will be
    'email_password_reset_url' => 'login/verifypasswordreset', 
    
    //Password reset email subject
    'email_password_reset_subject' => 'password reset for project xy', 
    
    //Logout redirect for page_protect()
    'logout_redirect' => '', 
    
    //Oauth credentials
    'oauth' => array(
        'fb' => array(
            'client_id' => '', 
            'client_secret' => '', 
            'client_redirect' => ''
        ), 
        'google' => array(
            'client_id' => '', 
            'client_secret' => '', 
            'client_redirect' => ''
        )
    ), 
    
    //Email messaging copy
    'message_copy' => array(

        //Registration without confirmation
        'registration' => '',

        //Registration WITH confirmation
        'registration_confirm' => '',

        //Password reset messages
        'password_reset' => '',

    ),
    
    //Copy => variable replacements for message copy above
    'message_replacements' => array(
    
        'email' => 'user_email',

        'password' => 'user_password',
    ),
);

$users = new userClass( SimplePDO::getInstance(), $options );

Register a user

User registration requires a few fields, any others would need to be added to the register() function.

Required fields:

  • user_name
  • user_email
  • user_password

Returns array for invalid submissions, or true (bool) for successful submissions.

$_POST = array(
    'user_name' => 'booooyahhhh',
    'user_email' => 'you@email.com',  
    'user_password' => '12345678'
);

$reg = $users->register();

//Handle any way preferred...
//Redirect on success...
if( $reg === true )
{
    header( 'Location: http://awesome.com' );
    exit;
}
else
{
    //Loop through the errors
    foreach( $reg['errors'] as $e )
    {
        echo $e;
    }
}

Register/login a user with Facebook

For this, you'll want to do some extra checks due to the redirect path required to authorize a user with social media, and you'll first need to be sure to set the 'oauth' params in the set_options, or the userClass will throw a warning. You can create an app at (https://developers.facebook.com/apps)

if( isset( $_GET['facebook_login'] ) || isset( $_GET['code'] ) )
{
    $facebook = $users->facebook_authenticate();
    if( $facebook === true )
    {
        //Do your stuff here
        header( 'Location: http://yoursite.com/loggedinsuccess' );
        exit;
    }
    else
    {
        foreach( $facebook['errors'] as $e )
        {
            echo $e;
        }
    }
}

Register/login a user with Google

For this, you'll want to do some extra checks due to the redirect path required to authorize a user with social media, and you'll first need to be sure to set the 'oauth' params in the set_options, or the userClass will throw a warning. You can create an app at the Google APIs console page http://code.google.com/apis/console, and in the API access tab, create a new client ID, and set the client_id to Client ID and client_secret with Client Secret. The callback URL must be '.$this->options['url'].' but make sure the domain is valid and can be resolved by a public DNS.

if( isset( $_GET['google_login'] ) || isset( $_GET['state'] ) )
{
    $google = $users->google_authenticate();
    if( $google === true )
    {
        //Do your stuff here
        header( 'Location: http://yoursite.com/loggedinsuccess' );
        exit;
    }
    else
    {
        foreach( $google['errors'] as $e )
        {
            echo $e;
        }
    }
}

Activate a user

If the 'confirm_users' or 'confirm_social_users' parameters are set to "true", you'll need to use the "activateaccount()" function (activation emails are automatically sent if the confirm option is set to true).

Returns bool only.

if( isset( $_GET['user'] ) && isset( $_GET['code'] ) )
{
    if( $users->activate_account() )
    {
        header( 'Location: http://yoursite.com/activationsuccess' );
        exit;
    }
    else
    {
        //show some sort of error or other redirect here
    }
}

Check to see if a user is logged in

Use it to protect pages for only logged in users or display content conditionally.

if( !$users->logged_in() )
{
    header( 'Location: http://yoursite.com/loggedout' );
    exit;
}

Login a user

Much like registration, a few parameters are required:

  • user_email
  • user_password

Optional fields:

  • user_name (if it's there, the system will check it against the usernames)
  • user_remember (sets remember cookie)
  • redirect (anywhere to redirect to IF headers have not already been sent AND the 'header_redirect' userClass option has been set)

In the event that headers have already been sent, or there's an issue initiating a header() redirect, AND the user is successfully logged in, an array is returned which you can handle any way you see fit:

array( 'success' => true, 'redirect' => $_POST['redirect'] );

Otherwise, a successful login simply returns a boolean which may ben handled according to your application's needs.

$_POST = array(
    'user_email' => 'you@email.com', 
    'user_password' => '12345678', 
    'user_remember' => true, 
    'redirect' => 'http://google.com'
);
$login = $users->login();
if( $login === true )
{
    header( 'Location: http://yoursite.com/loggedin/' );
    exit;
}
else
{
    foreach( $login['errors'] as $e )
    {
        echo $e;
    }
}

Logout a user

Pretty self explanatory, usually helps to add an extra check in the conditional to make sure the user is actually logged in.

If a uri is passed directly to the logout() function, a header() redirect will be initiated, otherwise a boolean is returned.

//Manually handle logout
if( isset( $_GET['logout'] ) && $users->logged_in() && $users->logout() )
{
    header( 'Location: '. $users->get_option( 'url' ) );
    exit;
}

//Handle logout with a specific uri
if( isset( $_GET['logout'] ) && $users->logged_in() )
{
    $users->logout( 'http://yoursite.com/loggedout/' );
}

Request password reset

Returns only bool so it may be handled on an application specific basis.

$_POST = array(
    'user_email' => 'you@email.com'
);

$reset = $users->password_reset();
if( $reset === true )
{
    echo 'Please check your email address for a password verification message.';
}
elseif( isset( $reset['errors'] ) )
{
    foreach( $reset['errors'] as $e )
    {
        echo $e;
    }
}
else
{
    echo 'Something broke somewhere';
}

Verify a password reset attempt

Should be located at the path defined as the 'email_password_reset_url' param in userClass configuration. Returns bool, and sets a $_SESSION['reset_key'] parameter which may then be used as a validation method for the update_password() function.

$_GET = array(
    'code' => 'longrandomstringofstuffhere'
);
$reset = $users->verify_pass_reset();
if( $reset === true )
{
    //Direct user to password change form
}
elseif( isset( $reset['errors'] ) )
{
    foreach( $reset['errors'] as $e )
    {
        echo $e;
    }
}
else
{
    echo 'Something broke somewhere';
}

Update a user's password

Can be used if the session param is set from a valid "verify_pass_reset()" action, OR if the user is currently logged in. Returns bool or array if passwords don't match.

$_POST = array(
    'old_password' => 'youroldpassword', 
    'new_password' => 'yournewpassword'
);
$change = $users->update_password();
if( $change === true )
{
    //toss awesome success message
}
elseif( isset( $change['errors'] ) )
{
    foreach( $change['errors'] as $e )
    {
        echo $e;
    }
}
else
{
    echo 'Something broke somewhere';
}

Forcibly protect a page

Initiate a forced redirect to a new page (if headers aren't already sent) for any user that isn't already logged in.

Place this function call before any other output on a page to lock it down to only logged in users.

This will ONLY work if the 'secure_redirect' parameter is set to an actual value, or if a URI is specified in the function call

//Send user to the default location specific in config
$users->page_protect();

//Send users to a custom location
$users->page_protect( 'http://yoursite.com/unauthorized ');