One time password authentication using Nodejs, passwordless and Twilio



One time password is a high demand authentication functionality in today's time while login into the system, making some transaction or taking some high risk action in the system. It provides an additional security in our application. Passwords can be hacked or guessed that depends on the password security policy of your website. However, the one time password give you a password in your email or your mobile number which can be used one time only and is valid for few minutes. Messages sent to your mobile numbers are secured in a way that you can only see them in your mobile.

Implementing one time password is really simple in Nodejs by using Passwordless and Twilio node packages. Please follow the below steps which will setup your webpage where you can enter your mobile number and then you will receive a 6 digit OTP in your own mobile number. Then you can verify the same and if verified then redirected to the login page.

Create an account in Twilio

Goto twilio.com and create an account by signing up. After this you will be logged in to twilio.

How Twilio works

There is an official description of how Twilio works:


Visit the Twilio's getting started page

Once you login, go to this url
https://www.twilio.com/console/sms/getting-started/basics

In the above page there is a step-by-step demo to create a phone number and send a test sms.
- Note down this phone number.

Note the API credentials

On the same page, click on "Show API credentials" on the right side of the page and note down the these two parameters - Account SID and AUTH Token


Install mongodb in your system (if not already installed).

If you have setup the mongodb without authentication, then your connection string will simply be -
'mongodb://localhost:<port>/passwordless-sms'
Replace <port> with your mongodb port (typically 27017).

If you have setup mongodb with authentication, then your connection string will be -
'mongodb://<dbUserId>:<dbPassword>@localhost:<port>/passwordless-sms'

Replace <port> with mongodb port.
Replace <dbUserId> with mongodb database user id.
Replace <dbPassword> with mongodb database password.

Clone the passwordless example demo Github repo

Clone the following github repo into your system
https://github.com/rbudiharso/smsauth-example


Edit the source code

Open the app.js in your favourite editor and edit the below lines:

Find this lines
accountSid = 'TWILIO_SID' 
and replace the TWILIO_SID with your Account SID which you have noted down before.

Now, find this line
authToken = 'TWILIO_AUTH_TOKEN'
and replace the TWILIO_AUTH_TOKEN with the AUTH Token you noted down before.

Now, find this line 
from: "TWILIO_NUMBER"
and replace the TWILIO_NUMBER with the phone number you noted down before.

Now, find this line
db = 'mongodb://localhost/passwordless-sms';
and replace this mongodb connection string with the connection string you made earlier.

Generating 6 digit OTP

Open nodejs console and go the github repository directory in your system. Execute the below command in console

npm install random-js --save

Open the app.js again find the below function

tokenAlgorithm: function() {
 // custom token generator
 // short random token generator, enough to fit into single SMS
 return '12345'
}

and replace this function with below line of code:

tokenAlgorithm: function() {
 var random = new Random(Random.engines.mt19937().autoSeed());
 console.log(random);
 var value = random.integer(100000, 999999);
 console.log(value);
 return value.toString();
}

Running our app to test

In node console execute the command
node app.js

Open the browser and enter this URL
http://localhost:9000

Type your mobile number with country code. You will receive a 6 digit OTP in your mobile number. Then in next page enter that 6 digit OTP and you will be logged in.

Note : You should also code out the token timeout functionality. When passwordless saves a token in mongodb, its timestamp is also saved. So, while OTP verification, you should get that timestamp and check if it is within range of our timeout setting and throw exception otherwise.

Print reverse level order traversal of Binary Search Tree

struct node
{
 int data;
 struct node* left;
 struct node* right;
};

struct node* newNode(int data)
{
 struct node* temp = (struct node*)malloc(sizeof(struct node));
 temp->data = data;
 temp->left = temp->right = NULL;
 return temp;
}

struct node* insertNodeInBst(struct node* root, int key)
{
 if (root == NULL)
 {
  return newNode(key);
 }
 if (key < root->data)
 {
  root->left = insertNodeInBst(root->left, key);
 }
 else
 {
  root->right = insertNodeInBst(root->right, key);
 }
 return root;
}

int level(struct node* root)
{
 if (root == NULL)
 {
  return 0;
 }
 else
 {
  int lLevel = level(root->left);
  int rLevel = level(root->right);
  if (lLevel > rLevel)
   return (lLevel + 1);
  else
   return (rLevel + 1);
 }
}

void printGivenLevel(struct node* root, int level)
{
 if (root == NULL)
  return;
 if (level == 1)
  printf("%d ", root->data);
 else if (level > 1)
 {
  printGivenLevel(root->left, level - 1);
  printGivenLevel(root->right, level - 1);
 }
}

void reverseLevelOrderTraversal(struct node* root)
{
 int h = level(root);
 int i;
 for (i = h; i >= 1; i--)
 {
  printGivenLevel(root, i);
 }
}

int main()
{
 //Read space separated numbers
 string rawInput;
 vector<string> numbers;
 while (getline(cin, rawInput, ' '))
 {
  numbers.push_back(rawInput);
 }
 
 // Uncomment the below code to Add your inputs here to test without inputting from user
 /*numbers.push_back("5");
 numbers.push_back("4");
 numbers.push_back("3");
 numbers.push_back("9");
 numbers.push_back("1");*/
 
 int key = 0;
 struct node* root = NULL;
 while (!numbers.empty())
 {
  string number = numbers.front();
  key = atoi(number.c_str());
  root = insertNodeInBst(root, key);
  numbers.erase(numbers.begin());
 }

 reverseLevelOrderTraversal(root);
 return 0;
}

Finding largest element in array having first increasing then decreasing elements in O(LogN)

