Category Archives: Uncategorized

OpenFGA – Open Source Authorization by Auth0

Few days back I came to know about OpenFGA – Open Source Authorization by Auth0. Since then I am exploring it a bit. Here in this blog post we will understand what is OpenFGA.

OpenFGA
OpenFGA – Open Source Authorization by Auth0

Whenever we discuss about authorization, there is always a confusion about difference between authentication and authorization. Let’s first clear that.

Difference between Authorization and Authentication

Authentication is all about identity of the user. Authorization is all about what user can do with your system. As an application developer or system architect we always face challenges with Authorization.

There are lots of things involved with Authorization. It includes,

  • Access to system entities.
  • What all URLs user can access
  • Types of actions, like create / read / update/ delete
  • Grant and revoke permissions etc.

Considering above factors it’s always a challenge to implement robust architecture for the authorization.

OpenFGA – Fine Grained Authorization Solution

It’s a fast, scalable and flexible system. It’s inspired by Google’s Zanzibar project. This paper presents the design, implementation, and deployment of Zanzibar, a global system for storing and evaluating access control lists.

Auth0 / Okta developed OpenFGA on top of Google’s Zanzibar and made is open source. It is easy for application developers to develop their access control layer, and to add and integrate authorization which is consistent across all of their applications.

Why it is important?

As mentioned earlier in the post authorization is very critical and complex aspect of modern applications and platforms. With increasing demands from users, it’s crucial to build robust system without compromising cyber security.

Let’s understand building blocks of OpenFGA one by one.

OpenFGA Server

This act as permission engine. It uses expressive language to define your authorization model. This server consists of HTTP APIs using which one can,

  • Define permission models
  • Querying and modifying them
  • Checking and granting permission

It has modular data storage. It supports an in-memory database and PostgreSQL. Also it has graph querying implementation inspired by Google Zanzibar. It is also available as docker image, you can check the quick start guide here.

OpenFGA Client

There are no of choices of SDK available to use in your application to set up a client. Available SDKs are GO SDK, .NET SDK, JS SDK. The client allows you to interact with the server API in an idiomatic way.

Client works with store. A store is a OpenFGA entity that contains your authorization data. You will need to create a store in OpenFGA before adding an authorization model and relationship tuples to it.

How does it work?

Let’s first get high level overview of how does it work before we see the code example. Let’s take an example of project management system.

Define the model

  • A project can be created by an employee.
  • It can be approved by manager of employee.
  • Team member can view project.

To solve this problems, we will define the authorization model.

type project
relations
define creator as self
define approver as manager from creator
define team-member as self or creator or approver

type employee
relations
define approver as self or manager

Define the tuples

Once model is defined you will pass data by using the OpenFGA’s Write API and a few “tuples”.

Define employee manager relation. Here John is the manager of Smith. Hence he become approver.

{ 
    "user": "employee:john",  
    "relation": "approver", 
    "object": "employee:smith" 
}

Employee create project

{
"user": "employee:smith",
"relation": "creator",
"object": "smith-project"
}

Team member added.

{
"user": "employee:jane",
"relation": "team-member",
"object": "smith-project"
}

Now we can use OpenFGA’s Check API, which will return true or false for the tuples. Based on the user, relation and object the API will return true or false.

In the next post, we will understand about js-sdk for OpenFGA and see how we can use it.

Access Amazon RDS from AWS Lambda

Recently I was working with serverless application created in NodeJs which was deployed to AWS Lambda. This app is connecting to MySQL database which was deployed to RDS. While I was testing in local machine it worked very well.

AWS Lambda Amazon RDS

After deployed it stopped working. After struggling for half a day I was able to finally make it working. In this blog I am going to mention what it takes to make it working.

Different Security Group is the First Solution

This is really strange, if your Amazon RDS and AWS Lambda function shares the security group it will never connect. Not sure why it’s this way, but to solve the problem.

  1. Create New Security Group and assign it to your Lambda function.
  2. Create Other Security Group and assign it your RDS
  3. Allow MySQL connection in RDS Security Group

