Generate random password PostgreSQL

juli 9th, 2010 — 2:41pm

While building our latest and greatest application, we needed to generate initial passwords for the users. This is not uncommon, and I’ve been generating passwords for quite some time using a PHP class called RandomString. However, in the last few months, I have been working with PostgreSQL more and more, and I started to write business logic into the database in the form of plpgsql stored procedures, instead of plain old PHP, as it turns out to make the application itself a lot smaller, leaner, cleaner and – most of all – more readable.

Adding a batch of users was easy: the usernames were derived from several other variables, so there was no need for PHP to get involved in creating the users and their passwords. So, I wanted to generate the passwords using a stored procedure and I don’t like doing the work myself, so I started to Google. Unfortunately, I couldn’t find even a snippet of code while searching the internet, and I’m not that well versed in plpgsql yet, so I decided to ask my geek-friends over at PFZ – PHP Community.

Vincent – also known as PgGuru – had a very nice solution which would allow you to create passwords based on a seed  and a length you could pass to the procedure, but I wanted passwords in the format that he suggested earlier: “BABABAB11“. So I started to hack away at his example, and came up with two stored procedures that you can use to generate random, readable passwords straight in the database, no interference of the client required. Without further ado:

--
-- Generates a random, human readable password with the format "BABABA00".
-- It will alternate between a consonant or a vowel, and appends two numbers
-- at the end of the password and then return it.
--
CREATE OR REPLACE FUNCTION generatePassword (
  _length INTEGER
) RETURNS varchar AS $$

DECLARE
 _counter INTEGER;
 _password VARCHAR;
 _vowels VARCHAR;
 _consonants VARCHAR;
 _numbers VARCHAR;

BEGIN
    _password = '';
    _vowels = 'aeiou';
    _consonants = 'bcdfghjkmnpqrstvwxyz'; -- left out 'l', because it can appear as "I".
    _numbers = '23456789'; -- Left out 0 and 1 because they can appear as O and I.

    FOR _counter IN 1.._length LOOP

       _password = _password || CASE
           WHEN _counter > ( _length - 2 ) THEN SUBSTRING( _numbers, CAST( RANDOM( ) * LENGTH( _numbers ) AS INTEGER ), 1 )
           WHEN ( _counter % 2 = 0 ) THEN SUBSTRING( _vowels, CAST( RANDOM( ) * LENGTH( _vowels ) AS INTEGER ), 1 )
           ELSE SUBSTRING( _consonants, CAST( RANDOM( ) * LENGTH( _consonants ) AS INTEGER ), 1 )
        END;

    END LOOP;

    RETURN _password;
END;
$$ LANGUAGE 'plpgsql';

--
-- Generates a random password out of the seed passed to it.
--
CREATE OR REPLACE FUNCTION generatePassword (
  _length INTEGER,
  _seed VARCHAR
) RETURNS varchar AS $$

DECLARE
 _counter INTEGER;
 _password VARCHAR;

BEGIN
    _password = '';

    FOR _counter IN 1.._length LOOP
       _password = _password || SUBSTRING( _seed, CAST( RANDOM( ) * LENGTH( _seed ) AS INTEGER ), 1 );
    END LOOP;

    RETURN _password;
END;
$$ LANGUAGE 'plpgsql';

--
-- Example of usage:
--
SELECT generatePassword( 8 );
SELECT generatePassword( 8, 'abc'::text );

So, there you have it. I hope someone else can benefit from these stored procedures, actually finding them instead of void while doing a Google search ;)

Cheers,

Berry.

2 comments » | plpgsql, postgresql, programming, stored procedures

svn ignores svn:ignore?

juni 7th, 2010 — 9:54pm

Well, it did. On one of my pet-projects called Sphoof, hosted over at Google Code, I had created directories for API documentation and log-output from the unit-tests, telling me if the unit tests were successful, the percentage of code coverage and violations of our coding standards. That’s great and all, but it doesn’t necessarily need to be in the repository. Nevertheless, I wanted those directories under the project’s main directory, to keep it all in the same place which makes it that much easier to find. Since they kept on popping up in svn stat, I decided to add the directories to the repository in a flash of humongous FAIL.

