Authentication in SPA

When working with an SPA (Single Page Application) all the view components and templates are already in the client and the authentication is used only for API calls. Because you don’t need (but you can if you want) to authenticate the user until the first interaction against an API is made, or you can even authenticate each API call for a more robust and secure communication between the server and the SPA. Let see what are our options:

  • Saving authentication information in the session data on the server side
  • Authenticating each API call using the password to create a digital signature of the request
  • Authenticate the user and return an authentication token to identify a session (combining both)

Saving authentication information in the session data on the server side

This is similar to the first approach of authentication used by web applications in past
When a browser makes a call to the server, the server returns a Session Id (usualy saved in cockies) to be re sent to the server in every call from that browser, then the server saves data associated to that session id for example a boolean variable containing if the user is authenticated or not. Then the browser sends the username and password and if the user is authenticated that variable is changed to true.
let see a diagram

Captura de pantalla 2013-11-11 a la(s) 02.52.46

this scheme is also supported by SPAs because every API call is made inside a browser window. So you can create an API let say

/api/login

where you receive the username and password and process it, save the result in session data and send a response to the client.Then all the subsequent API calls to that server will be already authenticated in the session data.

This is the simplest scheme of authentication but also it’s the less robust and secure.

Pros

  • Easy to develop
  • Simple to understand
  • Fastest to deploy

Cons

  • It doesn’t scale to clustered servers, because each server stores the session data (most servers have methods to overcome this)
  • if the session id is sniffed an attacker could impersonate the authenticated user
  • the username and password are sent over the wire (hashing the password won’t solve this because we are still sending the hashed version)

Authenticating each API call using the password to create a digital signature of the request

A newer authentication scheme could be used to overcome this faults. Based on the public and private key idea, we can think of them as «public key» = «Username» and «private key» = «password». We can improve this process using hashed versions of them («publicKey» = SHA1(«username»), «privateKey»=SHA1(password)) but we wont consider that for learning process.
In this case there is no need for an initial authentication request (/api/login) because each API call will be authenticated.
Here is the process:

First both ends (SPA and server) should know the public key and the private key.

Then, before making the request to the API (let say /api/doSomething/ ), the SPA takes the entire list of parameter values and adds the public key, then signs them using the SHA1 HMAC algorithm and the private key, this creates a digital signature that is also included in the request as a parameter and finally makes the request

On the other end, the server receives the request and all the parameters including the signature and the public key, retrieves the private key for that public key and recreates the signing process using SHA1 HMAC, then compares the signatures and if they are equal then the request is authenticated

Captura de pantalla 2013-11-11 a la(s) 03.42.33

But, as we usually need to present a login form to the user, it might be a good idea to have a login api (/api/login/) to know immediately if the user entered a correct username and password. to avoid sending always the same signature with the public key, you can add an extra parameter with random values.

pros

  • the password/private key is never sent over the wire
  • scales better against clustered servers
  • a timestamp could be added to the parameters list to avoid reusing a signature

cons

  • complex
  • requires authentication process on every API call
  • SHA1 HMAC depends on the same character coding on both sides

Authenticate the user and return an authentication token to identify a session (combining both)

Beyond the public and private key authentication scheme, we can introduce improvements to enhance the robustness and security. For example we can create a token of authentication to avoid signing the parameters always with the same private key, and instead of that usign the authentication token and the private key to sign the parameters with SHA1 HMAC this method prevents the inference of the private key from a set of API calls with parameters and signatures

Anuncio publicitario
Etiquetado , ,

Redirecting stdout of a process to a web page using websockets (socket.io)

I’m working on new features for init, meanwhile I’m also improving the development process so I’m working hard to add automated task with grunt. But since I added AMD and a few test with mocha.js and phantom.js my grunt-watch is getting slower and slower, but the real problem is that I’m using both of my monitors for development,

One with sublime

Captura de pantalla 2013-07-30 a la(s) 23.33.10

and the other with chrome and the inspector

Captura de pantalla 2013-07-30 a la(s) 23.33.10 (2)

So I don’t have space to see if my grunt automated build task has been successful. Usually I save (cmd+s) and then refresh the browser to find out that nothing works, just then I go to my terminal (cmd+tab) to see what happened and then realize that the build task for «X» task failed.
So I needed a third monitor just to see what was happening with my «grunt-watch» output. I know I could connect it to growl or use the live reloading feature, but I decided to do a much more fun exercise.

Spawning a process in node.js

To start I need to spawn a new process (grunt-watch) from node and listen the stdout. This is very easy thanks to the «child-process» module bundled with node.

var spawn = require(«child_process»).spawn;
watch = spawn(«grunt», [«watch»]);

watch.stdout.on(«data», function(data){
console.log(data);
});

Now to the tricky thing, how to redirect this to a web socket? well that’s easy, because using socket.io is easy. Just create your connect app (that’s easier),
and then listen to any data coming from the spawned process and emit that data through the socket.

