The Good Word http://blog.nategood.com Repository for a programmer's memory leaks posterous.com Fri, 04 May 2012 08:37:00 -0700 Sublime Text 2 Strip Whitespace on Save http://blog.nategood.com/sublime-text-strip-whitespace-save http://blog.nategood.com/sublime-text-strip-whitespace-save

I’ve become fond of Sublime Text 2. Gasp! Wait, what? You don’t use emacs/vim/butterflies? Anyway, regardless of the editor, I like to keep my whitespace under control. This usually means I add a hook to strip trailing whitespace when saving. The Sublime Text 2 Python API reference looks pretty complete, but there’s little pragmatic documentation. I tinkered with creating my own, found others that had semi decent solutions, but ultimately gave up. After my failed attempts and failed googling, my coworker informed me that Sublime Text has this built right in as a user setting you can set by adding a simple JSON snippet. Awesome.

Make it Happen

Go to SublimeText 2 > Preferences > User Settings (or just hit the Mac Standard cmd + ,). This should open your User Settings as a JSON file. Add the following to your file

"trim_trailing_white_space_on_save": true

That’s it. You’re good to go.

sublime text settings

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/1706667/d2ce351ee414282b93dfdb672ce51430.png http://posterous.com/users/3sylfe5BTkZj Nathan Good Nate Nathan Good
Sat, 07 Apr 2012 10:54:00 -0700 SSL Client Authentication in Node.js http://blog.nategood.com/nodejs-ssl-client-cert-auth-api-rest http://blog.nategood.com/nodejs-ssl-client-cert-auth-api-rest

A couple of years ago, I wrote a blog post about configuring nginx to use SSL client certificate authentication. It is to this day one of my most popular posts in terms of traffic. Since then, I’ve continued to advocate the use of client certificates as a form of authentication when your security requirements are a bit more stringent.

Recently, Node.js has piqued my interest. Most other languages/frameworks targetted for web development sit on top of a separate HTTP server (like Apache or Nginx). Node.js is unique in that it provides an HTTP server as one of the core libraries (to the shagrin of some). This means there isn’t (immediately) a need for a separate HTTP server. For fun, I decided to recreate the whole client SSL certificate authentication thing in Node.js.

If you need a refresher on how to create and sign the certs, check out the nginx post.

Turns out the more recent releases of Node.js have decent TLS/SSL support making things relatively straight forward. Here is a quick example of an HTTPS server that will allow us to perform client certificate authentication and determine authorization.

var https = require('https'),      // module for https
    fs =    require('fs');         // required to read certs and keys

var options = {
    key:    fs.readFileSync('ssl/server.key'),
    cert:   fs.readFileSync('ssl/server.crt'),
    ca:     fs.readFileSync('ssl/ca.crt'),
    requestCert:        true,
    rejectUnauthorized: false
};

https.createServer(options, function (req, res) {
    if (req.client.authorized) {
        res.writeHead(200, {"Content-Type": "application/json"});
        res.end('{"status":"approved"}');
    } else {
        res.writeHead(401, {"Content-Type": "application/json"});
        res.end('{"status":"denied"}');
    }
}).listen(443);

The first three options (key, cert, and ca) are pretty self explanitory (if they aren’t, read the previous post for a refresher). The requestCert option tells Node that it should request the client cert from a client attempting to connect. Lastly, rejectUnauthorized tells Node if it should flat out reject the connection if the certificate provided is not valid (valid meaning it must be signed by our ca, not revoked, and not expired). We’ll keep this set to false so we can make the decision in the app itself.

The https.ServerRequest object is passed to our https.createServer callback function as the first argument (named req above). Along with other information about the request (like the uri, http method, etc.), it includes some information about the client’s authorization state in the req.client.authorized attribute. This is pretty self explanitory, but this boolean attribute states whether or not the client presented a “valid” client certificate as part of its request.

We can test this out with a simple curl call.

# Denied (no cert)
curl -v -s -k https://localhost:5678

# Approved (using CA signed cert)
curl -v -s -k --key ssl/client.key --cert ssl/client.crt https://localhost:5678

There you have it. It’s a pretty trivial example, but you get the basic idea of how to get started with making client side cert authentication your authentication tier for you next Node API. All of the source code (including the example certs) is available on GitHub.

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/1706667/d2ce351ee414282b93dfdb672ce51430.png http://posterous.com/users/3sylfe5BTkZj Nathan Good Nate Nathan Good
Wed, 07 Mar 2012 09:12:00 -0800 MAMP Nightmares: Fixing HTTPS After Upgrading http://blog.nategood.com/mamp-https-ssl-cert-password-fix http://blog.nategood.com/mamp-https-ssl-cert-password-fix

