Authentication And Login Popup Window Handling For Social Media APIs [code example]

Authentication And Login Popup Window Handling For Social Media APIs [code example]

Reading Time: 12 minutes

This post will show how to handle user login to different social medias (for now the example is for Spotify Web API, but the idea is the same for most of the apps).
So lets say you are building great Gallery App using the Instagram API, or maybe an awesome music player with Spotify API features, and you want to grab information about user’s profile/images/playlists or whatever. you want to make user’s life easiest as you can UX-wise, and one of the annoying things user faces with web applications is logging in every single time he wants to refresh / open browser / etc. What I’m going to show is first how to handle the login popup and second how to store the key that gives the user the ability to stay logged in even after refreshing browser or restarting computer or whatever action that will require re-login.

So first thing you want to do is to create an app in the Spotify Developers console, create an account and add a new app. you need to grab your client id for running the example.

check out the code on github

If you want to run the code locally you are more than welcome to grab the code from the github repository above, play with it, ruin it, make it better 🙂

I use here regular jQuery lib and it is probably written not the best way you can think of, but we are not building here a real scalable web app. You can easily transform this code into a React component, or Angular directive or whatever.

The structure is very straight forward, we have entry point of index.html which includes index.js, we also have callback_spotify.html with respectively callback_spotify.js file. The callback should be added into you application configuration page in the spotify developers page as in the image:

(sorry image was deleted from old server, if you have troubles please contact me)

This callback URL is the URL Spotify redirects to after login and app approval has been made by the user, the redirect is made with addition of token parameter after hash, so the redirect URL ends up looking something like this: http://localhost:3001/callback_spotify.html#access_token=SOME_VERY_LONG_HASHED_STRING&token_type=Bearer&expires_in=3600 

This is what we get from Spotify and the access_token is what we basically need, this is the key that keeps our client logged in and get his information for our app. This key is private, so keep it in a safe place if you want your app to be secure, we will keep it on the clients end, on the user’s browser local storage.

So lets do some code:

So here we have very basic HTML file and the interesting parts are the div’s with the “spotify-login-form” and “spotify-details” classes, we are going to toggle them and show them based on the user’s login state, logged in or not. One of the divs has only login button and the other (where we later throw user data) has only logout button.


Here is where magic begins.
First, as I said earlier, we are going to store the auth token we get from Spotify in the user’s browser’s local storage. So the first check is if we have this token, and if true we are invoking the setSpotifyDetailsfunction that get as a parameter the token string (we are going to look at that function later, but for now lets say that it toggles the div that show info of user that is logged in).

Next we are setting an event listener to the click action of the login button. When user wants to log in and clicks the button handleSpotifyConnect function is invoked, lets jump straight to the function’s code. The first thing we do in the function is declaring some constants that we need in order to create the connect window’s URL . Notice that you should replace SPOTIFY_CLIENT_ID =YOUR_CLIENT_ID with your own id that you got from the Spotify Developer Console, and the redirect URL should be the same as we entered to the Spotify Developers Console earlier, as for response type, leave it ‘token’, it tells Spotify that in the response to our request they should pass the token to our callback.

Next thing is the assembling of the URL, nothing special here, we just concatenating the constants we declared earlier. Then we are opening a window with the URL we just created (notice that we are assigning the window to the w variable, this is very important so we have the window reference on our side, this is how we handle messaging between windows) and finally we set the event listener to message we have to get back from the window, this message will pass the token that Spotify gave us back to the callback URL (we are going to see the code for the callback URL handler in a moment).

We take the token string and invoke inner function called callback which is doing 2 things, first set the token to the local storage so when user next time refreshes the page we can pull it from there and we won’t have to re-authenticate him every single time page refreshed, and second we invoke the function handleSpotifyConnect we talked about earlier. This function makes a call to the Spotify api, with the token which ensures that the user is authenticated and we have permission to get his data, and we get back users data, we hide the login form and show the user’s username (could be any data we have permission to grab, not only the username) and logout button.

The logout button does 3 simple things, first removes the token from local storage, second removes user data from screen, third show again the login form (button) so the user can re-login.


In this file the only important thing is the include of the callback_spotify.js file we will talk about in a moment, other than that it only shows “loading…” string you can replace with a fancy loader or something.