var connect = require(«connect»),
app = connect().use(connect.static(«watch»)).listen(3000);
io = require(«socket.io»).listen(app);
buffer = «»;

io.configure(«development», function(){
io.set(«log level», 0);
});

io.sockets.on(«connection», function(socket){
var watch;

socket.on(«init», function(data){
watch = spawn(«grunt», [«watch»]);
watch.stdout.on(«data», function(data){
console.log(data.toString());
socket.emit(«data», data.toString());
});
});

socket.on(«disconnect», function(){
console.log(«finishing watch»);
watch.kill(‘SIGHUP’);
});
});

Now, for the client side it’s even much more easy. You just need to connect to the websocket and emit the «init» event to start the spawn process on the server, and just listen for any «data» coming. Then I’m just prepending a «pre» element with the string coming from the stdout, as you can see we are calling «.toString()» in the server because it is a byte stream and must be converted to a UTF8 string before sending it to the client

(function(){
var socket = io.connect(),
body = document.body;

socket.emit(«init»);
socket.on(«data», function(data){
var pre = document.createElement(«pre»),
i;
pre.innerHTML = data;
if(body.childNodes.length >0){
body.insertBefore(pre, body.firstChild);
}else{
body.appendChild(pre);
}
if(body.childNodes.length > 100){
for (i = 0; i< 50; i += 1){
body.removeChild(body.childNodes[body.childNodes.length]);
}
}
});
}());

I’m also deleting old «pre» element if i have more than 100 to avoid overloading the browser.

and that’s all, now I can use my iphone (or any device with a browser) to see what happened with my grunt automated tasks

just checkout the code from

https://github.com/picanteverde/watch

and you are ready to go

Estoy trabajando en nuevas características para init, mientras tanto tambien estoy mejorando el proceso de desarrollo por lo que estoy trabajando duro para añadir tareas automatizadas con grunt. Pero como he añadido AMD y unos pocos test con mocha.js y phantom.js y ademas grunt-watch que es cada vez más lento, pero el verdadero problema es que estoy usando mis dos monitores para el desarrollo,
Uno con sublime

Captura de pantalla 2013-07-30 a la(s) 23.33.10

y el otro con chrome y el inspector,

Captura de pantalla 2013-07-30 a la(s) 23.33.10 (2)

Así que no tengo espacio para ver si mis tareas automatizadas con grunt han sido exitosas o no. Por lo general,  guardo (cmd + s) y actualizo el navegador y me encuentro que nada funciona, en ese momento me voy al terminal (cmd + tab) para ver lo que pasó y luego darme cuenta de que la tarea de compilación para la tarea «X» ha fallado.
Así que necesitaba un tercer monitor sólo para ver lo que estaba pasando con mi salida «grunt-watch». Sé que podría conectarlo a growl o utilizar la función de Live Reloading, pero me decidí a hacer algo mucho más divertido.

Lanzando un proceso en Node.js

Para empezar tengo que generar un nuevo proceso (grunt-watch) desde node.js y escuchar la stdout. Esto es muy fácil gracias al módulo «child-process» incluido en node.

var spawn = require(«child_process»).spawn;
watch = spawn(«grunt», [«watch»]);

watch.stdout.on(«data», function(data){
console.log(data);
});

Ahora a lo difícil, cómo redirigir el stdout a un websocket ? bueno, eso es fácil, porque el uso de socket.io es fácil. Basta con crear su aplicación de connect (que es muy fácil),
y luego escuchar a los datos procedentes del proceso generado y emitir esos datos a través del socket.

var connect = require(«connect»),
app = connect().use(connect.static(«watch»)).listen(3000);
io = require(«socket.io»).listen(app);
buffer = «»;

io.configure(«development», function(){
io.set(«log level», 0);
});

io.sockets.on(«connection», function(socket){
var watch;

socket.on(«init», function(data){
watch = spawn(«grunt», [«watch»]);
watch.stdout.on(«data», function(data){
console.log(data.toString());
socket.emit(«data», data.toString());
});
});

socket.on(«disconnect», function(){
console.log(«finishing watch»);
watch.kill(‘SIGHUP’);
});
});

Ahora, para el cliente es aún mucho más fácil. Sólo tienes que conectar el websocket y emitir el evento «init» para iniciar el proceso en el servidor, y sólo escuchar el evento «data» que llegue. Entonces pre- agregar elementos «pre» con la cadena que viene del stdout, como se puede ver estamos llamando «. toString ()» en el servidor, ya que se trata de un stream de bytes y se debe convertir en una cadena UTF8 antes enviarlo al cliente

(function(){
var socket = io.connect(),
body = document.body;

socket.emit(«init»);
socket.on(«data», function(data){
var pre = document.createElement(«pre»),
i;
pre.innerHTML = data;
if(body.childNodes.length >0){
body.insertBefore(pre, body.firstChild);
}else{
body.appendChild(pre);
}
if(body.childNodes.length > 100){
for (i = 0; i< 50; i += 1){
body.removeChild(body.childNodes[body.childNodes.length]);
}
}
});
}());

