Cloudrail - Quick Guide



Cloudrail - Overview

CloudRail is an API integration solution that speeds up the process of integrating third-party APIs into an application and maintaining them. It does so by providing libraries for multiple platforms featuring abstraction layers that combine similar services behind a common interface.

CloudRail - Features

Here is a list of some of the most prominent features of CloudRail −

  • Unified API − CloudRail bundles multiple web APIs into a single unified API. For instance, the function upload() works exactly the same for Dropbox as it does for Google Drive. You can easily integrate whole categories of providers, e.g. Social Logins, or change a provider with a single line of code.

  • API Change Management − APIs change all the time, leading to broken integrations, unsatisfied customers and even more wasted development time. CloudRail monitors all APIs and maintains the integrations. You get immediate notifications about changes and all you need to do is update the CloudRail library to the latest version – no code changes required.

  • API Statistics − Understand which APIs and functions are being used most by your customers. Get the necessary insights you need to identify new features or improve marketing campaigns.

  • Direct Data − None of your data will ever pass a CloudRail server. The system doesn’t use a hosted middleware. All data transformation happens in the CloudRail library which is integrated in your App. This means no data privacy concerns, no down-times and no additional SPOF.

  • OAuth Made Simple − Doing OAuth authentications is a pain. CloudRail makes authorizations as simple as adding a single line of code.

The free version of CloudRail may only be used for non-commercial purpose or testing. Commercial users must purchase a license.

Cloudrail - Android

This section gives an introduction on how to use CloudRail's Android SDK.

Setup

The easiest way to install is via Maven. If you are using Android Studio with Gradle, it suffices to add the following to your build.gradle file

dependencies {
   compile 'com.cloudrail:cloudrail-si-android:2.8.1
}

Usage

The following example shows how to create a new folder and upload a file from an Android application's assets to the newly created folder on any cloud storage provider.

java
CloudRail.setAppKey("[CloudRail License Key]");

// CloudStorage cs = new Box(context, "[clientIdentifier]", "[clientSecret]");
// CloudStorage cs = new OneDrive(context, "[clientIdentifier]", "[clientSecret]");
// CloudStorage cs = new GoogleDrive(context, "[clientIdentifier]", "[clientSecret]");
CloudStorage cs = new Dropbox(context, "[clientIdentifier]", "[clientSecret]");

new Thread() {
   @Override
   public void run() {
      cs.createFolder("/TestFolder"); // <---
      InputStream stream = null;
      
      try {
         AssetManager assetManager = getAssets();
         stream = assetManager.open("UserData.csv");
         long size = assetManager.openFd("UserData.csv").getLength();
         cs.upload("/TestFolder/Data.csv", stream, size, false); // <---
      } catch (Exception e) {
         // TODO: handle error
      } finally {
         // TODO: close stream
      }
   }
}.start();

Cloudrail - Java

This section gives an introduction on how to use CloudRail's Java SDK.

Setup

The easiest way to install is via Maven. It suffices to add the following to your pom.xml file −

<dependencies>
   <dependency>
      <groupId>com.cloudrail</groupId>
      <artifactId>cloudrail-si-java</artifactId>
      <version>2.8.0</version>
   </dependency>
</dependencies>

Usage

The following example shows how to create a new folder and upload a file from the local machine to the newly created folder on any cloud storage provider.

java
CloudRail.setAppKey("[CloudRail License Key]");

// CloudStorage cs = new Box(redirectReceiver, "[clientIdentifier]", "[clientSecret]", "[redirectUri]", "[state]");
// CloudStorage cs = new OneDrive(redirectReceiver, "[clientIdentifier]", "[clientSecret]", "[redirectUri]", "[state]");
// CloudStorage cs = new GoogleDrive(redirectReceiver, "[clientIdentifier]", "[clientSecret]", "[redirectUri]", "[state]");
CloudStorage cs = new Dropbox(redirectReceiver, "[clientIdentifier]", "[clientSecret]", "[redirectUri]", "[state]");
new Thread() {
   @Override
   public void run() {
      cs.createFolder("/TestFolder");
      InputStream stream = null;
      
      try {
         stream = getClass().getResourceAsStream("Data.csv");
         long size = new File(getClass().getResource("Data.csv").toURI()).length();
         cs.upload("/TestFolder/Data.csv", stream, size, false);
      } catch (Exception e) {
         // TODO: handle error
      } finally {
         // TODO: close stream
      }
   }
}.start();

Cloudrail - Node.js

This section gives an introduction on how to use CloudRail's Node.js SDK.

Setup

