The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

CGI::AuthenticationFramework - A CGI authentication framework that utilizes mySQL for the user and session management

VERSION

Version 0.15

SYNOPSIS

Allows the login authentication, registration of user accounts, and password reset of webbased users. It also provides a framework for session management, form and list creation, and basic database management, everything you need to build a full web based application.

Sample CGI script :-

        #!/usr/bin/perl

        use strict;
        use CGI::AuthenticationFramework;
        use DBI;
        use CGI;
        my $cgi = new CGI;
        
        # == connect to the database
        my $dbh = DBI->connect("DBI:mysql:database=DATABASE;host=SERVERNAME",'username','password') || die $DBI::errstr;

        # == create the authentication link
        my $sec = CGI::AuthenticationFramework->new({
                dbh     => $dbh,
                cgi     => $cgi
                });
        
        # == create the tables
        $sec->setup_database(); # run this only once for performance.. No damage to keep it there
        
        # == do we go through, or block access.. This is where the rubber meets the road
        $sec->secure();
        
        # == once we get through that, we can send our headers
        print $sec->header();

        print "<p>\n";
        print "This is the secret message.<br>\n";
        print "Email Address is $sec->{username}<br>\n";
        print "Session ID is $sec->{session}<br>\n";
        print "</p>";
        print "<a href=\"#\">Me again</a>\n";
        
        # == when we're done, we call the finish function.  This clears the data connection, and prints the footer code
        $sec->finish();

FUNCTIONS

new

Creates a new authentication connection

        my $sec = CGI::AuthenticationFramework->new({
                dbh     => $dbh,
                cgi     => $cgi
        });

Options

dbh

Defined the database handle to use

cgi

Defines the CGI handle to use

The name of the cookie (default is 'my_cookie')

Default header code to include

Default footer code to include

yubikey

To enable yubikey support, set to 1.

When you enable yubikey support, you have to set the yubi_id and yubi_api fields as well. To get these, you need to sign up at https://upgrade.yubico.com/getapikey/

timeout

Defines the timeout before a user has to log on again. Default is 600 seconds.

register

If you need users to register on their own, set the register option to 1. Default is 0

register_template & forgot_template

Optional template that will be used to send the registration email.

use %URL% to define the URL that will be clicked by the user. Use %BASE% for the base URL of the program

register_subject & forgot_subject

Optional subject that will be used

register_from & forgot_from

Optional from email address to use

forgot

If you need users to have the ability to reset their passwords by emailing a new one to them, set this option to 1. Default is 0. =head4 SMTP server settings

If you have register enabled, you need to specify SMTP settings

smtpserver

The hostname of the SMTP server

smtpuser , smtppass

The smtpuser and smtppass parameters are optional. If your SMTP server requires you to authenticate, set these two fields.

captcha

Defined if you want to use a captcha. Default is 0.

Sign up for a free API from https://www.google.com/recaptcha/admin/create and enter the values in captcha_public and captcha_private

secure

The main gatekeeper.. Checks if the session is valid. If not, pass control to the login screen. If the session is still valid, the timeout is reset, and control is returned to the main program.

header

Works identical to CGI::header. The only difference is the adding of a cookie to the header, and passing the header value if defined from the new function.

Displays the basic system meny

finish