También estoy borrando todos los viejos «pre» si tengo más de 100, para evitar sobrecargar el navegador

Y eso es todo ahora puedo usar mi iphone (o cualquier otro dispositivo con un browser) como tercera pantalla para ver el resultado de mis tareas en grunt.

simplemente copia el código de

https://github.com/picanteverde/watch

y estarás listo para usarlo

Etiquetado , , ,

JavaScript inheritance and prototype chain search (the end of the inheritance discussion)

This post aims to be the end of the discussion in which JavaScript inheritance method is faster between parasitic and pseudoclassical models.
First of all let present the contenders

PseudoClassical inheritance

The pseudo classical inheritance is the basic method in JavaScript for creating new types, the syntax is quite complex and confusing for example let create a type named «PseudoClass» with just one method named «action1»:

var PseudoClass = function(){
};

PseudoClass.prototype.action1 = function(){
var i;
for(i = 0; i < 10; i += 1){
}
};

now if we want to create a type that inherit it behavior from the previous type and adds ne methods, then we need to do the following

var PseudoSubClass = function(){
};

PseudoSubClass.prototype = new PseudoClass();
PseudoSubClass.prototype.action2 = function(){
var i;
for(i = 0; i < 10; i += 1){
}
};

Now here there is a lot going on, we define the new PseudoSubClass constructor, and the we instantiate the inherited type in the prototype. why? well this is done to connect the prototype chain. When you call a method over an object:

object1.method1();

The JavaScript VM searchs for a property named «method1» in the «object1» object, if is not found then it searchs for a property named «method1» in the prototype of the object «object1», if is not found then it searchs the property in the prototype of the prototype and so on.

so by using the new operator we connect the prototype of the PseudoClass type to the prototype of the prototype of the PseudoSubClass type.

kind of hard ah?

 

Parasitic Inheritance

This is a much more comfortable model to create new types in JavaScript, is based on the two things JavaScript handles the better, functions and objects. Let create a new type named «parasitic» with a method named «action1» just reflecting the same behavior as in the previous example

var makeParasitic = function (){
return {
action1:  function(){
var i;
for(i = 0; i < 10; i += 1){
}
}
};
};

The simplicity is overwhelming. we just create a function that creates a new object and then it adds the method to it. Done!.

Now we’ll create a new type inheriting from the previous one

var makeSubParasitic = function(){
var o = makeParasitic();
o.action2 = function(){
var i;
for(i = 0; i < 10; i += 1){
}
};
return o;
};

Just equally simple, we just create a factory function that inside creates a new Parasitic object and adds new behavior to it, avoiding the prototype chain search. This is very important because in this case if you do

object1.method1();

«method1» will be a property in the «object1» object and then the function will be executed avoiding the need for a prototypal chain search.

The Tests

There is a maximum that dictates «if you can’t measure it…. you can’t improve it». Then I created a few jsPerf Test Cases to probe my point. And here is the data collected

Test 1

We’ll compare how much time takes to the VM to search for a method in the prototype chain agains finding the method right in the object.

http://jsperf.com/prototypalchainsearch

The results

test1

as you can see is much more faster to call methods on a parasitic type, than on a pseudoclassical type, this is just because of the prototype chain search of the method

test 1 graph

Test 2

Now let’s compare how about just instantiating objects?

http://jsperf.com/new-operator-instantiation-delay

The results

test 2

It clearly show optimizations an tweaks made on the VM vendor side in favor of the PseudoClassical model, I thinks this is mainly for two reasons. First JavaScript was conceived with this inheritance method in mind so most of the projects out there are using it, and Second it is more simple to optimize because it is just used for type creation, instead functions and objects (parasitic) are much more dynamics and can be used to anything else.

test2 graph

Test 3

Now, let’s compare what happens if we instantiate the object, and the stress the prototype chain search

http://jsperf.com/instantiation-and-method-calling

The results

test3

Here is a much more complex scenario, we are testing both sides, instantiation and method search, take a look how the 78% of difference between PseudoClassical and Parasitical types are drastically reduced to a 48%, and that is calling methods just once, if we stress the method calling for one object we found that the difference is reduce and at some point (500 method search) it is faster to instantiate with parasitic and call methods on that object.

Final Conclusion

It is clear that both methods have their own pros & cons, but if we think just about performance then we clearly see that:

PseudoClassical is a winner for applications that

  • instantiate a lot of objects
  • more object instantiation than methods calling
  • doesn’t call repeatedly methods on them.
  • flat hierarchy of types

Parasitical is a winner for applications with

  • few object instances
  • a lot of method calling
  • repeatedly calling methods
  • deep hierarchy of types

but that is just thinking about performance. If you think about design and elegance of code then the parasitic model is clearly a winner.

Etiquetado , , , , , ,

3D Side By Side with Three.js

THREE.js

I started to learn Three.js (in a serious way) two days ago, I’m reading a wonderful book for this:
WebGL: Up and Running by Tony Parisi (O’Reilly). Copyright 2012 Tony Parisi, 978-1-449-32357-8.
and then at the second chapter, I found this lines:

// Put in a camera
camera = new THREE.PerspectiveCamera( 45, container.offsetWidth / container.offsetHeight, 1, 4000 );
camera.position.set( 0, 0, 3 );
….
// Render the scene
renderer.render( scene, camera );

And then I thought, «wait, if I’m rendering the scene from the point of view of the camera, then I can render the scene from the point of view of another camera!! and that’s 3d (well stereoscopic vision)».

A little on 3D side by side

I bought my 3D tv a few month ago, since then I was looking for some content to use my brand new 3D glasses, sadly the 3d content out there, it might be vast, but is mainly boring long movies or 3D advertisement shorts. And even finding them was so dificult, till i learn the magic words side-by-side (sbs).

3d-side-by-side

Side-by-side is how the stereoscopic vision is achieved, you have a 1920×1080 viewport and is fullfiled with two images of 960×1080 one for each eye.
When you turn on the 3d effect in your tv, it stretch the images to 1920×1080 and interlaced both at the same frecuency it polarize each eye in the 3d glasses.
Awesome technology.

Back to THREE.JS

So I started two figured out how to put two cameras in a THREE.js scene and also how to render both cameras. The first thing I tried was to duplicate everything two container divs, two renderers and two cameras. but it crushed. Then, I looked for help and I found this
http://mrdoob.github.io/three.js/examples/webgl_multiple_views.html

that was it! Every thing I needed. Just a simple changes like

// Put in two cameras
cameraLeft = new THREE.PerspectiveCamera( 45, (container.offsetWidth / 2) / container.offsetHeight, 1, 4000 );
cameraLeft.position.set( 0, 0, 3 );
scene.add(cameraLeft);

cameraRight = new THREE.PerspectiveCamera( 45, (container.offsetWidth / 2) / container.offsetHeight, 1, 4000 );
cameraRight.position.set( 0, 0, 3 );
scene.add(cameraRight);

var width = Math.round(container.offsetWidth/2),
height = container.offsetHeight;
// Render the scene
renderer.setViewport( 0, 0, width, height);
renderer.setScissor( 0, 0, width, height);
renderer.enableScissorTest ( true );

cameraLeft.aspect = width * 2 / height;
cameraLeft.updateProjectionMatrix();
cameraLeft.position.set( separation, 0, 3 );

renderer.render( scene, cameraLeft );

renderer.setViewport( width, 0, width, height);
renderer.setScissor( width, 0, width, height);
renderer.enableScissorTest ( true );

cameraRight.aspect = width * 2 / height;
cameraRight.updateProjectionMatrix();
cameraRight.position.set( -separation, 0, 3 );

renderer.render( scene, cameraRight );

is easy to see that I’m just adding two cameras, but on the run loop (where I need to render the scene) I’m defining my width as half of the width of the container ( remember the 1920 to 960 thing), but I keep the aspect for the camera, of course the image will look stretch but the 3d effect on the tv will fix it later, then just used the same renderer to render on different viewports (side-by-side) and bingo stereoscopic vision.

3d-side-by-side

How far are your eyes?

Thats ok but I still cannot see 3d in my tv. Well to achieve a great 3D stereoscopic video effect, you need both of your cameras to render a slightly different view of the scene simulating the separation between your eyes.
But how do I do that?, well I don’t know so I added a simple keyUp Handler to increase and decrease the separation between both cameras, using the up key to increse the separation by a predefined increment and down key to decrese. (right and left keys could be used to increase and decrease the predefined increment)

function addKeyHandler(){
document.addEventListener( ‘keyup’, onKeyUp, false);
}

function onKeyUp (event){
event.preventDefault();
switch(event.keyCode){
case 38: //Up
separation += incrementation;
break;
case 40: //Down
separation -= incrementation;
break;
case 39: //Right
incrementation *= 1.1;
break;
case 37:// left
incrementation *= 0.9;
break;
}
}

That means, every time you hit the up key, both cameras will move in oposite direction a little bit. I played a few minutes till i found a coefficient of -0.04300000000000005 as a great separation between cameras to have a 3d effect, but I also pushed so far as -0.1040 and still have a great powerful effect, don’t play with this coefficient so much because it can cause a headache, because you will be trying to convience your brain that your eyes are now more separated.

And that’s all, now just connect your mac (of course you are using mac) to your tv duplicate the screens and go to:

http://picanteverde.github.io/3dtv/src/tv3d.html

or

earth and sun

http://picanteverde.github.io/3dtv/src/tv3d5.html

put your Browser in full screen mode and refresh (cmd+r) (remember to refresh).

now a few pictures of me

me and side-by-side

side-by-side-three.js

Etiquetado , , ,

Initial Commit!