After committing all of the API docs and logs, which are bigger than the project itself, I figured I accidentally added them, but I actually wanted to ignore them instead. So, I emptied the directories and “svn propedit svn:ignore .” would have to do the trick. I added the directories I didn’t want to see and committed again. I didn’t work. Figuring it must’ve been my error, I tried again. And again. And again. Finally, I asked one of my co-developers to try it for me instead, see if this was actually a problem between my keyboard and chair. He ignored, committed, and found the repository filled with logs and docs. He tried again. And again. And again.

Finally, I figured out the problem: although subversion will happily tell you that the properties for ‘.’ have been changed, it only ignores files and directories that do not exist in the repository at the time you try ignore them. Yes, I did read the otherwise excellent documentation, but it doesn’t tell you that it can’t be done. It took me a few hours to find out. So: if you find subversion does not listen to the svn:ignore property: make sure that the files aren’t in the repository already. If they are, delete them from the repository, commit the change in which they are deleted and set the ignores as usual.

I do hope this might save someone some time.

2 comments » | subversion

Volume control for Ubuntu 10.04

mei 7th, 2010 — 12:35pm

I updated to Ubuntu 10.04 this week, and now I’m listening to Nightwish, I suddenly felt the need to get the volume up. My mouse started on it’s way to the place the volume control-applet used to be, but it seemed to have disappeared. Luckily, this problem too is easy to fix: start the program “gnome-volume-control-applet” by pressing alt  + f2. If that works, you might want to go to “System” > “Preferences” > “Startup applications”, and see if volume control is there and checked. If it’s not there, you can add it, and if it’s there and it’s not checked… well, then check it.

Problem easily fixed. Nightwish: you just started to sound a lot louder. :)

2 comments » | ubuntu

Netbeans 6.8 didn’t survive Ubuntu upgrade

mei 4th, 2010 — 12:09pm

Well, actually, Netbeans did, sun-java6-bin didn’t. I could no longer start Netbeans after my upgrade from Ubuntu 9.10 to 10.04, because of the following error message. You can see that by trying to start Netbeans from terminal: Cannot find java. Please use the –jdkhome switch. It turns out that java went missing, must’ve missed it when the upgrade started. I’ve tried simply reinstalling sun-java6-bin, but that didn’t really work either: it appears that no longer exists. After a while, I found out I had to the following:

sudo add-apt-repository “deb http://archive.canonical.com/ lucid partner”
sudo apt-get update
sudo apt-get install sun-java6-jre sun-java6-plugin sun-java6-fonts

After that, Netbeans works like a charm, just like it did under Ubuntu 9.10. Hope this might help anyone.

Comment » | netbeans, ubuntu

Netbeans 6.8 on Ubuntu 9.10

april 7th, 2010 — 8:29pm

I’m a VIM kinda guy. I like love VIM for everything it is. I write e-mails in VIM, I write presentations and blogposts in VIM, I write todo-lists in VIM and I also write my software using VIM. VIM does have downsides in that respect though, and those downsides are well-known. For starters, VIM doesn’t have smart, context-aware auto-completion. I write a heck of a lot of classes and interfaces, and it’s not always easy to keep track of the names of classes and methods. I’ve always lived with that, as VIM has a lot of upsides as well: I can write and manipulate text in VIM faster than most people can manipulate text in any other editor I’ve seen. It’s also highly customizable, so if there’s anything VIM doesn’t do, I make it do that anyway.

Netbeans is a new kid in town of IDE’s suitable for PHP. In the past, I’ve used Eclipse for PHP development, but that always felt slow and too big for writing PHP. I’ve used the first beta of Netbeans for PHP, but that had issues with quotes, linefeeds and other stuff so I ditched it within half an hour. It seems that Netbeans got a lot better since that first beta, so I figured I should give it another try to see if it can fulfill my (absurdly high) demands when it comes to writing code. I had to install it first, obviously.