To allow MySQL connection, add inbound rules. Select MYSQL/Aurora fromType and allow it from 0.0.0.0/0

Allow VPC Access to Lambda Function

  1. Go to Roles page in IAM consle.
  2. Create new role and add policy AWSLambdaVPCAccessExecutionRole
  3. Assign this role to your Lambda function

Use Connection Pool in Your Code

While using serverless you have to be careful about asynchronous operations. Connection to MySQL is also asynchronous operations. If you do not handle it properly, lambda function will give you timeout as it’s expecting callback function to return result but because it’s async operations it will take time. So you have to explicitly let it know that, there is async operation so wait for it.

So for that create connection pool.

var mysql = require(‘mysql’);
var pool = mysql.createPool({
user : ‘username’,
password : “password”,
database: ‘database’,
host : ‘rds_end_point’
});

Now wait to get connection from the pool.

pool.getConnection((err, connection) => {
connection.query(‘SQL’,function(err, rows, fields) {
const response = {
statusCode: 200,
headers: {
“Access-Control-Allow-Origin” : “*” // Required for CORS support to work
},
body: JSON.stringify({
success: true,
rows: rows
})
};
connection.release();
callback(null, response);
});
})

As you can see in above code we are waiting for getting connection. Once we have the connection we query the database and get the result. After that we invoke the callback and release the connection so it can be used for next requests.

DialogFlow API – Use in Laravel

DialogFlow is one of the best tool available for Machine Learning. It is developed and maintained by Google Team. You can use DialogFlow for various applications like Chat bot, Customer support service etc. In this blog I am going to explain how you can connect DialogFlow with Laravel using APIs.

DialogFlow Logo

DialogFlow

Generate Connection File

For using API, you first have to generate connection file which will be used for Authentication. For this here are the steps.

  1. Login to DialogFlow Console
  2. Select the Project
  3. Go to Settings
  4. Click on Service Account Link
  5. You will be redirect to Google Project Console.
  6. Select Service Account menu from left hand side.
  7. Click on Add New Service Account
  8. Follow the steps and add last step create and download JSON file.

This file will be used as connection credentials.

Integrate SDK in the Laravel App

First of all you have to download SDK using composer. Execute command in terminal

composer require google/cloud-dialogflow

This will download the SDK in vendor folder. Now set a link of credential file in ENV file.

GOOGLE_APPLICATION_CREDENTIALS= /path/to/your/file

Now you can use the API to connect to DialogFlow. Here are few examples.

First of all add following dependencies in your file to use the SDK.

use Google\Cloud\Dialogflow\V2\IntentsClient;
use Google\Cloud\Dialogflow\V2\Intent;
use Google\Cloud\Dialogflow\V2\Intent\TrainingPhrase\Part;
use Google\Cloud\Dialogflow\V2\Intent\TrainingPhrase;
use Google\Cloud\Dialogflow\V2\Intent\Message;
use Google\Cloud\Dialogflow\V2\Intent\Message\Text;

Get List of All Intents

Now use following code to get list of all the intents.

$intentsClient = new IntentsClient();
$parent = $intentsClient->projectAgentName(“YOUR DIALOGFLOW PROJECT NAME”);
$intents = $intentsClient->listIntents($parent,array(“intentView”=>1));
$allIntents = array();
$iterator = $intents->getPage()->getResponseObject()->getIntents()->getIterator();
while($iterator->valid()){
$intent = $iterator->current();
$allIntents[] = array(“id”=>$intent->getName(),”name”=>$intent->getDisplayName());
$iterator->next();
}
return Response::json(array(‘success’=>true,”allIntents”=>$allIntents));

Get Text Prediction

Use following code to get text prediction.

$sessionsClient = new SessionsClient($credentials);
$session = $sessionsClient->sessionName($projectName, uniqid());
$languageCode = ‘en’;
// create text input
$textInput = new TextInput();
$textInput->setText($text);
$textInput->setLanguageCode($languageCode);

