Page 1 of 2 12 Last
  • Jump to page:
    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Location
    Ireland
    Posts
    42
    Rep Power
    12

    PEAR Auth example


    After searching the internet unsuccessfully for more advanced examples of using Auth than the manual shows with no success, I got writing.

    Hope this may be of benefit to others. Apologies if this is the wrong place to put this.

    <?php
    /*
    use as an include in <body> to make the form appear on a single line.

    Before using, set up the dsn line below with your database info:
    "dsn" => "mysql://usernameassword@localhost/database" ,

    this example uses a table call people with the format:
    CREATE TABLE `people` (
    `personid` mediumint(4) NOT NULL auto_increment,
    `personname` char(32) NOT NULL default '',
    `email` char(100) NOT NULL default '',
    `passw` char(32) NOT NULL default '',
    `persontype` char(12) default 'Any'
    PRIMARY KEY (`personid`),
    KEY `email` (`email`)
    ) TYPE=MyISAM
    */


    require_once('PEAR.php');
    require_once('DB.php');
    require_once('Auth/Auth.php');




    //---- setup Auth class
    $params = array(
    "dsn" => "mysql://usernameassword@localhost/database" ,
    "table" => "people" ,
    "usernamecol" => "email" ,
    "passwordcol" => "passw",
    "db_fields" => array('personid','personname','persontype')
    );

    $a = new Auth ("DB" ,$params, 'myLogin' );

    //---- REGISTER
    if ($_POST['register']) {

    // already filled in details, so save now
    if ($_POST['username']) {
    $err=$a->addUser($_POST['username'],$_POST['password'],
    array('personname'=>$_POST['personname'],'persontype'=>'Contributor'));
    if ($err==1) {
    $a -> start ();
    $contrib=&$_SESSION['auth']['data'];
    } else {
    // your error handling here ($err contains PEAR error)
    print_r($err);
    die();
    }
    } else {
    //display registration form
    myRegister();
    }

    //---- LOGIN

    } else {
    // normal login
    $a->setLoginCallback('myLoginCallback');
    $a -> start ();
    if ( $a -> getAuth ()) {
    // point to session data for convenience
    $contrib=&$_SESSION['auth']['data'];

    //---- LOGOUT

    if( $_GET ['act'] == "logout" ) {
    $contrib=NULL;
    $a->setLogoutCallback('myLogoutCallback');
    $a -> logout ();
    $a -> start ();
    }


    } else {
    // failed to login
    echo '<font color="#990000">Invalid email or password.</font>';
    } // $a->getAuth()

    } // $_GET['register']

    // logged in or registered okay
    if (!empty($contrib)) {

    echo 'Currently logged in as: '.$contrib['personname'];
    echo '&nbsp;&nbsp;<input type="submit" name="logout" id="logout" value="Logout" onClick="document.location.href=\''.basename($_SERVER["PHP_SELF"]).'?act=logout\'">';
    }

    //print_r($_SESSION);
    //print_r($a);

    function myLogin() {
    // note that even if you have different names for the username and password fields
    // in your database, you must use "username" and "password" in the form.
    // no validation included
    echo '<p class="login">';
    echo '<form name="login" method="post" action="'. $_SERVER['PHP_SELF'] . '">';
    echo 'eMail:<input type="text" name="username" value="'.$_POST['username'].'">';
    echo 'Password <input type="password" name="password" size="10">';
    echo '<input type="submit" name="login" id="login" value="Login">';
    // echo '<input type="submit" name="sendpw" id="sendpw" value="Forgotten Password?">';
    echo '<input type="submit" name="register" id="register" value="Register...">';
    echo '</form></p>';
    } //myLogin

    function myRegister() {
    // note that even if you have different names for the username and password fields
    // in your database, you must use "username" and "password" in the form.
    // validation required
    echo '<p class="login">';
    echo '<form name="register" method="post" action="'. $_SERVER['PHP_SELF'] . '">';
    echo 'Full Name:<input type="text" name="personname" value="'.$_POST['personname'].'">';
    echo 'eMail:<input type="text" name="username" value="'.$_POST['username'].'">';
    echo 'Password <input type="password" name="password" size="10">';
    echo '<input type="submit" name="register" id="register" value="Register Now">';
    echo '</form></p>';
    } //myRegister

    function myLoginCallback() {
    // this is called when the user initially logs in using the form

    } // myLoginCallBack

    function myLogoutCallback() {
    // this is called when logout is called, object $a is no longer available

    } // myLogoutCallBack
    ?>
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2004
    Location
    Romania
    Posts
    22
    Rep Power
    0
    hi there , thanks for the example i have a little question ... you've commented a line in your script , more exactly this one :
    echo '<input type="submit" name="sendpw" id="sendpw" value="Forgotten Password?">';
    Is there any way to make that piece of code functional ?
    I am new to Pear , and as far as I see , only a few packages are documented ...some class methods are not even mentioned in the description , the only chance to work with them or to discover them is to study the source code , thing that is not always good when you're involved in a big project where speed and time are essential .
    Best regards ,
    Emil Tamas
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Location
    Ireland
    Posts
    42
    Rep Power
    12
    I havn't implemented that bit yet but I think what I will do is write a new function sendPassword that makes use of a mail class ( I like this one http://www.phpclasses.org/browse.html/package/32.html). It will need to make sure that a mail address has been entered and then generate a new password (another function) and then mail it. Yes I remember why I havn't done it yet!

    Let me know if you solve the problem and I'll pass on my solution when I get to it.

    Good luck.

    Phoebe.
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2004
    Location
    Romania
    Posts
    22
    Rep Power
    0
    The passwords are encrypted with md5 so , as far as I know that encription method is not reversible and the only chance is to reset the value of the password , then send it to an email .
    I have the code in my head , It's just a matter of days before I will write it because I need it .
    Good luck to you too ,
    Emil
  8. #5
  9. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2004
    Location
    UK
    Posts
    1
    Rep Power
    0

    Smile You are a star


    I also looked for ages on the web for examples, no luck.

    I found lots of example code on authenticating a user, but how do you add a user to the database??

    Then I saw you code....

    addUser();

    Many Thanks.
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2004
    Posts
    1
    Rep Power
    0
    Thanks for this very helpful post. I am having a problem with the getAuthData() method. For some reason, can't get it to return any data.

    Here is my code:

    PHP Code:
    require_once("Auth/HTTP.php");
    $AuthOptions = array(
    'dsn'=>"mysql://user:pass@localhost/auth",
    'table'=>"tbl_auth",
    'usernamecol'=>"username",
    'passwordcol'=>"password",
    'cryptType'=>"md5",
    'dbfields' => '*'
     
    );


    $a = new Auth_HTTP("DB"$AuthOptions);

    $a->setRealm('Private');
    $a->setCancelText('You clicked cancel.');
    $a->start();

    if(
    $a->getAuth())
    {
        echo 
    "Hello $a->username welcome to my secret page <br />";
        echo 
    "Your details on file are: <br />";
        echo 
    $a->getAuthData('userid');
        echo 
    $a->getAuthData('telephone');
        echo 
    $a->getAuthData('email');
    }; 
    I tried this with the field names and * in the dbfields array.

    Anyone have any thoughts as to why I can't get the data back out? I am not having any problems using addUser() to get them in there
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Location
    Ireland
    Posts
    42
    Rep Power
    12
    Sorry to take so long to get back to you, I had a holiday!

    Have you sorted it yet? Having a quick look at the code, it is assuming sessions are being used. You could try putting print_r($_SESSION); next to your echos and see if there is anything there.

    If you still have a problem, let me know and I will investigate further.

    Phoebe.
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2004
    Posts
    10
    Rep Power
    0

    Question Where did addUser(), setLoginCallback(), etc., come from?


    Boy, do I have a headache from trying to figure out PEAR::Auth (simulataneously with learning PHP OOP). This page is helping a lot, but I still have a ways to go.

    First of all, I understand from the Auth documentation that "auth()," "getAuth()," and "start()" are properties of the Auth class, and I see these being used in Phoebe's program.

    I also see that Phoebe has defined four functions, myLogin(), myRegister(), myLoginCallback(), and myLogoutCallback(). I think I understand that.

    But where did these guys come from?:

    -- addUser()

    -- setLoginCallback()

    -- setLogoutCallback()

    -- logout()

    Are these undocumented properties of Auth?

    Another question: The callback functions are blank. What sorts of things might you want or need to put in there?

    Yet another question: under what circumstances might you need to use getStatus()?

    I'm sure there are lots of other things I don't understand, but this is enough for now.

    bh
  16. #9
  17. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2004
    Posts
    10
    Rep Power
    0

    Lightbulb Aha!: API documentation


    I googled the four mystery properties, and it led me to the PEAR::Auth API documentation. Before, all I was looking at was the so-called End-user Documentation. I guess the end-user stuff is incomplete?
  18. #10
  19. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2004
    Posts
    85
    Rep Power
    11
    Just FYI, md5 isn't encryption but hashing. This means that you'll always get the value returned is the same every time. As md5 is fixed length (never more or less than 32chars) there are chances for duplicates and cannot be reversed.

    Just thought you might like to know
  20. #11
  21. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2004
    Posts
    10
    Rep Power
    0

    Question Cookie vs. HTTP authentication?


    I read here

    http://www.sklar.com/page/article/owasp-top-ten

    that PEAR::Auth is cookie-base authentication, while PEAR::Auth_HTTP is HTTP-based authentication. Is is necessary or even possible to use both of them if you want to have a fallback for users who don't have cookies enabled?

    Also, how does PEAR::Auth relate to session tracking? Does it handle session tracking, or do you need to do that yourself?
  22. #12
  23. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2004
    Posts
    10
    Rep Power
    0

    Wink


    Phoebe's example formatted in a more easy-to-read way:

    PHP Code:
    <?php
        
    /*
        use as an include in <body> to make the form appear on a single line.
       
        Before using, set up the dsn line below with your database info:
        "dsn" => "mysql://usernameassword@localhost/database" ,
       
        this example uses a table called people with the format:
        
            CREATE TABLE `people` (
                `personid` mediumint(4) NOT NULL auto_increment,
                `personname` char(32) NOT NULL default '',
                `email` char(100) NOT NULL default '',
                `passw` char(32) NOT NULL default '',
                `persontype` char(12) default 'Any'
                PRIMARY KEY (`personid`),
                KEY `email` (`email`)
                ) TYPE=MyISAM
        */

    require_once('PEAR.php');
    require_once(
    'DB.php');
    require_once(
    'Auth/Auth.php');

    //---- setup Auth class
    $params = array( 
        
    "dsn" => "mysql://username:password@localhost/database" ,
        
    "table" => "people" ,
        
    "usernamecol" => "email" ,
        
    "passwordcol" => "passw",
        
    "db_fields" => array('personid','personname','persontype')
        ); 

    $a = new Auth ("DB" ,$params'myLogin' ); 

    //---- REGISTER 
    if ($_POST['register'])
    {
        
    // already filled in details, so save now
        
    if ($_POST['username'])
        { 
            
    $err=$a->addUser($_POST['username'],$_POST['password'],
            array(
    'personname'=>$_POST['personname'],'persontype'=>'Contributor'));
            if (
    $err==1)
            {
                
    $a -> start (); 
                
    $contrib=&$_SESSION['auth']['data'];
            }
            else
            {
                
    // your error handling here ($err contains PEAR error)
                
    print_r($err);
                die();
            }
        }
        else
        {
            
    //display registration form
            
    myRegister();
        }
    //---- LOGIN
    }
    else
    {
        
    // normal login
        
    $a->setLoginCallback('myLoginCallback');
        
    $a -> start (); 
        if ( 
    $a -> getAuth ())
        {
            
    // point to session data for convenience
            
    $contrib=&$_SESSION['auth']['data'];

            
    //---- LOGOUT
            
    if( $_GET ['act'] == "logout" )
            { 
                
    $contrib=NULL;
                
    $a->setLogoutCallback('myLogoutCallback');
                
    $a -> logout (); 
                
    $a -> start (); 
            } 
        }
        else
        {
            
    // failed to login
            
    echo '<font color="#990000">Invalid email or password.</font>';
        } 
    // $a->getAuth()

    // $_GET['register']

    // logged in or registered okay
    if (!empty($contrib))
    {
        echo 
    'Currently logged in as: '.$contrib['personname']; 
        echo 
    '&nbsp;&nbsp;<input type="submit" name="logout" id="logout" value="Logout"
            onClick="document.location.href=\''
    .basename($_SERVER["PHP_SELF"]).'?act=logout\'">';


    //print_r($_SESSION);
    //print_r($a);


    function myLogin()
    {
        
    // note that even if you have different names for the username and password fields
        // in your database, you must use "username" and "password" in the form.
        // no validation included
        
    echo '<p class="login">';
        echo 
    '<form name="login" method="post" action="'$_SERVER['PHP_SELF'] . '">';
        echo 
    'eMail:<input type="text" name="username" value="'.$_POST['username'].'">';
        echo 
    'Password <input type="password" name="password" size="10">';
        echo 
    '<input type="submit" name="login" id="login" value="Login">';
        
    // echo '<input type="submit" name="sendpw" id="sendpw" value="Forgotten Password?">'; 
        
    echo '<input type="submit" name="register" id="register" value="Register...">';
        echo 
    '</form></p>'
    //myLogin

    function myRegister()
    {
        
    // note that even if you have different names for the username and password fields
        // in your database, you must use "username" and "password" in the form.
        // validation required
        
    echo '<p class="login">';
        echo 
    '<form name="register" method="post" action="'$_SERVER['PHP_SELF'] . '">';
        echo 
    'Full Name:<input type="text" name="personname" value="'.$_POST['personname'].'">';
        echo 
    'eMail:<input type="text" name="username" value="'.$_POST['username'].'">';
        echo 
    'Password <input type="password" name="password" size="10">';
        echo 
    '<input type="submit" name="register" id="register" value="Register Now">';
        echo 
    '</form></p>'
    //myRegister

    function myLoginCallback()
    {
        
    // this is called when the user initially logs in using the form
    // myLoginCallBack

    function myLogoutCallback()
    {
        
    // this is called when logout is called, object $a is no longer available
    // myLogoutCallBack
    ?>
  24. #13
  25. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2004
    Posts
    10
    Rep Power
    0

    Question What is this?: $_SESSION['auth']['data']


    In Phoebe's code, I see $_SESSION['auth']['data'] being assigned to $contrib. I am wondering what this is ("auth" and "data") and where the original session data for "auth" and "data" comes from. I can't find it in Phoebe's code, and I read the Auth.php source code and couldn't find any reference to it. Does it go all the way back to PEAR.php?

    I'm guessing that "auth" contains something like the authorization status of the user, and "data" contains maybe an array with his name, etc.? But I don't know.
  26. #14
  27. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2004
    Posts
    10
    Rep Power
    0

    Cool Forgotten Password?


    In reference to the question about implementing a Forgotten Password feature, I don't think it's possible in most cases, if you want to send the user his old password.

    PEAR::Auth uses PEAR::DB for database access, which in turn uses MD5 hashes for password storage. What this means is that you, the webmaster, don't even have access to the passwords: they are hashed and then discarded. So there is no way to send them to the users.

    Version 1.3 beta of Auth has implemented a changePassword() method (that hooks into DB's changePassword() method). To do a password recovery feature, you would need to create a new password, perhaps using PEAR::Text_Password, use changePassword() to put the MD5 hash of the new password in the database, and then send the new password by email to the user.

    Another option would be to disable MD5 hashing for password storage, and just store the plaintext passwords, not a very secure solution.
  28. #15
  29. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2004
    Posts
    2
    Rep Power
    0
    good posts by all users! helped me alot. didn't know that there are many more methods within PEAR::Auth.
Page 1 of 2 12 Last
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo