Your browser (Internet Explorer 7 or lower) is out of date. It has known security flaws and may not display all features of this and other websites. Learn how to update your browser.

X

WordCamp Prague 2012

I am planning to organize a conference focused, but not limited to blogging, hacking and freedom of speech and WordPress in Praha /Prague in February or March 2012.

If you are interested in helping, speaking nor sponsoring the event, please drop me a line via my contact page. The conference will be on English and Czech.


Mám v úmyslu uspořádat konferenci zaměřené mimo jiné na blogování, hacking a svobodu projevu a WordPress v Praze v únoru nebo březnu 2012.

Pokud máte zájem pomoci, mluvit ani sponzorování akce, prosím, napište mi linku přes kontaktní stránku . Konference bude v anglickém a českém jazyce.

What is a WordCamp?
/click on the image to see it big/
What is a Wordcamp

MongoDB, Node.js and admin auth

There is a big challenge to make MongoDB driver to work with Node.js, but here is an cool and working example to do that:

Require:

var mongodb = require("mongodb"); //require node-mongodb-native
var settings = require('./mconfig'); //for <a href="http://talkweb.eu/openweb/901">settings</a>

Connect to the admin database:

var mongoserver = new mongodb.Server(settings.mongo_host, settings.mongo_port, {});
admindb = new mongodb.Db('admin', mongoserver);

Try to auth with admin cretentials:

 
exports.adminlogin = function(callback) {
 
		admindb.open(function (error, client) {
 
			admindb.authenticate(settings.mongo_user, settings.mongo_pass, function (err, val) {
		        if (err) {
		             callback(0);
		        } else {
		            	callback(1);
 
		        }
   		 });
 
 	 });
 
 
};

It returns 1 on success and 0 on failure.

Full HTTPS REST server in Node.js

I will show you now, how to write a simple HTTPS JSON REST server using node.js components. Grab a beer, open your IDE and let’s start hacking.

0. Create certificates.

If you don’t have valid https certificates, you can generate one for testing purposes. If you need one cool certificate, you can join cacert community. Anyway, let’s openssl for a while:

openssl genrsa -out privatekey.pem 1024 
openssl req -new -key privatekey.pem -out certrequest.csr 
openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem

1. Install additional modules.

We will need just one aditional module, called journey.

It’s working only in JSON mode, but anyway I don’t like XML REST at all. JSON is the future, baby.

npm install journey

2. Writing the router.js file.

- Define the modules required:

var journey = require('journey');
var https = require('https');
var fs = require('fs');

- Define the certificates part:

var privateKey = fs.readFileSync('../certs/privatekey.pem');
var certificate = fs.readFileSync('../certs/certificate.pem');
 
var options = {
  key: privateKey,
  cert: certificate
};

- Define the router that will handle all REST requests (GET, POST, PUT, DELETE):

var mrouter = new (journey.Router)();

- Define the map of all requests. In other words what to do when the router receive a request:

mrouter.map(function () {
// Default URL
this.root.bind(function (req, res) { res.send("Welcome to my application") });
 
//GET request on /databases
this.get('/databases').bind(function (req, res) {
do something
});
 
//GET request on a specific database - /database/users21
this.get(/^databases\/([A-Za-z0-9_]+)$/).bind(function (req, res, id) {
	 //id contains 'users21' part       
 });
 
/**PUT request example. 
* You can deal with as many parameters as you need, just write the regexp for it and assign a parameter. 
* Here is an example to update a document on a collection on MongoDB database. 
* We have 3 user parameters - 6 parameters in URL:
**/
this.put(/^databases\/([A-Za-z0-9_]+)\/collections+\/([A-Za-z0-9_]+)\/documents+\/([A-Za-z0-9_]+)$/).bind(function (req, res, dbid, collid, docid, data) {
	        res.send('update '+docid+ 'in '+collid + 'on: '+ dbid);
 });
}); //end mapping

3. And the last thing we should do is to turn on the HTTPS server and the router

https.createServer(options,function (request, response) {
    var body = "";
 
    request.addListener('data', function (chunk) { body += chunk });
    request.addListener('end', function () {
 
        mrouter.handle(request, body, function (result) {
 
            response.writeHead(result.status, result.headers);
            response.end(result.body);
        });
    });
}).listen(8081);

4. Run and connect your JSON client on httpS://127.0.0.1:8081 to test it.

node router.js

One file to rule them all

Here you can see the whole WORKING simple app including nice tricks like adding settings and whole bunch of regexp examples for handling the URL parameters.

Enjoy!

Capture API

I am looking forward Capture API to become part of Firefox soon. It’s really cool if I have the opportunity to capture my camera and my microphone.

function success(data) {
  var container = document.createElement("div");
  document.body.appendChild(container);
 
  for (var i in data) {
    var img = document.createElement("img");
    img.src = data[i].uri;
    container.appendChild(img);
  }
}
 
function error(err) {
  alert(err.message + " (" + err.code + ")"); 
}
 
navigator.device.captureImage(success, error, { maxNumberOfMediaFiles: 1 });

This is already implemented here and it’s really useful if you want to work on mobile devices:

// capture callback
var captureSuccess = function(mediaFiles) {
    var i, path, len;
    for (i = 0, len = mediaFiles.length; i < len; i += 1) {
        path = mediaFiles[i].fullPath;
        // do something interesting with the file
    }
};
 
// capture error callback
var captureError = function(error) {
    navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
};
 
// start audio capture
navigator.device.capture.captureAudio(captureSuccess, captureError, {limit:2});