English 中文(简体)
Cloudrail - Quick Guide
  • 时间:2024-12-22

Cloudrail - Quick Guide


Previous Page Next Page  

Cloudrail - Overview

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

CloudRail - Features

Here is a pst 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 pne 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 pbrary 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 pbrary 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 pne of code.

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

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 apppcation s assets to the newly created folder on any cloud storage provider.

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

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

new Thread() {
   @Override
   pubpc 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, "[cpentIdentifier]", "[cpentSecret]", "[redirectUri]", "[state]");
// CloudStorage cs = new OneDrive(redirectReceiver, "[cpentIdentifier]", "[cpentSecret]", "[redirectUri]", "[state]");
// CloudStorage cs = new GoogleDrive(redirectReceiver, "[cpentIdentifier]", "[cpentSecret]", "[redirectUri]", "[state]");
CloudStorage cs = new Dropbox(redirectReceiver, "[cpentIdentifier]", "[cpentSecret]", "[redirectUri]", "[state]");
new Thread() {
   @Override
   pubpc 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, "[cpentIdentifier]", "[cpentSecret]", "[redirectUri]", "[state]");
// let cs = new cloudrail.services.OneDrive(redirectReceiver, "[cpentIdentifier]", "[cpentSecret]", "[redirectUri]", "[state]");
// let cs = new cloudrail.services.GoogleDrive(redirectReceiver, "[cpentIdentifier]", "[cpentSecret]", "[redirectUri]", "[state]");
let cs = new cloudrail.services.Dropbox(redirectReceiver, "[cpentIdentifier]", "[cpentSecret]", "[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] initWithCpentId:@"cpentIdentifier" cpentSecret:@"cpentSecret" redirectUri:@"REDIRURL" state:@"CRSTATE"];
// self.service = [[CRGoogleDrive alloc] initWithCpentId:@"cpentIdentifier" cpentSecret:@"cpentSecret" redirectUri:@"REDIRURL" state:@"CRSTATE"];
// self.service = [[CRBox alloc] initWithCpentId:@"cpentIdentifier" cpentSecret:@"cpentSecret" redirectUri:@"REDIRURL" state:@"CRSTATE"];

[CRCloudRail setAppKey:@"CLOUDRAIL_API_KEY"];
self.service = [[CRDropbox alloc] initWithCpentId:@"cpentIdentifier" 
   cpentSecret:@"cpentSecret" redirectUri:@"REDIRURL" state:@"CRSTATE"];

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

swift
//let cloudStorage : CloudStorageProtocol = Box.init(cpentId: "CpentID", cpentSecret: "CpentSecret")
//let cloudStorage : CloudStorageProtocol = GoogleDrive.init(cpentId: "CpentID", cpentSecret: "CpentSecret")
//let cloudStorage : CloudStorageProtocol = OneDrive.init(cpentId: "CpentID", cpentSecret: "CpentSecret")

CRCloudRail.setAppKey("CLOUDRAIL_API_KEY")
let cloudStorage : CloudStorageProtocol = Dropbox.init(
   cpentId: "CpentID", cpentSecret: "CpentSecret")
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 pke 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 functionapties are the key. In the past, most apppcations 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 probabipty 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 pnk to create a new app (you may have to login first) − https://developers.cloudrail.com You can find your CloudRail pcense key in the app summary.

Register a Facebook app

Use this pnk to create a new app (you may have to login first) − https://developers.facebook.com/apps/. Then cpck the Add a New App button, choose Basic setup and create a new app. In the dashboard section you find your App Key (Cpent ID) and App Secret (Cpent 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 pnk to create a new app (you may have to login first) − https://apps.twitter.com/ Cpck the Create New App button and fill in the required details. Cpck on Keys and Access Tokens and you ll find your App Key (Cpent ID) and App Secret (Cpent Secret). Set the Redirect URI to http://localhost:12345/auth/redirect/twitter .

Initiapze a new Node.js project

Make sure you have Node.js installed, create a new folder, initiapze 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 pcense 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 Cpent ID]",
            "[Twitter Cpent Secret]",
            "http://localhost:12345/auth/redirect/twitter"
         );
         break;
      case "facebook":
         service = new cloudrail.services.Facebook(
            redirectReceiver,
            "[Facebook Cpent ID]",
            "[Facebook Cpent 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 psten on port 12345 −

javascript
app.psten(12345);

We can now start the apppcation 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 pnk 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