Using Express and Dust.js with Node.js

Filed in Javascript Leave a comment

Express.js is the most full-featured and popular Node.js open source framework. However, its default template library of choice – Jade, is far from impressive. Not only does it use it’s own syntax(you cannot use plain HTML), but it is limited to server-side rendering. In this post, we will setup Dust.js with Express.js for server-side rendering, as well as discuss a possible implementation with client-side rendering.

Server-side rendering

Dust.js can easily be integrated into the latest Express.js version using the Consolidate.js module. This integration could easily be completed without this module, however, Consolidate.js performs the exact functionality we need, including support for caching.

For this example, we are using the latest Express 3.0 alpha source from Github.

// Module dependencies.
var express = require('express')
    , routes = require('./routes')
    , http = require('http')
    , fs = require('fs')
    , path = require('path')
    , cons = require('consolidate')

var app = express();

// assign the dust engine to .dust files
app.engine('dust', cons.dust);

app.configure(function(){
    app.set('view engine', 'dust');
    app.set('views', __dirname + '/views');
    app.use(express.static(__dirname + '/public', {redirect: false}));
    app.use(express.bodyParser());
    app.use(express.session({ secret: 'very_unique_secret_string',
        cookie: { maxAge: 1800000 }}));
    app.use(app.router);
 });

app.get('/', function(req, res){
  res.render('index', {
    title: 'Testing out dust.js server-side rendering'
  });
});
view raw app.js This Gist is brought to you using Simple Gist Embed.

Note: Make sure to install the latest Consolidate.js from the Github source, since Dust.js support has been added only recently, and is not available in the node package manager just yet.

This is my code for app.js for my sample Node.js application. First we include all the required modules. We set our default template engine with the app.engine command. We pass in the default extension of all the template file-names, as well as the default engine that will be used to render them.

We can set the default file-name extension by setting the ‘view engine’ property. This is a very convenient feature. Let’s say our file-names end with .dust. Instead of specifying ‘filename.dust’, we can just pass in ‘filename’.

Here is my ‘index’ page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>{+title}7th-Degree{/title}</title>
    <script type="text/javascript" src='/javascripts/utils.js'></script>
    <link rel="stylesheet" type="text/css" href="/stylesheets/style.css">
    {+http_header/}
</head>
<body>
<div id="wrapper">
    <div id="header">
        <div class="logo"></div>
        <div class="header_login">
            {?username}
              {username}
            {:else}
            <form method="POST" action="/signin">
            <label>Email <input type="text" name="user[username]" id="s-user"></label>
            <label>Password<input type="text" name="user[password]" id="s-pass"></label>
            <input type="submit" class="submit" value="Login">
            </form>
            {/username}
        </div>
        {+header/}
    </div>
    <div id="content">
        <div id="right">
          {+right/}
        </div>
        <div id="left">
          {+left/}
        </div>
    </div>
    <div id="footer">
        <ul>
            <li>About</li>
            <li>Contact/Bug Report</li>
            <li>Copyright © 2011-2012 Stanislav Palatnik. All rights reserved.</li>
        </ul>
    </div>
</div>
</body>
</html>

After this index page gets rendered through dust.render(), it will replace all the keys and conditional statements with plain HTML code. For example, let’s say I added username: ‘Stan’ to the response object. Dust.js would detect that the username token is present, and would show my username stead of the login form!

Dust.js Crash Course

You might not recognize some symbols or tags in that HTML code. That’s because they are used by the Dust.js parser to add additional functionality(conditionals, includes). Let’s start with the title. {+title}7th-Degree{/title}. First let’s ask ourselves what problem we are trying to solve. We want to have a standardized header and footer. We want to dynamically change the title in each page, without having to change it manually in the layout.

By surrounding the title with {+title} tags, we can dynamically change the title by passing the variable ‘title’ during the request. If you look back at the previous Gist, we are calling res.render, and passing in  title: ‘Testing out dust.js server-side rendering’. Dust.js will see this and dynamically replace the title within those tags on the server. When the client(or crawler) loads this page, they will only see the ladder title. Similarly, the {+http_header/} tag serves the same purpose. But this case, we don’t have a default value, so we open and close the tag to create a placeholder to add additional more information in the header, like additional JavaScripts of stylesheets.

