Login

User Authentication With patUser (part 2)

In this second part, find out how you can use the patUser API to
view, add, edit and delete users (and user attributes) from your user
database.In the first part of this article, I focused almost entirely on how patUser
could simplify the task of adding authentication to your site. I explained the
patUser database schema, ran you through the process of initializing a patUser
object instance and linking it to a database and template engine, and showed you
how built-in patUser methods could simplify the task of verifying user
credentials and writing login and logout scripts.

However, patUser can
do a lot more than just handle user authentication – the library also comes with
a large number of methods designed to make the task of managing user data as
simple and efficient as possible. Over the course of this second installment,
I’m going to show you how these methods work, and how they can be used to
quickly create scripts to view, add, edit and delete users (and user attributes)
from your database. Keep reading!{mospagebreak title=Meeting The Family} Let’s
start with the basics – obtaining a list of current users from the database. If
you’ve been following along, you already know that right now, the database has
only a single user, “joe”. Let’s add a couple more:

The first part of this script should be easily recognizable to you by now
– it consists of the code needed to instantiate a patUser object instance and
prepare it for use. Once the object has been prepared, the getUsers() function
is used to retrieve a list of all the users in the database. The return value of
the getUsers() method is an associative array containing user records, one
element for each record.

The first argument to the getUsers() function
is an array containing the names of the fields to be included in the result set
– these field names appear as keys in the returned array, and can be used to
access the corresponding values. Here’s the output:

You’re
not restricted to using just the default fields built into the patUser database
schema – you can just as easily add your own. Find out how, on the next
page.{mospagebreak title=Asking For More} Now, let’s make some additions to the
patUser-provided schema for the “users” table. You might remember that the
original schema looked like this:

In this case, I’ve told getUsers() to retrieve a few extra fields from the
database – specifically, the “age”, “sex” and “tel” fields. You’ll remember
these are not standard patUser fields, but have been added by me for
illustrative purposes.

Here’s the output:

{mospagebreak
title=Drilling Deeper} You can also get fancy by adding selection criteria in
your call to getUsers(), as a second argument to the method. Consider the
following variant of the example above, which only returns records of those
users who are male and between 18 and 25:

In this case, the second argument to the getUsers() method – a series of
nested arrays containing selection criteria – provides patUser with a list of
additional conditions to be satisfied when querying the database. Only those
user records that match the specified conditions will be included in the
result.

Here’s the output:

{mospagebreak
title=All For One, And One For All} patUser also allows you to organize users
into named collections or groups. You might remember, from the discussion of the
patUser database schema in the previous segment of this article, that there are
two tables designed specifically for this task, the “groups” table (which
maintains a list of available groups) and the “usergroups” table (which
maintains a list of which users belong to which group).

Obviously, we can perform the same task using patUser’s getGroups()
function, which works in much the same way as the getUsers() function discussed
on the previous page. The following code listing demonstrates:

Note the
introduction of a new method in the script above, setGroupTable(). This method,
together with the setGroupFields()method, allows you to configure patUser to use
a different set of tables than its default by remapping the default table and
column references to custom values.{mospagebreak title=Accounting For Change}
The default patUser-supplied database schema for the “groups” table includes
only two group attributes: its name, and a unique group ID. Most of the time,
this is sufficient; however, in case you need to add more attributes, patUser
can be easily tweaked to work with this extra data.

Let’s alter the
default “groups” table to include some additional fields, for description and
location:

{mospagebreak title=California Calling} You can also apply selection
criteria in your call to getGroups(), so as to return only a specific subset of
records. Consider the following variant of the example above, which only returns
those groups located in California:

{mospagebreak title=Making New Friends} It’s just as simple to add new users and groups to the
system – all you need to do is use patUser’s addUser() and addGroup() methods,
which accept an array of field-value pairs and uses them to create a new user or
group record in the database. Both methods return the ID of the newly-created
user or group if successful. Consider the following example, which demonstrates
how to add new users:

{mospagebreak title=A Fast Edit} Once a user is entered into the system,
patUser allows you to add new data to the user record, or make changes to the
existing data, with its modifyUser() method. This method accepts two primary
arguments: an array containing the data to be inserted, and an array containing
the user ID of the record to edited and related options.

Consider the
following example, which illustrates the process of editing a user record and
entering new information into it:

Note that in the example above, all changes will be made to the record
with user ID 15. If no user ID is provided, the currently logged-in user’s ID is
used instead.

You can also modify group data with the corresponding
modifyGroup() method. I’ll leave that to you to experiment with.{mospagebreak
title=Here Today, Gone Tomorrow} Just as you can add and edit users, patUser()
also comes with – obviously! – a deleteUser() method. This method accepts, as
input, a user ID, and removes the corresponding user record from the database.
If no user ID is provided, the currently logged-in user’s ID is used instead.
The following example demonstrates:

Needless to say, these utility functions come in very handy when you need
to find out which users belong to which groups, or if you need to alter the
various user and group configurations. You’ll see this in action in the
composite example on the next page.{mospagebreak title=A Well-Formed Plan} Now,
how about a couple of examples to put all this in context? This first example
demonstrates how the various user and group manipulation methods discussed in
this article can be used to rapidly build a user administration module for a Web
application or Web site. Consider the following script, which is designed to
allow administrators to add new users to the system.

This script is split into two parts. The first part is a simple HTML form
containing fields for user information (including the critical username and
password fields) and group membership. The list of groups is obtained from the
system itself, via a call to the getGroups() method. An administrator may fill
up this form with the components of a user record, and also attach a user to one
or more of the named groups.

Once the form has been submitted and the
data within it validated, the addUser() method is invoked to add the user to the
system. The unique user ID returned by the addUser() method can then be used by
the modifyUser() and addUserToGroup() methods to set up the rest of the user
record and group memberships.

You’ll notice that, unlike traditional
scripts of this nature, there are no SQL queries in the code above. This is
because patUser does most of the heavy lifting for you, encapsulating all needed
queries within its user management API; all you need to do is invoke the
appropriate method and pass it the data that needs to be entered into the
database. Integrating patUser, therefore, can substantially reduce the time you
spend on building such utility scripts.{mospagebreak title=Slice And Dice} How
about one more? Once the user has been registered in the system (perhaps using a
script like the one on the previous page), it becomes possible to slice and dice
that user information for a variety of different purposes. In this next script,
different sections of a single Web page are hidden or displayed on the basis of
a user’s credentials and group membership.

Most of this should be fairly easy to understand. The page is divided into
three sections, with the first one available to all authenticated users and the
remaining two turned on only if the user is a member of the appropriate groups.
The isMemberOfGroup() method discussed on the previous page is used to test
whether the user belongs to the group or not, while the the getGroups() method
is used, this time with additional selection criteria, to obtain the group ID of
the various groups involved.

Business logic similar to that above can be
used to create Web pages that are sensitive to user credentials and privileges,
and that can dynamically change so that only the appropriate information is
presented to each user. And with patUser again doing most of the work, adding
this business logic to a Web page is a snap.

And that’s about it for the
moment. This article was a little longer than the previous one, but it also
covered a lot more ground. You should now have a better understanding of
patUser’s concepts of users, groups and group membership, and of the user and
group management API available in the patUser library. In this article, I
demonstrated most of the important components of this API, showing you how to
list, add, edit and modify users and groups, and how to organize users into
groups. Finally, I wrapped things up with two examples of how these API calls
can be used in real-world situations: a script for administrators to add new
users via a Web-based interface, and a Web page that altered its visible content
based on the logged-in user’s permissions.

In the third (and concluding)
article in this series, I will be briefly looking at a number of
hard-to-categorize-yet-very-useful methods in the patUser library. These include
methods to handle errors, track user movement, collect statistics and identify
users and groups using different criteria. Make sure you don’t miss that
one!

Note: Examples are illustrative only, and are not meant for a
production environment. Melonfire provides no warranties or support for the
source code described in this article. YMMV!