Robert Basic's blog

Archives for January, 2009

Trac on Ubuntu

by Robert Basic on January 27, 2009.
Heads-up! You're reading an old post and the information in it is quite probably outdated.

Today I was messing around with Trac, installing it and doing some basic configuration. While my dev machine gets updated, I want to share my process of installing Trac.

What is Trac?

As said on the Trac homepage:

Trac is an enhanced wiki and issue tracking system for software development projects.

It’s free, it’s open source, it comes under the BSD license and it’s really awesome. You can write a wiki with it, have a ticket system, connect it with SVN, so you can browse the sources from the browser and see all the commit messages, when was something changed, added… It can support one project, it can support multiple projects. It can be viewable/editable by anyone, or you can close it down for your little team…

Trac is big. It has lots of plug-ins, so you can extend and customize your Trac. I haven’t played with them yet, but as soon as I will, you’ll get notified ;)

It’s written in Python. It can run on it’s own server, or it can run under Apache (where there are also several options). It can use SQlite, PostrgeSQL or MySQL databases. Currently it can connect only to SVN.

I’ll show you how to setup a basic Trac 0.11-dot-something-dot-something. It will run under Apache with mod_wsgi, use a SQlite database, connect to the SVN repository and require user authentication.

Installing Trac

Before anything, I want to say that my machine where I installed Trac has LAMP and SVN configured like this. So, this post is kinda the next part of that post.

First, I installed a Python tool, called Easy Install. It’s here to make our installation process easier. Lovely. Go to http://pypi.python.org/pypi/setuptools/, scroll down to the downloads section and choose a Python egg to download (match it to your currently installed Python version — I have Python 2.5 so I downloaded “setuptools-0.6c9-py2.5.egg”).

Fire up a console and type:

sudo sh setuptools-0.6c9-py2.5.egg

Of course, you need to match this to your own setuptools file.

Next, type:

sudo easy_install Trac

EasyInstall will now locate Trac and it’s dependencies, download and install them.

Download the mod_wsgi:

sudo apt-get install libapache2-mod-wsgi

It will install and enable mod_wsgi. And, in my case, it only tried to restart Apache, but for an unknown reason it fails to do so. If that happens, just do a quick:

sudo /etc/init.d/apache2 restart

If you want Subversion with your Trac, you’ll need the python-subversion package:

sudo apt-get install python-subversion

If you have it already, it’ll just skip it. If you want SVN, but you don’t have this package, later on it will show an error message like: Unsupported version control system “svn”.

Now to make a folder for Trac, where it will keep all the Trac projects and stuff.

sudo mkdir /var/trac /var/trac/sites /var/trac/eggs /var/trac/apache
sudo chown -R www-data /var/trac

Under /var/trac/sites will be the files for Trac projects. The /var/trac/eggs folder will be used as a cache folder for Python eggs. /var/trac/apache will hold a wsgi script file.

The wsgi script is actually a Python script, but with the .wsgi extension, used by mod_wsgi. With this script, Trac will be able to run as a WSGI application.
File: /var/trac/apache/trac.wsgi

import sys
sys.stdout = sys.stderr

import os
os.environ['TRAC_ENV_PARENT_DIR'] = '/var/trac/sites'
os.environ['PYTHON_EGG_CACHE'] = '/var/trac/eggs'

import trac.web.main

application = trac.web.main.dispatch_request

With this kind of script, one single Trac installation will be able to manage multiple projects (you can see here some other scripts).

Configure Apache, add this to your httpd.conf file:

WSGIScriptAlias /trac /var/trac/apache/trac.wsgi

<Directory /var/trac/apache>
    WSGIApplicationGroup %{GLOBAL}
    Order deny,allow
    Allow from all
</Directory>

Restart Apache:

sudo /etc/init.d/apache2 restart

If you go to http://localhost/trac/ in your browser, you should see an empty list of Available Projects. It’s empty, cause we haven’t added any project yet.

Now, let’s asume that we have a project called “testProject” with it’s source located in /var/www/testProject and a SVN repo located in /var/svn/repos/testProject. I’ll show how to add that project to Trac.

In console type:

sudo trac-admin /var/trac/sites/testProject initenv

Note that you need to provide the full path to /var/trac/sites, cause it will create a Trac project in the current folder you’re in.

It will ask you now a few things:

  • Project Name — the name of the project, e.g. “Trac testing project”
  • Database connection string — leave it empty, and it will use SQlite
  • Repository type — leave it empty, and it will use SVN
  • Path to repository — path to the project repo, e.g. /var/svn/repos/testProject