Conditional tags:

{?username}
  {username}
{:else}
  Please Log-In!

Another great feature of Dust.js is support for conditionals. Putting ? in front of a tag is similar to checking if the variable the tag represents has been set. If not, we render the content in after the {:else}.

 

Client-side rendering:

A recent case study by LinkedIn shows the true benefits of client-side rendering: How LinkedIn leverages Dust.js.They make a strong case in support of Dust.js. One of the major advantages is removing load from your servers. Client-side templates can be served from your CDN network, while the data that populates them can come straight from your server. In this scenario, you get the best of both worlds. Offloading bandwidth to CDN servers while constantly serving the most updated content. Additionally, you are offloading the computational power to parse and render the templates on the client’s browser. This results in reduced server latency. The major downside is that you have to include the entire Dust.js framework inside the webpage, which adds considerable overhead for slow internet connections and under-powered devices.

Let’s take our previous example and port it to client-side rendering. In this case, we do not need to load the consolidate module on the server. We do not need to parse any variables on the server. So what’s the catch? In order to enable client-side rendering, we need to compile the dust templates into JavaScript files before we serve them to the client.That means that every time we make a change to the template, we need to compile it into JavaScript. Compiling can be done with the dust.compile() command. The alternative would be to compile the HTML source each time on the client. This is most efficient approach for the server, it does not have to worry about tracking changes to the template. However, compiling a complicated template on the client will create substantial overhead for the browser.

<html>
<head>
<script src="dust-full-0.3.0.min.js"></script>
<script type="text/javascript">
//example showing client-side compiling and rendering
var compiled = dust.compile("Hello {name}!", "index");
dust.loadSource(compiled);

dust.render("index", {name: "David"}, function(err, out) {
  if(err != null)
    alert("Error loading page");
  //assume we have jquery
  $("#pageContainer").html(out);
});
</script>
</head>

<body>
<div id="pageContainer"></div>
</body>
</html>
view raw index.html This Gist is brought to you using Simple Gist Embed.

In this simple example, we are compiling and rendering the template all inside the client. First we compile the template into JavaScript that Dust.js can understand. Then we render the template using Dust.js. In this case, the engine performs a variable substitution to replace {name} with David. In this case, we maximized the amount of work the client does, which minimizes the work for us on the server. However, there are some issues to pure client-side rendering:

  1. Increased Bandwidth - The entire Dust.js framework is 26 kb. If we remove client-side rendering functionality, the size is drastically reduced to 6 kb. That extra 20 kb will substantially increase bandwidth usage.
  2. Search Engine Optimization - Search engine crawlers will not be able to use the template because they cannot execute JavaScript. However, in the LinkedIn article mentioned earlier in the article, they address this issue by falling back to server-side rendering if the client does not support JavaScript. This solves the crawler issue, as well as client that does not support JavaScript these days.

Click here to check out more information about the Dust.js API

The major takeaways from this post is that Dust.js is a great templating engine. It’s powerful, versatile, and efficient. And with Express 3.0, it’s a breeze to setup.

 

 

Securing Flash/PHP communication

Filed in Flash | PHP Leave a comment

Virtually every computer in the world has flash installed. Whether you’re running Debain or Windows 7, there’s a distribution of Adobe Flash available for you. That makes Flash the most interoperable environment available. Now let’s say you want to embed Flash into a website. Either you want a submission form, chat box, or a simple game, you will most likely need to communicate back and forth with the server. Doesn’t sound hard at all, especially with so many libraries available and so many services you can use(REST, XMLRPC, JSON, XMLSocket for low latency communication, or just a simple HTTP GET request to the PHP page). However, how sure are you of the validity of the data transferred from the client-side Flash app back to your server?