// create query input
$queryInput = new QueryInput();
$queryInput->setText($textInput);

// get response and relevant info
$response = $sessionsClient->detectIntent($session, $queryInput);
$queryResult = $response->getQueryResult();
$queryText = $queryResult->getQueryText();
$intent = $queryResult->getIntent();
$displayName = $intent->getDisplayName();
$confidence = $queryResult->getIntentDetectionConfidence();
$fulfilmentText = $queryResult->getFulfillmentText();

Things To Learn Before Start Developing Chatbot

Chatbot, is a hot topic and many companies are developing bots for various businesses. Check my post here on Why Why Your Business Needs A Chat bot

chatbot

In this blog I am going to mention some key points you have to consider before start developing chatbot for any business.

Domain Knowledge

This is most important point to consider and learn before you start developing chatbot for any business. You have to get domain knowledge of the business or industry. Because each domain has it’s own set of process and methods. Customers of each domain are different. So you have to get complete domain knowledge of the business before implementing chatbot for it.

For example if you are creating chatbot for eCommerce portal. You have to learn about eCommerce process like how customer search for products. What type of queries they can have. What do they expect in support if they contact customer care. For this you have to get complete knowledge of eCommerce domain, so you can build smart intelligence in your chatbot program.

To get domain knowledge you must consult some functional expert who has good and experience of domain. A person who knows each and everything about domain will be a good learning source for you.

Possible Scenarios

When you are creating a chatbot it will have to deal with customer queries and they can have any type of query. So you have to look at all the perspective from the customer end. You have to learn all the possible scenarios that can have in domain. For example if you are building a chatbot for say customer care. You have to know what type of queries customers can have. What types of questions they ask and what are the possible outcome or answers for it.

This will help you in building smart intelligence in chatbot to give precise answer to customer queries. If you know possible outcome and possible solutions you can easily program it and help customer with chatbot. So learn all the possible scenario with functional experts. Ask them as many questions as possible to get all the scenarios.

Understand the Customers

This is another important aspect to consider for development of Chatbot. You have to know customers and the way they communicate with customer care. You have to know..

  • What type of questions do they ask?
  • What language they use in communication?
  • Do they make grammatical mistakes?
  • Do they use sarcasm in their communication?

This will help you in programming and let you know build intellgence to give proper answer to the queries. Otherwise customers can get angry and you will have very bad customer service.

Step By Step Guide on iOS TestFlight Beta Testing

In this blog I am going to explain step by step procedure of TestFlight Beta Testing in iOS.

What is TestFlight?

TestFlight was the platform built for iOS beta testing. As we know iOS does not allow any application to be installed our of App Store and earlier to test you have to sync Apps with iTunes and proper provisioning profiles which was hard for newbies and non technical users. So TestFlight made this process simple and built platform where you can do it easily with TestFlight app. Later on TestFlight was acquired by Apple and it was integrated in iTunes Connect. Still it sometimes confuses new user. So in this blog I am going to explain step by step procedure. 
Please note that you should have valid Apple Developer Account. If you don’t have one please signup for it. 

Step 1 : Create Application Id

For this go to Apple Developer Member Center. Here is the Link Login here with Apple Developer Account credentials. Once you logged in following screen will be displayed. From here click on 
“Certificates, Identifiers & Profiles”
First of all we will create new Application Id. For that click on it Identifiers —> App IDs and it will show you following screen. Click on + symbol on top right .
Once you click on + sign following form. Fill up information here as displayed below. Here you have to specify name of app and bundle ID and click on continue.
After continue, it will ask you to confirm it. Click on Register and your App id is created. Here your app id registration is completed. Click on Done. 

Step 2: Create Distribution Certificate and Distribution Provisioning Profile 

