Wednesday, June 01, 2022

Setting up Tizen App Development Environment - All about Installation, Emulator, Remote Watch Device Setup - Part 1

Using and building applications for Android Wearables has always been a dream for me since 2015. Unfortunately, the cost and access to such watches 5 years back made them impossible to explore and debug in real-time. Luckily, around 2021 I got my first Samsung Wearable Watch 4 model in Canada 🍁 with my employer's wellness benefits. However, I used them to track calories burnt, alarms, & alerts. Samsung Health is one of my favorite applications, which creates a competitive environment to challenge people online.

Setting up Tizen Development Environment - All about Installation, Emulator, Remote Watch Device Setup

After a while, I was curious about Samsung App development and started reading through docs and wiki to learn the basics quickly. Fortunately, Tizen App development is similar to Android app development with its own IDE interface. Let's explore them one by one to set up the environment for building a stock ticker application on a watch in a series of a blog posts.

Setting up Tizen App Development Environment - All about Installation, Emulator, Remote Watch Device Setup

Requirements:

- Preferably 8 Gb RAM machine comparing Android Studio, which requires tons of RAM.
- < 5 Gb of Storage
- Samsung Watch to have live debugging enabled. (optional)
- Virtualization is enabled on the laptop to run the emulator.

Installation:

Head over to the Tizen site to grab the IDE application and make sure to install them.
  • Install Watch Development SDK 3+
  • Mobile SDK is optional
  • From extras > choose Certificate Manager Addon
Install the relevant SDK to have them offline to build quickly and deploy.

Certificate Profile Manager:

Make sure to create your own signing certificate by choosing "Samsung" as your primary way. This has been discussed in Stackoverflow as none of the developer sites talks about the issue.

- Create a new certificate and sign in to your Samsung account to accept the terms.

Setting up Tizen App Development Environment - All about Installation, Emulator, Remote Watch Device Setup

Here is the complete step-by-step way to create and save the certificate profile.

Emulator and Watch Setup:

Now that we have successfully set the Tizen SDK with signing certificates, We'll next pivot to develop a sample hello world app that successfully deploys on both emulator and actual watch device in less than 10 minutes. And, that will be covered in the next blog post.

Until then, stay tuned. For bugs/hugs feel free to comment below. Share is care.

Tuesday, May 31, 2022

Odometer.js Animated Number Counter From Zero To Value - JavaScript Animation Part 2

The last time when I wrote Animated Number Counter From Zero To Value post around 2014, there was a substantial unexpected appreciation for this post as it was one of the first blog posts describing the methodology to animate numbers. However, It lacks a few formating and configurations for modern currency usage, number formatting in finance, and other sectors. So, this time I had to either add them as a feature or find some great library to do that. Fortunately, Hubspot (NYSE: HUBS) has open-sourced one of its implementation similar to an animated number counter from zero to value. I'm explaining the odometer.js library in this blog post with a small demo.

Odometer.js Animated Number Counter From Zero To Value - JavaScript Animation Part 2

Install

In the traditional way, contrary to npm install nowadays just include script tag and CSS stylesheet import for theme support.

<link rel="stylesheet" href="http://github.hubspot.com/odometer/themes/odometer-theme-default.css" />

<script src="http://github.hubspot.com/odometer/odometer.js"></script>


Animated Number Counter from Zero to Value

As simple as JQuery API, this time find the reference in the DOM and set up a few configurations to start the animation rolling.

var odometerRef = document.querySelector(".odometer");

od = new Odometer({
  el: odometerRef,
  value: 0,   // initial value
  format: "(,ddd)",
  theme: "default"
});

This time we have theme and format support to customize the numbers displayed in the DOM. Feel free to play with the configuration and themes listed here

Finally, time to update the values:

setInterval(function () {
  qty = qty + 15000;
  odometer.innerHTML = qty++;
}, 3000);

to simulate the value updation, I have utilized setInterval from core javascript to run the function on a defined interval to update the odometer value. 

Demo:


Whenever there is a change in the value, the odometer observes the change and reflects with ease animation. Thus, we have more control now and with a lot of formating and theming options. Imagine building a Stock ticker with an odometer with fluctuation in prices, and a Gasoline meter which odometer.js comes in handy with a few API calls.

Kudos to the Hubspot team 💗and the fantastic CRM product they have built.

That's all for now, meet you soon in the next blog post. Bugs & Hugs, feel free to comment below. Share is care.

Tuesday, January 04, 2022

LRU Cache Implementation LeetCode Solution

Idea

To implement an LRU Cache data structure to store and retrieve data in constant time i.e., O(1). However, We'll have to look for an existing data structure that can perform both store and retrieval processes in almost constant time. HashMap or Hashing generally can help here to efficiently store and retrieve them but with a caveat of not storing them in the least recently used order.

If you're new to LRU Cache, I would suggest you check out this video first.