Hello guys, welcome back to my blog! Sorry I wasn’t able to write over the past 6 month but I’m coming back to the Blog and anxious of adding a lot a new projects, like this.
How many times you find yourself asking on how to start a project for X technology? or Where could I find the perfect project template to start from?
Well I’m tired of asking my self exactly the same question over and over so I decide to start my own Init project https://github.com/picanteverde/init/
Where you will be able to find, in different branches, templates to start projects on several different technologies based on JavaScript of course.
For example to start projects on node.js you have one branch,
but if you want to star a project on express.js there is a branch derivated from the last one.
The idea is to finish with a simple project template for an applications as follows:

Backend
node.js
express.js
mongodb
heroku

Front End
Backbone
Marionette
Bootstrap

that is the main idea for now, if you disagree, feel free to contribute to the repo.
Cheers!

 

 

Hola chicos, bienvenidos a mi blog! Lo siento, no fue capaz de escribir en los últimos 6 meses, pero yo voy a volver al blog y ansiosos de añadir mucho a los nuevos proyectos, como éste.
¿Cuántas veces te encuentras preguntando sobre cómo iniciar un proyecto para la tecnología X? o ¿Dónde puedo encontrar la plantilla de proyecto perfecto para empezar?
Bueno, yo estoy cansado de pedir mi ser exactamente la misma pregunta una y otra vez, así que decide comenzar mi propio proyecto https://github.com/picanteverde/init/ Init
Donde usted podrá encontrar, en diferentes ramas, plantillas para iniciar proyectos en diferentes tecnologías basadas en JavaScript, por supuesto.
Por ejemplo, para iniciar proyectos en Node.js que tiene una sucursal,
pero si quieres destacar un proyecto sobre express.js hay una rama que se derive del último.
La idea es terminar con una plantilla de proyecto simple para una solicitud de la siguiente manera:

Backend
Node.js
express.js
mongodb
Heroku

Front End
columna vertebral
marioneta
Manos a la Obra

esa es la idea principal por ahora, si no estás de acuerdo, no dude en contribuir a la repo.
¡Salud!

Etiquetado , , , , ,

RESTful APIs with Node.js and Express.js, and Backbone.js client side

Una de las cosas más divertidas que me encontré para hacer durante el desarrollo de ttTodoMVC fue sin duda pensar en un esquema de autenticación stateless contra el servidor, pese a que mi primer idea fue enviar continuamente el nombre de usuario y contraseña por cada petición, luego de muy poca investigación entendí que no era lo optimo en lo más minimo, por lo que comencé a buscar alternativas hasta que me encontré con:

http://www.thebuzzmedia.com/designing-a-secure-rest-api-without-oauth-authentication/

que explica como funciona la autenticación en servicios tan utilizados como AWS (Amazon Web Services) como tal me resultó más que interesante y decidí implementar este método.

El Método

La forma de autenticación no es más que el viejo y conocido esquema de publicKey/privateKey donde existe una clave publica que puede ser conocida por cualquiera (y por tanto enviada en todas las peticiones, resistiendo spoofing) y una clave privada que una vez creada solo es conocida por los dos puntos de la comunicación y JAMAS es enviada durante la comunicación entre ambos puntos, ni siquiera aún cifrada. Entonces para confirmar la autenticidad de cada petición solo es necesario que las peticiones sean «firmadas» digitalmente. De que manera firmamos la petición? Simple tomamos todos los parámetros (o incluso todos los nombres de los parámetros) utilizando nuestra clave privada, para esto utilizamos el protocolo de cifrado SHA1 HMAC que nos permite cifrar un conjunto de datos con una clave privada.

Por lo que construimos un conjunto de datos a partir de nuestros parámetros y los ciframos utilizando nuestra clave privada para obtener nuestra firma electronica y adjuntamos tanto nuestra clave pública como nuestra firma al conjunto de parámetros enviados en cada petición, y lo enviamos todo.

Luego, del lado del servidor simplemente tomamos el listado de parámetros construimos nuevamente nuestro conjunto de datos y buscamos en la base de datos la clave privada a partir de la clave pública, y generamos nuevamente la firma para el conjunto de datos enviados, finalmente comprobamos la igualdad entre ambas firmas y si hay coincidencia, entonces la petición es autentica!.

Para resumir

Del lado del cliente:

  • Tomamos todos los parámetros (y nombres) a enviar, y construimos un conjunto de datos
  • Firmamos el conjunto de datos utilizando una encriptación SHA1 HMAC y la clave privada
  • Adjuntamos la clave pública y la firma a los parámetros de la petición
  • Enviamos la petición

Del lado del Servidor:

  • Tomamos todos los parámetros (menos la public key y la signature (o firma)) y construimos un conjunto de datos
  • Con la Public Key buscamos la Private Key en la base de datos
  • Generamos nuevamente la firma (signature) utilizando SHA1 HMAC y la private Key
  • Comparamos ambas firmas, si coinciden, la petición ha sido autenticada!

al describirla así puede sonar simple pero a la hora de la implementación, a veces son necesarias algunas estrategias a tener en cuenta.

veamos como implementé esto dentro de ttTodoMVC.

The SHA1 algorithm

Si hablamos de una implementación SHA1 sobre JavaScript no hablamos de otra librería más que de:

http://caligatio.github.com/jsSHA/

que implementa toda la familia de protocolos SHA, incluyendo SHA1 en

https://github.com/Caligatio/jsSHA/blob/master/src/sha1.js

aunque no es AMD compatible, pero facilmente puede hacerse compatible, simplemente agregando al final:

root = this;

if (typeof exports !== ‘undefined’) {
exports = jsSHA;
} else {
root.jsSHA = jsSHA;
}

y encerrandolo en una función wrapper para que this esté asociado a la window del browser.

del lado del servidor simplemente agregamos

module.exports= jsSHA;

y esto lo hace 100% compatible con Common.js

Luego, para usarlo es simplemente necesario crear un Objeto jsSHA de la siguiente manera

shaObj = new jsSHA(data,»ASCII»);
signature = shaObj.getHMAC($(privateKey, «ASCII»,»HEX»)

y esto nos da la firma digital SHA1 HMAC por private Key,

Con SHA1 tanto del lado del servidor como del cliente, estamos listos para la implementación

Client Side

Backbone.js ofrece muy pocos puntos para definir estrategias de acceso a un servicio RESTful, en casos simples, totalmente fuera del MVC propuesto por Backbone.js, como el login solo tratamos contra una url enviando una petición ajax con jQuery como en:

https://github.com/picanteverde/ttTodoMVC/blob/RESTFulAuth/public/app/modules/login.js

donde podemos ver simplemente generamos un conjunto de datos a firmar utilizando la publicKey como parte de los parametros y generamos un parámetro randomico para simplemente generar ruido en cualquier intento de ubicar nuestra private key

var rnd = Math.random()*1000,
sign = «publicKey=» + $(«#login-username»).val() + «rnd=»+rnd,
shaObj = new jsSHA(sign,»ASCII»);

en este caso utilizo por cuestiones de simplificación solo el nombre de usuario como publicKey, aunque tambien podría haber sido utilizado un Hash SHA1 del mismo nombre de usuario

Acto seguido generamos nuestra firma electronica SHA1 HMAC y la adjuntamos al conjunto de parámetros enviados a la API

$.ajax({
url: «/api/auth»,
type: «POST»,
dataType: «json»,
data: {
publicKey: $(«#login-username»).val(),
rnd: rnd,
signature: shaObj.getHMAC($(«#login-password»).val(), «ASCII»,»HEX»)
},

y enviamos la petición.

ahora a la hora de trabajar con Modelos y Colleciones de Backbone.js es necesario sobre escribir Backbone.Sync, aunque el mismo podría ser escrito de mejor manera esto es lo que tengo hasta ahora:

// Ensure that we have the appropriate request data.
if (!options.data && model && (method == ‘create’ || method == ‘update’ || method == ‘delete’)) {
params.contentType = ‘application/json’;
var data = model.toJSON();
if(publicKey && privateKey){
var key, sign =»», shaObj;
data.publicKey = publicKey;
for(key in data){
if(data.hasOwnProperty(key)){
sign += key + «=» + data[key];
}
}
shaObj = new jsSHA(sign, «ASCII»);
sign = shaObj.getHMAC(privateKey,»ASCII»,»HEX»);
data.signature = sign;
}
params.data = JSON.stringify(data);
}

agregamos delete para enviar un payload en el verbo «delete» de http y de estar definidos public y private key simplemente generamos la signature y agregamos ambos parámetros a la petición

tambien como pueden ver mas adelante hacemos lo mismo con al verbo «read»

if(method==’read’ && publicKey && privateKey){
var rnd = Math.random()*1000,
sign = «publicKey=» + publicKey + «rnd=»+rnd,
shaObj = new jsSHA(sign,»ASCII»);
if(!params.data){
params.data ={};
}
params.data.publicKey = publicKey;
params.data.rnd = rnd;
params.data.signature = shaObj.getHMAC(privateKey, «ASCII», «HEX»);
}

de esta forma firmamos todos los verbos.

Server Side

en el server side es mucho, mucho, más fácil gracias a la idea de middleware traída a expresss.js por connect.js

de esta forma simplemente podemos deifinir una función que se encargue de autenticar nuestra petición

var authorize = function(req, res, next){
var container = null, key, sign,shaObj;
if(req.body.publicKey && req.body.signature){
container = req.body;
}
if(req.query.publicKey && req.query.signature){
container = req.query;
}
if(!container){
res.status(401);
res.json({«error»:»Authentication required!»});
}else{
db.getUser(container.publicKey,function(err, user){
if(!user){
res.status(401);
res.json({«error»:»Authentication required, invalid publicKey»});
}else{
sign = «»;
for(key in container){
if(container.hasOwnProperty(key) && key !== «signature»){
sign += key + «=» +container[key];
}
}
shaObj = new jsSHA(sign, «ASCII»);
sign = shaObj.getHMAC(user.password,»ASCII»,»HEX»);
if(sign === container.signature){
next();
}else{
res.status(401);
res.json({«error»:»Authentication required, Authentication failed!»});
};
}
});

de esta forma via middle ware podemos autenticar cada petición simplemente añadiendo la función como middleware para cada petición que sea necesario autenticar

app.post(«/api/auth»,[authorize], function(req, res, next){
res.json({«auth»:true, «username»: req.body.username});
});

de esta forma podemos autenticar cada petición del lado del servidor sin tener que requerir el password por cada petición solo una signature.

Peróooooooooooooooooooooon por el largo post pero no había forma de explicarlo todo sin ser tan extenso.

Saludoooos

Etiquetado , , , , ,

TDD, BDD, Unit Test

No siempre es fácil encarar un nuevo proyecto con TDD o BDD, más especificamente cuando tenemos una leve idea de que queremos hacer en lugar de una completa especificación de requerimientos contra la que escribir los test. Digo esto porque varias veces me he encontrado totalmente convencido de iniciar un proyecto con BDD pero me ha sido imposible debido a que estaba codeando no como parte del desarrollo en si, sino más como parte del diseño, porque algunas veces el diseño (bajar de una idea a una implementación) nos obliga a sentarnos y definirlo con algo de código. por tanto creo que herramientas tan importantes como BDD y TDD deberían ser consideradas para su uso con mayor frecuencia en casos donde necesitamos cumplimentar un listado muy descriptivo de requerimientos, en una etapa de desarrollo cuando el diseño, (por quien lo haya hecho) terminó, y es hora de escribir el (utopico) código final de la aplicación que cumpla respete e implemente lo que los requerimientos describen, en cambio, en un escenario muy distinto si es necesario comenzar a codear pequeños prototipos muy fuertemente asociados a cambios durante la etapa de diseño de una solución no siempre es útil intentar BDD y me atrevo a ir aún más alla y decir que no siempre es posible ya que por nuestra mente pueden estar pasando miles de cosas que podemos agregar en el momento sin necesidad de ir a escribir el test porque puedan derivar en complementos o componentes diferentes del que estamos haciendo.

Solo un pensamiento que quería compartir con ustedes

Saludos

Etiquetado , , , , ,

Backbone.js, Backbone boilerplate, and RESTful Apis

Estuve jugando/peleando con Backbone.js, Backbone.js Boilerplate, el nunca bien ponderado Backbone Layout y RESTful Services ultimamente, así que decidí darles un paseo por estas tecnologías en una aplicación de prueba que hice en mi repositorio:

https://github.com/picanteverde/ttTodoMVC

Donde intenté dejar plasmados los siguientes requerimientos:

  • One Page App: una aplicación cliente 100% contra un RESTful service
  • Todo List: simple administración de «Tareas para hacer»
  • Backbone.js: usando Backbone.js como framework principal de la aplicación
  • Boilerplate: haciendola profesional con boilerplate, incluyendo Backbone Layout, Require.js, and Async Handlebars templates
  • RESTful: del lado del servidor solo una API stateless (sin estado)
  • MongoDB: almacenando todo en MongoDB
  • Login & SignIn: multiples perfiles

Con estas ideas en mente intenté hacerlo lo mejor que pude. y el resultado es la aplicación en el repositorio.

Como podrán ver hay 2 branchs

master branch: donde trabajé el servidor en un sentido stateful, aunque debatible porque almacené la información en un hash dentro de la session que es enviada junto con cada petición al servidor

RESTFulAuth: donde utilicé una encriptado  SHA1 para firmar cada una de las peticiones a la API, la pueden encontrar en:

https://github.com/picanteverde/ttTodoMVC/tree/RESTFulAuth

que fue sin duda una de las cosas más divertidas y desafiantes que encontré durante el desarrollo.

Más adelante le voy a dedicar una serie de post a cada parte de la aplicación para contar mi experiencia con cada reto que me encontré por ahora los dejo revisando el código e intentando hacerlo andar.

Saludos

Etiquetado , , , , , , ,

Para todo Three.js siempre hay un tQuery que nos puede ayudar

tQuery es una INCREIBLE librería creada por Jerome Etienne que nos viene a solucionar la vida a la hora de trabajar con Three.js sobre WebGL.

Es, según sus palabras, a Three.js lo que jQuery es al DOM, así que podemos esperar que sea increiblemente facil de usar y muy gratificante al obtener resultados rápidos y satisfactorios

vamos a ver como es un mundo simple con tQuery

primero que nada, por supuesto, agregamos una referencia a la librería, en este caso ya podemos olvidarnos de agregar Three.js ya que tQuery viene con su propio Bundle de Three.js incluido por lo que no necesitamos incluirla nuevamente

<script src=»../libs/tquery-all.js»></script>

luego simplemente creamos el mundo tQuery

var world = tQuery.createWorld().boilerplate().start();

como podrán ver en tutoriales más adelante ese «start» está asociado con que comenzó un ciclo de renderizados para mantener nuestro mundo «vivo» o continuamente renderizandose

ahora simplemente agregamos un objeto y listo!

var object = tQuery.createTorus().addTo(world);

pueden divertirse si quieren levantando el inspector (a estas alturas imagino que usas chrome o algún browser basado en webkit)

y tirar comandos de la forma

var o = tQuery.createSphere().addTo(world);

y luego

o.position(1,1,1);

y muchos comandos más que pueden encontrar en la referencia de tQuery aunque no es muy buena

el ejemplo completo está en

http://picanteverde.github.com/bucefalo-html5/examples/tquery/first.html

para hacer algunas pruebas les recomiendo dos video tutoriales del autor que por ser frances tiene una muy particular forma de pronunciar su ingles jajajaja

http://learningthreejs.com/blog/2012/03/05/tquery-version-0/

http://learningthreejs.com/blog/2012/02/15/valentine-card-in-tquery/

ademas pueden visitar el blog del autor que es de lo más interesante que se puede ver en tQuery

http://learningthreejs.com/

Etiquetado , , ,

JavaScript 3D! aprendiendo Three.js

Vamos a aprender a programar objetos 3D y para eso nos vamos a ayudar con una de las librerías más conocidas en el entorno 3D de JavaScript, estoy hablando de

Three.js

Para aprender a usar Three.js primero debemos entender como funciona

Three.js renderiza una Escena 3D dentro de nuestro Canvas (o svg) utilizando un Renderizador y una Cámara, a la vez las Escenas a renderizar están compuestas por Luces y Formas(meshes), las Formas están compuestas por Geometrías y Materiales y finalmente las Geometrías poseen VerticesCaras.

Bien dicho esto solamente de teoría podemos comenzar a crear nuestra primer escena.

Primero por supuesto debemos incluir la librería, es recomendable utilizar algún build ya minificado

<script src=»three.min.js»></script>

Luego creamos nuestro renderizador, en este caso voy a usar WebGL, por lo tanto

var renderer = new THREE.WebGLRenderer();

Ahora vamos a crear nuestra cámara, para la cual necesitamos algunos parámetros, es recomendable usar estos prefijados (obviamente el alto y ancho pueden definirlo ustedes)

var WIDTH = 400,
HEIGHT = 300;

var VIEW_ANGLE = 45,
ASPECT = WIDTH / HEIGHT,
NEAR = 0.1,
FAR = 10000;

var camera =
new THREE.PerspectiveCamera(
VIEW_ANGLE,
ASPECT,
NEAR,
FAR);

Luego comenzamos a definir nuestra Escena

var scene = new THREE.Scene();

agregamos la cámara y la posicionamos en nuestra escena 3d utilizando posicionamiento en X, Y y Z

scene.add(camera);
camera.position.z = 300;

seteamos el tamaño de nuestro renderizador y pedimos que nos devuelva el nodo HTML donde va a renderizar para insertarlo dentro de nuestro árbol DOM

renderer.setSize(WIDTH, HEIGHT);

// attach the render-supplied DOM element
$container.append(renderer.domElement);

el ejemplo presupone que usamos jQuery para insertar elementos en el DOM pero podríamos utilizar directamente document.body.appendChild(renderer.domElement);

Si renderizaramos ahora no veríamos absolutamente nada ya que no hay objetos que mostrar, así que vamos a crear uno

Primero definimos un Material para nuestro objeto, aunque en Three.js hay distintos tipos de materiales vamos a utilizar uno de los más sencillos para mantener simple nuestro ejemplo, el MeshLambertMaterial puede recibir solamente un color (en hexadecimal) y con eso tiene información suficiente para renderizarse

var sphereMaterial =
new THREE.MeshLambertMaterial(
{
color: 0xCC0000
});

Ahora vamos a crear nuestro objeto

var radius = 50,
segments = 16,
rings = 16;

var sphere = new THREE.Mesh(

new THREE.SphereGeometry(
radius,
segments,
rings),

sphereMaterial);

atención que el Objeto Mesh necesita tanto de una Geometría como de un Material para poder crearse.

y finalmente agregamos el objeto a nuestra escena 3d

scene.add(sphere);

Ahora éste sería un mundo muy obscuro si no agregamos algo de iluminación asi que vamos a agregar una luz

var pointLight =
new THREE.PointLight(0xFFFFFF);

// set its position
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 130;

// add to the scene
scene.add(pointLight);

nuevamente definimos el color de nuestro punto de luz utlizando hexadecimal

Finalmente…. RENDERIZAMOS

renderer.render(scene, camera);

y voila! nuestra escena está lista!

No es muy divertida como pueden ver, pero hemos sentado las bases para poder hacer muchas más cosas de ahora en adelante!

si quieren pueden ver el ejemplo funcionando en:

http://picanteverde.github.com/bucefalo-html5/examples/threejs/first.html

Para más info

Links:

http://aerotwist.com/tutorials/getting-started-with-three-js/

 https://github.com/mrdoob/three.js/wiki/Getting-Started

http://www.12devsofxmas.co.uk/2012/01/webgl-and-three-js/

Etiquetado , ,