All programming languages preach to never trust user input directly. For a simple example, a good program will even check that a person’s name is made of valid and accepted characters. However, too many people unfortunately ignore this rule when they create Flash apps. Even if you’re creating a contact form field, there are many ways a user could exploit your site if you don’t properly secure the client’s input. Most notably, he could create an SQL injection the input fields.

Fortunately for form fields, there are bullet proof ways to secure them. In the following section I will discuss those. However, I will also talk about more sophisticated applications such as games which track levels and submit high scores. In these cases, it’s not possible to secure your high score list 100% , but you can make hard enough for virtually everyone to back down.

Securing simple form fields:

The first basic step is to obviously validate the form fields inside of Flash. But this is by no means makes your application secure. If anything, it saves an extra HTTP request. You will also have to duplicate this form verification on the server side. The most important thing you can do on server-side verification is check for an SQL injection. If you’re using MySQL, pass it through the mysql_real_escape_string or mysqli_real_escape_string. I strongly prefer you use mysqli_real_escape_string because it avoids some security flaws present in the former function.

Now that we secured basic input, we need to protect against spoofing and DDOS attacks. Suppose that an attacker wants to slow your site down considerably, or even bring it down. One way he could do it is by flooding the server with requests. If the server believes this request came from your trusted application, it will send it to your database. Even though your database will filter the content, hundreds of thousands of requests to your database will most likely bring it down. One way to protect against spoofing is by using tokens.

Tokens:

Here’s one way to approach it. Every time your trusted form sends a request to the server, it will also send along a secure token.

First the server will send a random string to the Flash and save the encrypted version of this string in the database. This string will be encrypted using a token that will be hard-coded into the Flash game as well as in the PHP. Now, whenever the Flash form loads, it must request a random string to be sent to it. It will then use the secure key that you hard coded to create a token and send the token along with the response. Once the server recieves your request, it will compare your encrypted token with the ones stored in the database. If there is a match, only then should you process the form. Also remember to delete the matching token from the database after that. If the token received does not match any token that have been generated in say, the last hour, then discard that request.

Encrypting Your Source

The last part is to obfuscate your action-script source good enough to deter hackers from trying to find the form fields and even the encryption key. Encrypt the entire action-script with a library like as3corelib. This will prevent the vast majority of people from proceeding. They will not be able to read your source and even think about finding the encryption key. Now whenever a user submits the form from your trusted app, it will also send the token. However, decompiling action-script is much easier then other languages because action-script is a very high level programming language, not to mention the byte-codes are well documented. Here are some ways to deter or confuse an attacker who has decrypted your application:

  • Replacing key byte arrays with functions that calculate the key
  • Placing numerous fake encrption keys throughout the app.

I also recommend this strategy for securing Flash games, so I will not go over it again.

Securing Flash Game Points Submission

The biggest problem with Flash-based games is how easily the high score lists can be hacked. One of the best(and most complicated) ways to protect against this is to put all the game logic on the server. That way, whenever a user submits a new high score, your server side script checks if that score is possible with the moves that the user has. For example, if the highest recorded level that the user has reached is 5, there is no way for him to have reached score x. For this to work, you cannot send HTTP requests indicating when the level has changed. The change must be determined on the server, after the Flash client has sent some command. This command should trigger a change in the level.

If you have a fast paced game, where there are a lot of command getting executed at the same time, you could open a socket.

There are many other ways to secure Flash apps, but to have basic security, I advise that you follow the encryption method mentioned in this post.

Parenthesis Confusion in C++

Filed in C++ Leave a comment

I ran into this problem at least once, and I never actually thought about why it worked with or without the parenthesis, and thought that I was just doing something else wrong. But it was only so easy for me because I was doing a relatively small project, and the changes usually didn’t affect any other files. I never really thought why or how it works. But if you’re developing large scale applications or just portions of it, you need to make sure that you use it properly, or it might be a pain to debug it later. For example, as I will explain later, forgetting to add a parenthesis will keep POD class values from being properly initialized in some cases. If you don’t know the properties of POD class initialization, you could be scratching your head when a comparison fails or the compiler throws you a run-time error! If this doesn’t make sense yet, I recommend that you continue reading.