Explanation

Before jumping into the code snippet, The general idea behind this implementation will require DoublyLinkedList and HashMap internally to make this magic happen.

1. DoublyLinkedList is capable of managing the usage order in almost constant time.

    - Move to Head

    - Remove Object

    - Add Object 

2. HashMap is capable of serving the get and putting a request in almost constant time.

Why not merge them and form an LRU data structure.

class LRUCache {

    class DoublyLinkedListNode {
        int key;
        int value;
        DoublyLinkedListNode previous;
        DoublyLinkedListNode next;
    }
   
    private void addNode(DoublyLinkedListNode node) {
        node.previous = head;
        node.next = head.next;
       
        head.next.previous = node;
        head.next = node;
    }
   
    private void removeNode(DoublyLinkedListNode node) {
        DoublyLinkedListNode previousNode = node.previous;
        DoublyLinkedListNode nextNode = node.next;
       
        previousNode.next = nextNode;
        nextNode.previous = previousNode;
    }
   
    private void moveToHead(DoublyLinkedListNode node) {
        removeNode(node);
        addNode(node);
    }
   
    private DoublyLinkedListNode popTail() {
        DoublyLinkedListNode node = tail.previous;
        removeNode(node);
        return node;
    }
   
    private Map<Integer, DoublyLinkedListNode> cache = new HashMap<>();
    private DoublyLinkedListNode head, tail;
    private int capacity;
    private int size;

    public LRUCache(int capacity) {
        this.size = 0;
        this.capacity = capacity;
       
        head = new DoublyLinkedListNode();
        tail = new DoublyLinkedListNode();
       
        head.next = tail;
        tail.previous = head;
    }
   
    public int get(int key) {
        DoublyLinkedListNode cacheNode = cache.get(key);
       
        if(cacheNode == null) return -1;
       
        moveToHead(cacheNode);
       
        return cacheNode.value;
    }
   
    public void put(int key, int value) {
        DoublyLinkedListNode cacheNode = cache.get(key);
       
        if(cacheNode == null) {
            DoublyLinkedListNode newNode = new DoublyLinkedListNode();
            newNode.value = value;
            newNode.key = key;
           
            addNode(newNode);
            cache.put(key, newNode);
           
            ++size;
           
            if(size > capacity) {
                DoublyLinkedListNode lruNode = popTail();
                cache.remove(lruNode.key);
                --size;
            }
        } else {
            cacheNode.value = value;
            moveToHead(cacheNode);
        }
    }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */

Monday, March 08, 2021

Mitigate ExpressJS CSRF using csurf npm module tutorial

Cross-Site Request Forgery attack is a prominent and classic web-based attack where you can request sensitive actions on behalf of the users and that may cause severe damage to the user data. To overcome such request forgery issues, a CSRF token is added explicitly to the request header or in the cookie or post request body which is then decoded on the server-side and validated against the session.

Mitigate ExpressJS CSRF using csurf npm module tutorial
Mitigate ExpressJS CSRF using csurf npm module tutorial

Install

> npm install csurf

Initialize

We've imported csrf module and initialized the csurf module with a cookie as a false option by default. This would start accepting the Anti-CSRF tokens either via header or request body which effectively prevents csrf attacks instead of sending cookies.

var csurf = require('csurf')

var csrfProtection = csrf({ cookie: false })

CSRF Token Generation

As the client-side API requires attaching the ant-csrf token, We need to send out the csrf token by generating it and responding via GET API. Either one can respond with render function or directly with JSON/XML based response to the frontend client.

app.get('/form', function (req, res) {
  // pass the csrfToken to the view
  res.render('send', { csrfToken: req.csrfToken() })
})

CSRF Validation Middleware

As the validation of the CSRF token happens in the server, ensure to install body-parser to parse any tokens passed via body part or access the token directly via header. Add the middleware above all request routes to have seamless verification of the token before executing the actual route.

app.use(csrfProtection)

Error Handling

To efficiently respond to the API client or frontend service, I would strongly recommend adding an error handling layer before the request route with a specific format response by which clients can easily parse and understand the error message thrown from the server.

app.use(function (err, req, res, next) {
  if (err.code !== 'EBADCSRFTOKEN') return next(err)
 
  // handle CSRF token errors here
  res.status(403)
  res.json({err: "CSRF ERROR"}) // respond with JSON response
})
Thus, We have successfully added CSRF validation logic as middleware to verify the request before being executed. For bugs/hugs, feel free to comment below. Share is care.

Sunday, March 07, 2021

Integrating Google Recaptcha with ExpressJS

Fighting spam and bots over the internet is a never-ending problem and that's why companies like Cloudflare kick-off their journey from the building/contributing honeypot to IPO. However, there are other few ways to prevent spam API calls, brute force attacks and they are solving captchas, and Google is one of the pioneers in providing better user experience plus spam prevention techniques. There are other online services such as Funcaptcha captcha as a service for SaaS companies.

Today, let's see about implementing Google ReCaptcha with expressjs Node server as middleware and rendering them in forms.

Integrating Google Recaptcha with ExpressJS
Integrating Google Recaptcha with ExpressJS 

Installation

npm install express-recaptcha --save

Setup:

Signup for Google Account and click here to create new Recaptcha keys and specific to Version 3. Enter the domain including localhost for testing purposes and grab the Site key and Secret key to access Recaptcha APIs from Nodejs backend.

var Recaptcha = require('express-recaptcha').RecaptchaV3;

var recaptcha = new Recaptcha('SITE_KEY', 'SECRET_KEY');

Frontend Client setup

As the client-side is so specialized and varies from ReactJS, Vue, or plain vanilla javascript, I recommend you to follow Google docs to implement them.

Server Validation

As this blog post covers primarily server validation logic, ExpressJS provides excellent integration with middleware where the Recaptcha validation can be added to the routes before even route logic executes.

app.post('/', recaptcha.middleware.verify, function(req, res){
  if (!req.recaptcha.error) {
    // success code
  } else {
    // error code
  }
});
As mentioned before, the middleware function that contains Recaptcha verification executes first and the results are attached to the request object for implementing the business logic. One could use the req.recaptcha.error object to verify if the Recaptcha request is successful.

Req.recaptcha object

{
  error: string, // error code (see table below), null if success
  data: {
    hostname: string, // the site's hostname where the reCAPTCHA was solved
    score: number, // the score for this request (0.0 - 1.0)
    action: string // the action name for this request (important to verify)
  }
}
Feel free to follow the npm package of Express Recaptcha for more details and customization logic.

For bugs/hugs, feel free to comment below. Share is care.

Thursday, May 28, 2020

How to automate AWS SES E-mail Template Update

Amazon Web Service Simple Email Service ( SES ) is a popular and considerably cheap service to send out bulk transactional & personalized promotional emails. However, when it comes to the Template-based emails which help to bind values and send HTML email, the most frustrating part is updating the template and testing them.

Problems:

1. Creating a valid JSON file by escaping the HTML Email Text property
2. Updating the templated HTML file ( manual command-line task )
3. Testing the templated emails

How to automate AWS SES E-mail Template Update
How to automate AWS SES E-mail Template Update


Solution:


I've come up with a normal update script written in Nodejs language with the help of AWS SDK that can help in scaling email template updates faster.


Usage:

> node template-creater.js emailtemplate.html emailtemplate.json false emailtemplate-unique-name "Subject for the email"

This will automatically accept the templated HTML file and creates a valid JSON file and tries updating/creating templates in the AWS SES console based on configuration or command-line argument values.