Installing Netbeans on Ubuntu really is easy enough, if you have an understanding of how Ubuntu works. For the people who don’t, I’ve kept a short log of how I’ve installed it, hopefully someone will benefit from this. There are a few different methods of installing Netbeans in Ubuntu, which all have there up- and downsides. The way of installing I chose has the downside of being slightly more complex, but you get the last version anyway.

The first, and probably easiest way of installing Netbeans on Ubuntu, is to download and install the Java JDK and Netbeans bundle. To be fair, I’ve never tried it and it seems easy enough, but I’m not sure if you’ll always have the latest version of Netbeans in the bundle. At this time, it seems it does indeed include the latest version.

The second easy way to install Netbeans, is using Ubuntu’s software distribution: simply typing “sudo apt-get install netbeans-ide” will install Netbeans, including all of it’s dependencies. Again, there is the downside that you may not have the most current version in the distribution channels.

The third way, slightly more complicated, ensures you have the latest version of Netbeans installed. Open a terminal and type “which java”. If the command returns a response, you have Java, so you can skip the following. If it doesn’t return anything, Java SDK is not installed on your system, so you have to install it. Luckily, that is easy enough: type “sudo apt-get install sun-java6-bin sun-java6-jdk”, and agree to the license. To prepare you: the download is 160Mb, but that shouldn’t be a problem in this day and age.

After installing Java, it’s time to download the Netbeans installer from the Netbeans download page. I write PHP mostly, so the PHP version seems to be the most decent option. Start the download and save it to a location of your choice. If you’re done downloading, go back to the terminal and cd into the directory you’ve just saved the installer to. Execute the following commands, and enjoy while Netbeans presents you with an installation wizard:

chmod +x netbeans* && ./netbeans-*

That’s it, you’re done. Netbeans should now have an icon on your desktop. Start the application, and start writing code. I’ll give Netbeans an honest chance for about a month and will give an update of it later. Obviously, I won’t abandon VIM for anything but writing code.

Comment » | netbeans, ubuntu

1440×900 Ubuntu on Aspire One 751

april 7th, 2010 — 7:42pm

I’ve upgraded my Ubuntu install from 9.04 to 9.10, even though version 10.04 seems to be on the way. After the upgrade though, it seemed my preferred resolution of 1440×900 wasn’t available any longer. As the title states, I have an Acer Aspire One 751 which I’ve been using for quite a while and am quite happy about. Before the upgrade, I installed some drivers to accommodate the 1440×900 resolution, but I couldn’t remember which one. I fixed it, eventually.

The Acer Aspire One 751 packs an integrated Intel GMA 500 video card, and it appeared it needs the Poulsbo driver to operate decently. On the Ubuntu Wiki, I found a page describing how to install it for Ubuntu 10.04. To make this blog post a bit more complete, here’s what I did: first of all, open a Terminal screen if you didn’t have one open already. Type (or copy and paste) the following:

wget http://dl.dropbox.com/u/1338581/Gma500/scripts/poulsbo.sh \
&& sh ./poulsbo.sh

After that I rebooted the netbook and chose a recovery shell, which gave me a few options to choose from. I then picked to boot dpkg, which eventually led me to a shell. The only command I issued were the following:

sudo dpkg-reconfigure psb-kernel-source && reboot

Type in your password, let the netbook rattle and hum a little and by the time it rebooted, you should be seeing the Ubuntu login screen with 1440×900. It did in my case anyway :)

Comment » | ubuntu

OMG Kittens! Mew, mew, mew!

april 1st, 2010 — 10:34am

Yesterday afternoon, I was called by my mother, requesting me to go home for the day and take care of our Felis catus, Kiki. She told me that our cat had started labour, and that the kittens might appear every minute. After a quick drive home from the office, I arrived at home to see our cat interestingly calm and simply stretching out on the floor. I started giving a live broadcast on IRC, but nothing ever happened before I left to go out for dinner.

When I came back from dinner though, the contractions had started and not before long, a little red-ish kitten was lying on the floor, and some disgusting ritual started. Anyhow, when the new kitten was kind of clean, breathing and looking for a nipple, contractions started again and another kitten popped out, a black one, this time. After cleaning that kitten and everything that accompanied her in the womb, it became silent for a while. Ten minutes later, the contractions started again, and yet another black kitten appeared.