It will start to print out a bunch of lines, about what is it doing. In the end you’ll get a message like “Project environment for ‘testProject’ created.” and a few more lines. One more thing. We need to add the whole project to www-data user, so it can manage the files:

sudo chown -R www-data /var/trac/sites/testProject

If you direct your browser again to http://localhost/trac/, you will now see a link for the testProject. Click it. There, a fully working basic Trac environment for your project. A wiki, a ticket/bug tracking system, a repo browser in only a few minutes. How cool is that? Very.

This Trac environment can now be accessible by everyone. If we do not want that, we need to add this to the httdp.conf file:

<Location /trac>
    AuthType Basic
    AuthName "Trac login"
    AuthUserFile /var/trac/.htpasswd
    Require valid-user
</Location>

Create the .htpasswd file:

sudo htpasswd -bcm /var/trac/.htpasswd your_username your_password

All set. You’ll now have to login to Trac to be able to work on it. As I’m the big boss on my localhost, I gave myself some super-power privileges for Trac: TRAC_ADMIN. It’s like root on *NIX.

sudo trac-admin /var/trac/sites/testProject permission add robert TRAC_ADMIN

Read more about privileges.

That would be it. With this kind of setup, for now, it’s working perfectly for me. For Trac that’s available from the whole Internet, more security measures are needed, but this is only on localhost, so this is enough for me.

Comments, thoughts, ideas?

Happy hacking!

Tags: apache, example, lamp, linux, setup, svn, trac, ubuntu.
Categories: Development, Software.

Login example with Zend_Auth

by Robert Basic on January 05, 2009.
Heads-up! You're reading an old post and the information in it is quite probably outdated.

Happy New Year! Hope everyone had a blast for New Year’s Eve and managed to get some rest :) This is my first working day for this year. I’m still kinda lazy and sleepy. And I wanna eat something all the time. Damn you candies!!!

So, here’s what I’m going to do: authenticate an user against a database table using Zend Framework’s Zend_Auth component. It’s really a piece of cake. You can see a working example here: http://robertbasic.com/dev/login/. Feel free to test it and report any misbehavior down in the comments. In the codes below all paths, class names, actions, etc. will be as are in the example, so you probably will need to changed those according to your setup.

Preparation

Because I’m gonna use a database, be sure to have set the default database adapter in the bootstrap file, I have it setup like this:

<?php
$config = new Zend_Config_Ini('../application/dev/config/db_config.ini', 'offline');
$registry = Zend_Registry::getInstance();
$registry->set('db_config',$config);
$db_config = Zend_Registry::get('db_config');
$db = Zend_Db::factory($db_config->db);
Zend_Db_Table::setDefaultAdapter($db);

I’ll need it later in the code. The table structure is as follows:

--
-- Table structure for table `zendLogin`
--