//Array which has n elements in it.
//1st element->a[k] ascending order.
//a[k]->last element descending order.
//Find largest element in this array.
//
//Example :
//1 2 3 4 3 2 1
//Output 4

char calculateOrder(int first, int second, int third)
{
 //desc
 if (second< first && second > third)
 {
  return 'd';
 }
 else if (second > first && second < third)
 {
  return 'a';
 }
 else
 {
  return '0';
 }
}

int CompareThree(int first, int second, int third)
{
 //max of three
 if (first>second && first > third)
  return first;
 else if (second> first && second > third)
  return second;
 else
  return third;
}

void kElement(int arrIntegers[], int left, int right)
{
 int mid = (left + right) / 2;

 //Calculate order of mid-1, mid, mid+1

 char order = calculateOrder(arrIntegers[mid - 1], arrIntegers[mid], arrIntegers[mid + 1]);
 if (order == 'd') //discard right
 {
  kElement(arrIntegers, left, mid);
 }
 else if (order == 'a')
 {
  kElement(arrIntegers, mid, right);
 }
 else
 {
  printf("%d", CompareThree(arrIntegers[left], arrIntegers[mid], arrIntegers[right]));
  return;
 }
}

int main()
{
 int intArray[6] = { 1,2,3,4,3,2 };
 kElement(intArray, 0, 5);
 return 1;
}

Top new features of Angular 4.0





Angular 4.0 is now officially released on 23rd March 2017.
You might probably be wondering it was Angular 2 that was running and now Angular 4. Where has Angular 3 gone?
The answer is much simpler than you might expect. The angular core team have certain components which have been targeted to 4.0 while the Angular core was still in 3.0. These components are necessary angular components and has to be shipped with Angular library. So to cope with this conflict, they have skipped version 3 and target all the components to version 4.0 only.

One of the great thing about Angular 4 is that it is backward compatible with Angular 2.

Angular releases over 2.0

Release Features
2.1 Route Preloading
2.2 Ahead of Time (AOT) + ngUpgrade
2.3 Language Service.
* The language service is useful for IDEs to integrate with Typescript. Its not just they are shipping the compiler. Its been better now to show errors and warnings on the fly.

Angular transition from 2.3 to 3.0

Release Features
Patch 2.3.1 No Features, No Breaking Changes
Minor 2.3.0 New Features, No Breaking changes
Major 3.0.0 New Features, Potential breaking changes

Angular team has clearly mentioned that every release will be - Predictable, Transparent and Incremental. It will not be like what happened when the transition took place from Angular 1 to Angular 2.

Angular 4 future evolution (Tentative schedule)

Angular 5 - September / October 2017
Angular 6 - March 2018
Angular 7 - September/October 2018

Upgrading to Angular 4

It's very easy to upgrade to Angular 4 from Angular 2 app. We just need to run the following commands.

For Mac:

npm install @angular/{common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router,animations}@latest typescript@latest --save 

For Windows:

npm install @angular/common@latest @angular/compiler@latest @angular/compiler-cli@latest @angular/core@latest @angular/forms@latest @angular/http@latest @angular/platform-browser@latest @angular/platform-browser-dynamic@latest @angular/platform-server@latest @angular/router@latest @angular/animations@latest typescript@latest --save

Angular Universal

Now Angular app can be rendered on the server using Angular Universal. For more info check out https://universal.angular.io/

Semver (Semantic Versioning) now

Angular Team will now be using Semver to version their releases. For more details to Semver you can visit http://semver.org/

Angular 4 new features

Animations

Animations now have their own package @angular/platform-browser/animations

Templates

The template tag has been changed to ng-template. The template tag being more generic to other frameworks, Angular has made it to ng-template.

Else is now supported with ngIf 

<div*ngIf="stack.length > 0; else handleBlank"><p>The stack has some elements.</p>
 <ng-template#handleBlank>Stack is empty. Please add some numbers.
the handleBlank is a local reference to the ng-template. We use this reference name in the else clause of the ngIf. The old way will still work.

Typescript 2.2 is supported now.

Since Angular 2 release, the team has made the Angular framework easy to code with Typescript (it can still be used with javascript and dart). Typescript is a syntactical sugar. Typescript 2.2 is supported now in Angular 4. For more info visit https://www.typescriptlang.org/

The 'as' keyword

The 'as' keyword is used to store the output of a result in a temporary variable. For. e.g.
<div ngif="let price of book | currency as LocalPrice; index as = i">
{{i}} ) {{book.Name}} - LocalPrice
</div>

It can effectively be used as an output of async result.
observable_or_promise_expression | async as result
{{result.prop}}

Http

Search parameters have been simplified in http request.
http.get('${apiUrl}/api/getBookInfo', {params : {id : 1} });

In previous version:
const params = new URLSearchParams();
params.append('id', 1);
http.get('${apiUrl}/api/getBookInfo', {search : params });

Pipes

A new pipe has been introduced with the Angular pipes collection that is - titlecase. It changes the first letter of each word to the uppercase. For e.g. the below code will display "Hello World".

<p>{{ 'hello world' | titlecase }}</p>

Test

To override a template in a test has been simplified.

TestBed.overrideTemplate(DialerComponent, '<div>{{dialer.name}}</div>'

In previous version:
TestBed.overrideComponent(SomeComponent, {
 set: {
    template: '<div>Overridden template here</div>'
    // ...
 }
});

Email Validator 

An email validator is introduced along with other validators in Angular. The email validation can be done with Regex, however since email is very frequently used field, so it does make sense to introduce a inbuilt validator for this.