 1st Argument => Templated HTML File
 2nd Argument => Name of the auto-generated template json file
 3rd Argument => Update or Create template ( boolean )
 4th Argument => Unique template name
 5th Argument => Subject of the email

Final Words:


Feel free to use the script ( No license Restrictions for personal/commercial projects and No Warranty from Author ) and for bugs/hugs do comment below. Share is care.

Monday, May 25, 2020

Hashing with Bcrypt in Nodejs

Publishing tutorials on nodejs after a long time 😀😀 and additionally, quarantine made me productive to learn more about Nodejs core concepts and implementing server-side code.

Background:


Learning cryptography is tricky and requires more patience to master those areas. Additionally, If you want to learn more about Bcrypt Algorithm and implementation, check out the link here.

Hashing with Bcrypt in Nodejs
Hashing with Bcrypt in Nodejs


Simple Steps to implement Bcrypt in Nodejs

Installation:

1. npm install bcrypt --save 

Start installing the bcrypt package into your nodejs apps which helps to implement the hashing function.

Hashing Function ( Sync and Async ):


Hashing function with Salt Generation ( Sync )

const salt = bcrypt.genSaltSync(saltRounds);
const hash = bcrypt.hashSync(myPlaintextPassword, salt);
Hashing function with Salt Generation ( Async )

bcrypt.genSalt(saltRounds, function(err, salt) {
    bcrypt.hash(plainText, salt, function(err, hash) {
        // Store hash in your password DB.
    });
});

Verify Function ( Sync and Async ):


Hash verification function ( Sync )

bcrypt.compareSync(myPlaintextPassword, hash); // true/false

Hash verification function ( Async )

bcrypt.compare(myPlaintextPassword, hash, function(err, result) {
    // result == true/false
});

Final note:

Bcrypt is safe as of now from timing attacks and other cryptographic reverse engineering or cryptanalysis. If you would like to check more about implementing using Async and Promises for Bcrypt Module, please check out the documentation of the bcrypt npm module.

Finally, for Hugs/Bugs do comment below. Share is care.