CREATE TABLE `zendLogin` (
  `id` int(11) NOT NULL auto_increment,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;

The login controller

The magic happens in the LoginController. It has two actions: indexAction and logoutAction. The indexAction will take care of showing the login form and processing the login process. The logoutAction will just logout the user. You would never figure out that one on your own, right?

Now, let’s get to the fun part — the code:

<?php
class Dev_LoginController extends Zend_Controller_Action
{
    public function indexAction()
    {
        // If we're already logged in, just redirect
        if(Zend_Auth::getInstance()->hasIdentity())
        {
            $this->_redirect('dev/secured/index');
        }

        $request = $this->getRequest();
        $loginForm = $this->getLoginForm();

        $errorMessage = "";

Not much happening here: if the user is already logged in, I don’t want him at the login form, so just redirect him somewhere else; most likely to a home page or a control panel’s index page.

The Zend_Auth implements the Singleton pattern — if you’re not familiar with it read http://framework.zend.com/manual/en/zend.auth.html#zend.auth.introduction and http://www.php.net/manual/en/language.oop5.patterns.php (at php.net scroll down to the example #2).

So, I’m just asking the Zend_Auth does it have an user identity stored in it; the identity gets stored only upon successful log in. I’m also getting the request object. The getLoginForm() is a function that I wrote for assembling the login form and is a part of the LoginController, I’ll show it’s code later.

<?php
if($request->isPost())
{
    if($loginForm->isValid($request->getPost()))
    {
        // get the username and password from the form
        $username = $loginForm->getValue('username');
        $password = $loginForm->getValue('password');

This doesn’t needs a lot of explanation: if it’s a post request, it means the form is submitted. If the submitted data is valid, just get the wanted values from the form.

<?php
        $dbAdapter = Zend_Db_Table::getDefaultAdapter();
        $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);

        $authAdapter->setTableName('zendLogin')
                    ->setIdentityColumn('username')
                    ->setCredentialColumn('password')
                    ->setCredentialTreatment('MD5(?)');

Here I’m getting the default database adapter, so I know whit which database I’m working with. Then I’m creating an adapter for Zend_Auth, which is used for authentication; the docs give good explanation on the adapter, read it here: http://framework.zend.com/manual/en/zend.auth.html#zend.auth.introduction.adapters.

Next, I’m telling the authentication adapter which table to use from the database, and which columns from that table. Also, I’m telling it how to treat the credentials — the passwords are stored as MD5 hashes, so the submitted passwords will first be MD5ed and then checked.

<?php
        // pass to the adapter the submitted username and password
        $authAdapter->setIdentity($username)
                    ->setCredential($password);

        $auth = Zend_Auth::getInstance();
        $result = $auth->authenticate($authAdapter);

I’m passing to the adapter the user submitted username and password, and then trying to authenticate with that username and password.

<?php
        // is the user a valid one?
        if($result->isValid())
        {
            // get all info about this user from the login table
            // ommit only the password, we don't need that
            $userInfo = $authAdapter->getResultRowObject(null, 'password');

            // the default storage is a session with namespace Zend_Auth
            $authStorage = $auth->getStorage();
            $authStorage->write($userInfo);

            $this->_redirect('dev/secured/index');
        }

If the user is successfully authenticated, get all information about him from the table (if any), like the real name, E-mail, etc. I’m leaving out the password, I don’t need that. Next I’m getting the Zend_Auth’s default storage and storing in it the user information. In the end I’m redirecting it where I want it.

<?php
else
{
    $errorMessage = "Wrong username or password provided. Please try again.";
}
}
}
$this->view->errorMessage = $errorMessage;
$this->view->loginForm = $loginForm;
}

And this is the end of the indexAction. I know I could take the correct message from $result with getMessages(), but I like more this kind of message, where I’m not telling the user which part did he got wrong.

<?php
public function logoutAction()
{
    // clear everything - session is cleared also!
    Zend_Auth::getInstance()->clearIdentity();
    $this->_redirect('dev/login/index');
}

This is the logoutAction. I’m clearing the identity from Zend_Auth, which is also clearing all data from the Zend_Auth session namespace. And, of course, redirecting back to the login form.

<?php
protected function getLoginForm()
{
    $username = new Zend_Form_Element_Text('username');
    $username->setLabel('Username:')
            ->setRequired(true);

    $password = new Zend_Form_Element_Password('password');
    $password->setLabel('Password:')
            ->setRequired(true);

    $submit = new Zend_Form_Element_Submit('login');
    $submit->setLabel('Login');

    $loginForm = new Zend_Form();
    $loginForm->setAction('/dev/login/index/')
            ->setMethod('post')
            ->addElement($username)
            ->addElement($password)
            ->addElement($submit);

    return $loginForm;
}

As promised, here’s the code for getLoginForm function. That’s the whole LoginController code, not really a rocket science :) Sorry if it’s a bit hard to keep up with the code, I needed it to break it up in smaller pieces…

And here’s the view script for the indexAction.

<?php
<h2>Zend_Login example</h2>

<p>
Hello! This is an example of authenticating users with the Zend Framework...
</p>

<p>Please login to proceed.</p>

<?php if($this->errorMessage != ""): ?>
<p class="error"><?= $this->errorMessage; ?></p>
<?php endif; ?>

<?= $this->loginForm; ?>

Other controllers

Couldn’t come up with a better subtitle :(

Here’s an example how to require the user to log in to see the page: in the init() method ask Zend_Auth is the user logged in, and if not redirect him to the login form. This way the user will have to log in to the “whole controller”. Implement the same only to the indexAction, and the user will have to only log in to see the index page; he’ll be able to access another page without logging in.

<?php
class Dev_SecuredController extends Zend_Controller_Action
{
    function init()
    {
        // if not logged in, redirect to login form
        if(!Zend_Auth::getInstance()->hasIdentity())
        {
            $this->_redirect('dev/login/index');
        }
    }

    public function indexAction()
    {
        // get the user info from the storage (session)
        $userInfo = Zend_Auth::getInstance()->getStorage()->read();

        $this->view->username = $userInfo->username;
        $this->view->name = $userInfo->name;
        $this->view->email = $userInfo->email;
    }

    public function anotherAction()
    {
    }
}

I’m also reading out the user information from the Zend_Auth’s storage, that I have stored there during the log in process.

So there. A fully working login system, which can be setup in a really short time.

Update: If you want, you can get an example source code from here: zendLogin.zip ~8kB

Happy hacking!

Tags: authenticate, authentication, example, framework, login, php, zend, zf.
Categories: Development, Programming.