First thing I want to clear up is this post deals with the dilemma when you create objects using the new operator. If you don’t, then there really is no debate. Consider the following example:

struct Stan
{
     int man;
};

//now to test it out

Stan s1;
Stan s2();

Here, the second initialization is obviously wrong, because the C++ compiler will interpret it as a function definition with no parameters that returns a Stan object. Glad that’s over with aren’t you? Now let’s get down to the exciting stuff.

So does it matter if you add a parenthesis at the end of a dynamically generated class? It should definitely matter right? Let’s give a test run shall we?

//using the Stan class from the previous example

Stan *s1 = new Stan;
Stan *s2 = new Stan();

So what’s going on here! s1 and s2 can’t both be correct right? But once you test it out, it might appear that it doesn’t matter at all. In Visual Studio 2008, the compiler doesn’t throw an error or warning at either of these two declarations. But there are some important differences between these two initializations. I will review the differences in accordance with the c++03 revision. For the run down with the c++98 revision, see Philip Taylor’s comment here on a msdn blog.

First let me introduce some terminology. POD means ‘Plain Old Data’. In C++, objects are either POD or non-POD. A POD class can be described as a simple class with little logic. More specifically, to be a POD class, it has to have data members of one of the following data-types: a built-in type(ie int, double), pointer, union, struct, array, or a class with a trivial constructor. The constructor part basically means that if you did not create a default constructor for your class, the C++ compiler will generate the generic constructor for you. A trivial constructor is a constructor that the compiler generates for you. In addition, a POD class cannot have other data types that are non-POD(for example, a string data type is not a POD class because it has a defined constructor). There are many things that would make a class non-POD even if it contains any of the members mentioned above:

  1. User defined constructor
  2. User defined copy constructor
  3. User defined assignment operator
  4. User defined destructor
  5. Non-POD data types such as a string or a non-POD class

So now let’s example the differences between these two initializations.

//using the Stan class from the previous example

Stan *s1 = new Stan;

In this case, s1 is default initialized, which means that all POD data-types will be left uninitialized. In this case, any int will be uninitialized.

//using the Stan class from the previous example

Stan *s2 = new Stan();

Here s2 will be value initialized, which means that all data members will be initialized. Here, int will be zero-initialized to 0. Looking at the differences between these two initializations(s1 and s2), it’s clear that if you initialize a POD class without parenthesis, you risk having uninitialized data members. Now if you try to access them, you might get a segfault error. This can be a real headache. If you don’t know that leaving out parenthesis can cause an int to be uninitialized, then it will be hard to find the problem.

Now let’s consider another class.

struct Stan
{
     int the;
public:
     Stan():the() {};
};

According to C++03, since I have create a non-trivial default constructor, this is a non-POD class now. So it doesn’t matter if I use the parenthesis, or I don’t.

So to sum it up, if you don’t have a POD class, or if you’re not intentionally planning to leave member objects uninitialized, then I would recommend that you always use parenthesis at the end of your class initializations to avoid possible headaches down the road. In reality, you will rarely create POD classes because they are so simple, it would make little sense to even need such a class.

Note that there is a bug/feature in Visual Studio users where you might have unitialized data members even if you use parenthesis. I find this to be more of a bug then a feature, but then again I don’t work for Microsoft.

TOP

winrar download free

winrar download free

winrar free download

winrar free download

download winrar free

download winrar free

winzip activation code

winzip activation code

windows 7 ultimate product key

windows 7 ultimate product key

windows xp product key

windows xp product key

winzip free download

winzip free download

winzip freeware

winzip freeware

winzip registration code

winzip registration code

windows 7 crack

windows 7 crack

free winrar download

free winrar download

windows 7 key generator

windows 7 key generator

winrar free

winrar free

free winrar

free winrar

windows 7 activation crack

windows7 activation crack

free winzip

free winzip

windows 7 product key

windows 7 product key

winzip free download full version

winzip free download full version