Figuring that’d be it, I left to have a good night at my local pub, as there was a live band (Enrico Crivellaro, a guitar and blues-legend). Later that night, when I came back home (don’t worry, the cats weren’t alone), the score had remained on three, but there was a nice surprise anyway: the first black one wasn’t actually completely black, but it has got stripes on it.

Anyway, pictures are here, the eewww-pictures are in the eewww directory, and some old pictures of the happy mom are in the mama directory. Have fun.

PS: Some of the pictures suck, I know, but it’s not like you can tell a kitten to stay put and stop moving (-:

2 comments » | kittehs

/usr/bin/blog –engine=wordpress

januari 28th, 2010 — 1:48pm

It’s been a while since I ever looked at my blog, and in the meanwhile we wrote a one-click installer for WordPress at the company I currently (still) work for, Town QSP. I figured I should test that one-click installer, and here is the result, so it works like a charm indeed. As of yet, I’m not sure with what interval blogposts will appear on this new and fancy blog, and I don’t know what they will be about either. It helps that I know there’s a place for my rants, though.

I’ve written a few stories here and there, scattered over forums that relate to application design. If I ever get to it, I’ll make sure I’ll write some excerpts of the posts, and post them here as well.

Comment » | wordpress

OO: een introductie (deel 1)

april 2nd, 2009 — 5:05pm

Wat is een object?

Uiteraard is het van belang om te begrijpen wat een object nu precies is voordat je begint met OO programmeren, ze zijn immers de basis van OO programmeren. De beste definitie van een object is: een representatie van een concept, inclusief kenmerken (staat) en gedrag, maar dit is natuurlijk wat lastig te volgen. Een stuk simpeler is om het zo te zien: kijk om je heen en alles wat je ziet is eigenlijk een object: een kat, een televisie, een koffiemok en zo verder.

Dat is natuurlijk lastig om te vergelijken met software, waar je omgaat met variabelen, lussen, functies en constanten. Het eerste wat je dus zal moeten doen als je begint met OO programmeren, is alles wat je weet over programmeren even naar de achtergrond toe laten zakken, syntax is in OO programmeren een stuk minder belangerijk dan de onderliggende concepten.

Goed, objecten dus. Kijk de ruimte waar je in zit nog eens een keer rond en probeer te denken in objecten. Bedenk dan vervolgens wat het mogelijke gedrag van een bepaald object kan zijn: je kunt een televisie aan zetten of uit zetten. Je kunt het volume omhoog schroeven, of juist omlaag en dat noemen we allemaal gedrag. Een televisie heeft ook staat (kenmerken): hij staat aan, of uit, het volume staat hard of zacht. Een object kan ook nog eens andere objecten bevatten: een televisie heeft een beeldbuis en knoppen die ingedrukt kunnen worden.

Software objecten zitten globaal gezien hetzelfde in elkaar als objecten in de echte wereld: ze bestaan net zo goed uit gedrag en kenmerken. Het grote verschil tussen “echte” objecten en objecten in de programmeerwereld is dat wij kenmerken in zogenaamde velden opslaan, en gedrag definiëren we door middel van zogenaamde methoden. Het is van belang om ten alle tijden te onthouden dat objecten een combinatie van gedrag en kenmerken zijn en dat deze in OO respectievelijk worden bepaald door methoden en velden. Methoden werken door de kenmerken van een object te veranderen: als je op de aanknop van een televisie drukt, dan gaat deze aan en dus is hij in de “aan” status.

Communicatie tussen objecten gaat dus ook altijd via de methoden van een object: je kunt een televisie niet uitzetten zonder op de aanknop van de televisie te drukken. Dat houdt dus in dat je de methode zetUit aan zou moeten roepen voordat hij uit gaat. Het verbergen van kenmerken (en dus de status of ook wel internal state) is een van de belangrijkste principes die er bestaat binnen object geörienteerd programmeren en staat beter bekend als het begrip “encapsulation”, daar kom ik later op terug. Hopelijk.

Comment » | Object Oriented, Theory, programming

Back to top