I use MAMP to run my local dev environment (been meaning to get a Linux VM with true LAMP going for a while but let’s face it, I’m just too damn lazy). While it’s better than the built in OS X “LAMP” support, it still is a pain. Another prime example just occurred after upgrading to MAMP 2.05 when my entire SSL configuration stop working. Here’s what I did to fix it:

  1. Get rid of all the default cruft in your ssl.conf file (this file can have different names and be found in different locations depending on your MAMP version, but basically find wherever you and get it down to something like below. While these settings probably aren’t sufficient for production, they are more than sufficient for your dev environment.

    Listen 443
      VirtualHost localhost:443
          DocumentRoot "/path/to/your/public_html/dir"
          ServerName localhost
          SSLEngine on
    
          ErrorLog "/Applications/MAMP/logs/apache_error.log"
    
          SSLCertificateFile /Applications/MAMP/conf/apache/ssl_crt/server.crt
          SSLCertificateKeyFile /Applications/MAMP/conf/apache/ssl_crt/server.key
      /VirtualHost
  2. Make sure the SSL cert and key actually exist (mine did not). However I found the old keys from my previous version and used them. If you can’t find them, just whip up another pair and remember to remove the passphrase on the key (otherwise MAMP won’t be able to start it from its GUI).

Voilá.

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/1706667/d2ce351ee414282b93dfdb672ce51430.png http://posterous.com/users/3sylfe5BTkZj Nathan Good Nate Nathan Good
Thu, 09 Feb 2012 00:56:00 -0800 Httpful: The Sane PHP HTTP Client Library http://blog.nategood.com/httpful-the-sane-php-http-library http://blog.nategood.com/httpful-the-sane-php-http-library

cUrl is awesome. Sadly cUrl in PHP is not. More often than not, using the PHP cUrl library means digging through the curl_setopt page to figure out which poorly named constant is needed to tune our HTTP requests. Alternatives like HTTP_Request and Zend_Http aren’t much more usable or are too bloated for the common case. One evening while plugging away at some code to migrate us from BaseCamp to FogBugz, I decided I had enough. That evening Httpful came to be.

A Readable Curl HTTP Client Alternative

The goal of Httpful was simple: create a sane HTTP library focused on readability, simplicity, and flexibility – basically provide enough features to get the job done and make those features really easy to use. Before we dive into how Httpful accomplishes this, let’s start with a quick snippet:

// Fire off a GET request to FreeBase API to find albums by The Dead Weather.

$uri = "https://www.googleapis.com/freebase/v1/mqlread?query=%7B%22type%22:%22/music/artist%22%2C%22name%22:%22The%20Dead%20Weather%22%2C%22album%22:%5B%5D%7D";

$response = \Httpful\Request::get($uri)->expectsJson()->sendIt();

echo 'The Dead Weather has ' . count($response->body->result->album) . ' albums.';

Okay, that looks a bit more sane than that curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); stuff. Let’s look at some of the things that Httpful has to offer.

Chaining

Anyone that has used jQuery can attest to the awesomeness and conciseness of “chaining”. Httpful allows similar chaining to neatly build up your requests. Need to specify a content-type? Tack on an HTTP body? Custom header? Just keep tacking them on to your initial request object.

Make the Important Stuff Easy

Choosing HTTP methods beyond GET and POST, quickly setting Content-Types, setting request payloads… these are the things we should be able to do quickly. This library makes those things easy using the aforementioned chaining. Let’s show a quick example doing a few of our favorite things.

$response = \Httpful\Request::put($uri)        // Build a PUT request...
    ->sendsJson()                      // let's tell it we're sending (Content-Type) JSON...
    ->body('{"json":"is awesome", "httpful": "is too"}') // lets attach a body/payload...
    ->sendIt();                        // and finally, fire that thing off!

Custom Headers

The library allows for custom headers without sacrificing readability. Simply chain another method on to your request with the “key” of the header as the method name (in camel case) and the value of the header as that method’s argument. Let’s add in two custom additional headers, X-Example-Header and X-Another-Header:

$response = \Httpful\Request::get($uri)
    ->expectsJson()
    ->xExampleHeader("My Value")            // Add in a custom header X-Example-Header
    ->withXAnotherHeader("Another Value")   // Sugar: You can also prefix the method with "with"
    ->sendIt();

Smart Parsing

If you expect (and get) a response in a supported format (JSON, Form Url Encoded, XML and YAML Soon), the Httpful will automatically parse that body of the response into a useful response object. For instance, our “Dead Weather” example above was a JSON response, however the library parsed that request and converted into a useful object. If the text is not supported by the internal parsing, it simply gets returned as a string.

// JSON
$response = \Httpful\Request::get($uri)
    ->expectsJson()
    ->sendIt();

// If the JSON response is {"scalar":1,"object":{"scalar":2}}
echo $response->body->scalar;           // prints 1
echo $response->body->object->scalar;   // prints 5

Custom Parsing

Best of all, if the library doesn’t automatically parse your mime type, or if you aren’t happy with how the library parses it, you can add in a custom response parser with the parseWith method. Here’s a trvial example:

// Attach our own really handler that could naively parse comma 
// separated values into an array
$response = \Httpful\Request::get($uri)
    ->parseWith(function($body) {
        return explode(",", $body);
    })
    ->sendIt();

echo "This response had " . count($response) . " values separated via commas";

Request Templates

Often, if we are working with an API, a lot of the headers we send to that API remain the same (e.g. the expected mime type, authentication headers). Usually it ends up in writing boiler plate code to get around this. Httpful solves this problem by letting you create “template” requests. Subsequent requests will by default use the headers and settings of that template request.

// Create the template
$template = \Httpful\Request::init()
    ->method(\Httpful\Http::POST)     // Alternative to Request::post
    ->withoutStrictSsl()              // Ease up on some of the SSL checks
    ->expectsHtml()                   // Expect HTML responses
    ->sendsType(\Httpful\Mime::FORM); // Send application/x-www-form-urlencoded

// Set it as a template
\Httpful\Request::ini($template);

// This new request will have all the settings 
// of our template by default.  We can override
// any of these settings by settings them on this 
// new instance as we've done with expected type.
$r = \Httpful\Request::init()->expectsJson();