Function to send the footer, and sign everything off. Call this function last (or if you want to terminate the program

form

Generates an HTML form based on a schema

form (schema,submit text,hidden func field,title for the header,captcha option,%VALUES)

Schema format (field name, description, type, validation, default, sql)

fieldname

The field name that will be used in SQL and param calls

description

The field name that will be displayed

type

The type of the field, ie text, textarea, dropdown, or password

size

Defines the size of the field.

validation

Defines the input data check that will be performed to ensure the input validation is passed. Options can be email, password, number or text.

sql

Defines the SQL query to execute that will populate a dropdown list, should you use a dropdown.

form_update

Updates the data in the table

input : schema, table name, where

form_edit

Shows the edit form after an id was passed to it

input : schema, table, title, button text, func field, where

form_delete

Deletes the entry from the table

input : table, where

form_insert

Takes the input from a form, and inserts it into a database

Input : schema, table, default values (for readonly fields)

form_list

Show the result of a SQL table

input : schema, table, title, linkfield, next func, where, actions

form_create_table

Create a mySQL table based on a schema definition

input : schema, table name

set_variable

Defines a session variable

input : parameter, value

get_variable

Retrieves a session variable

input : parameter

Output : value

setup_database

Call this module once to setup the database tables. Running it multiple times will only introduce excessive load on the DB, but won't delete any tables.

It will create the tables tbl_users, tbl_session, and tbl_logs.

It will also create the default user 'admin', with it's password 'password'. Remember to change this password on your first logon.

Instead of using <a href links, call this function instead. It will embed a proper javascript substitute to ensure no GET urls are posted

input : text, func

wrapper

Wrapper module

input : schema, func prefix, table

schema_dump

Will show a table of the schema (helpful to debug if the schema is buggy)

is_admin

Will advise if the user is an administrator

Additional information

Using an existing database

All tables need an id field (auto increment primary key), and a varchar of xx_created_by. The xx_created_by field is populated by the username that created that particular entry. This is used in scenarios where a filter has to be set on only showing items belonging to the particular user. See phonebook2.pl for a practical example.

AUTHOR

Phil Massyn, <phil at massyn.net>

TODO

Bugs

New features * Searching of tables * Authorization module (ie group membership) * Include proper CSS and div tags for full template customization * Ability to have a 2nd table list linked to an earlier selection * Ability to read and search logs

Enhancements * If a user was already registered, but not activated, allow the token to be reset, and sent again * Process for a lost Yubikey * Ability to record additional fields during registration * Change form_* functions to use hashes as inputs, not seperate fields * Change dropdown & select to use native CGI parameters * Ability upload files * Ability to render files (ie if you upload an image, be able to show it in the browser) * Add a workflow example

Stuff we won't do * Split the module into smaller files (because when I run the code on GoDaddy, it becomes a mess to cross reference)

REVISION 0.15 Added viewport (for iPhone use) Created a wrapper procedure Security fix - cookie set to httponly Bug with state when manually adding new users Added where fields to all major data modules Created phonebook2 example (using the same table for multiple users with seperate information) Added additional css (maintitle, title) Added X-frame-options to prevent clickjacking

0.14 Fixed bug when filtering (sorting field -1) Swapped the arrows around Added list paging

0.13 Fixed Bug with showing admin menu when a non admin is logged on Fixed logic problem with validity vs required input fields Fixed a bug with not emailing the registration tokens correctly Prents fields from auto capitalizing on iOS devices Fixed showing the wrong menu when user is no longer logged on

0.12 Send via /usr/bin/sendmail (if it exists) on Unix boxes instead of Net::SMTP Include state on admin page Fixed user2 vs user bug on the registration page

0.11 Fixed bug after adding xx_created_by (did not add ? to values1) Added required check to sub form, with a corresponding div in the style sheet Added required check to sub form_insert Added input validation to sub form_update Updated logging of update, delete and insert Added yubikey and yubiid as validation inputs Changed admin schema to check yubi id as it's input validation Added xx_created_by to tbl_users (so admin module can edit it) Added header and footer css div tags and style sheets Added common font across css Removed table border from cgi and moved to css Fixed security bug - Removed readonly fields from being passed in form_update fields

0.10 Do not show "textarea" in a list Removed Home link from default header code Added additional actions to form_list Updated phonebook example Fixed bug with default admin user generation Fix admin module to use formlist's new actions feature Added xx_created_by field to all our created tables Added schema_dump procedure to display schemas Started adding some basic style sheet detail (system menu) Added system menu to changing passwords Ability to call is_admin without logged on will not call the database System_menu can detect if a user is logged on, and will show one of two menus Added more css to error and success messages Added default value to the schema Added required value to the schema

0.09 Customize register & forget emails Added msg_* to allow customization of feedback messages Added admin module Added funclink to manage hyperlinks through javascript better Delete accounts not validated within 24 hours as part of housekeeping Clean up of logs older than 30 days in housekeeping Change javascript calls to use native cgi->a calls Added a home link to the error messages Add timestamp, IP and user agent of machines used to create account and validate account for legal requirements - This requires a schema update. If you had a version prior to 0.09, your database will need to be updated.

0.08 Change order of form_list by clicking headers Create tbl_session_vars table Added session variables through get_variable and set_variable Added housekeeping to remove orphaned table entries Fixed dropdown bug not selecting the right value - This requires a schema update. If you had a version prior to 0.08, your database will need to be updated.

0.07 Fixed GET blocking not to prevent register and forget from working Added field in database to indicate administrators Prevented "password" fields from being displayed in lists Added the 2nd field to self param Encrypt passwords when using form_insert function Encrypt passwords if they're being changed through form_update Fixed number validation when validating a 0. Added a text input validation

0.06 Added autocomplete to login form Added form_delete function Added strong password enforcement Removed debug logs from captcha procedure Added logging when database gets changed

0.05 Fixed xss to check all array elements when calling fetchrow_array Replaced all GET with POST functions, and prevent futher usage of GET Added form_edit function Fixed missing hidden id in form function Updated param function to strip unsafe characters

0.04 Updated form to handle hidden field, and input values Added textarea, and readonly fields Included dropdown with SQL in the schema support Added form_create_table Added form_insert Added form_list Added HTML::Entities for encoding output string (prevent cross site scripting) Changed the cookie's session ID to reset on every click Make the cookie secure

0.03 Added no-cache tags to header function Added input validation procedure Added input validation for tokens Moved valid_email procedure into validate_input Fixed omission of $forgot parameter check on sub forgot Added reCaptcha

0.02 Added registration option (including Net::SMTP) Changed password encryption to a salted hash Added forgotten password option Logging all messages being displayed

0.01 Initial version

BUGS

Please report any bugs or feature requests to bug-cgi-authenticationframework at rt.cpan.org, or through the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=CGI-AuthenticationFramework. I will be notified, and then you'llautomatically be notified of progress on your bug as I make changes.

SUPPORT

You can find documentation for this module with the perldoc command.

    perldoc CGI::AuthenticationFramework

You can also look for information at:

ACKNOWLEDGEMENTS

LICENSE AND COPYRIGHT

Copyright 2013 Phil Massyn.

This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License.

See http://dev.perl.org/licenses/ for more information.

DISCLAIMER

This module has not been scrutinized yet. It may very well contain security issues. Although unintentional, you should excersize caution, and not start deploying production systems on this code. Any bugs or issues raised will be rectified. Use this module at own risk.