Friday, May 4, 2018

Security Mechanisms in the API

Hello Everyone,

From this post I will talk about the security mechanisms that followed during the API production.

Advanced Encryption Standard (AES) is used in this API to protect the sensitive data of the customer. In here, I have used AES Mechanism to encrypt the user login details where no third party intruder can access to that information. For that purpose, I have created a separate file, which could be used as the helper in encrypting data.

   public static String encrypt(String data) throws Exception{
        Key key = generateKey();
        Cipher cipher = Cipher.getInstance(ALG);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptValue = cipher.doFinal(data.getBytes());
        return new BASE64Encoder().encode(encryptValue);
    }

As this is an online-based system, it should have proper mechanism to protect credit card details of the customers, as that information is the most important out of all. For that purpose, I have used the same AESEncryption.java class with encryption and decryption facilities applying service reusability.

    public static String decrypt(String data) throws Exception{
        Key key = generateKey();
        Cipher cipher = Cipher.getInstance(ALG);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decodedValue = new BASE64Decoder().decodeBuffer(data);
        byte[] value = cipher.doFinal(decodedValue);
        return new String(value);
    }
At the end of the, both the encrypted credit card details are validated against the decrypted credit card details to ensure that no any intruder had changed the information providing secure transactions.

String cardNumber = aesEncryption.encrypt(creditCardNumber);
String cvc = aesEncryption.encrypt(String.valueOf(cvcNumber));
String name = aesEncryption.encrypt(holderName);
getcreditCardDetails = bankService.decryptData(creditCardNumber,cvcNumber,holderName);
if(getcreditCardDetails.get(0) == creditCardNumber && getcreditCardDetails.get(1) ==
              String.valueOf(cvcNumber) && getcreditCardDetails.get(2) == holderName)
     {
      return true;
     }

At the frontend both the username and password are validated using authguard.service.ts class.

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (localStorage.getItem('currentUser')) {
        return true;
    }
    // not logged in so redirect to login page with the return url
    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
    return false;
  }
  logout() {
    localStorage.removeItem('currentUser');
  }

In here angular defined canActivate interface is used to guard to decide the path or the route to be activated based the validity of the user. 

Let's meet again with drug management coding part.Happy coding :)




©Copyright Viraj Wickramasinghe.

Wednesday, April 25, 2018

Food Ordering System with SpringBoot

Hello Everyone,

From this post I will present you the API plan which was created to make a new application.

This system provides functionalities for customers to place their orders and “Cater for You Service” restaurant will fulfill the need.

Execution Order
First, when the customer visits the website of the restaurant he/she need to log in to place any order. For that login screen will be provided. If the customer is not a registered customer, he/she need to register with the system. Every component is loosely coupled to each other. 

After a successful login, customers will be prompted with the food list, which is generated through the REST API service.


Customers can choose the food item and quantity. To place the order customer need to provide the relevant personal details for a successful delivery. Meanwhile system updates and notifies the kitchen and stock.


Customers can choose their own payment method from credit card or via the phone. That request will be transferred to the ESB Enterprise integrator and through that, relevant dummy services will be invoked from the abstract layer service.


After a successful response from the service, customers can select their preferred payment confirmation receiving method out of receiving SMS or an email.


For each Rs.100, one loyalty point is added to their total tally and they can use them when it reaches more than 100 points to buy food.


Additionally another dummy service is implemented for the admin to select a customer on weekly basis, to be awarded as a winner in receiving priceless experience.



Functionalities for the Customer
o   Create an account
o   Log in to their account
o   Navigate through the restaurant’s menu
o   Select items from the menu
o   Add items to their current order
o   Review their current order
o   Provide payment details
o   Receive confirmation in the form of order number
o   View order placed
Functionalities for the Admin
o   Add/Update/Delete food item from the menu
o   Update price for a given food item
o   Update additional information(photo, description)
o   Select a winner on weekly basis


Let's meet again with drug management coding part.Happy coding :)



©Copyright Viraj Wickramasinghe.


Sunday, April 15, 2018

Pharmacy With MERN I

Hello Everyone,

From this post I will start a series of posts talking about the project that we have to do for our AF module.

For our team topic assigned was to make a pharmacy module with MERN(MongoDB, ExpressJS, ReactJS and NodeJS).




First of all we divided our topic vertically into 4 main parts...

  • Stock Management
  • Drug Management
  • Patient Management
  • Sales Management

I was assigned to make the drug management sub module and from this series I will talk about how I started to make it and difficulties that I faced in making it.

Project Initiation

First we decided to use either visual code or webstorm as our IDE.After installing one of them I open an ide of my choice(visual code) and created a folder in the workspace as pharmacy module to initiate our project.

Next, through the integrated terminal I navigated to the project folder and installed nodejs and npm from below site.

                                                             https://nodejs.org/en/

Then I checked whether it's installed properly from below commands.






 Next we want to create the package.json file to hold the meta data of the  project.It can be created from the following command.





Next we have to create a app.js file and index.html file to render our project. As we have decided to create our project using MVC architecture I created separate 3 folders namely models, controllers and views to hold our project files.

Finally required dependencies are installed using npm.

npm install --save react 
npm install --save react react-dom
npm install --save express 
npm install --save mongoose 
npm install --save mongodb 
npm install --save babel-core 

As the required dependencies initially.Later on more and more dependencies will be added to the project. All these dependency versions can be found in the package.json file.

Let's meet again with drug management coding part.Happy coding :)



©Copyright Viraj Wickramasinghe.

Wednesday, April 4, 2018

Rest Services and ExpressJS

Hello Everyone,

By this post I will introduce you about Rest Services.

REST is the acronym for REpresentational State Transfer.It is used to develop wide variety of application used over the different types of networks.


HTTP verbs

Below are the HTTP methods which are used in REST architecture
  • GET − Used to fetch resources
  • POST − Used to insert a new resource.
  • DELETE − Used to remove a resource.
  • PUT − Used to replace a new resource.
  • OPTIONS − Used to get all options that are allowed.
  • HEAD − Used to get the requested header

What is RESTful service?

REST architecture based web services which identified by their URIs. Client applications uses HTTP GET and POST methods.These methods will invoke Restful services called upon.
This is reflected as a subsititution which came over SOAP web services.Main advantage of this was, it is light weighted and no strict standards to follow. 
Both JSON and XML data types used for requests and responses.

Below is an example of creating RESTful web service

POST
  • http://www.afsliit.com/students 
This POST request is used to create a new resource student in the system.


GET
  • http://www.afsliit.com/students/1234 
This GET request is used to get the data of student of ID 1234.

PUT
  • http://www.afsliit.com/students/2312
This PUT request is used to update the data of student of ID 2312.

DELETE
  • http://www.afsliit.com/lecturer/eT45w2
This DELETE request is used to delete the data of lecturer of code eT45w2.




Let's meet again with another exiting post.Happy coding :)



©Copyright Viraj Wickramasinghe.

Thursday, March 22, 2018

Maven and Spring Boot Basics

Hello Everyone,

By this post I will talk about what maven is and it's uses along with depth knowledge about Spring Boot.

Let's first talk what maven is.........

Maven automates downloads dependencies, putting additional jars on a class path, compiling source code into binary code, running tests, packaging compiled code , minimizing the risk of humans making errors while building the software manually and separating the work of compiling and packaging our code from that of code construction.

Inorder to check whether your computer has installed with maven check below command,



What is a POM?

A Project Object Model or POM is the fundamental unit of work in Maven.It is XML format which contain all the dependencies and configuration details project need to process and get build.



Few commands that maven uses
  • mvn clean       - previously generated artifacts will be removed
  • mvn compile   - compile source code
  • mvn package   - bundle is created
  • mvn install      - package is copied to local repo
  • mvn deploy     - final package is copied to remote repo
  • mvn test          - testcases are executed


Before talking about Spring Boot let's talk about spring framework......

Spring is a lightweight framework which act as a framework of frameworks. It provides support to various frameworks such as Struts, Hibernate, Tapestry, EJB, JSF etc. The framework is used to find solution to the various technical problems.

The Spring framework comprises several modules 


  • IOC
  • AOP
  • DAO
  • Context
  • ORM
  • WEB MVC 

What is a Dependency Injection (DI)?

By the name it gives you the maening. Dependencied are injected to classes rather than allowing them to have links to other classes.
This reduces coupling between each classes. DI is a specific type of Inversion Of control(IOC)


 Figure 1

 Figure 2


In figure 1 there is a tight coupling between address and student.If the address class get changed, the student class also need to be changed.But in figure 2 Address Object is passed to the constructor to set the value which reduces the coupling between the address and student.

DI can be achieve through using 3 methods.

● Setter Based
@Autowired
public void setName(StudentService sv){
this.name=sv;
}


● Constructor Based
@Autowired
public Student(StudentService sv){
this.student=sv;
}


● Fields
@Autowired
private CacheMonitor cache;


Now let's talk about what Spring Boot do...

Why to use Spring Boot?

Though Spring is a good framework, It is hard to configure and manage the code while it takes some time to bootstrap the project. But by using Spring Boot we can minimize those drawbacks.Integration of the 3rd party libraries are highly supported by Spring Boot. Presence of integrated server to run the application also provides Spring Boot more special.

Starters can be downloaded from the Spring Boot website easily.Below are some starters used by spring boot..


  • spring-boot-starter-security 
  • spring-boot-starter-web-services
  • spring-boot-starter-integration
  • spring-boot-starter-validation
  • spring-boot-starter-actuator

First Spring Boot Code

Bootstrapping the application.



By using run method, Spring Boot server gets started.By annotation @SpringBootApplication we tells to the application that we want to run the application using spring boot.

Let's see how Rest controller can be used with spring boot..



Using the browser we can navigate to the localhost and relevant port number we can get the output as hello world.This is the base of building large web services.

Let's meet again with another exiting post.Happy coding :)

©Copyright Viraj Wickramasinghe.

Monday, March 12, 2018

NodeJS Basics I

Hello Everyone,
By this post you will be able to understand the basic stuff about NodeJS.
Firstly I will introduce what NodeJS is,

Node.js is a very powerful JavaScript-based framework.Platform was built on Google Chrome's JavaScript V8 Engine. Node.js is a server side scripting language which is mostly used for back end of the application.

In order to see whether node.js is successfully installed in your machine, use the following commands.




Basic Hello World Program


Using the require directive I have used the http module and returned an instance of it.Instance of server is created from createServer method and in the body 'Hello World' is printed.By using listen keyword, we define that server runs on that port number and output will be available in that port number.After connection is successfully established, console log statement will be executed in the console.

In order to run the node.js file, first open a terminal in the directory where your js file exists.




Output to the console

Reading a File

Now Let's look at some of the capabilities node.js has. It has the ability to read files in either synchronous way or asynchronous way.When both forms are present, node.js tends to read in the synchronous way first.



To read files node file system module is required.It is represented as fs in node.js. In here read.txt is an external file which contains some content which is read by node application. Below is the read.txt file.



Asynchronous reading takes callback function with 2 parameters err and data.First parameter is used to represent any errors that can occur while reading and data parameter is used to state the completion of the function.
In synchronous reading readFileSync keyword is used where no callback functions is used.In general Asynchronous reading is more approprite than synchronous reading where no blocks can occur in the reading process.


Output to the console




Writing a File

In here we over write the existing file using writeFile method.First parameter is said to be the file name where we want to write the content and second parameter is the content that we want to write to the file and at third we use call function with err as the parameter to display any errors that can occur during writing.




Output to the console







Let's meet again with another exiting post.Happy coding :)

©Copyright Viraj Wickramasinghe.