The easiest way to install is via NPM. Simply use the following command −

npm install cloudrail-si

Usage

The following example shows how to create a new folder and upload a file from the local machine to the newly created folder on any cloud storage provider.

javascript
const cloudrail = require("cloudrail-si");
cloudrail.Settings.setKey("[CloudRail License Key]");

// let cs = new cloudrail.services.Box(redirectReceiver, "[clientIdentifier]", "[clientSecret]", "[redirectUri]", "[state]");
// let cs = new cloudrail.services.OneDrive(redirectReceiver, "[clientIdentifier]", "[clientSecret]", "[redirectUri]", "[state]");
// let cs = new cloudrail.services.GoogleDrive(redirectReceiver, "[clientIdentifier]", "[clientSecret]", "[redirectUri]", "[state]");
let cs = new cloudrail.services.Dropbox(redirectReceiver, "[clientIdentifier]", "[clientSecret]", "[redirectUri]", "[state]");

cs.createFolder("/TestFolder", (err) => { // <---
   if (err) throw err;
   let fileStream = fs.createReadStream("UserData.csv");
   let size = fs.statSync("UserData.csv").size;
   
   cs.upload("/TestFolder/Data.csv", fileStream, size, false, (err) => { // <---
      if (err) throw err;
      console.log("Upload successfully finished");
   });
});

Cloudrail - IOS

This section gives an introduction on how to use CloudRail's iOS SDK.

Setup

The easiest way to install is via CocoaPods. Simply add the following to your podfile

pod "cloudrail-si-ios-sdk"

Make sure the "use_frameworks!" flag is set and run

Pod install

Usage

The following examples shows how to download a file from any cloud storage provider in Objective-C and Swift.

objective-c
// self.service = [[CROneDrive alloc] initWithClientId:@"clientIdentifier" clientSecret:@"clientSecret" redirectUri:@"REDIRURL" state:@"CRSTATE"];
// self.service = [[CRGoogleDrive alloc] initWithClientId:@"clientIdentifier" clientSecret:@"clientSecret" redirectUri:@"REDIRURL" state:@"CRSTATE"];
// self.service = [[CRBox alloc] initWithClientId:@"clientIdentifier" clientSecret:@"clientSecret" redirectUri:@"REDIRURL" state:@"CRSTATE"];

[CRCloudRail setAppKey:@"CLOUDRAIL_API_KEY"];
self.service = [[CRDropbox alloc] initWithClientId:@"clientIdentifier" 
   clientSecret:@"clientSecret" redirectUri:@"REDIRURL" state:@"CRSTATE"];

NSInputStream * object = [self.service downloadFileWithPath:@"/mudkip.jpg"];
//READ FROM STREAM

swift
//let cloudStorage : CloudStorageProtocol = Box.init(clientId: "ClientID", clientSecret: "ClientSecret")
//let cloudStorage : CloudStorageProtocol = GoogleDrive.init(clientId: "ClientID", clientSecret: "ClientSecret")
//let cloudStorage : CloudStorageProtocol = OneDrive.init(clientId: "ClientID", clientSecret: "ClientSecret")

CRCloudRail.setAppKey("CLOUDRAIL_API_KEY")
let cloudStorage : CloudStorageProtocol = Dropbox.init(
   clientId: "ClientID", clientSecret: "ClientSecret")
do {
   let inputStream = try cloudStorage.downloadFileWithPath("/TestFolder/Data.csv")
} catch let error{
   print("An error: \(error)")
}
//READ FROM STREAM

Cloudrail - Social Login

This section presents the use-case of implementing social login for a (web) app. This chapter provides just an overview on Social Login and in the subsequent chapters, we will show how to set it up for Facebook and Twitter but it is very easy to add more services like Google Plus, LinkedIn, GitHub, Instagram, Slack, Windows Live and Yahoo. We will be using Node.js with Express on the server side.

Why Social Login?

One of the most common reasons why software developers and architects add a backend to their frontend(s) is the need for user management. In order for user management to work, signup and sign-in functionalities are the key. In the past, most applications had their own system for authentication and thus every user needed to actively create an account by providing email address, password and other information.

Not only is this cumbersome to the user but also notoriously insecure. Many users will use the same password everywhere, known as password fatigue, and with every party that has the password stored, the probability grows that it is stolen.

Of late, more and more services offer “social login” (“Login with Facebook”, “Login with GitHub”, etc.) which improves user experience by letting users signup/login with their already existing account on a popular platform.

Cloudrail - Setup

Register a CloudRail app