So here we are first declaring the host url string that we are sending message to, and declaring the hash empty object in which we are going to hold the token key we receive from Spotify. Next there’s a function that take the windows location string after the hash sign and assigns it to the hash object, so lets say the locations string is “http://localhost:3001/spotify_callback.html#token=BLAH” we get and object looks like hash = { token: “BLAH” }. Then we check if the access_token exists in this object and if true we are posting it as a message to the window of the login form index.html and close the current window. You can read about the window messaging here, very very useful and good to know thing there, especially the security concerns.

That’s it, we are now logged in and very very happy 🙂

React Hot Loader – With Stateless components (webpack) [Code Example]

React Hot Loader – With Stateless components (webpack) [Code Example]

Reading Time: 2 minutes

Everybody knows React or at least heard of it, if not it is never too late. I saw a great tutorial by Robin Wieruch The SoundCloud Client in React + Redux which takes you, step by step, making a cool SoundCloud app from scratch. You need some basic knowledge if you want to follow the tutorial, but is it really basic stuff you can get in the video tutorials around the web.

check out the code on github

The issue I faced was with step 6: “First React Component” where you want the react-hot-loader automatically refresh the changes you make on your files. RHL is not compatible yet with stateless functions components so the recommendations around the web was to use the beta of version 3 which gives you some boilerplate, I struggled to get it work but finally managed to get the configuration to make it work as expected.