That’s it

So that is the main gist of things. You can find the source code on GitHub. Hopefully the next time you find yourself pulling your hair out using the PHP cURL client library to connect to a third party API, maybe Httpful can come to the rescue.

Update

Finally have a landing page for the project. Checkout the Httpful PHP HTTP Client Site.

tl;dr

The PHP cURL library is ugly and unintuitive. Httpful is a sane HTTP library alternative that includes chaining, template requests, easy GPPD support, built in parsing and more. It is on GitHub.

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/1706667/d2ce351ee414282b93dfdb672ce51430.png http://posterous.com/users/3sylfe5BTkZj Nathan Good Nate Nathan Good
Thu, 22 Dec 2011 22:07:00 -0800 Quickly Add and Edit Cookies In Chrome http://blog.nategood.com/quickly-add-and-edit-cookies-in-chrome http://blog.nategood.com/quickly-add-and-edit-cookies-in-chrome

Occasionally whilst developing, I have the need to manually set a cookie. For example, in our production environment we have multiple app servers and multiple load balancers. We follow a “round robin” approach as opposed to a “sticky session” approach when it comes to load balancing. From time to time it is really handy to be able to isolate yourself to one box for the purposes of testing/debugging a particular box. Our stack will allow this if you have a cookie telling the load balancer where you want it to take you (e.g. setting the “takeMeToServer” cookie to “app3” would hypothetically send all your requests to application box 3). After doing this the ugly way with temporary “set cookie” scripts hosted on the server I was trying to reach, I decided to look for a simpler route.

Chrome has awesome Developer Tools. Included in these tools is the handy “Resources” section which lets you inspect and delete your existing cookies for the site you are on. Unfortunately, it does not let you add or edit your cookies. This is where the old javascript: protocol comes in handy. You can use the URL bar and javascript to set a new cookie for a particular page.

Steps

  1. Navigate to the site where you wish to set a new cookie
  2. In your URL bar enter javascript:document.cookie="myCookieName=myCookieValue" where myCookieName is the name of the cookie you wish to set, and myCookieValue is the value.

Bam you are done. You may be taken to a new screen that echos out the contents of your cookie, however if you go back to the domain where you set the cookie, you should be able to open up the Developer Tools again and see your newly set cookie.

Now ain’t that sweet?

If you need to set the same cookie or two repeatedly, I would recommend adding a “bookmarklet” for your javascript above. They work just as nicely for the javascript protocol as they do for regular old http links.

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/1706667/d2ce351ee414282b93dfdb672ce51430.png http://posterous.com/users/3sylfe5BTkZj Nathan Good Nate Nathan Good
Sun, 18 Dec 2011 21:06:00 -0800 Software Engibeering: Recruiting Revisted http://blog.nategood.com/software-engibeering-recruiting-revisted http://blog.nategood.com/software-engibeering-recruiting-revisted

One of my many responsibilities at ShowClix is to recruit software engineer folk for the team. It’s one of my favorite and yet most frustrating tasks. If your name isn’t Google or Facebook, if you aren’t located in “the valley”, if your pockets aren’t infinitely deep, recruiting talented engineers can be a challenge.

Even in a down economy software engineering remains a “recession-proof” job. The good software engineers are working. This is most evident by the fact that the applicant list for our Software Engineer position is only a fraction of the size of the 800 or so new applicants competing for our recent Customer Care Representative opening.

The Usual Approach

There are two common options when it comes to hiring a software engineer:

  • Throw a listing out on Craigslist/Monster/Dice/Stack Overflow Careers/Reddit Jobs and wait for the fish to bite
  • Hire a recruiting agency to do the head hunting for you

While the latter option may work great for some companies, I personally find the business model behind recruiting agencies fundamentally flawed (but that’s for another blog article). For this and other reasons I tend to stay away from them.

As a result, we’ve historically went with the route of posting on various free and paid job boards. Résumés would trickle in – with most of the candidates being what I like to call “extra mediocre”. We’d sift through the candidates, send out a “code puzzle” or setup a phone screen with the folks we thought looked promising, and eventually bring a couple of people in for an on-site.

The process was long, ineffective, and costly. Hiring should be an exciting time for a small company but with this approach it became monotonous. For this reason, when it came time to hire another software engineer, we decided to try something a bit different.

Beer Me

Instead of shelling out the $300 to $400 per job listing, we decided we’d take that money and invest it in something that was a little more fun: beer. We would throw a free event for like minded tech folk in the area to meet the ShowClix team, see the offices, and drink some delicious local craft brew. Seeing as we’re in the business of helping people throw successful events, we figured if anyone could pull it off, it should be us.

The Goals

  • Spend no more than the cost of a job listing (~$300)
  • Attract 50 local people from the Industry
  • Turn it around in one week
  • Come away with 5 to 10 really solid recruiting leads
  • Promote ShowClix as a “tech contender” in the city of Pittsburgh

The Strategy

  • Leverage what we’ve got: Let people see our awesome office packed with fun perks and a great view of the city and let them meet our young, fun, and bright team.
  • Get delicious local craft beer: There seems to be a correlation between software engineers and drinkers of quality beer.
  • Use our own platform to ticket it: Let them experience our product first hand. Turn on mobile ticketing and let them see why our product is different than what they may be accustomed to.
  • Don’t make it seem too much like a recruiting event: We wanted to attract a mixed crowd of people from the tech world, including those that weren’t looking for a job.
  • Reach out to local groups: We got in touch with the local schools (CMU and University of Pittsburgh), contacted various language specific “Meetup” groups, sent personalized emails to a handful of local active github users, and posted on the local subreddit.

The Results

We came up just short of our goal of 50 people but were quite pleased with the turnout. A few of the takeaways from our engibeering event:

  • Informal Speed Interviewing: Having all the candidates in one spot let us conduct informal preliminary interviews and cut out the need for phone screening.
  • Relaxed Atmosphere: Interviews can be intimidating. I can recall at least one horrible interview experience with a larger tech company where I felt so out of my element and flustered that I completely flubbed the interview. Getting some food and a beer or two in your candidates should help them cool the nerves a bit.
  • Turn Around Time: Going the job posting route takes a lot of time (wait for the resumes to trickle in, review, schedule screens, etc.). On that night alone we were able to “screen” many qualified candidates and walk away with several very promising leads.
  • Street Cred: As we had hoped, we got a decent mix of people actively looking for employment, people happily employed in the industry, graduate students, and those that were just curious about ShowClix. As a result, we were able to further promote ShowClix as a contender in the local tech space.
  • A Group Thing: The existing software team had the chance to meet with the candidates and play a part in deciding which candidates we would pursue. This is something that is usually done very late in the interview process or sometimes not even done until the new hire walks in on day one. Getting the gang involved early on was a major benefit.

All in all, we chalked it up as a win. We met a lot of bright, talented locals and found some quality candidates for our job opening. Best of all, the whole team had a ton of fun doing it. I’m hoping that this can become a regular occurrence.

UPDATE We just finished our most competitive round of hiring and we’re happy to announce @tomschlick will be joining the ShowClix team. Pleased with our Engibeering experiment. My only regret is that I couldn’t hire a few more of this round’s candidates. Cheers!

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/1706667/d2ce351ee414282b93dfdb672ce51430.png http://posterous.com/users/3sylfe5BTkZj Nathan Good Nate Nathan Good
Sun, 20 Mar 2011 14:42:42 -0700 TextMate Won't Launch http://blog.nategood.com/textmate-wont-launch http://blog.nategood.com/textmate-wont-launch

My MacBook Pro’s battery died sometime last night whilst I was painfully watching the performance of my Pitt Panthers in the NCAA tournament. This morning when I booted it up again, TextMate would not launch. A quick Google search revealed no help. So I dug around in the ~/Library/Application Support directory to see if TextMate had left some dirty laundry there. Sure enough, a TextMate.pid file existed there. Most of the time when a .pid file exists for an Application that isn’t running, that isn’t a good thing. I deleted it. TextMate now launches.

tl;dr

If TextMate won’t open for you after not shutting down properly:

  1. Go to the ~/Library/Applications Support/TextMate directory
  2. Delete the TextMate.pid file

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/1706667/d2ce351ee414282b93dfdb672ce51430.png http://posterous.com/users/3sylfe5BTkZj Nathan Good Nate Nathan Good
Thu, 10 Mar 2011 21:50:00 -0800 Javascript Prototypal Object Oriented Programming in Practice http://blog.nategood.com/javascript-prototype-object-oriented-programm http://blog.nategood.com/javascript-prototype-object-oriented-programm

I recently wrote a post about my Javascript Prototypal Object Oriented Enlightenment. In that post I discussed how I learned to break my Classical Object Oriented habits and stop forcing Javascript to do something it really wasn’t suited to do. I focused more on my process of transitioning from failed Class-based OO attempts in Javascript to Prototypal Enlightenment and the differences between the two approaches.

I wanted to follow up that post with a post focused on the implementation and use of Prototypal OO in Javascript. We’ll start with the short function that inspired the last post and allows for easier Prototypal OO in Javascript…

function extend(o) {
    function F() {}
    F.prototype = o;
    return new F();
}

With this function we can easily create new objects from existing objects (this is the heart of Prototypal OO Javascript). Let’s see it in practice.

Instantiation: The Prototypal Way

Using this extend method we created, we create a new object nathan, that inherits all of it’s behavior from Person.

// Define a Person as an Object Literal
var Person = {
    name: null,
    sayName: function() {
        alert(this.name);
    }
};
var nathan = extend(Person);
nathan.name = "Nathan";
nathan.sayName();

We’ve just created a nathan object from another object, Person. In classical terms, we would be tempted call Person a “class” and we would call the process of creating nathan instantiation. We are going to stay far away from those terms. Person is a fully functional object itself (this will come in handy when we discuss “static” methods in Prototypal OOP). Secondly, we aren’t so much instantiating nathan from a class as we are cloning it from an existing prototype object.

Inheritance: The Prototypal Way

So we now have an example of Prototypal’s version of “object instantiation”. What about subclassing aka inheritance? In my previous post, I mentioned that in Prototypal OOP inheritance and instantiation are the same thing. Let’s consider this example…

var Animal = {
    kingdom: "Animalia"
};

var Dog = extend(Animal);
Dog.genus = "Canis";
Dog.speak = function() {
    console.log("Bark bark!");
};

var Sparky = extend(Dog);
Sparky.speak();

Notice that the process for creating Dog is the same process we used above for creating sparky. The only exception is that we added some behavior to Dog after we created it from the Animal prototype.

Improving extend

Relying on a single global function extend isn’t a great idea. We can tidy it a bit by tying it into the Object prototype. Object is the object from which all objects are initially “extended” from. If don’t explicitly set an object’s prototype (or implicitly through our extend method), it’s prototype will be Object.

Object.extend = function() {
    function F() {}
    F.prototype = this;
    return new F();
};

var nathan = extend(Person); from our first example,can now be written as var nathan = Person.extend();.

// Define a Person by extending Object
var Person = Object.extend()
Person.name = "John Doe";
Person.sayName = function() {
    console.log();
};

var nathan = Person.extend();
nathan.name = "Nathan";
nathan.sayName();

Another note: you may be tempted to add this to add this method to Object.prototype but beware! Extending native types can get you in trouble, in particular when using objects as dictionaries.

Now our code is a bit more OO and a bit more readable. Also, Object serves as a namespace for our method, adding additional encapsulation.

Improving extend for “Inheritance”

You’ll notice that in our Animal/Dog example, creating Dog was still a multi-step process. We extended Animal and then added behavior with a sequence of assignments. We can improve this process by modifying our extend function to take an optional object parameter that defines the before unique to our new class (in this case Dog).

Object.extend = function (def) {
    var F = function() {};
    F.prototype = this;
    return typeof def == "object" ? $.extend(true, new F(), def); : new F();
};

Note: This snippet uses the jQuery extend method which merges two objects into a new object. You can certainly get away with writing this functionality yourself if you don’t want to include jQuery.

Our definition for Dog now looks something like this:

var Animal = Object.extend({
    kingdom: "Animalia"
});

var Dog = Animal.extend({
    genus: "Canis",
    speak: function() {
        console.log("Bark bark!");
    }
});

var Sparky = Dog.extend();
Sparky.speak();

Now we can extend and add behavior in one single step. We are now left with a clean, readable way to accomplish both “instantiation ” and “inheritance” in one single step.

This last version of the extend method is closest to the one I’m currently using. I have a short boot.js file that contains this function as well as a few other helper methods that I commonly use. Another one of the methods included in this boot.js file is one that I use to easy support mixins in javascript. I’ll be following up with a post on Mixins in Javascript and how to accomplish “static methods” in Javascript over the next week or so.

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/1706667/d2ce351ee414282b93dfdb672ce51430.png http://posterous.com/users/3sylfe5BTkZj Nathan Good Nate Nathan Good
Wed, 09 Mar 2011 07:22:00 -0800 Redis CLI Select Port and Host http://blog.nategood.com/redis-cli-select-port-and-host http://blog.nategood.com/redis-cli-select-port-and-host

This wasn’t immediately obvious to me from any READMEs or docs I looked at (although it’s rather standard convention in hindsight): you can change the port and host on for the redis-cli tool via -p and -h

./redis-cli -p 8989 -h 127.0.0.1

Verify with a ping…

redis> ping 
PONG 
redis>

Hopefully this saves someone a few hairs on their head or a few google searches.

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/1706667/d2ce351ee414282b93dfdb672ce51430.png http://posterous.com/users/3sylfe5BTkZj Nathan Good Nate Nathan Good
Sun, 06 Mar 2011 10:13:00 -0800 Finally Grasping Prototypal Object Oriented Programming in Javascript http://blog.nategood.com/finally-grasping-prototypical-object-oriented http://blog.nategood.com/finally-grasping-prototypical-object-oriented

Javascript and I have had a long love/hate relationship that dates back to my middle school days of hacking “DHTML” websites. One thing in particular that always bothered me was Javascript’s Object Oriented programming.

Most “Intro to Object Oriented Programming for Javascript” examples go a lot like this…

// Define a new "class"
function Person(name)  {
    this.name = name;
}

// And then we add some instance methods...
Person.prototype.sayMyName = function() {
    alert(this.name);
};

// And maybe another instance variable...
Person.prototype.age = -1.0/0.0; // forever young

// Instantiate
var nathan = new Person("Nathan Good");

How could they get it so wrong?! Why was the “class” a single function? Why was the class defined by several statements scattered around? Where was the encapsulation? How could I define my static methods? It just seemed wrong and ugly.

Unsatisfied with this approach, I ended up trying to find clever and cleaner solutions for OO programming in Javascript. I loved object literals. They were so simple and clean. I thought those had to be the answer. While object literals were definitely on the right track, my approach was still far from pretty…

// Futile attempt at "cleaning up" class definitions
var Person = function(name) {
    this.name = name;
};
Person.prototype = {
    age: -1.0/0.0,
    sayMyName : function() {
        alert(this.name);
    }
};
var nathan = new Person("Nathan Good");

And even worse…

// Another futile, "clever" solution
(Person = function(name) {
    this.name = name;
}).prototype = {
    age: -1.0/0.0,
    sayMyName : function() {
        alert(this.name);
    }
};
var nathan = new Person("Nathan Good");

Though these solutions were a little more encapsulated, these clever hacks still felt wrong. This was so not OO. So not Java.

And that was just it. Despite the name, Javascript is so not Java. Not even close.

Enlightenment

I knew Javascript was “prototype” based object oriented programming and I thought I knew what that meant… until I came across this snippet of Javascript from Douglas Crawford, the author of an awesome book call “Javascript: The Good Parts”:

function extend(o) {
    function F() {}
    F.prototype = o;
    return new F();
}

Note: His initial definition used the name object, I think extend is more readable. I’m going to go Tarantino on you and jump back a little bit before explaining why this code is so eye opening.

Ditching the Dichotomy

As victims, er, I mean students of Java school and class-based object orientation teachings, we learn the dichotomy of object orientation: there are classes and then there are instances. A class defines the structure of how objects should look/behave. Instances are the examples made from those classes. Classes serve as the blueprint. Instances are the house built from the blueprints.

In Javascript’s Prototypal OOP, there is no separation. There are just objects. Now what could be more OO than that? Each new object is cloned (sort of) from an existing Object. We can then optionally transform that newly created object to make it suit our needs. This pattern of building from a prototype goes both for (in class-based terms) creating “new instances” AND creating “new subclasses”. Let’s think about that one for a bit.

In class-based object oriented programming inheritance and instantiation feel like two very different things. When defining a sub class, we are creating a new class that inherits attributes/behavior from its parent class and then tweaking it to suit that particular subclass' needs. To continue the analogy from before, we’re making a photocopy of our blueprints and tweaking them a bit. When instantiating that class, we make a new instance of that subclass and define that instance by setting its attributes or via getter/setter methods (barf).

In Prototypal OO, the act of “inheritance” and “instantiation” feel like the same process. There is no notion of a “class”. There are just objects. Person is an object. nathan, an example of a person, is an object that inherited its behavior from Person. Unlike in classic OOP where Person would be considered a class and nathan considered a class instance, Person and nathan are both objects on the same playing field.

Okay, you may be thinking, what in the hell are you talking about? No classes? Let’s jump to some examples.

Back to the Code, Sort of…

Originally here is where I intended to break down that short 3 line function that makes Prototypal OO Programming so much more streamlined. However, in the interest of staying on topic and teaching the Prototypal approach, I’m going to save that break down for another post or let you read more about it from Crawford.

Instead let’s focus on how we’ll use this short extend function to achieve Prototypal OO Bliss.

// Define a Person as an Object Literal
var Person = {
    name: null,
    sayMyName: function() {
        alert(this.name);
    }
};
var nathan = extend(Person);
nathan.name = "Nathan";

Whoa! Where is the new? Why aren’t I using .prototype? Well you kind of are, but they are now behind the scenes and they are there for good reason. Our focus here is to create a new object, nathan, that inherits all of its behavior from an existing prototype object, Person. That’s exactly what we’ve done here. Person is still an object. It is defined with our nice clean object literal syntax. By extending the Person object, nathan now has all of the characteristics of a Person. What’s even cooler is that I can add things/attributes/methods to nathan now that may not be common of all Persons! But thats for another post…

This seems weird…

If you learned OO the Java way, it should seem weird. When learning OOP, we always use real world examples. Physical things. Like people or animals. From that point on, the dichotomy is born. There are classes, typically abstract concepts like “Person”, that define structure and then there are living, breathing instances of those classes, like “Nathan Good”. When we’re setup with that mentality, Prototypal OO does not make sense. “A Person should be a class not an object!?!” you might think. That’s because we’ve coupled “object” to mean “physically existing” and “class” to mean “blueprint”. There is no need for this separation. If you are like me, it may take you a while to break that coupling.

Wrap up and Future Work

In reality the Prototypal OO approach makes OO programming much simpler and flexible. In later posts I’ll discuss how it removes the need for “static” methods and attributes, how we can handle “inheritance” with it, how it allows for the extremely popular “mixin” language feature, how we can achieve namespacing and how it easily allows for “one-offs”. I’ll also touch on my version of the three line function that makes all of this possible and how I’m now regularly using it. In the mean time, I’ll leave you with a snippet to whet your appetite that uses my prototypal OO helper functions.

I hope that, if nothing else, this has opened your eyes a bit to what “Prototypal Object Oriented Programming” really is. Hopefully I’ve even persuaded you to use this approach for your next big Javascript project.

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/1706667/d2ce351ee414282b93dfdb672ce51430.png http://posterous.com/users/3sylfe5BTkZj Nathan Good Nate Nathan Good
Fri, 05 Nov 2010 17:24:00 -0700 Installing Mongo PHP Client on Debian http://blog.nategood.com/installing-mongo-php-client-on-debian http://blog.nategood.com/installing-mongo-php-client-on-debian

We recently started using MongoDB for part of our new Admin project at ShowClix. Mongo provides a compiled PHP extension for their PHP client.

Installing the extension on my local OS X dev machine was a piece of cake. Installing the extension on our Debian production servers was a pain in the ass. To prevent others trying from having to pull their hair out, I decided to throw this up here. As a side note, this looks like this is the case for ANY compiled PECL extension on Debian.

If you haven't installed it already, you'll need to install the php5-dev package.

apt-get install php5-dev

Next, grab the tar ball from the downloads Mongo provides on their github account (you'll want to use the most up-to-date tarball).

wget --no-check-certificate https://github.com/mongodb/mongo-php-driver/tarball/1.0.10 
tar -xzf mongodb-mongo-php-driver-1.0.10-0-g7ac74f1.tar.gz 
cd mongodb-mongo-php-driver-8153548/

Here's where we should be able to just run phpize and compile the extension. However, doing this may yield something along the lines of...

$ phpize 
Configuring for: 
PHP Api Version: 20041225 
Zend Module Api No: 20060613 
Zend Extension Api No: 220060519 
cp: cannot stat `libtool.m4': No such file or directory 
cp: cannot stat `ltmain.sh': No such file or directory 
cat: ./build/libtool.m4: No such file or directory 
configure.in:3: warning: prefer named diversions configure.in:8: warning: LT_AC_PROG_SED is m4_require'd but not m4_defun'd 
aclocal.m4:2619: PHP_CONFIG_NICE is expanded from... 
configure.in:8: the top level 
configure.in:74: error: possibly undefined macro: AC_PROG_LIBTOOL 
 If this token and others are legitimate, please use m4_pattern_allow. 
 See the Autoconf documentation. 
configure:2275: error: possibly undefined macro: LT_AC_PROG_SED

Turns out Debian has some broken symlinks and phpize needs a few additional files. To fix this we can correct the symlinks and concatenate a few required files together. You'll likely need to su/sudo here.

rm /usr/lib/php5/build/ltmain.sh 
ln -s /usr/share/libtool/config/ltmain.sh /usr/lib/php5/build/ltmain.sh 

rm /usr/lib/php5/build/libtool.m4 
ln -s /usr/share/aclocal/libtool.m4 /usr/lib/php5/build/libtool.m4 

cd /usr/share/aclocal 
cat lt~obsolete.m4 ltoptions.m4 ltsugar.m4 ltversion.m4 >> libtool.m4

This should fix our problems. Now run...

phpize 
./configure 
sudo make install

This should now place the mongo.so in you default extensions dir which on Debian will probably be something like...

/usr/lib/php5/20060613+lfs/mongo.so

The last thing to do is add the extension to your php.ini file, or if you're following Debian convention, dropping a mongo.ini file with the extension in conf.d dir

# /etc/php5/conf.d/mongo.ini 
extension=mongo.so

You can also drop a few other directives here.

Now you should be ready to start using the Mongo client for PHP.

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/1706667/d2ce351ee414282b93dfdb672ce51430.png http://posterous.com/users/3sylfe5BTkZj Nathan Good Nate Nathan Good
Fri, 22 Oct 2010 01:44:00 -0700 RESTful Intro http://blog.nategood.com/restful-intro http://blog.nategood.com/restful-intro

Wrote this a while back as a brief intro to REST for the ShowClix API. Figured I'd share here as well.

A Brief, High-Level REST Introduction

A RESTful Web Service can be thought of as just Nouns and Verbs, or in more RESTful terms, Resources and Operations. A RESTful Service has a group of things (aka Nouns, aka Resources) that we can do stuff to (aka we can apply Operations to these things/Resources). Pretty simple idea. These Resources and Operations have a few general principles:

Resources:

Uniform Resource Identifiers (URIs)

Resources must be universally identifiable through what is typically called a URI. If the Resources/Nouns we were talking about were people, we could consider Social Security Number as the URI for our Resources (assuming the people were US Citizens and SSNs were actually unique). Given a URI, I should be able to determine exactly what Resource is being referred to. When talking about RESTful Web Services, URIs are almost always in the form of the familiar URL. An example URI might be https://www.example.com/post/123 to represent a single blog post.

Representations

Resources in RESTful Web Services are exchanged as representations. When requesting a Resource in a RESTful Service, the client does not get a physical copy of that Resource. Instead, the client would receive a representation describing that Resource. In RESTful Web Services, this representation is text describing the resource, structured in the form of XML, JSON, YAML, RSS, Atom, etc..

Operations

Uniform Interface

Resources don't do us any good unless we can do things with them. In the RESTful style of things, what we can do is limited to a defined set of operations that can be performed to all Resources. This is commonly referred to as the uniform interface. Going back to the Noun/Verb analogy, our vocabulary only contains a certain amount of verbs that were applicable to all Nouns. In RESTful Web Services, this uniform interface is almost always HTTP. HTTP defines four main operations: GET (retrieving data), PUT (editing data), POST (creating data), DELETE (removing data). These are the only operations that can be applied to a Resource. There are several other methods as part of the HTTP spec, most notably HEAD and TRACE, but we'll stick with the main four for now.

RESTful Architectures follow the Client/Server design pattern. This means that the client machine initiates all requests to a server machine that handles client's request. The server then sends a response to the client once it has processed the request. In standard HTTP, the server does not initiate any requests.

RESTful Architectures have a few other principles and perks (cachability, hyperlinking, statelessness, inherent scalability...) but this covers the main ideas. To recap, in a RESTful Web Service, a client makes a request to a server to perform an operation on resource that is identified by a URI.

If you're really interested in learning REST the right way (REST is a very abused term), check out the following:

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/1706667/d2ce351ee414282b93dfdb672ce51430.png http://posterous.com/users/3sylfe5BTkZj Nathan Good Nate Nathan Good
Sun, 20 Jun 2010 18:22:00 -0700 Client Side Certificate Auth in Nginx http://blog.nategood.com/client-side-certificate-authentication-in-ngi http://blog.nategood.com/client-side-certificate-authentication-in-ngi

Why Client-Side Certificate Authentication? Why nginx?

I sometimes peruse the ReST questions of stackoverflow.com. Many times I see questions about authentication. There are many options (Basic HTTP Auth, Digest HTTP Auth, OAuth, OAuth Wrap, etc.) however when security is of importance, I like to recommend client side certificates. This is the route our team at ShowClix chose when implementing our API.

When first implementing the API Authentication, we were using Apache for our ReST API Servers. It took some serious google-fu and tinkering to get Apache cooperating with the client-side certs and passing that info into our PHP App layer. I remember it being a semi-painful process.

Lately, I've become a huge fan of nginx. Its clean, familiar config syntax and speed make it a great alternative for Apache in many cases. Its reverse proxy capabilities are quite nice as well. So, I thought I'd give client-side cert authentication a shot in nginx. Whereas a quick search for "Client Side Certs in Apache" yielded a few relevant results, a similar search for nginx yielded no results, so I figured I'd share here.

I ran this on a small 256MB Rackspace cloudserver instance running Arch Linux, nginx 0.7.65, PHP 5.3.2 and PHP FPM.

Creating and Signing Your Certs

This is SSL, so you'll need an cert-key pair for you/the server, the api users/the client and a CA pair. You will be the CA in this case (usually a role played by VeriSign, thawte, GoDaddy, etc.), signing your client's certs. There are plenty of tutorials out there on creating and signing certificates, so I'll leave the details on this to someone else and just quickly show a sample here to give a complete tutorial. NOTE: This is just a quick sample of creating certs and not intended for production.

# Create the CA Key and Certificate for signing Client Certs
openssl genrsa -des3 -out ca.key 4096
openssl req -new -x509 -days 365 -key ca.key -out ca.crt

# Create the Server Key, CSR, and Certificate
openssl genrsa -des3 -out server.key 1024
openssl req -new -key server.key -out server.csr

# We're self signing our own server cert here.  This is a no-no in production.
openssl x509 -req -days 365 -in server.csr -CA ca.crt -CAkey ca.key -set_serial 01 -out server.crt

# Create the Client Key and CSR
openssl genrsa -des3 -out client.key 1024
openssl req -new -key client.key -out client.csr

# Sign the client certificate with our CA cert.  Unlike signing our own server cert, this is what we want to do.
openssl x509 -req -days 365 -in client.csr -CA ca.crt -CAkey ca.key -set_serial 01 -out client.crt

Configuring nginx

server {
    listen        443;
    ssl on;
    server_name example.com;

    ssl_certificate      /etc/nginx/certs/server.crt;
    ssl_certificate_key  /etc/nginx/certs/server.key;
    ssl_client_certificate /etc/nginx/certs/ca.crt;
    ssl_verify_client optional;

    location / {
        root           /var/www/example.com/html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_param  SCRIPT_FILENAME /var/www/example.com/lib/Request.class.php;
        fastcgi_param  VERIFIED $ssl_client_verify;
        fastcgi_param  DN $ssl_client_s_dn;
        include        fastcgi_params;
    }
}

The main things to note here are...

  • We specify our the server's certificate (server.crt) and private key (server.key)
  • We specify the CA cert that we used to sign our client certificates (ca.crt)
  • We set the ssl_verify_client to optional. This tells nginx to attempt to verify to SSL certificate if provided. My API allows both authenticated and unauthenticated requests, however if you only want to allow authenticated requests, you can go ahead and set this value to on.
  • Lastly, you'll notice that I add a location directive that routes all the requests to a single PHP script. You can handle this differently (and technically don't even need to use PHP as there are other fast cgi options)

Passing to PHP

There are several options for running PHP from nginx. I chose to use PHP FPM, however these steps should also work for any of the fast cgi options in theory. You'll notice I added a few additional fastcgi_params to the usual fastcgi_params.

First, we pass in the $ssl_client_verify variable as the VERIFIED parameter. This is useful when we are allowing authenticated and unauthenticated requests. When the client certificate was able to be verified against our CA cert, this will have the value of SUCCESS. Otherwise, the value will be NONE.

Second, you'll notice we pass the $ssl_client_s_dn variable to the DN parameter. This will provide "the line subject DN of client certificate for established SSL-connection". The Common Name part of this certificate may be of most interest for you. Here is an example value for DN...

/C=US/ST=Florida/L=Orlando/O=CLIENT NAME/CN=CLIENT NAME

Nginx also provides the option to pass in the entire client certificate via $ssl_client_cert or $ssl_client_cert_raw. For more details on the SSL options available to you in nginx, checkout the Nginx Http SSL Module Wiki.

Consuming the ReST Service

So, we've created our certs, signed our client certs, installed nginx and PHP, and setup nginx verify the certs and finally pass along client cert details. Now we are ready to consume our ReSTful service.

There are lots of tools out there for consuming true HTTP based ReSTful services. Some of them are prettier than others, but I prefer the good old cli version of cURL.

NOTE: This is run from your client computer. Make certain that you have scpd your client.key and client.crt files from your server onto your client machine that is making the requests. You'll also be prompted for the pass phrase you used when you first created the client cert. There are ways to remove the need for pass phrases. Also, you don't need the verbose flag (-v) or silent flags (-s). We're using the -k flag here because we used a self-signed cert for the server.

curl -v -s -k --key client.key --cert client.crt https://example.com

Source code is also available on git hub.

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/1706667/d2ce351ee414282b93dfdb672ce51430.png http://posterous.com/users/3sylfe5BTkZj Nathan Good Nate Nathan Good
Sun, 31 Jan 2010 11:18:00 -0800 Hello World http://blog.nategood.com/hello-world-2480 http://blog.nategood.com/hello-world-2480

I've finally given in.  I've joined the blogosphere.  As a young software engineer growing up in this age of social media/web 2.0/or is that 3.0/<insert cliché buzzword here>, I suppose it is my duty to have an online repository for my two cents.  Don't expect anything riveting, thought provoking, or awe inspiring.  This will most likely be a place for me to write about the mistakes I make as a maturing developer, interesting tid bits I come across, thoughts on the status quo of the interwebs, and maybe a little about the work going on at ShowClix from the developer's desk.

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/1706667/d2ce351ee414282b93dfdb672ce51430.png http://posterous.com/users/3sylfe5BTkZj Nathan Good Nate Nathan Good