Use this link to create a new app (you may have to login first) − https://developers.cloudrail.com You can find your CloudRail license key in the app summary.

Register a Facebook app

Use this link to create a new app (you may have to login first) − https://developers.facebook.com/apps/. Then click the 'Add a New App' button, choose 'Basic setup' and create a new app. In the dashboard section you find your App Key (Client ID) and App Secret (Client Secret).

Go to 'Add Product' and select 'Facebook Login'. Set the Redirect URI to 'http://localhost:12345/auth/redirect/facebook'.

Register a Twitter app

Use this link to create a new app (you may have to login first) − https://apps.twitter.com/ Click the 'Create New App' button and fill in the required details. Click on 'Keys and Access Tokens' and you'll find your App Key (Client ID) and App Secret (Client Secret). Set the Redirect URI to 'http://localhost:12345/auth/redirect/twitter'.

Initialize a new Node.js project

Make sure you have Node.js installed, create a new folder, initialize the package.json and install Express and CloudRail by issuing the following commands in the console (or the equivalent commands on non-Unix OSs) −

mkdir myProject
cd myProject
npm init
npm i --save express cloudrail-si

Cloudrail - Coding

Create a new file for your server code in the created folder and add the following to import and setup Express and CloudRail

javascript
const express = require("express");
const cloudrail = require("cloudrail-si");
const app = express();
cloudrail.Settings.setKey("[CloudRail license key]");

Now, we continue by writing a function that will instantiate the services we want to use for social login −

javascript
function makeService(name, redirectReceiver) {
   let service;
   switch (name) {
      case "twitter":
         service = new cloudrail.services.Twitter(
            redirectReceiver,
            "[Twitter Client ID]",
            "[Twitter Client Secret]",
            "http://localhost:12345/auth/redirect/twitter"
         );
         break;
      case "facebook":
         service = new cloudrail.services.Facebook(
            redirectReceiver,
            "[Facebook Client ID]",
            "[Facebook Client Secret]",
            "http://localhost:12345/auth/redirect/facebook",
            "state"
         );
         break;
      // More services from the Profile interface can be added here, 
      //the services above are just examples
      default: throw new Error("Unrecognized service");
   }
   return service;
}

We need a way to keep track of user identities. This is normally done in a database but to keep this tutorial short, we will use an object that acts as a pseudo-database.

All its data is kept in memory and is thus lost when the server restarts −

javascript
const users = {
   records: {}
};
users.find = (id) ⇒ {
   return users.records[id];
};
users.save = (id, data) ⇒ {
   users.records[id] = data;
};

After, we register the server endpoint that will handle the start of the social login flow −

javascript
app.get("/auth/start/:serviceName", (req, res) ⇒ {
   let serviceName = req.params["serviceName"];
   
   let redirectReceiver = (url, state, callback) ⇒ {
      res.redirect(url);
   };
   let service = makeService(serviceName, redirectReceiver);
   service.login();
});

The service we have started the social login with will redirect to our server and we need to handle this redirect.

After getting a unique identifier for the user, we check if we have seen this user before. If yes, then we greet him with his name. If not, we get the name from the social network and save a new user −

javascript
app.get("/auth/redirect/:serviceName", (req, res) ⇒ {
   let serviceName = req.params["serviceName"];
   
   let redirectReceiver = (url, state, callback) ⇒ {
      callback(undefined, "http://bla.com" + req.url); 
      // The callback expects a complete URL but only the query matters
   };
	let service = makeService(serviceName, redirectReceiver);
   service.getIdentifier((err, identifier) ⇒ {
      if (err) res.status(500).send(err);
      let user = users.find(identifier);
      
      if (user) {
         res.send("Welcome back " + user.name);
      } else {
         service.getFullName((err, name) ⇒ {
            if (err) res.status(500).send(err);
            users.save(identifier, {
               name: name
            });
            res.send("Welcome greenhorn!");
         });
      }
   });
});

Finally, we have the server listen on port 12345 −

javascript
app.listen(12345);

We can now start the application and test it in our local browser.

If you navigate to http://localhost:12345/auth/start/facebook you will start the Facebook login flow.

If you navigate to http://localhost:12345/auth/start/twitter you will start the Twitter login flow.

After logging in with the service and granting access, you will be seeing "Welcome greenhorn!" if you do it for the first time and "Welcome back [your name]" on consecutive visits.

To integrate it into an actual website, you would, for example, include the service provider's logos there and make the logos link to the respective URLs.

Besides, the pseudo-database should be replaced with a real one. And there you go, social login for up to 9 different providers!

Advertisements