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.


Sunday, March 22, 2020

Hassle free Appointment Scheduling Software for Business

Last month while traveling to the SaaS conference, one of the business owners I used to do contract work for asked for a small recommendation of software tools that can be used to optimize and automate the business task. So, quickly I got into the requirements and suggested a bunch of tools from Zoho, Shopify, Google to automate tasks that included Google Calendar for GSuite that helps in scheduling, reminding events. But now the requirement came differently to allow clients to prebook appointments and getting paid online to prevent spam signups by which Google calendar is not the right solution for scheduling needs. Stepping back little I googled for potential solutions and recommendations for Online Appointment Scheduling software by searching to Capterra, G2Crowd, FinanceOnline and even more. Fortunately, I met Guru from Zealschedule who attended the event and when introduced to each other with current work and he was so much happy to invite me for Contract works related to Android. Meanwhile, to my surprise, he pitched his company and motive behind his product that was an astonishing way about online appointment scheduling space where a lot of apps are behind lag and in need of a leader.


Signup
| Pricing | Help Docs | Support | Free Appointment Scheduling Software

Why Zealschedule?

Prior to trying out Zealschedule, I've been trying out calendly, Acuity Scheduling, Zoho Bookings, and even more calendar-based scheduling apps. But every app I used and started customizing for the requirements, I literally found limitations in the product side or the lag in UI/UX and integrations with the other business application. Keeping that in mind, I have tried out Zealschedule and most of the business requirements were satisfied and the team was super flexible to support customization that can be generalized for all customers.

Integrations

Zealschedule has extra-ordinary support for native integrations and zapier support to make the workflow easy for all types of business from SMB to Enterprise organizations. So that made our life easy to trigger workflows within the application based on realtime booking stats from the API and Zapier. Checkout zapier for Zealschedule which is available in private beta. Apart from Zapier, Microsoft calendar ( office 365 ), GSuite Calendar and zoom integrations are available in realtime that happens when the booking is done from Zealschedule apps.

Payment Integrations

Additionally, We could collect online payments via integrated payment hosted solution pages such as Stripe, Square Checkout, Razorpay, Paytm and even more. Payments are additionally tracked within the Zealschedule reports to checkout for revenue, sales and booking reports from the dashboard.

Tech Support

The team from Zealschedule is really enthusiastic working from remote while facing customers and tech support is super fast. They do support phone, chat, and email support and check out the options here

Now that this product has excellent traction and minimal features, this can be a good start for any business organization to have an appointment scheduling application instead of hitting excel sheets or maintaining a separate calendar with Google or Microsoft. Let me add more features to this blog post once trying out different types of appointments and use cases that Zealschedule tries to solve for business organizations and professionals.

Feel free to comment below. Share is care.



Sunday, July 08, 2018

DesignEvo Review- One of the Best Online Logo Maker for You

Essential elements of a successful business:


Attraction & Uniqueness


A business needs something attractive to catch the clients’ eyes, and the most suitable thing is the logo. A logo plays a vital role in the business world, and it is important to have a unique one to distinguish between you and others. Although there are many professional designers to help you create logos, you know that no one can understand your business than yourself. On the other hand, if you run a small business, you may have the budget problem to hire a designer. Thus, the best logo should be designed by yourself with the help of DesignEvo logo maker.

DesignEvo Review- One of the Best Online Logo Maker for You


DesignEvo logo maker is devoted to helping people create professional logos without spending much time or effort. Even you know nothing about design, you can use abundant resources of DesignEvo to create unique logos with a professional appearance in minutes.

Handy & Resourceful

First, there is no registration or download requirement.  

Second, DesignEvo logo maker has prepared 5000+ well-designed logo templates to help you design. They cover many kinds of themes, such as animal & pet logos, photography logos, hipster logos and so on. Besides, all of them are fully customizable. If you have no idea how to make a logo, you can select a preferred template and adjust the elements to custom a unique logo at will.
DesignEvo Review- One of the Best Online Logo Maker for You

Third, there are millions of icons, various shapes, and stylish fonts. In order to make it comfortable to meet users’ needs, DesignEvo allows you to search millions of icons with any themes and styles to create logos. All of them are vector graphics and will enable you to adjust the size without worrying about the sharpness. You can also choose right shapes and fonts to perfect your custom logo.

Powerful

DesignEvo offers you full edit features: change background and colors, rotate, adjust the effect, layout, layer, and duplicate, etc. When you have finished editing, preview it before saving and downloading. It shows six occasions of your logo, on a business card, on a book cover, on a wall, on a T-shirt and so on. When you ensure that everything is well done, then download it. There are three options for you, free package, basic package and plus package. The latter two are paid options but with many more features to meet your needs, so please feel free to select the suitable one to download your logo.
DesignEvo Review- One of the Best Online Logo Maker for You

Final words

Whether you need logos for your business or not, only if you want to try to create logos online by yourself, you can come to use DesignEvo to help you. It is born to help people who need logos. With all the brilliant features, you can design professional logos in minutes easily even if you are a newbie. By the way, all of the features are free to use. DesignEvo is waiting for serving you.

Feel free to comment below. If you would like to share your Guest/sponsored post in our blog, kindly write to my inbox/Google+ Hangout. Share is care.

Monday, July 10, 2017

Gitlab Shared Runner CI with Docker Tutorial - Complete Guide on Building Android Studio Project in Gitlab

After a long break, writing a new post on building Android Studio Gradle project on Gitlab Pipelines with Docker without hassling about server charges or build time. Gitlab Pipelines and Registry is a boon for developers who need CI for their apps and additionally, Gitlab provides private repo. Today let's look at creating a pipeline with an environment where our app is built within Docker when you commit to Gitlab repository.


Gitlab Shared Runner CI with Docker Tutorial - Build Android Studio Project in Gitlab

One of the most hassling things is building the project and moving into production phase by testing the app on several devices. The thing is maintaining a private server to build your production ready apps will cost you high like Travis CI, Circle CI. For startup companies, Gitlab shared runner is more than enough for building the application and delivering it with artifacts on regular basis.


Getting Started:

If you're familiar with Docker basics, It would be fine to continue with this tutorial. If not you can just learn about Docker basics here. Docker is an awesome environment where you virtualize your environment from the Host environment and run your specific test, build, commands. Since you virtualize your docker environment you won't be affected by external dependencies or prone to vulnerabilities while shipping your application. If you don't have Gitlab Account, signup now. It's completely free for individual developers.
  1. Create Gitlab Repo 
  2. Commit your Android Studio project in master branch

Enabling Shared Runner and Pipeline in Gitlab:

After creating the project, visit Settings -> Pipelines in your project repo and make sure Shared Runner is Enabled. You may get up to 4 Shared instance to build your project. Fortunately, Gitlab has collaborated with DigitialOcean to maintain servers for running such builds, test for users. so, you need not worry about scaling, downsizing the server size. 

Gitlab Shared Runner CI with Docker Tutorial - Complete Guide on Building Android Studio Project in Gitlab
Enable Shared Runner for this Project

Build Configuration File

In order to trigger our build, we need to write some configuration file. First, let's build our Docker image using Dockerfile. Gitlab too provides private docker registry for users, where you can build the Docker image in the pipeline and upload it to Gitlab registry. So, this will reduce our build time in halfway because installing our build tools ( Android SDK ) and other tools earlier will reduce the time and concentrate on compiling the source code into APKs.

Our Docker file looks like given below, it's just series of Linux commands where you process it and save it as Docker image. Whenever need you can deploy it as a container and make your desired process run inside the Docker container.

Prerequisites :

  • Create a new branch from existing master branch, remove all your application code. 
  • Create new file named as Dockerfile
  • Checkout docker file snippet below
  • Create new file named .gitlab-ci.yml 
  • Checkout Gitlab-ci file below, customize it as per your repository name
  • Commit all your files, this will automatically trigger a build to create new Docker Image and upload it to Docker registry.
Dockerfile for creating Android environment image is given below,




gitlab-ci.yml file for instructing the pipeline to perform the job is also given below, kindly replace with your own repository registry name, branch name or else build won't be triggered.


once you commit your code, Gitlab automatically triggers an Image Build in the pipeline. if everything goes smooth, your docker image will be uploaded to your Gitlab Docker registry. You can use the Docker image for further building the project without any hassle. Whenever you need to refresh or update your SDK tools, you can simply change and commit it, that will trigger an image building process and it'll be uploaded to your Gitlab Docker registry.

Gitlab Shared Runner CI with Docker Tutorial - Complete Guide on Building Android Studio Project in Gitlab
Building process after each commit

Build your Application:

Switch to your master branch, start writing similar gitlab-ci.yml file to instruct the build machine in order to trigger build and building the artifacts. It's going to be normal Gradle commands to build your application project and generate your APKs, AAR files and even more out of it. you can sign your application here with confidence by adding your Keystore file as Environment variable.

Let's look at our configuration file for building the application,



So, in before script, we added execution permission for gradlew executable file in user level (normally root/guest in terms of Docker). In build script, we simply added our Gradle command to build our application project. Since it's a sample I haven't added release build script here. After building process is over, you can specify your artifact folder, so that Gitlab can detect that folder and make it available for downloading. Normally it contains your project APK files, logs, Gradle profile report and even more if you have used custom tasks in Gradle.

So, commit this code and Gitlab will automatically trigger a build. Now, Docker is launched in a shared runner and then your Gradle scripts will be running to produce APK. It's up to you to have some integration with Gitlab to deliver your APK artifacts into team e-mails, slack channel, chat or even more.

Gitlab Shared Runner CI with Docker Tutorial - Complete Guide on Building Android Studio Project in Gitlab
Application building in Docker Container

Skip triggering build for each commit

you can skip the triggering build by adding an extra commit message, such as [skip ci] or [ci skip]. This will be automatically understood by Gitlab and it won't be triggering build automatically.

I hope this was an awesome tool for Developers who don't need to write the script for building, launch Build server and run, test, build your source code into release files. You don't need to worry about infrastructure, deliver and testing it seamlessly.


Gitlab Shared Runner CI with Docker Tutorial - Complete Guide on Building Android Studio Project in Gitlab
pipeline containing previous Docker Image Build and Artifact build


If you've any doubts, comment below or chat with me in Google+/Fb. Share is care.