Next step is to create distribution certificate and provisioning profile as we need to sign application with it. 
First lets create Distribution Certificate. Click on Certificates —> Production in the side menu. And then click on + icon on top right side.
It will start Add iOS certificate wizard. In first step. What type of certificate do you need? Select 
App Store and Ad Hoc below production and click on continue.  It will show you screen about creating certificate signing request. Create CSR file as mentioned here and save to your desktop and click on continue.
In the next step upload Certificate Signing Request you created and click on continue. In the final step it shows Your certificate is ready. Click on Done here.
Next we will create distribution provisioning profile. Click on Provisioning Profiles —> Distribution and click + on top right side. 

It will start a wizard to create provisioning profile. 
In Step 1 What type of provisioning profile do you need? select Distribution —> App Store and click on continue.
In Step 2 Select App ID, select App Id we created in Step 1 above and click on continue.
In Step 3: Select certificates, select the distribution certificate we created and click on continue.
In Step 4: Name this profile and generate. Give name of profile and click on continue.
In Step 5: Your provisioning profile is ready. Click on Done and your provisioning profile.

Step 3: Configure Xcode project and Generate Build

Next step is to configure Xcode project with provisioning profile and distribution certificate we created. Open your Xcode project. First we have to add your apple developer account in Xcode.
Go to Xcode —> Preference —> Accounts
Click on + sign and bottom and select Add Apple Id. It will ask for your credentials. Add  your email and password and Sign In.
Now select your project and in General tab select your Apple Developer Account.
It will download all the necessary profile and sing up your app. Now create an Archive to upload. First select Generic iOS device and then go to Product—>Archive
Now product is Archived.

Step 3: Create Application in iTunes Connect

we will upload it for the beta testing. Login to iTunes Connect with your apple development account credentials and click on My Apps. On the left side there is + sign. Click on that and choose New App. It will show following pop up, where you have to select the app and add necessary details.

This will create App. Now we will have to upload archive we created in Xcode. Go back to Xcode. Select the archive we created and Click on Upload to App Store.
It will prepare iPA file and shows you following dialog. Click on upload here. It will upload build to iTunes Connect.
Once the build is uploaded. It will take some in processing in iTunes connect. That you can select in activity screen. 
Once the build is processed, you have to submit it for beta review. For that go to TestFlight -> External Testing and click on select Add Build to Test.
Select the build you have submitted and add the necessary information on the screens which are prompted. Be specific to each information and give as much info as possible and submit for beta review. It will take couple of days to get it approved. Once approved. Add the external tester and click on Save. All the users will be notified with email and link to TestFlight app. 
Hope this helps you.

Sencha Touch Get Yahoo News RSS using JsonP request

Hello,

Recently I was working on project where requirement was to display rss feeds from yahoo news in sencha touch application. For that we have to use JsonP request as it will be cross domain request. If we use simple Ajax request, we will get error of cross domain access and if we use JsonP request, we can not parse the response as normally RSS feed response is in XML format. So what is the solution?

Solution is to use YQL (Yahoo Query Language). YQL is the is the SQL like language that lets you search, filter data across yahoo services. We can write a select statement just like we use select statement for a table in database. We can also use joins to combine more than one results. Checkout following example.

Ext.data.JsonP.request({
            url: ‘http://query.yahooapis.com/v1/public/yql’,
            params: {
                q: ‘select * from rss where url =”http://news.search.yahoo.com/rss?ei=UTF-8&p=USD”‘,
                format: ‘json’
            },
            success: function (response) {
                console.log(response);
            },
            failure: function () {

            }
});

That’s it and you have rss feeds in json format using cross domain jsonp request for sencha touch. Above example will return all the news related to USD currency published on yahoo news. This way you can query for any other topic.

Please note that yahoo will not return results if you try to access yql frequently from single IP. This is for security reasons. If you need uninterrupted results, you need to sign up for api and get authentication key and pass it along with the your request. Above example if of JsonP request. Same way you can use it in Ext.data.Store along with JsonP proxy. See the following code.

 Ext.define(‘MyApp.store.MyStore’,{
       extend: ‘Ext.data.Store’,
       config:{
           model:’MyApp.model.MyModel’,
           autoLoad: true,
            proxy : {
                type : ‘jsonp’,
               url: ‘http://query.yahooapis.com/v1/public/yql’,
                 reader: {
                  type: ‘json’,
                  rootProperty: ‘query.results.item’,
                }
            }
       }
});

