Using regex to strip specific html tags using JavaScript


A few weeks back I had to tackle a problem. I’ve been working on a set of JavaScript based eBook readers with not a few constraints involved because of the target market. One of the features I needed to implement was the ability to highlight text using various colors. Sure, this wasn’t a big deal but I had a nightmare because the output wasn’t coming out as expected.

Here’s what I was getting:

Screen Shot 2015-10-13 at 14.41.42

as opposed to this:

Screen Shot 2015-10-13 at 14.42.53

And where was the problem? In the HTML that contained the contents of the page. We have a process in-house that does some nifty stuff and converts our PDF files to HTML, thus, helping us retain paging, number of words per line and lines per page.

What this process does is not so important as its output. Here’s the html that generated the “skippy” highlights:

Screen Shot 2015-10-13 at 14.44.44

Notice how each word on the highlighted line is wrapped by a “span” tag? That’s the issue! The highlight code, in trying not to interfere with the page’s markup just picks words inside tags and wraps them with a tag and adds a custom highlight css class.

Here’s the markup that would generate the “smooth” highlight:

Screen Shot 2015-10-13 at 14.45.43

See the difference?

So, after months of ignoring the problem and reporting to management that it’s a small issue, I finally came around to fixing it and solved it with quite a few lines of CoffeeScript code:

Here’s the JavaScript equivalent:

And voila! My headache was solved! Looks easy but I had to scour StackOverflow for this and I just thought I’d save myself the headache of looking for this all over again at a later time.

Generating Amazon S3 file upload Policy in Node.js


I recently (by recently, I mean two days ago) had to upload files – images to be precise – to a newly created Amazon S3 bucket. After going through a few documents online and following instructions (at least, I think I did), I had my environment (MEAN – MongoDb, Express, AngularJS and Node.js) setup for the upload.

On trying the upload, Amazon returned an error telling me the policy I was using was not the same as that which they generated. Apparently, I did something wrong somewhere so I sought to right my wrong. I found a valuable script on github (though for the life of me, I can’t seem to remember the name of the project) and here’s what I distilled it down to:

To use this, I just issue a  GET  request of the form:  http://localhost:3000/s3_policy?subFolder=folder_name&mimeType=image/png

Creating Base64 Encoded String from an Image in Node.js


I’ve been writing a lot of MEAN (MongoDb, Express, AngularJS and Express) code lately and the latest in the series of hurdles I’ve been able to cross of recent has been generating the Base64 encoded version of an image file.

I had just added a new endpoint to an API I was working on and it included photos of users. For the web app, I was happy to just get the url of the photo and have the browser request it when needed but the API consumers (Android and iOS mobile devs) thought differently. The wanted to have the image as a base64 encoded string and so I reached out to Google.

Using this StackOverflow question and answer as my base, this is the function I eventually arrived at:

It should be noted that there are a few differences between my solution and that on StackOverflow.

  • First, I’ve created a function which expects a callback.
  • Secondly, line 6 makes use of  http.request  instead of  http.createClient  and  client.request . This is because  http.createClient  has been deprecated in my version of Express (4.0.0)

Handling Web Application Authentication with AngularJS


Last Friday, I published a post about how I fused the jQuery plugin (Select2) and AngularJS. If you’ve not read it, click here to do so.

Today, I’m inclined to share details of how I conquered (maybe not completely but enough to solve my problems) a problem that confronts most rookie AngularJS developers: HOW TO HANDLE USER AUTHENTICATION. When we build web applications, it’s almost often certain that a form of user authentication would be needed and the traditional model of Web Application design and construction supported this because there was a simple mechanism called “page reloads” which ensures that identities are re-validated and sessions are maintained before or during the service of a request.

Using a client-side technology like AngularJS, this mechanism isn’t built into the library (as at the time of this writing) and so many developers – not unlike myself – wander into this wilderness without a guide. I inquired and scoured the web for many weeks before gaining confidence in the amount of resources that I had in order to make this possible.

Enough of the story now! First thing I realized was that I needed to have a rest API for my AngularJS application to talk with and it was also logical for this API/back-end to handle the authentication of all requests. For my API (and being first a PHP developer before Java, Python, etc), I went with an exciting framework I just discovered about 4 months ago – PhalconPHP. I picked up a GitHub project (Phalcon-Rest) which, by the way, is also pretty exciting in itself.

The Phalcon-Rest README describes the project as follows:

The purpose of this project is to establish a base project with Phalcon that uses the best practices from the Phalcon Framework to implement best practices of API Design.

Writing routes that respond with JSON is easy in any of the major frameworks. What I’ve done here is to go beyond that and extend the framework such that APIs written using this project are pragmatically REST-ish and have convenience methods and patterns implemented that are more than a simple ‘echo json_encode($array);’.

After modifying Phalcon-Rest to be able to competently authenticate requests using a custom HTTP-HEADER set in all requests, I then focused on handling the AngularJS side of things.

First I created an ‘AuthService’ which handles basic user login.

BE WARNED: Most of the code in this post is in CoffeeScript!

December 22 Update: By popular demand, I’ve put up the JavaScript Equivalent for the code in this post on github. Check out the gist here.

At first glance, you’d see a dependency on ‘Session’ and ‘AuthToken’. Basically, Session is a service that I use to (as the name implies) save and retrieve application state on the Client side using HTML5’s SessionStorage so that it’s destroyed when the browser is closed. AuthToken however, I use to save the API request token in localStorage.

The definitions for these Singletons follow:

Obviously this code doesn’t do much by itself. You’d need to create an AngularJS powered login form and attach to it a Controller that depends on AuthService. You can then call the login method once, the form is submitted.

But all of this is just one leg of it all. You still need to check the state of the application for certain routes (when a user navigates to a certain route and maybe reloads the page, how do you handle authentication/identity management then?).

For this, I use ngRoute and in defining my routes, I specify which routes need authentication and which ones do not using the “access” property.

Then in my “run” section, I subscribe to ngRoute’s $routeChangeStart event.

When a request is caught and the user is not authenticated, you can then redirect the user to a login page or if you don’t want them to lose their progress, just show a login modal.

A final step I took was to intercept all $http requests (which were not login requests) and transform the request header to include the API key we now have in localStorage. Here’s the code for my interceptor:

You can then attach this Interceptor to $httpProvider:

That’s it. You should be home and dry now. If you have any questions, please feel free to use the comments section.

I’ve also put all this code into a module and published it as a gist. Click here to view CoffeeScript module.

December 22 Update: JavaScript module now available here.