Help Tips « back
How can I use AuthDb to implement authentication?


All the scripts that need to test authentication must instantiate AuthDb (or a child class), and test if the session exists using the isValid method.

if ($authInstance->isValid())
   logged
else
   not logged

Well... if you want to do something when there's no active session, then you can use the callbacks to define a function that builds the login form or redirects to the login page (using the setLoginFunction method).

Besides, you can define callbacks to handle idleness (between 2 requests) and the expiry time (total logged time). These events will automatically destroy the session and verify if there is a login function (again, setLoginFunction callback!). If the class finds a callback that handles the "not-logged" state, it will be called.

If you want to use a login page to show the login form and process the post request, validating the submitted data, the only callback methods that must be called are setLoginFunction, setLoginCallback and setErrorCallback.

The first defines the function in your code that builds the form and inserts it in a valid Document instance (or child class). The second defines the action that is taken when the user was logged in successfully. The third handles an error. In this case, you can rebuild the login with an error message in the template (tip: reuse the code that builds the form !).

If this solution seems too complicated, you can change it: forget that you have a "login" page. Set all callbacks in all pages using an AuthDb instance attached to every Document that you create. The framework will detect that there's no active session and will call your "loginFunction". The only detail here is that you must build the login and "abort" the script, to avoid processing the rest of the page. There's a little and poor example below:

//... in your document child class
class MyDoc extends Document
{

    
//. . . properties of the class

    
function MyDoc() {
        
Document::Document("mylayout.tpl");
        
$this->a = new AuthDb():
        
$this->a->setLoginFunction(array($this, 'buildLogin'));
        
// . . . set other callbacks
    
}

    function
buildLogin() {
        
$f = new FormTemplate( . . . );
        . . .
set the form properties
        $this
->elements['main'] = $f->getContent();
        
$this->display();
        exit;
// when this callback is called, you must generate the form and abort !
    
}
}
    

For more details about the auth package, please consult the examples page, where you can find a complete example using the AuthDb class.