Ext.getStore(‘MyStore’).getProxy().setExtraParams({
                   q:’select * from rss where url =”http://news.search.yahoo.com/rss?ei=UTF-8&p=USD”,          
                   format: ‘json’
              });
Ext.getStore(‘MyStore’).load();

This is the example of dynamic loading of store.

Hope this help you.

Hide browser address bar in Sencha Touch 2 app

Hello,

This is quick blog on how to hide browser address bar in sencha touch 2 app.

You need to specify autoMaximize propery of view port in the application. Checkout following code.

Ext.application({
                            name: ‘MyApp’,
                            icon: ‘resources/images/icon.png’,
                            tabletStartupScreen: ‘resources/images/tablet_startup.png’,
                            phoneStartupScreen: ‘resources/images/phone_startup.png’,
                            glossOnIcon: false,
                            viewport: {
                                autoMaximize: true
                            },
                            models: [‘MyModel’],
                            stores: [‘MyStore’],
                            views: [‘MyView’],
                            controllers: [‘MyController’],
                         
                            launch: function () {

                                   Ext.Viewport.add({
                                                        xclass: ‘ MyApp .view. MyView’
                                  });
                           }
                });

That’s it and open the application in any mobile browser, it will hide the browser address bar. Please note that this trick will only work for mobile browsers.

Sencha Touch fieldset, title wrap to new line

Hello,

This is quick blog on one issue I faced recently. I was working on an application where I was having unwanted horizontal scroll bar while working with form panel and field sets. That was causing bit annoying effect for end user because when they try to scroll sometimes it scrolls horizontally sometime it scrolls vertically. After searching a lot I found that it was due to title of fieldset. When title goes beyond some characters it does not warp to next line but it increases the width of container and because of that horizontal scroll bar becomes visible. To prevent this I made following CSS changes.

If you check sencha touch debug css you will find following class in it.

.x-form-fieldset-title {
       text-shadow: white 0 1px 1px;
       color:  #333;
       margin: 1em 0.7em 0.3em;
       color:  #333;
       font-weight: bold;
       white-space: nowrap;
}

Check the last property white-space: nowrap; because of this it does not wrap to next line. So you need to override this class with following definition.

.x-form-fieldset-title {
       text-shadow: white 0 1px 1px;
       color:  #333;
       margin: 1em 0.7em 0.3em;
       color:  #333;
       font-weight: bold;
       white-space: normal;
}

You have to add this class in any CSS file which you load after sencha touch css and it will make the difference. This trick can also be applied for form panel labels.

Hope this helps you.

Align Sencha Touch Overlay in Center

Hello,

Recently I was working on a project where requirement was to show overlay panel with some controls and align it to center.  We know that sencha provide function showBy where we can pass an element to display overlay.

Something like this panel.showBy(element)

Overlay will be displayed adjacent to the element you pass with a triangle arrow displayed towards control. See the image below.

So to make it center I did some tweaks. See the code below.

myPanel.showBy(ele);

var viewPortHeight = Ext.Viewport.windowHeight;
var viewPortWidth = Ext.Viewport.windowWidth;

var windowWidth = viewPortWidth / 2.5;
var windowHeight = viewPortHeight / 3.0;

myPanel.setWidth(windowWidth);
myPanel.setHeight(windowHeight);

 myPanel.setLeft((viewPortWidth – windowWidth) / 2);
 myPanel.setTop((viewPortHeight – windowHeight) / 2);

Following code is to remove that black triangle if you want.

if (discountPanel.element.dom.childNodes[1]) {
         myPanel.element.dom.childNodes[1].parentNode.removeChild(myPanel.element.dom.childNodes[1]);
        }        

That’s it and your overlay is aligned to center.