Monthly Archives: November 2016

Onsen UI YouTube Jukebox with AngularJS

By [object Object]

Onsen UI YT Jukebox

The YouTube Jukebox app has been updated to Onsen UI 2.0 + AngularJS and now includes
a Material Design version. This app uses the YouTube Data API v3 to fetch
videos and display them in our hybrid apps. Learn more about the
included changes here.

YouTube Jukebox sample app was released some time ago for Onsen UI 1. It has
a tutorial about how to use the YouTube Data API v3 with AngularJS in Onsen UI that is
still completely valid for Onsen UI 2. You can check it
out
for more details.

YouTube Jukebox

The source code of this application is on
Github
.

After the latest changes it now includes a Material Design version that will
be displayed in Android devices. This version contains a modal that overlays a new
ons-toolbar which includes a search input. This behavior is quite common in
Material Design apps.

Another interesting change is that it now loads new videos when the scroll
reaches the bottom of the page using onInfiniteScroll functionality instead
of a “Load more” manual button.

This app is included in our samples page along with other useful
samples. If you have any doubt about this app, please leave a comment or open
an issue on Github.

Source:: https://onsen.io/

Explaining JavaScript Closure & Scope Chain with Examples

By Alec Lownes

Explaining JavaScript Closure & Scope Chain with Examples

In this article, I will attempt to explain JavaScript Closures & the Scope Chain with examples, so that you will understand how to debug specific issues and how to use them to your advantage.

While Javascript’s inheritance and scoping is different from most languages, I think that with proper understanding, these quirks can be embraced and used to their full potential.

The first part of the series explains the JavaScript Prototype Chain and Inheritance.

JavaScript Scope Chain Explained

Every Javascript developer has at one point or another run into a bug (most of the time when trying to write asynchronously), that is described mysteriously online as the result of incorrect “closure”. As a result, most developers have learned not to write functions in certain ways, for fear of awakening the beast once more.

However, knowledge of closure and the scope chain can make Javascript’s biggest headache into a great ally.

Anonymous Functions and State

The root of the problem is that functions have a state. We call this state the scope of the function, and it stores references to all of the variables that were declared at the time the function was created. Due to hoisting, named functions have the scope present at the top of whatever block they belong to, but anonymous functions have whatever scope exists at the line they are initialized.

JavaScript Closure Example

Closure is the act of capturing an object and separating it from its original scope, making it available to the capturing function forever. The example below illustrates accidental closure.

var helloStr = 'world';

//I want to make a function which returns a function that will print out
//a hello message when I execute it.
var sayHello = function(name){  
    return function(){
        console.log('Hello ' + name + '!');
    }
}

var sayGreeting = sayHello(helloStr);

//woops, I meant to greet Bob
helloStr = 'Bob';  
sayGreeting();//Hello world!  

This is an example of assuming that your function will use a reference to the string helloStr when in reality you have accidentally captured the specific value of that string at the time of function execution.

What about this next example of an asynchronous counter? What do you expect it to output?

for (var i = 0; i < 10; i++){  
    setTimeout(function(){
        console.log(i);
    }, 1000);
}

Output:

10  
10  
10  
10  
10  
10  
10  
10  
10  
10  

In this example, closure was needed and did not happen. When the function goes to print out the values one second later, it references the current value of i, which has long ago been incremented to 10. To understand when a function will capture a variable and when it will not, we need to understand scope.

What is Scope?

If you think of functions in Javascript as state machines, scope is that state. Wherever the cursor in your Javascript program is, it has a scope. If it is inside a function, it is that function’s scope. If it doesn’t have a scope, it is said to have the global scope. You can think of scope as an object structured like so:

{
    _scope,
    variables
}

The _scope variable points to the scope that the program cursor was at when the function was created, or null in the case of the global scope. This creates a chain of scopes called the Scope Chain. The variables variable is a map of all variable that are passed into the function or will be declared in the function (due to hoisting, they are all declared at the top of the function even though you may write them as being declared at other points). Whenever a variable is changed in the function, its entry in the variables map is changed too.

How are Closures related to the Scope Chain?

When a variable is used, the program traverses the scope chain until it finds an entry for that variable. Redeclaring a variable or passing it into a function is a way of separating it from its previous existence in the scope chain.

var str1 = 'hello';  
//Redeclaring the variable
var str2 = str1;  
str1 = 'goodbye';  
//Redeclaring the variable has separated it from its original reference
console.log(str2);//hello

var str1 = 'hello';  
var printVar = function(v){  
    return function(){
        console.log(v);
    };
};
//Passing in variable into a function
var printHello = printVar(str1);  
str1 = 'goodbye';  
//Passing the variable into a function has saved it in the function's scope
printHello();//hello  

In the Hello Bob example, the original string was preserved because it was passed into a function and persisted in the function’s scope, even though its variable outside the function was reassigned.

At the last line of the Hello Bob example, this is what the scope chain looks like when the program cursor is at the console.log statement.

  • scope (nothing here)
  • scope.scope
    • name: ‘world’
  • scope.scope.scope (global for this program)
    • sayHello: function
    • helloStr: ‘Bob’
    • sayGreeting: function

In the async counting example, after one second when the program cursor starts to execute the console.log statements, this is the scope chain at each execution.

  • scope (nothing here)
  • scope.scope (global for this program)
    • i: 10

If we wanted to rewrite the async counting example correctly, we would write it so that it captured the current value of i instead of using the final value.

//Even though the name of the variable is the same, we are using the
//value that is passed into the function, not the value that keeps incrementing
var logI = function(i){  
    return function(){
        console.log(i);
    };
};

for (var i = 0; i < 10; i++){  
    setTimeout(logI(i), 1000);
}

The value of i that has been captured in the function returned by logI is now ungettable and unsettable outside of the scope of the returned function. This is one way of making private variables in Javascript.

Advanced: Immediately Invoked Functional Expression

Immediately Invoked Functional Expressions (IIFE) are a pattern in Javascript that allow variables and methods to be made private by declaring them inside a scope. This is how libraries like jQuery are structured. Passing the window object into these functions allows specific parts of the IIFE to be exported to the global namespace.

(function(global){
    var privateVariable = 'No one can ever see me or change me outside of this scope';
    var publicVariable = 'No one can change me, but some can see me';

    global.getPublicVariable = function(){
        return publicVariable;
    };
})(window);

Now the window object has a getPublicVariable method.

Conclusion

When using Javascript, it can sometimes get confusing to determine exactly which variable you are referencing at any given line. With an object attribute it can be anywhere along the prototype chain, and with a variable, it can be anywhere along the scope chain.

Hopefully, this primer on the JavaScript Prototype Chain and scope chains will increase your confidence when using these features of the language.

Let me know in the comments if you have any questions!

Source:: risingstack.com

Prevent Errors from Crashing Gulp Watch

By kayandrae

8aTzqMzgSq6ZE3esT6SP_prevent-errors-from-crashing-gulp.png.jpg

Developers are a lazy bunch. Or at least I assume we are. Because of this reason we tend to build tools that make our work faster. From highly customizable editors to task runners.

Today’s article is on gulp. If you don’t know what gulp is, we have a good article and course that serves as a good intro to gulp.

With gulp, we can build tasks that automatically compile SASS, start a laravel server, live reload the browser, transpile es6 to es5, etc.

But, just as with life, sh&^ happens. A silly little punctuation (; I’ve got my eyes on you) can easily mess up our work. Thankfully, there’s a few languages out there like Javascript which is very forgiving. Nonetheless, mistakes can happen.

Since we have a “gulp watcher” that watches our project and runs defined tasks when we make any change, an error can easily break our pipeline.

Creating and Watching a Gulp Task

Watching in Gulp refers to triggering a task when a change is made to a project’s source.

So, before we watch a task, let’s create a task that we will use as our example throughout this tutorial. The task we will create is a SCSS compilation task.

We can create a new working directory, name it whatever you want. We can now create our gulpfile.js in our working directory. Then we add our build task. Before we define our task, we need to install our dependencies.

For this article, here is a list of our dependencies.

{
  "private": true,
  "devDependencies": {
    "gulp": "^3.9.1",
    "gulp-notify": "^2.2.0",
    "gulp-plumber": "^1.1.0",
    "gulp-sass": "^2.3.2",
    "gulp-util": "^3.0.7"
  }
}

Now that we have our dependency list, we can run npm install or if you have the new yarn package manager based on npm, you can run yarn install.

In the gulpfile, we can then define our gulp task.

const gulp = require('gulp');
const sass = require('gulp-sass');

gulp.task('compile-scss', function () {
    gulp.src('scss/main.scss')
        .pipe(sass())
        .pipe(gulp.dest('css/'));
});

So from the command line, we can run gulp compile-scss and our sass file should be compiled.

Watching a Task

Now that we have a task defined, let’s trigger the file whenever we make a change to the project’s source.

gulp.task('watch', function () {
    gulp.watch('scss/**/*.scss', ['compile-scss']);
});

From the terminal, we can run gulp watch and whenever a file ending with .scss extension in any folder within the scss directory gets changed, compile-scss task is run.

Prevent Errors from Breaking Tasks

We’ve got our task and watcher up and running, but if an error occurs in our SCSS file, the gulp watcher gets terminated. We then have to go back to the terminal and type gulp watch again. This gets very annoying really fast. A silly little ; can break our watcher.

To avoid breakage like this, we can one of three things:

  1. Swallow the Error.
  2. Gulp Util.
  3. Gulp Plumber.

Swallow the Error

One a way to go about dealing with errors is to “swallow the error“. The error(s) will be taken in by the application to prevent the task from breaking. Basically, errors will not be reported and the task will keep running.

Since gulp sends a lot of events, we can hook into the error event of the task we don’t want to fail.

gulp.task('compile-scss', function () {
    gulp.src('scss/main.scss')
        .pipe(sass())
        .on('error', function (err) {
            console.log(err.toString());

            this.emit('end');
        })
        .pipe(gulp.dest('css/'));
});

As you can see above, from the on listener on the task. The on event listener takes in two parameters: the event and a function to be triggered when the event gets called. The function that gets called takes in the error object. We then log the stringified version of the error to the terminal.

It is absolutely important to this.emit('end'), if this event is not triggered, the next pipe in this task pipeline never gets called, and the buffer will be left open.

Gulp Util

This method involves using the gulp-util plugin.

The gulp-util plugin provides a lot of helpful methods, one of them is log. With this method, we can log the error to the terminal. To use this, we attach an error event listener to the pipe.

var gutil = require('gulp-util');

gulp.task('compile-scss', function () {
    gulp.src('scss/main.scss')
        .pipe(sass())
        .on('error', gutil.log)
        .pipe(gulp.dest('css/'));
});

But this method also requires us to go through each pipe in the pipeline and attach .on('error', gutil.log) listener to all tasks. Something like this.

gulp.task('compile-scss', function () {
    gulp.src('scss/main.scss')
        .pipe(sass())
        .on('error', gutil.log)
        .pipe(autoprefixer())
        .on('error', gutil.log)
        .pipe(gulp.dest('css/'));
});

Gulp Plumber

Out of all three methods, this is my favorite. With gulp-plumber, we don’t need to go to each pipe and add a listener, we can just add a global listener to the task and have a meaningful error displayed.

var plumber = require('gulp-plumber');

gulp.task('compile-scss', function () {
    gulp.src('scss/main.scss')
        .pipe(plumber())
        .pipe(sass())
        .pipe(autoprefixer())
        .pipe(cssnano())
        .pipe(gulp.dest('css/'));
});

We can have multiple pipes in this task and still only ever need to call plumber once.

Alerting the User to Errors

Now that we can see the errors without breaking out of watch, we need to find a way to get some kind of notification when an error occurs. There are several ways to do this, but I will cover only one method.

The method I will cover in this article: will play a beeping sound when an error occurs, and also show a system notifcation that looks like this.

This notification looks different according to your operating system.

To get this feature to work, we need to extend the gulp-plumber plugin. So in our gulp task, we update our call to plumber.

gulp.task('scss', function () {
    gulp.src('scss/main.scss')
        .pipe(plumber({ errorHandler: function() {
            // do stuff here
        }}))
        .pipe(sass())
        .pipe(gulp.dest('css'));
});

Notice, we pass an object that has an errorHandler property that takes a closure to plumber. We can then call our notify plugin in that closure.

var notify = require('gulp-notify');

gulp.task('scss', function () {
    gulp.src('scss/main.scss')
        .pipe(plumber({ errorHandler: function() {
            notify.onError({
                title: "Gulp error in " + err.plugin,
                message:  err.toString()
            })(err);
        }}))
        .pipe(sass())
        .pipe(gulp.dest('css'));
});

We call the notify plugin and pass it an object that has a title and message property. Now, when an error occurs, a notification is triggered. To play a beeping sound, we can use gulp-util for that.

var notify = require('gulp-notify');

gulp.task('scss', function () {
    gulp.src('scss/main.scss')
        .pipe(plumber({ errorHandler: function() {
            notify.onError({
                title: "Gulp error in " + err.plugin,
                message:  err.toString()
            })(err);

            // play a sound once
            gutil.beep();
        }}))
        .pipe(sass())
        .pipe(gulp.dest('css'));
});

Now, when an error occurs, we get both sound and system notification and then you can check your terminal for more information.

Conclusion

The configuration in this article should be suitable for most users, but if you have any suggestions/improvements, please let us know in the comments.

Source:: scotch.io

Webinar: 10 Ways Angular 2 Makes Development Easier

By chris

UbP1s5HLQAmnA8n57aoR_10-ways-angular-2-makes-life-easer.png.jpg

This will be our very first webinar! We recently moved into making video courses in our Scotch School; now we’re continuing the Scotch video movement and creating our first webinar!

Here are the straight details:

What? Learn the 10 Ways Angular 2 Makes Development Easier
When? Thursday, December 8 at 2pm EST

Links to the videos. We’ll be broadcasting using many services including Facebook Live, YouTube, and others we’re looking into. If you have any suggestions, let us know in the comments. We want to open it up to allow as many people to watch as possible.

Links will be added here when we go live.

RSVP

To get an accurate head count and accommodate everyone, could you please RSVP here:

Loading…

Who Are We?

Chris Sevilleja

Co-Founder of Scotch

Ryan Chenkie

Google Developer Expert (GDE)

We look forward to seeing you in there!

Source:: scotch.io

Get Angular 1 Features in Angular 2

By kmaida

uve8lwjJR1iR3jNeHFP9_Angular2.png.jpg

Introduction

If you have solid experience with AngularJS 1.x, you’re well aware of the framework’s features and intricacies. Many of us have plenty of Angular 1 projects in development and production. But Angular 2 was officially released in mid-September 2016. Maybe you’ve dabbled with the Angular 2 Tour of Heroes tutorial, but if you haven’t had the opportunity to build a real-world Angular 2 app, let’s face it: the prospect can be daunting.

The entire Angular framework has been rewritten into a brand new platform. Change detection is better. New dependencies and understanding are required for development (TypeScript, RxJS, ES6, a new style guide, etc.). Many of the old standbys are gone (no more $scope, no $rootScope.broadcast, no filter or orderBy pipes, etc.).

There aren’t many shortcuts for an Angular 1 developer looking to learn Angular 2 quickly. You may have heard about the difficulties of upgrading an existing codebase from Angular 1.x to Angular 2. Many developers have had the best luck migrating to a clean Angular 2 build. This is a great way to learn a new platform, though it requires a certain climate with ample time, budget, and stability testing.

So how can we decrease the learning curve when transitioning from Angular 1 to Angular 2?

About This Guide

The purpose of this tutorial is to provide guidance for implementing common features of Angular 1 in Angular 2. Some things have been removed or replaced. Some require a mental model shift. We’ll cover the basics and hopefully you’ll be able to get up and running more quickly with your own Angular 2 apps.

What We’ll Cover

We’ll address several features that many real-world Angular apps require:

Note: The Angular 1 code samples use AngularJS version 1.5.x.

What We Won’t Cover

We aren’t going to go indepth explaining Angular 2 project setup, Angular CLI, TypeScript, ES6, RxJS, functional reactive programming (FRP), or testing.

However, this tutorial does assume a basic understanding of Angular 2 prerequisites. This includes Angular 2 project architecture, TypeScript, ES6, and RxJS. To familiarize yourself, check out some of these resources:

For a full migration tutorial including all setup steps, check out Migrating an Angular 1 App to Angular 2 – Part 1, Part 2, and Part 3.

Code Repository

Sample Angular 2 code is available for each section in the migrating-angular-features-to-angular2 GitHub repo.

Dependencies

To use the code samples in your own project, you’ll need to set up an Angular 2 project. You can generate a boilerplate app using the Angular CLI. There are also various seed projects available, such as AngularClass/angular2-webpack-starter and mgechev/angular-seed.

Samples in this tutorial are simplified so that templates are included in the component TypeScript. In a real-world project, you would likely want to separate the TS, HTML, and CSS into their own files.

The Angular CLI can set this up quickly and easily for you. To create your own starter project and take advantage of automatic component generation, check out the Angular CLI GitHub README. The Ultimate Angular CLI Reference Guide is also a great resource.

Passing Data from Parent to Child

Download Angular 2 code samples: parent-to-child-component-communication

One of the most basic features of any app is communication. Angular 1 leverages the concept of componetization but not nearly to the extent of Angular 2. In Angular 1, it’s simple to allow hierarchical controllers and directives access to the $scope of other app components. In Angular 2, some component communication is very similar to Angular 1 and some is different.

First let’s examine parent-to-child component communication.

Scenario: In our parent component, we want to use a repeater to iterate over an array of objects and pass each object to a child component. The child should then display the data.

Parent to Child Communication in Angular 1

In Angular 1, our approach probably involves setting up (or fetching) data in a parent controller and assigning the collection to a bindable member (ie., parent.items). We would use ng-repeat to loop over a child directive and pass the item to it as an attribute. The child directive’s template would then display the data.

In AngularJS 1.5, our child directive might resemble the following:

// Angular 1 - child.directive.js

angular.module('ng1-app').directive('child', child);

function child() {
  return {
    restrict: 'EA',
    replace: true,
    template: '<div>{{child.data.name}}</div>',
    controller: childCtrl,
    controllerAs: 'child',
    bindToController: true,
    scope: {
      data: '<'
    }
  };
}
function childCtrl() {
  var child = this;
  console.log('Data for child:', child.data);
}

The markup containing the parent might look something like this:

<!-- Angular 1 - parent-to-child markup -->
<div ng-controller="ParentCtrl as parent">
  <child ng-repeat="item in parent.items" data="item"></dino>
</div>

Parent to Child Communication in Angular 2

The implementation for this is similar in Angular 2, but we need to use input binding with the @Input decorator.

In the parent component, we’ll set up our items data and then use the NgFor directive to repeat the child component and pass items to it:

// Angular 2 - parent.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `
    <app-child *ngFor="let item of items" [data]="item"></app-child>
  `
})
export class ParentComponent {
  items: Object[] = [
    { name: 'Allosaurus' },
    { name: 'Brachiosaurus' },
    { name: 'Dionychus' },
    { name: 'Elasmosaurus' },
    { name: 'Parasaurolophus' }
  ];
}

Our items property has a type annotation of Object[] signifying that it will be an array of objects.

The selector for this component is app-parent because we generally want custom elements to be hyphenated as per the W3C spec for custom elements and Angular 2 Style Guide.

The square brackets in [data] are one-way data binding punctuation. You can read more about binding syntax in the Angular 2 docs.

Our child component might then look like this:

// Angular 2 - child.component.ts

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
    <div>{{data.name}}</div>
  `
})
export class ChildComponent implements OnInit {
  @Input() data: Object;

  ngOnInit() {
     console.log('Data for child:', this.data);
  }
}

We’ll import the Input class from @angular/core. Then we’ll give the @Input() decorator a name (data) and an Object type annotation.

The Angular 1 and Angular 2 examples are now functionally equivalent. At a glance, we can see how the lack of $scope makes the Angular 2 example refreshingly simple.

Passing Data from Child to Parent

Download Angular 2 code samples: child-to-parent-component-communication

We often need to pass data from a child to a parent. Consider this hypothetical scenario:

Scenario: We have a property that adds or removes an element in a component. We have a button in a child component that must be able to toggle the parent’s element.

Child to Parent Communication in Angular 1

In Angular 1, there are several ways to tackle this scenario. We can allow children to inherit the parent scope. We can broadcast and emit events. We can two-way data bind to a directive’s scope. Angular 1’s automagic two-way data binding was one of the most oft-demoed features when Angular first appeared in the JavaScript framework landscape. If you’re experienced with Angular 1, you should be familiar with how the digest cycle / dirty-checking works.

Child to Parent Communication in Angular 2

In Angular 2, two-way data binding is no longer built in. Angular 2 components are modular and encapsulated. After Angular 1’s emphasis on two-way binding, its absence from Angular 2 can seem challenging. The key is understanding component communication and the greater control we have when binding doesn’t happen automagically.

If we want a child component to notify a parent of changes, we can use the EventEmitter API and @Output decorator. The parent can then bind to the event outputted by the child to update its data.

Note: This method should be used for component-to-component communication but not service-to-component interactions. We’ll cover communication with services shortly.

Our parent might look like this:

// Angular 2 - parent.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `
    <div *ngIf="elementShow">Show this conditionally in parent template!</div>
    <app-child (elementToggled)="elementToggleHandler($event)"></app-child>
  `
})
export class ParentComponent {
  elementShow: boolean;

  elementToggleHandler(e: boolean) {
    this.elementShow = e;
  }
}

We have an element that is being conditionally stamped with the NgIf directive if the elementShow property is truthy. Then we have a child component with an (elementToggled) event listener. When this event is detected in the parent component, it executes a handler that updates the elementShow property with the value of the event parameter. But where does this elementToggled event come from?

Note: The parentheses in (elementToggled) are data binding punctuation for listening for events. You can read more about binding syntax in the Angular 2 docs.

Our child component emits the elementToggled event that the parent is listening for. In this case, the child might look like this:

// Angular 2 - child.component.ts

import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
    <button (click)="toggleElement()">Toggle Parent from Child</button>
  `
})
export class ChildComponent {
  @Output() elementToggled = new EventEmitter();
  elementShow: boolean = false;

  toggleElement() {
    this.elementShow = !this.elementShow;
    this.elementToggled.emit(this.elementShow);
  }
}

We need to import the Output and EventEmitter APIs. In our template, we’ll listen for a (click) event and execute a toggleElement() method when the user interacts with the button. We’ll use the @Output() decorator to create a new event emitter. We also need a boolean elementShow property to track the state of the toggle.

Finally, we’ll define the click event handler toggleElement(). This method should toggle the elementShow property and emit the elementToggled event with the current state of elementShow.

We can now toggle the parent from the child:

Migrating Angular 1 features to Angular 2: communication from child to parent component

Note: To see a practical, real-world use case, please check out Migrating an Angular 1 App to Angular 2 – Part 1. You can also read Two-way Binding in Angular 2 for more on this topic.

Hopefully you can see the benefits of this approach. What’s happening is more transparent and less magical when things like $scope and $watch aren’t in the picture.

Global Communication with Services

Download Angular 2 code samples: global-communication-with-service

Most apps that grow to a certain scale require some kind of global communication. Scope (and root scope) are gone in Angular 2, but we can still implement app-wide communication with services.

Scenario: We have some data and associated methods for setting and getting it. We want to be able to display and manipulate that same data from anywhere in our app. We also want to react to data changes in script.

Global Communication in Angular 1

With Angular 1, there are several options for managing app-wide data. We can use service (and factory) singletons to get and set global data and provide methods. We can also use $rootScope to store data and emit and broadcast events.

Global Communication with Services in Angular 2

One of the interesting things about Angular 2 is that services can be singletons or they can create multiple instances depending on how we provide them. For globals, let’s assume that a singleton is exactly what we want.

Let’s create a trusty standby, the good old counter example:

// Angular 2 - counter.service.ts

import { Injectable } from '@angular/core';
import { ReplaySubject } from 'rxjs/ReplaySubject';

@Injectable()
export class CounterService {
  count: number = 0;
  private countSource = new ReplaySubject<number>(0);

  inc() {
    this.count++;
    this.updateCountSbj(this.count);
  }
  dec() {
    this.count--;
    this.updateCountSbj(this.count);
  }
  get getCount(): number {
    return this.count;
  }

  count$ = this.countSource;

  private updateCountSbj(value) {
    this.countSource.next(value);
  }
}

The simple part: our service is Injectable and has methods to increment, decrement, and return an integer. There’s nothing fancy there.

However, we’ve also imported BehaviorSubject. We want to be able to subscribe to count changes in our components. We need to be able to do this if we want to execute script logic in response to changes in global data. In Angular 1, we might do this by emitting an event or by $watch()ing in a directive/controller. In Angular 2, services should not use EventEmitter, and $scope.$watch is gone. An RxJS BehaviorSubject extends an observable and allows us to create subscriptions in our components.

Note: Subjects are both observers and observables. You can learn more about subjects here.

Now let’s say we have two components, Cmpt1Component and Cmpt2Component. Each of these components should have buttons to increment, decrement, and display the counter. They can subscribe to the count$ subject to execute logic. They both need access to a single instance of CounterService.

To do this, we need to provide our counter service globally in our app.module.ts:

// Angular 2 - app.module.ts
...
import { CounterService } from './counter.service';

@NgModule({
  ...,
  providers: [CounterService],
  ...
})
export class AppModule { }

We import CounterService and then provide it in the providers array of our app’s @NgModule. Now we can use it in any component belonging to this module and trust that they’ll share the same instance.

For the sake of example, say both of our components are essentially the same. They might look like this:

// Angular 2 - cmpt1.component.ts / cmpt2.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { CounterService } from './counter.service';

@Component({
  selector: 'app-[cmpt1/cmpt2]',
  template: `
    <div>
      <h2>Counter</h2>
      <button (click)="counter.dec()">-</button>
      {{counter.getCount}}
      <button (click)="counter.inc()">+</button>
    <div>
  `
})
export class [Cmpt1/Cmpt2]Component implements OnInit, OnDestroy {
  countSub: Subscription;

  constructor(private counter: CounterService) { }

  ngOnInit() {
    this.countSub = this.counter.count$.subscribe(
      value => {
        console.log('global counter value changed:', value);
      }
    );
  }

  ngOnDestroy() {
    this.countSub.unsubscribe();
  }
}

Because we provided the service in the app module, we only need to import it to use it in our components. We’ll make it available in our constructor() function. Now we can use its methods in the component templates.

We can also create a Subscription to the count$ subject to execute component-level logic. We then need to unsubscribe when the component is destroyed to prevent memory leaks.

If we display both components, they’ll look and behave like this:

Migrating Angular 1 features to Angular 2: counter service as a singleton

Incrementing or decrementing either component’s counter will affect the other. We now have globally shared data!

Angular 2: Services with Multiple Instances

Download Angular 2 code samples: service-with-multiple-instances

We mentioned above that services can be provided in a way that creates multiple instances. Doing this was a hassle in Angular 1 and thankfully, Angular 2 easily solves this with its use of classes.

Scenario: We have a service that provides properties and methods for a counter. We want more than one counter in our app. Manipulating one counter should not affect the others.

We’ll use our Angular 2 CounterService from the previous example. Instead of providing it in the app module @NgModule, we’ll add it to each @Component in a providers array like this:

// Angular 2 - cmpt1.component.ts / cmpt2.component.ts
...
@Component({
  ...,
  providers: [CounterService]
})
...

The result is unique counter instances in Cmpt1Component and Cmpt2Component:

Angular 2 counter service with multiple instances

To do this in Angular 1, we have to use factories as APIs that return collections with getters and setters. Doing so isn’t simple or elegant. Angular 2 solves this nicely!

Using Native Events and DOM Properties

Download Angular 2 code samples: using-native-events-and-dom-properties

In Angular 2, it’s easier to hook into native events and DOM properties. In Angular 1, doing this is often fraught with $scope hazards and the danger of bad practices. We’ll use the window.resize event as an example. Consider this common scenario:

Scenario: When a user resizes the browser, we want to dynamically set the minimum height of a DOM element.

Window Resize Event in Angular 1

In Angular 1, we can bind directly to an Angular 1 $window resize event in a directive or we can use a factory API such as angular-resize. We have to manage $scope and carefully clean up our listeners on $destroy. Then we either have to use JS to set the DOM property (min-height in this case) or we have to add watchers by binding in the template. None of this is ideal.

Window Resize Event in Angular 2

We’ll demonstrate using an event observable in Angular 2:

// Angular 2 - app.component.ts

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Rx';

@Component({
  selector: 'app-root',
  template: `
    <div class="fullHeight" [style.min-height]="minHeight"></div>
  `,
  styles: [`
    .fullHeight { background: red; }
  `]
})
export class AppComponent implements OnInit {
  minHeight: string;
  private initWinHeight: number = 0;

  ngOnInit() {
    Observable.fromEvent(window, 'resize')
      .debounceTime(200)
      .subscribe(event => this.resizeFn(event)
    );
    this.initWinHeight = window.innerHeight;
    this.resizeFn(null);
  }
  private resizeFn(e) {
    let winHeight: number = e ? e.target.innerHeight : this.initWinHeight;
    this.minHeight = `${winHeight}px`;
  }
}

First we’ll import dependencies. We’re going to use the OnInit lifecycle hook from @angular/core to manage the observable and implement initial height. Then we need Observable from the RxJS library which is packaged with Angular 2.

Important Note: Angular 2 binds to DOM properties, not HTML attributes. This may seem counter-intuitive because we declaratively add things like [style.min-height] or [disabled] to our markup, but these refer to properties, not attributes. Please read Binding syntax: An overview to learn more.

We can bind our minHeight member to the [style.min-height] DOM property on the

element. (For the sake of example, we’re assuming that a global CSS reset has removed default margins and padding on the body.)

We’re using an RxJS observable to subscribe to the window.resize event and execute a debounced function that sets a min-height. The window.resize event doesn’t fire on page load, so we then need to trigger the handler in ngOnInit().

Note: You’ve already seen native (click) event bindings in earlier examples. We could do the same with (window.resize), but we’re subscribing to an observable instead because we want to debounce the handler.

Router Events

Download Angular 2 code samples: router-events

Angular 2 routing is thoroughly covered in the Angular 2 docs and the Tour of Heroes tutorial. There are also real-world examples in Migrating an Angular 1 App to Angular 2 – Part 2 and Part 3. Therefore, we’ll only cover router events here.

Scenario: Whenever a navigation change is initiated, we want to execute some functionality (for example, closing a navigation menu).

Navigation Events in Angular 1

In Angular 1, we can listen for navigation events such as $locationChangeStart or $locationChangeSuccess like so:

// Angular 1 - on location change

$scope.$on('$locationChangeStart', function(event, newUrl, oldUrl) {
  // do something every time a location change is initiated
});

Navigation Events in Angular 2

We can do something similar in Angular 2, but now router events are observables. We need to subscribe to them:

// Angular 2 - app.component.ts

import { Component, OnInit } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';

@Component({
  selector: 'app-root',
  template: ``
})
export class AppComponent implements OnInit {

  constructor(private router: Router) { }

  ngOnInit() {
    this.router.events
      .filter(event => event instanceof NavigationStart)
      .subscribe(event => {
        // do something every time a location change is initiated
      });
  }
}

We need to import Router and NavigationStart from @angular/router. Next we need to make private router: Router available in our constructor() function.

Router.events is an observable of route events. We’ll filter for when the event is an instance of NavigationStart. Then we can subscribe and execute our desired functionality. Other navigation events can be found in the Angular 2 router event documentation.

Note: To learn about a great use-case, check out Dynamic page titles in Angular 2 with router events.

Calling an API

Download Angular 2 code samples: calling-an-api

Many Angular applications utilize external APIs. Calling an API is not significantly different between Angular 1 and Angular 2. Angular 1 uses promises whereas Angular 2 uses observables.

Scenario: We want to use the reddit API to display the titles and links of posts from the reddit front page.

You can check out the data we’ll be using here: https://www.reddit.com/.json.

Calling an API in Angular 1

Most Angular 1 apps use a factory or service to make API calls. The controllers or directives then inject and use that service to fetch or send data. We react to successes or failures using promises.

Calling an API in Angular 2

We’ll do something very similar in Angular 2. First we’ll create the API service:

// Angular 2 - api.service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class ApiService {
  private baseUrl = 'https://www.reddit.com/';

  constructor(private http: Http) { }

  getFrontPage$() {
    return this.http
      .get(`${this.baseUrl}.json`)
      .map(this.handleSuccess)
      .catch(this.handleError);
  }
  private handleSuccess(res: Response) {
    return res.json().data.children;
  }
  private handleError(err: Response | any) {
    let errorMsg = err.message || 'Unable to retrieve data';
    return Observable.throw(errorMsg);
  }
}

This is pretty straightforward and isn’t much different from our Angular 1 implementation. Starting from the top: we import our dependencies. Services are injectable. We also need Http and Response from @angular/http, Observable from RxJS, and map and catch operators.

Note: RxJS observables are preferable over promises. Angular 2’s http.get returns an observable but we could convert it to a promise with .toPromise() if we had to (but we won’t in this tutorial).

We set our private API baseUrl property and make private http: Http available in the constructor.

Then we define our getFrontPage$() function. The $ at the end of the function name indicates that an observable is returned and we can subscribe to it.

Finally we manage successes and errors. The map operator processes the result from the observable. In our case, we’re returning the response body as JSON. The reddit API returns a data property and inside that, we want the value of children, which is an array of the posts. We’ll use the catch operator to handle failed API responses and generate an observable that terminates with an error.

The API service should be a singleton so we’ll provide it in the app module:

// Angular 2 - app.module.ts
...
import { ApiService } from './api.service';

@NgModule({
  ...,
  providers: [ApiService],
  ...
})
export class AppModule { }

Now we can use the service in a component to display reddit post titles:

// Angular 2 - reddit.component.ts

import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';

@Component({
  selector: 'app-reddit',
  template: `
    <ul>
      <li *ngFor="let post of redditFP">
        <a href="http://reddit.com{{post.data.permalink}}">{{post.data.title}}</a>
      </li>
    </ul>
  `
})
export class RedditComponent implements OnInit {
  redditFP: Object[];

  constructor(private redditApi: ApiService) { }

  ngOnInit() {
    this.getRedditFront();
  }
  getRedditFront() {
    this.redditApi
      .getFrontPage$()
      .subscribe(
        res => this.redditFP = res,
        err => console.log('An error occurred', err)
      );
  }
}

First we import our new ApiService. Then we’ll declare that the redditFP property should be an array of objects. We’ll add the private redditApi: ApiService to the constructor parameters.

The template should display an unordered list with the title of each post linked to its location on reddit.

We can then write the getRedditFront() method to subscribe to the redditApi.getFrontPage$() observable and assign the response to the redditFP property. We’ll call the getRedditFront() method in our ngOnInit() lifecycle hook.

Note: We’re using a third party API for this example. However, when we have tighter control over our own APIs, we can use TypeScript to set defined models for the data we expect. To learn more about using models, please check the “Calling an API in Angular 2” section of Migrating an Angular 1 App to Angular 2 – Part 2.

When this component is displayed, we should see a list of links to the current posts on reddit’s front page.

Filtering by Search Query

Download Angular 2 code samples: filtering

You may have heard about Angular 2 pipes. Pipes transform displayed values within a template. In Angular 1, we use the pipe character (|) to do similar things with filters. However, filters are gone in Angular 2.

Let’s address the following scenario:

Scenario: We have an array of objects and want the user to be able to filter the array using a search query.

Filtering in Angular 1

In Angular 1, we can give an input an ng-model and then use a filter on the repeater:

<label for="search">Search:</label>
<input id="search" type="text" ng-model="query">

<div ng-repeat="item in array | filter:query">
  {{item.name}}
</div>

Simple, right?

Well, yes and no. Angular 1 apps can take a huge performance hit if care isn’t taken when filtering. If you’ve ever filtered hundreds or thousands of items (or implemented faceted search), you’re probably familiar with the pitfalls of Angular 1’s built-in filter.

In such cases, you may have used a service to implement filtering or added your filtering logic right in your controller. We can regain some performance by exerting tighter control over how and when filtering is executed.

Filtering in Angular 2

The Angular 2 team recommends against replicating Angular 1 filter functionality with a custom pipe due to concerns over performance and minification. Instead, we’ll create a service that performs filtering.

Note: You can read more about why the filter pipe was removed in the “No FilterPipe or OrderByPipe” section of the Pipes docs (at the very bottom).

Let’s create a FilterService. The first step is establishing some rules regarding implementation. Let’s say we want to ensure the following:

  • We expect to filter an array of objects.
  • Search function should accept the array and a query predicate (filter criteria) and return an array with all objects that contain a match.
  • Search should be case-insensitive.
  • We’ll only search string values for matches.

With these simple guidelines, our FilterService might look like this:

// Angular 2 - filter.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class FilterService {
  search(array: Object[], query: string) {
    let lQuery = query.toLowerCase();

    if (!query) {
      return array;
    } else if (array) {
      let filteredArray = array.filter(item => {
        for (let key in item) {
          if ((typeof item[key] === 'string') && (item[key].toLowerCase().indexOf(lQuery) !== -1)) {
            return true;
          }
        }
      });
      return filteredArray;
    }
  }

}

This is very straightforward and we have direct control over how filtering works. If we want to include other value types in the future (such as numbers or dates), we’d modify search() or create new methods.

We typically would want a singleton FilterService, so we should provide it in our app.module.ts file:

// Angular 2 - app.module.ts
...
import { FilterService } from './filter.service';

@NgModule({
  ...,
  providers: [FilterService],
  ...
})
export class AppModule { }

We can then use it in our components like this:

// Angular 2 - list.component.ts

import { Component } from '@angular/core';
import { FilterService } from './filter.service';

@Component({
  selector: 'app-list',
  template: `
    <label for="search">Search:</label>
    <input id="search" type="text" [(ngModel)]="query" />
    <button (click)="search()" [disabled]="!query">Go</button>
    <button (click)="reset()" [disabled]="!query">Reset</button>

    <ul>
      <li *ngFor="let item of filteredArray">{{item.name}}</li>
    </ul>
  `
})
export class ListComponent {
  array: Object[] = [
    { id: 1, name: 'Jon Snow' },
    { id: 2, name: 'Sansa Stark' },
    { id: 3, name: 'Arya Stark' },
    { id: 4, name: 'Bran Stark' },
    { id: 5, name: 'Petyr Baelish' },
    { id: 6, name: 'Danaerys Targaryen' },
    { id: 7, name: 'Jaime Lannister ' },
    { id: 8, name: 'Cersei Lannister' },
    { id: 9, name: 'Samwell Tarly' },
    { id: 10, name: 'Sandor Clegane' }
  ];
  filteredArray: Object[] = this.array;
  query: string;

  constructor(private filter: FilterService) { }

  search() {
    this.filteredArray = this.filter.search(this.array, this.query);
  }
  reset() {
    this.query = '';
    this.filteredArray = this.array;
  }
}

We now have working filtering:

Migrating Angular 1 features to Angular 2: filtering by search query

This example uses a button to trigger filtering. If we wanted to mimic Angular 1’s native filter, we could run the search on (keyup) on the input and remove the “Go” button, like so:

<input
  id="search"
  type="text"
  [(ngModel)]="query"
  (keyup)="search()" />

This is less performant, but may be a desirable user experience in some cases.

Migrating Angular 1 features to Angular 2: filtering by search query with keyup

Note: You’d never want to use (keyup) if each search query involved expensive processing, huge amounts of data, or API calls. These situations cause problems with the built-in filter in Angular 1 and we don’t want to recreate them in Angular 2.

Aside: User Authentication with Auth0 Lock

Download Angular 2 code samples: user-authentication-with-auth0

Let’s learn how to implement user authentication in Angular 2 with Auth0. We’ll take advantage of Auth0’s Lock widget to manage user identity.

Scenario: We need user authentication to secure our app. Users should be able to sign up and log in with username and password or with third-party Oauth credentials.

Auth0 Lock implemented in an Angular 2 app

Configure Your Auth0 Client

The first thing you’ll need is an Auth0 account. Follow these simple steps to get started:

  1. Sign up for a free Auth0 account.
  2. In your Auth0 Dashboard, create a new client.
  3. Name your new app and select “Single Page Web Applications”.
  4. In the Settings for your newly created app, add http://localhost:4200 to the Allowed Callback URLs and Allowed Origins (CORS).
  5. If you’d like, you can set up some social connections. You can then enable them for your app in the Client options under the Connections tab. The example shown in the screenshot above utilizes username/password database, Facebook, Google, and Twitter.

Setup and Dependencies

You will need Node.js with npm. The current LTS version is recommended.

We’ll add the Auth0 Lock CDN link to our app’s index.html file. We’re using version 10.6 for our tutorial:

<!-- Angular 2 - index.html -->
...
  <!-- Auth0 Lock widget -->
  <script src="https://cdn.auth0.com/js/lock/10.6/lock.min.js"></script>
</head>
...

Next we need the angular2-jwt helper library. Install this in your Angular 2 project with npm:

$ npm install angular2-jwt --save

Create an Authentication Service

We need an Angular 2 service to implement login functionality and authentication methods. For a simple implementation, our AuthService should look like this:

// Angular 2 - auth.service.ts

import { Injectable } from '@angular/core';
import { tokenNotExpired } from 'angular2-jwt';

// Avoid name not found warnings
declare var Auth0Lock: any;

@Injectable()
export class AuthService {
  lock = new Auth0Lock('[YOUR_AUTH0_CLIENT_ID]', '[YOUR_AUTH0_CLIENT_DOMAIN]', {});
  userProfile: Object;

  constructor() {
    this.userProfile = JSON.parse(localStorage.getItem('profile'));

    // Add callback for lock 'authenticated' event
    this.lock.on('authenticated', (authResult) => {
      if (authResult.idToken) {
        // Successful authentication result
        localStorage.setItem('id_token', authResult.idToken);

        // Get user profile
        this.lock.getProfile(authResult.idToken, (error, profile) => {
          if (error) {
            throw Error('There was an error retrieving profile data.');
          }

          localStorage.setItem('profile', JSON.stringify(profile));
          this.userProfile = profile;
        });
      }
    });
  }

  login() {
    // Call the show method to display the Lock widget
    this.lock.show();
  }

  logout() {
    // Remove token and profile
    localStorage.removeItem('id_token');
    localStorage.removeItem('profile');
    this.userProfile = undefined;
  }

  get authenticated() {
    // Check if there's an unexpired JWT
    // This searches for an item in localStorage with key == 'id_token'
    return tokenNotExpired();
  }

}

Let’s talk about the imports. Injectable is necessary for any injectable service. We also need tokenNotExpired from angular2-jwt to get a user’s authentication state.

In order to avoid TypeScript name not found warnings, we’ll declare Auth0Lock‘s type annotation as any.

Then we’ll create a new lock instance:

lock = new Auth0Lock('[YOUR_AUTH0_CLIENT_ID]', '[YOUR_AUTH0_CLIENT_DOMAIN]', {});

Replace [YOUR_AUTH0_CLIENT_ID] with your Auth0 client ID and [YOUR_AUTH0_CLIENT_DOMAIN] with your Auth0 domain. These can both be found in your Auth0 dashboard client settings.

Now we’ll add some functionality to the constructor function. We’ll check local storage for existing data. If the user’s profile is available, let’s set it.

Next we need to implement an authenticated Lock event callback. On successful authentication, we’ll do the following:

  • Save the ID token to local storage.
  • Use the token to get the user’s profile.
  • Save the profile to local storage and set our userProfile property.

Now we need a login() method. This will be called when the user clicks a button. We’ll show the Lock widget so they can sign up or log in.

We also need a logout() method. This will simply remove the user’s token and profile.

We’ll provide our AuthService in the app module:

// Angular 2 - app.module.ts
...
import { AuthService } from './auth.service';

@NgModule({
  ...,
  providers: [AuthService],
  ...
})
export class AppModule { }

Add Login, Greeting, and Logout

Now we need to use our AuthService to give users a way to log in and out. A simplified component might contain code like this:

// Angular 2 - app.component.ts

import { Component } from '@angular/core';
import { AuthService } from './auth.service';

@Component({
  selector: 'app-root',
  template: `
    <button *ngIf="!auth.authenticated" (click)="auth.login()">Log In</button>

    <div *ngIf="auth.authenticated">
      <p *ngIf="auth.userProfile">Hello, {{auth.userProfile.name}}!</p>
      <button (click)="auth.logout()">Log Out</button>
    </div>
  `
})
export class AppComponent {
  constructor(private auth: AuthService) { }
}

This component shows a login button when the user is not authenticated. It shows a personalized greeting and a logout button when the user is logged in. We now have user authentication in an Angular 2 app!

What Next?

With Auth0 authentication in place, we can do things like authorize route access and call protected APIs with authenticated HTTP requests. To learn how to implement this kind of functionality, explore these resources:

Note: If you’d like to see a more robust implementation of Auth0 Lock with Angular 2, check out the Migrating an Angular 1 App to Angular 2 – Part 3 section Aside: Authentiating an Angular 2 App with Auth0 Lock. The example demos a real-world app with routing and dynamic redirection when the login is located in a global header component.

Conclusion

We’ve now discussed several common features of Angular 1 apps and how to implement them in Angular 2. This guide focused on features that:

  • are needed the soonest when building an app,
  • are used very frequently,
  • differ significantly from Angular 1 implementation, OR
  • may not be documented as well as others.

Hopefully this guide has helped you feel more comfortable in the Angular 2 space. For the whole picture, the docs are an excellent source of information. Now let’s go build!

Source:: scotch.io

Freebie: 3 Elegant Bootstrap Forms

By Georgi Georgiev

freebie-3-elegant-bootstrap-footers

The newest edition to our ever growing collection of freebies! This time we’ve prepared for you 3 awesome Bootstrap forms that you can directly copy and paste into your projects. Like all of our freebie templates, these forms are fully responsive, easy to implement, and 100% free to use.

The Forms

To make these forms we’ve used the Bootstrap 3 framework which helps with responsiveness and gives a solid styling base. No other libraries have been used – everything is done via simple HTML and CSS. We’ve also taken into consideration CSS scope so that our styles are self-contained and won’t break anything on the rest of your page.

Registration Form

How to use

To use any of the templates from the demo, follow these simple steps:

  1. Grab the zip archive from the Download button near the top of the page and extract it.
  2. There are 3 folders, one for each form. Decide which template you want and grab it’s HTML from the index.html file.
  3. The styles are located in separate CSS files for each design. You can find them in the respective directories.
  4. We’ve used a couple of images from pexels.com. You can use the same images or you can replace them with your own.
Advanced Search Form

Advanced Search Form

Free for Commercial Use

You have all rights to customize and use these templates in both personal and commercial projects. All our freebies are 100% royalty free, no attribution required (our license page). Enjoy!

Source:: Tutorialzine.com

ZeroMQ & Node.js Tutorial - Cracking JWT Tokens (Part 1.)

By Luciano Mammino

ZeroMQ & Node.js Tutorial - Cracking JWT Tokens (Part 1.)

This article teaches you how to build a distributed application with ZeroMQ and Node.js by developing an exciting sample project: a brute-force cracker for JWT tokens.

This is a two-part story – this first post will focus on theory, and the second one is about coding. You’ll get to know ZeroMQ, how JWT tokens work and how our application can crack some of them! Be aware, that the application will be intentionally simple. I only want to demonstrate how we can leverage some specific patterns.

What is ZeroMQ

ZeroMQ (also known as ØMQ, 0MQ, or zmq) is an open source embeddable networking library and a concurrency framework built in C++. It is available for many platforms and programming languages (including Node.js).
The goal of ZeroMQ is providing developers with a foundation of network utilities that can be easily used across systems with heterogeneous architectures. ZeroMQ provides sockets that can carry atomic messages across various transport layers like in-process, inter-process, TCP, and multicast.

And in case you are wondering why it is called “Zero”…

The Ø in ZeroMQ is all about tradeoffs. On the one hand this strange name lowers ZeroMQ’s visibility on Google and Twitter. On the other hand it annoys the heck out of some Danish folk who write us things like “ØMG røtfl”, and “Ø is not a funny looking zero!” and “Rødgrød med fløde!”, which is apparently an insult that means “may your neighbours be the direct descendants of Grendel!” Seems like a fair trade.

For more info, you can read the The ZeroMQ official guide.

Building a JWT token cracker with ZeroMQ and Node.js

In the course of this article, we are going to build a functional distributed application: a JWT token cracker.

If you know what JWT tokens are and how they work feel free to skip this section, otherwise you are going to need a bit of theory here…

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA.

If you need more, read the introduction to JWT page.

JWT is often used as a mechanism to enforce authentication and authorization in websites and APIs, so being able to “crack” one of these tokens might mean gaining access to sensitive information or being able to impersonate a particular user on a given system.

But what do we really mean with “cracking” a JWT token?

In order to really understand this question we need to know how a JWT token is composed.

A typical JWT token is a string composed by 3 parts (separated by a “.”): the header, the payload and the signature.

To have a visual cue about how it looks like, take the following token as an example:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ  

The header

The header, also called JOSE header (JSON Object Signing and Encryption header), contains some metadata that describes which algorithm is used for signature and/or encryption. If we use base64 to decode the header in our example token we will get the following JSON string (properly beautified for your convenience):

{
  "alg": "HS256",
  "typ": "JWT"
}

The most common algorithms available are HS256 (HMAC signature) and RS256 (RSA public/private key pair signature).

In our application we will focus on cracking only HS256-based tokens.

The payload

The payload is the most important part of the token, because it is the one that actually contains the information exchanged between the parties.

In our example, the decoded payload (using base64) is the following JSON string:

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

The payload can contain virtually any kind of data that can be serialized to a JSON string. In this case it’s fairly obvious that the token is used to exchange the information about the user that is currently logged in.

This should ring a bell (a malicious one). What if we could alter the payload of this token at our convenience? Yes, in this particular use case we might be able to impersonate another user or to obtain access to resources that might be restricted to our regular user.

The signature

Of course JWT has a mechanism to avoid people to easily forge their own tokens: the signature.

The signature, which is the third and last part of the token, can be (in theory) generated only by the token issuer authority, for example by an authentication server.

Every time the issuer needs to verify the authenticity of a previously generated JWT token, it simply calculates again the signature for the given header and payload. If it matches the original signature contained in the token, it can safely assume that the token is authentic and not maliciously forged.

As we said, we can have different signature algorithms. In case of HS256 the algorithm to calculate the signature is the following:

HMACSHA256(  
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  <password>
)

As you can see the function HMACSHA256 is used to generate a hash-based signature. This function accepts two arguments: a string consisting of the encoded header and payload separated by a dot and a password (also known as secret).

So the password is what actually protects tokens from being forged, and it must be accessible only to the issuer authority. If the password is disclosed, a malicious attacker will be able to forge a token with an authentic signature and the issuer authority will not be able to distinguish forged tokens from authentic ones anymore.

Our application will use a brute force approach to try to find out the password. Given a specific token, it will be able to try any possible combination of characters over a specific alphabet and check if the resulting string is the valid secret for the token signature. If we are successful we can then use the discovered password to sign tokens that contains information that we can alter at our own will.

Are JWT tokens safe to use?

That’s probably what you are asking yourself right now…

My personal answer to this question is “definitely YES“!

The weakness that we are trying to exploit here is the same that every password-based system has: passwords can be guessed or be subjected to brute force attacks!

So it’s your responsibility to choose strong passwords in order to protect the signature of your JWT tokens from common attacks like brute force (the one we are going to use here) or dictionary attacks.

Also, if you need an increased level of security and having longer tokens is not an issue, you can switch to the RS256 signature algorithm.

There are also other techniques that you can adopt:

  • Store all the generated tokens in a database so that if a token signature is verified you can also check if it was really generated by the issuer.
  • Add a level of encryption over the full token string (which will even hide the fact that the original token is in JWT format).

These techniques are not really necessary though, and even if they might increase the security of your application they will add extra layers of complexity. In most of the cases, choosing a long random password over a big alphabet (e.g. including lowercase, uppercase, digits and symbols) should be enough to make your tokens virtually “uncrackable”.

Finally, we need to take into consideration that a brute force attack is the least performant attack that we can make, and it might take years, even centuries to disclose a very strong password, even using a large cluster of performant machines working in parallel.

The approach to the problem

Our JWT token cracker application will consist of two parts: a server and a client.

The goal of the server is to collect the information needed to perform the computation and then distribute and coordinate the workload between the clients.

The server will be initialized with two parameters:
– A sample well formatted JWT token from a given issuer authority,
– An alphabet of characters to use to generate all the possible variations of strings.

The space of the possible solutions is the infinite space of all the strings (of any length) that can be generated within the given alphabet. In short, the role of the server is to divide this space into chunks and assign them to the clients, making sure that every client gets a different chunk.

The server doesn’t know how to crack the token (which is the goal of the client), it just knows how to distribute the chunks. To understand how the chunks are managed we need to clarify how the space of solutions can be represented.

Let’s do this with an example.

If we take an alphabet containing the characters a, b, c and 1 we can generate the following strings:

(empty string), a, b, c, 1, aa, ab, ac, a1, ba, bb, bc, b1, ca, cb, cc, c1, 1a,
1b, 1c, 11, aaa, aab, aac, aa1, aba, ...  

As you might have noticed, there is an implicit order in the way we listed these strings on the given alphabet.

If we keep progressing with the iteration, it will be endless but we can be sure we are not going to miss any possible string over the chosen alphabet. In other words we can enumerate the possible solutions. If we start from 0 our enumeration will look like:

 0 ''
 1 'a'
 2 'b'
 3 'c'
 4 '1'
 5 'aa'
 6 'ab'
 7 'ac'
 8 'a1'
 9 'ba'
10 'bb'  
...

The enumeration associates univocally a non-negative integer to one and only one possible solution over the alphabet.
With this approach we can form a one-to-one relationship between the space of the non-negative integers to the space of strings built over the given alphabet.

This approach makes tracking the distributed workload relatively simple for the server, because a chunk of the solutions space can be represented simply with two integers (from and to) that define the boundaries of the sub-space.

If all the chunks have a fixed size, then the server only needs to maintain an integer in memory that identifies the starting point of the next chunk (a cursor over the space of solutions) and a list of the chunks currently being processed by every connected client.

When a new client joins the cluster, it will get the next chunk available (as pointed by the cursor) and the cursor gets moved forward.
The same happens when a client in the cluster finishes to analyze its chunk and requests a new one.

To make this clear, let’s see an example where the size of our chunks is 3.

At first no client is connected, so the state of our distributed application can be represented as follows.

{
  "cursor": 0,
  "clients": {}
}

Then a client connects, so the server gives it the next available chunk ([0,2]) and moves
the cursor forward:

{
  "cursor": 3,
  "clients": {
    "client1": [0,2]
  }
}

Then after some time, 2 new clients connect, client 2 arrives slightly earlier than client 3, so it gets the second chunk ([3,5]) while client 3 gets the third chunk ([6,8]):

{
  "cursor": 9,
  "clients": {
    "client1": [0,2],
    "client2": [3,5],
    "client3": [6,8]
  }
}

Client 2 is “super” fast and after few milliseconds it already finished his job and requested a new batch, so it gets the next available chunk ([9,11]):

{
  "cursor": 12,
  "clients": {
    "client1": [0,2],
    "client2": [9,11],
    "client3": [6,8]
  }
}

I think you got the idea…

This process continues until one of the clients find the solution in a chunk. New clients can join the cluster at any time.

When the solution is found, the server is notified which then notifies all the connected clients, so that they can stop and exit from the cluster.

To make it work, we will need an efficient algorithm to calculate the string associated to a specific integer over the given alphabet. For this purpose, we will use the library indexed-string-variations, which was built exactly for this use case. If you are curious to know how it works have a look at the official repository.

Networking patterns

Let’s analyze what type of messages will flow on the network in order to choose the ideal networking patterns for our specific use cases.

From the clients point of view, we have 4 different type of networking messages:

  1. Start: a client joins the cluster and receives the current token, the current alphabet and a first batch to process.
  2. Batch: a client finishes to process a batch without finding the password and requests a new batch.
  3. Success: a client finds the password and communicates it to the server.
  4. Exit: a client receives an exit message because some other client in the cluster found the password.

To support these messages we can leverage two different networking patterns offered by ZeroMQ: the router/dealer pattern and the pub/sub pattern.

The router/dealer pattern is used to exchange messages between the server and the clients, and it supports complex multi-layer network structures. It allows managing multiple request-response cycles maintaining the relationship between every request and the associated response.

In our case, the server will act as a router dispatching tasks to the clients (the dealers) and expecting them to respond with a success (the password was found in the given batch) or a failure (the password was not found and a new batch can be processed). Every client gets a different batch, so every client has an exclusive router-dealer connection with the server. With this pattern we can manage Start, Batch and Success messages.

The pub-sub pattern connects a publisher to a set of subscribers, allowing a specific message to be distributed to all the subscribers that are interested in it. This is the perfect pattern to propagate (broadcast) the exit messages to all the clients. In the ZeroMQ implementation of this pattern, every message needs to have a topic and the subscriber needs to tell the server which topics they are interested in. In our case, we will only have the exit topic and every client will be subscribing it to receive the exit message.

To have a visual understanding of these patterns and see how they are composed in our architecture you can have a look at the following image:

ZeroMQ & Node.js Tutorial - Cracking JWT Tokens (Part 1.)

As you can see in the picture the server has two sockets. One to act as a router (to distributes the batches) and one to act as a publisher (to publish the exit signal). Every client has two sockets as well, one to act as dealer (to process the batches) and one to act as a subscriber (to listen for the exit signal).

Notice that the router/dealer connections are exclusive (not shared across clients), while every client subscribes the same channel on the server for the pub/sub connection.

Next Up

This was the first part of the article, where my aim was to get you up to speed on theory and to outline how the application will work. In the next part, we are going to actually build our password cracker application!

If you have any questions about this topic, find me in the comments section!

Meanwhile if you feel like you want to strengthen your knowledge of Node.js and design patterns to get ready for the second part, I recommend you to have a look at Node.js Design Patterns Second Edition.

A little spoiler: in the second part of the article, we are going to have a nice challenge with a prize, so be sure you won’t miss it 🙂

Acknowledgements

This article was peer reviewed with great care by Arthur Thevenet, Valerio De Carolis, Mario Casciaro, Padraig O’Brien, Joe Minichino and Andrea Mangano. Thank you guys for the amazing support!

Source:: risingstack.com