What did I do:


  "name": "favesound-project",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server --progress --colors --hot --config ./webpack.config.js"
  "devDependencies": {
    "babel-core": "^6.0.20",
    "babel-loader": "^6.0.1",
    "babel-preset-es2015": "^6.0.15",
    "babel-preset-react": "^6.0.15",
    "babel-preset-stage-0": "^6.0.15",
    "chai": "^3.5.0",
    "enzyme": "^2.3.0",
    "exports-loader": "^0.6.3",
    "imports-loader": "^0.6.5",
    "jsdom": "^9.2.1",
    "mocha": "^2.5.3",
    "react-addons-test-utils": "^15.1.0",
    "react-hot-loader": "^3.0.0-beta.0",
    "webpack": "^1.12.2",
    "webpack-dev-server": "^1.12.1"
  "dependencies": {
    "react": "^15.1.0",
    "react-dom": "^15.1.0",
    "react-redux": "^4.4.5",
    "react-router": "^2.4.1",
    "react-router-redux": "^4.0.5",
    "redux": "^3.5.2",
    "redux-logger": "^2.6.1",
    "redux-thunk": "^2.1.0",
    "soundcloud": "^3.1.2",
    "whatwg-fetch": "^1.0.0"
  "author": "",
  "license": "ISC",
  "keywords": [],
  "description": ""



<pre class="javascript">const webpack = require('webpack');
module.exports = {
    entry: [
    module: {
        loaders: [{
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loaders: ['babel']
    resolve: {
        extensions: ['', '.js', '.jsx']
    output: {
        path: __dirname + '/dist',
        publicPath: '/',
        filename: 'bundle.js'
    devServer: {
        contentBase: './dist',
        hot: true


<pre class="json">{
  "presets": ["es2015", "stage-0", "react"],
  "plugins": ["react-hot-loader/babel"]

index.js – the app should be surrounded by the AppContainer element

<pre>import { AppContainer } from 'react-hot-loader'; // required
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

const rootEl = document.getElementById('app');

 &lt;App /&gt;

if (module.hot) {
 module.hot.accept('./App', () =&gt; {

 const NextApp = require('./App').default;

 &lt;NextApp /&gt;


<pre>import React, { Component } from 'react';
import Stream from './components/Stream';

const tracks = [
 title: 'Some track 11'
 title: 'Some other track 22'

export default class App extends Component {
 render() {
 return (
 <Stream tracks={tracks}/>

and last file is the component that represented by stateless function Stream.js

<pre>import React from 'react';

function Stream({ tracks = [] }) {
 return (
 tracks.map((track, key) => {
 return <div className="track" key={key}>{track.title}</div>;

export default Stream;</pre>

You can find the full code example in my github project, just clone it and “npm install” it :).

VBS extract a zip out of url [Code Example]

VBS extract a zip out of url [Code Example]

Reading Time: 1 minute

Never thought I would touch any kind of Microsoft languages, but I had to develop some solution that included creating a file for MS Windows that eventually will get input in form of URL of a zip file (that is also automatically generated by some PHP server code – not on this post’s scope) and the output is unzipping the zip file’s contents to a certain location.

Set objNetwork = CreateObject("Wscript.Network")
loc = "C:\Users\" &amp; objNetwork.UserName &amp; "\WHATEVER_DIR_YOU_WANT"
' Set oShell = CreateObject("WScript.Shell")
' strHomeFolder = oShell.ExpandEnvironmentStrings("%USERPROFILE%")
' loc = strHomeFolder &amp; "\WHATEVER_DIR_YOU_WANT"
' -----------------------------------------------------------------
HTTPDownload "{{file_name}}", loc
' -----------------------------------------------------------------
ZipFile = loc &amp; "\{{file_name}}"
ExtractTo = loc
Set fso = CreateObject("Scripting.FileSystemObject")
If NOT fso.FolderExists(ExtractTo) Then
End If
set objShell = CreateObject("Shell.Application")
set FilesInZip = objShell.NameSpace(ZipFile).items
Set fso = Nothing
Set objShell = Nothing
DeleteAFile loc &amp; "\{{file_name}}"
WScript.Echo "Zip successfully unzipped."
' ------------------------------------------------------------------
' --------------------- SUBS I USED WITH CREDITS -------------------
Sub HTTPDownload( myURL, myPath )
    Dim i, objFile, objFSO, objHTTP, strFile, strMsg
    Const ForReading = 1, ForWriting = 2, ForAppending = 8
    Set objFSO = CreateObject( "Scripting.FileSystemObject" )
    If objFSO.FolderExists( myPath ) Then
        strFile = objFSO.BuildPath( myPath, Mid( myURL, InStrRev( myURL, "/" ) + 1 ) )
    ElseIf objFSO.FolderExists( Left( myPath, InStrRev( myPath, "\" ) - 1 ) ) Then
        strFile = myPath
        WScript.Echo "ERROR: Target folder not found."
        Exit Sub
    End If
    Set objFile = objFSO.OpenTextFile( strFile, ForWriting, True )
    Set objHTTP = CreateObject( "WinHttp.WinHttpRequest.5.1" )
    objHTTP.Open "GET", myURL, False
    For i = 1 To LenB( objHTTP.ResponseBody )
        objFile.Write Chr( AscB( MidB( objHTTP.ResponseBody, i, 1 ) ) )
    objFile.Close( )
End Sub
Sub DeleteAFile(filespec)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
End Sub

It looks simple but so useful for making 1 file installer (kinda) with 0 work!


Responsive email template for mobile apps, native mobile apps and outlook

Responsive email template for mobile apps, native mobile apps and outlook

Reading Time: 8 minutes

Email template development is a headache, especially when it comes to optimizing it for all the various devices out there (and by devices, I mean desktop computers, mobile devices, mobile native apps, as well as email apps such as Gmail app). Also we can’t forget Microsoft with the agenda of making the lives of developers miserable (why make their lives easy? Let’s make them sweat to death).

In this blog post, I’ll try to give you some guidelines for making the best email templates, increasing your mail open rate and conversion rate, and some general tips (written with blood) that I gathered along the way. I’m not a content guy, so I won’t talk about how to create good content, or how to raise your email conversion rate by making good content.

tip #1: Use tables

Think like it’s ‘98 all over again. Writing your HTML template with tables is the most bullet proof way to do it today (Outlook’s rendering engine is Microsoft Word’s rendering engine).  That is why you won’t see crazy HTML+CSS templates with animations and cool stuff. You can’t ignore Outlook, unfortunately. The Radicati Group counted 730 million business email inboxes worldwide in 2010, 25% of all email accounts. That was in 2010; today in 2016, the numbers have grown exponentially. Google Apps claims that over five million businesses are using their tools, and that means that the other 725 (again, according to the year of 2010) use Microsoft’s solution (not all of them, but over 90%). Conclusion: we have to use a format that supports Outlook’s rendering engine.

Here are some general tips for writing HTML templates for Outlook:

  • No Background image support
  • No div’s – outlook strangely replace them with paragraphs
  • No position or float (we have some hacks for that – later)
  • Poor support for padding and margin (simple solution for padding for a button – later)
  • No animated GIFs
  • Use old attributes (bgcolor, width, height, valign, align etc) specially with table cells and images
  • As for outlook 2010 read this article by Litmus to get a overall view about rendering and optimizing for outlook
  • All block elements such as H1, P, should become table cells (td’s) or be included inside table cells.
  • Break your email templates into sections and treat them as table cells, for example:

When you get used to it, it is not that difficult to write HTML with tables.

tip #2: Be mobile, be responsive

It is not a secret that we are in a mobile oriented era. People use their cell phones or tablets as the main (or one of their main) work devices. While there was a small drop (1%) in the email open rate, mobile devices still rule the open rates with around 50% – twice the  open rate of desktop users.

Take a look at Email client market share for more information.

The problem is that there are so many mail apps, and each one of them has its own rendering engine. Fortunately, we know how to deal with those restrictions (although we need to use some tricks).

We’ll take the Gmail app for Android for example. Did you know that Gmail for Android strips the <style> tags (especially the tags that are in the HEAD section) out of your email? That is not good news; forget about using media queries.

A great blog post I read about Gmail First Strategy for Responsive Emails will get you through all of steps you need in order to get the perfect responsive email template. Julie Ng’s post helped me to create a great template at work that looked good with the Gmail mobile app as well as Outlook – and believe me, it is not trivial. There are also some good tools she developed to get some automation at work.

tip #3: Be ready, save templates

Too many times I’ve found myself writing the code for pretty much similar templates. Do a list for yourself with screenshots and dummy “Lorem Ipsum” text and save it. It takes time to write those HTML templates, and especially to run tests over all browsers and email clients. I’ve made some mistakes, so you won’t need to make the same ones. Here are 2 templates I wrote and tested over the most popular clients:

  1. 2 columns template
  2. 1 column template

More tips:

  • Follow the CSS rules each email client supports
  • Be mobile and Outlook oriented
  • use the <!– [if mso] > tags for outlook
  • Use ‘align’ attributes instead of ‘float’, specially when working with tables
  • some email clients ignore the cellspacing attribute a
    simply add to the table those styles:
    style=”border-collapse: separate; border-spacing: 10px 50px;
  • See resources attached below








WordPress 301 redirect from Upercase url’s to lowercase

WordPress 301 redirect from Upercase url’s to lowercase

Reading Time: 2 minutes

This is something stupid I had to do when some Google crawl errors occurred on webmaster tools, and I saw some deprecated stuff on the web and had to trick it a little bit.

function isPartUppercase($string) {
  return (bool) preg_match('/[A-Z]/', $string);

add_action('parse_request', 'parseUppercase');

function parseUppercase($wp) {

  $query = $wp-&amp;gt;query_vars;
  $query = $query['pagename'];

    $link = site_url().'/'.strtolower($query);

      $link.= '?'.$_SERVER['QUERY_STRING'];

    wp_redirect( $link , 301 );


Add this snippet to your functions.php file.

So here we use the ‘parse_request’ hook which handles the request for a page from the server and runs when someone makes a request. We add a ‘parseUppercase’ function which gets the $wp global wp variable and gets the name of the page in the request we are converting it to lowercase, and concatenating the query variables (if exist) to the redirected URL with wp_redirect function.

Reflux Sweeper – React, Reflux And ImmutableJS Explained By Example

Reflux Sweeper – React, Reflux And ImmutableJS Explained By Example

Reading Time: 12 minutes

Recently I have been diving into the understanding of managing simple data structure when building simple Mines Sweeper game inspired by the React Sweeper project. I also used Facebook’s ImmutableJS library to manage my data structure. In this blog post I will describe,step by step, how I managed to build this app, and what led me to the decisions I took.

First, I will start with basic background on Flux. If until now we had ReactJS that handled the view, Flux is not a library, it is a concept, or maybe we can call it “data flow architecture on client side”. It is a complement concept that gives us the Model and the communication between UI and Model. The fastest coverage I can give is that the UI talks with the Model with Actions that invoked by UI. The Actions are delivered to the Dispatcher which is responsible to manage the logic of invoking the Actions on the Stores that affect the UI and it goes on and on… that sounds like completely gibberish but when you try to play with some implementations of this Flux concept you get the point pretty fast. Here’s some diagram taken from Flux page to show the flow of the data:


Reflux is a simple library that implements Flux architecture. There are some implementations out there that honestly I haven’t tried (except of Redux), but what makes Reflux special is that it jumps over the concept of the Dispatcher (I will examine Redux in other post) and leaves the flux architecture even simpler to look like this:

First we’ll start with the file-system structure, logic and data structure.

  • The app is sitting under /app directory obviously.
  • App.js contains one single function that renders the app to the DOM with ReactDOM came with version 0.14 of React.
  • Utils.js includes the utillities I use to make two dimensional array or default initialized board etc.
  • Then we have the /assets dir which contains all dependencies and libraries I’m using such as : React, Reflux, Immutable, React-DOM, underscoreJS etc.
  • The source core code is under src and Grunt is compiling my files from ES6 to ES5 so browsers could read it properly.
  • Under /src we have /actions which contains single file Action.js that stores an array of actions (look for points in the end of the post).
  • Under /Components I store all app components (see description of the components below) – for this app: BoardPiece.js, GameBoard.js, ScoreBoard.js.
  • Under the /stores dir we have the 2 stores of the app GameStore.js, BoardStore.js.
  • Under /views dir I store the different views of the app and right now I have only one so we name it RefluxSweeper.js.
  • /public dir includes in /assets sub directory the compiled files, app.js – the application compiled es5 and minified.
  • infrastructure.js – compiled file with all libraries in single file (see concat for grunt).

This part is the least important in my opinion in here and if you want to learn more about it just google “mines sweeper logic” or something and boom you have tons of information and methods. I want to concentrate on the communication between the components using the Flux architecture.

Data Structure && Reflux

2 Main components:

  • ScoreBoard – the configuration part of the app, new game, change level, change board size etc.
  • GameBoard – the board itself which holds all of the board pieces

Both of them need to communicate so when something changed in the GameBoard it affects the ScoreBoard and vice versa, for example right click on the BoardPiece will set flag to it and reduce flag count from the ScoreBoard. We can do it by passing functions through the props of the element BUT when your app will grow trust me you don’t want to pass the your function by props upstream the hierarchy tree of the elements, it starts to mess very quickly. What we can do is (and here comes the magic of the Flux, drums…) fire an action that the store listens to, and then the store notifies all components listen to that store.

You can notice that notification that comes from the BoardPiece is not notifying its parent component GameBoard but fires action that goes directly to the GameStore. (events firing and event listeners, sounds familiar?)

  • BoardPiece – every tile on board is represented by this component, it manages the state of single tile over the game life cycle.

BoardStore – as said above here I listen to all changes made on the board such as revealing tiles, marking them as flags, winning game, losing game, etc. If you are familiar with the MVC methodology so we can say that is the mutation of controller and model, it is very intuitive and simple, you listen to action comes from the view and do you thing in the store, then update view that something happen.

GameStore – the store that is in charge of the state of the game itself, are you started the game? have you won? have you lost? the dimensions of the board, the level and etc. Some thing interesting that I figured out is that you can actually listen to changes that occur on other store and act accordingly, the actions that you are listening to are the same actions that the BoardStore listens to, so if they listen to a same action (onNewGame for example), they each do what they supposed to do. This gives you some kind of “thready” feeling and it is awesome power of Reflux.


  1. Actions in one place – well, there is not a good case of why separate your actions into few files, especially if you have a small app. You can make separation inside the Actions.js by comments if you really want. These actions inside this file are store in an array of strings.
  2. State – state must be managed in the components. I tried to manage the state in the stores but this led to some wrong use of react, I had to FORCE render the component because I hadn’t a way to determine if state changed but to get notation from the store and then render the component manually, this is a bad idea. The state of a component should contain only properties that you know that are going to change through the life cycle of the component and that will affect the view of it, such as isFlag, or isRevealed etc.

code is written in half ES6 and half ES5, sorry about that, it will be fixed as soon as possible :), please feel free to comment what do you think about this simple app, improvements etc.


  1. https://scotch.io/tutorials/getting-to-know-flux-the-react-js-architecture – great flux explanation
  2. https://www.youtube.com/watch?v=wA98Coal4jk – great talk about ImmutableJS and building a mines sweeper with it.
  3. https://ochronus.com/react-reflux-example/ – another good reflux by example
  4. http://blog.krawaller.se/posts/the-reflux-data-flow-model/ – explanation of Reflux data model
  5. http://reactjsnews.com/building-components-with-react-js-and-flux/
  6. https://medium.com/swlh/the-case-for-flux-379b7d1982c6#.tg83wo7fo