Git Product home page Git Product logo

jvalentik / ionic-mfp-app Goto Github PK

View Code? Open in Web Editor NEW

This project forked from ibm/ionic-mfp-app

0.0 2.0 0.0 22.31 MB

This repository contains instructions to develop a secure, enterprise-grade Ionic/Cordova based hybrid mobile app that connects to CouchDB/Cloudant and ObjectStorage via IBM Mobile Foundation service.

License: Apache License 2.0

TypeScript 60.80% HTML 12.84% CSS 5.74% JavaScript 1.39% Java 19.23%

ionic-mfp-app's Introduction

Develop Enterprise-grade Hybrid Mobile App with Cloud-native Backend

When developing your enterprise mobile app that needs centralized hosting of data, use of cloud-native services such as Cloudant No-SQL Database for storing textual data and Object Storage service for storing image/video/audio data, allows you to quickly go from idea-conception to reality. The Mobile Foundation service available from IBM Cloud provides a scalable mobile access gateway for securely accessing those backend services, and it provides other essential mobile backend capabilities such as push notifications, app lifecycle management and app analytics.

This code pattern gives you step by step instructions for developing an Ionic/Cordova based hybrid mobile app that securely connects to Cloudant and Object Storage services via IBM MobileFoundation (aka MFP) service.

When you have completed this pattern, you will understand:

  • How to authenticate users (through preemptive login) using MFP security adapater.
  • How to write an MFP adapter that authenticates with Cloud Object Storage service and pass back the Authorization token to the mobile app.
  • Recommended architectural patterns for coding the interaction between mobile app and Cloud Object Storage service.
  • How to use imgcache.js in Ionic app for caching images fetched from Cloud Object Storage service.
  • How to show Google Maps in Ionic app as well as capture user’s geo-location & image from camera.
  • How to upload the captured image from mobile app to Cloud Object Storage service.
  • How to fetch data from Cloudant service to mobile app via MFP adapter as well as post new data to Cloudant.
  • How to customize the Ionic app logo and splash, and build the release apk for uploading to public/private app stores.

Flow

Architecture diagram

  1. User launches the mobile app, enters his/her credentials on the login screen and clicks Login.
  2. Mobile app sends the user credentials to MFP server for validation.
  3. MFP server invokes the security adapter logic to validate user credentials and returns an appropriate response to the mobile app. For the sake of this demo, we will use a simple security adapter that returns success when password equals username.
  4. If user authentication succeeds, mobile app proceeds to show the home page. As part of this, it makes a call to MFP adapter to fetch the data from Cloudant NoSQL database.
  5. MFP adapter fetches the data from Cloudant and returns it to the mobile app. The data fetched from Cloudant will have references to the images stored in Cloud Object Storage.
  6. Mobile app makes a call to MFP adapter to get the Authorization token for interacting with Cloud Object Storage service.
  7. MFP adapter makes a call to Cloud Object Storage service's token manager endpoint to get the Authorization token and returns it to the mobile app.
  8. Mobile app initializes image-caching plugin and asks it to use an HTTP header of Authorization=<value returned from MFP adapter> while fetching images. Mobile app displays the data obtained from MFP adapter as a list of items. The image caching plugin running on the mobile app downloads and caches images from Cloud Object Storage.
  9. User clicks on one of the list item to see more details. A detail page is shown consisting of image and geo-location marked inside Google Maps.
  10. Back in the home page, user clicks on + button to report a new civic problem. A new page is shown where user can enter a description for the new civic problem as well as capture image and geo-location of the problem spot. User clicks on Submit button.
  11. Mobile app uploads the textual data to Cloudant NoSQL DB via MFP Adapter.
  12. Mobile app creates a thumbnail image by resizing the captured image and uploads both the captured image and thumbnail to Cloud Object Storage.
  13. Other users who click on refresh button on the home page (and those who log in afresh) are shown the updated list of problem reports.

Included Components

  • Cloudant NoSQL DB: A fully managed data layer designed for modern web and mobile applications that leverages a flexible JSON schema.
  • Cloud Object Storage: A highly scalable cloud storage service, designed for high durability, resiliency and security.
  • Mobile Foundation: A scalable mobile access gateway powered by the market-leading IBM Mobile Foundation Technology. The service offers a comprehensive set of mobile backend capabilities such as, App life cycle, Push, Analytics, Feature Toggle, Security and Authentication and offline synch.

Featured Technologies

  • Mobile: Systems of engagement are increasingly using mobile technology as the platform for delivery.

Watch the Video

Steps

  1. Setup Ionic and MFP CLI
  2. Create Cloudant database and populate it with sample data
  1. Create IBM Cloud Object Storage service and populate it with sample data
  1. Create Mobile Foundation service and configure MFP CLI
  2. Download source repo and customize
  1. Deploy MFP Adapters and Register the App to MFP server
  1. Run application on Android phone

Step 1. Setup Ionic and MFP CLI

$ node --version
v8.6.0
  • Install Cordova
$ sudo npm install -g cordova
$ cordova --version
7.0.1

Note: If you are on Windows, instead of using sudo, run the above command (and the ones below) in a command prompt opened in administrative mode.

  • Install Ionic
$ sudo npm install -g ionic
$ ionic --version
3.19.0
  • Install IBM MobileFirst Platform CLI
$ sudo npm install -g mfpdev-cli
$ mfpdev --version
8.0.0-2017091111
$ git --version
git version 2.9.3 ...
  • Install Maven: On Mac, you can use brew install for installing Maven as shown below:
$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
$ brew install maven
$ mvn --version
Apache Maven 3.5.0 ...
$ java -version
java version "1.8.0_101"
  • Install an IDE for TypeScript such as Atom on Mac.

    After installing Atom, install TypeScript plugin for Atom as shown below.

apm install atom-typescript

Step 2. Create Cloudant database and populate it with sample data

2.1 Create Cloudant database

  • Log in to IBM Cloud Dashboard and create Cloudant NoSQL DB service.
  • From the welcome page of Cloudant service that you just created, launch the Cloudant Dashboard.
  • In the Cloudant dashboard, click on Databases.
  • Click on Create Database. Specify name of database as myward as shown below. Click Create.

Create Database in Cloudant NoSQL DB

Once the database is created, the dashboard will update to show the documents inside myward database (which, as expected, will be empty to begin with).

  • Click Create Document. Under document content, after the auto populated _id field, enter grievance details as shown below. Please note that you need to put a comma (,) after the auto populated _id field.

{
  "_id": "7fc63023799dfda9582609e75127b4fa",
  "reportedBy": "[email protected]",
  "reportedDateTime": "20171125_152627",
  "picture": {
    "large": "IMG-20171125-WA0012.jpeg",
    "thumbnail": "thumbnail_IMG-20171125-WA0012.jpg"
  },
  "problemDescription": "Car parking on busy market road chocking movement of other vehicles and pedestrians",
  "geoLocation": {
    "type": "Point",
    "coordinates": [
      77.7893168,
      13.0773568
    ]
  },
  "address": "Basaveshwara Temple road (behind Market Road), Hosakote, Bangalore 562114"
}

Click Create Document to create/save the document.

2.2 Generate Cloudant API Key

  • In the Cloudant dashboard, under myward database, click on Permissions and then click on Generate API Key as shown in the snapshot below.
  • Make a note of the Key and Password generated.
  • The newly added key would get listed under Cloudant users with default permission of reader only. Select the checkbox under writer next to the new key to give it write permission as well.

Generate Cloudant API Key

Step 3. Create IBM Cloud Object Storage service and populate it with sample data

3.1 Create IBM Cloud Object Storage

  • In the IBM Cloud Dashboard, click on Catalog and select Object Storage service under Infrastructure -> Storage. Click on Create as shown below.

    Create IBM Cloud Object Storage service
  • The IBM Cloud Object Storage dashboard will get shown. In the Buckets and objects page, click on Create bucket. Give a unique name for the bucket. Leave the default selections as-is for Resiliency (Cross Region), Location (us-geo) and Storage class (Standard), and click on Create as shown below.

    Create a bucket in IBM Cloud Object Storage
  • The Bucket overview page for the newly created bucket will get shown. Click on Add objects. In Upload obects dialog, click on Add files and select all the images under SampleData directory (the six images and their thumbnails). Click Open. Click on Upload as shown below. Once upload is complete, you should see the images listed under your bucket.

    Upload objects to IBM Cloud Object Storage

3.2 Create Service ID and API Key for accessing objects

  • Create Service ID

    • In a separate browser tab/window, launch the IBM Cloud Identity & Access Management dashboard using URL https://console.bluemix.net/iam/.
    • In case you have multiple IBM Cloud accounts, then select the target Account, Region, Organization and Space.
    • Under Identity & Access (on the left side of the page), select Service IDs and click Create. Give a name and description, and click Create.
    • Make a note of the Service ID as shown below.
    Copy Service ID from IBM Cloud Identity and Access Management dashboard
  • Add Cloud Object Storage Writer role to that service ID

    • Back in IBM Cloud Object Storage dashboard, select Bucket permissions under Buckets and objects.
    • Click on Service IDs tab. Under Select a service ID, select the service ID created in the above step. Under Assign a role to this service ID for this bucket, select Writer. Click Create policy as shown below. You should get a confirmation dialog saying “Service permission created“.
    Add Writer role to the Service ID in IBM Cloud Object Storage
  • Create API Key

    • Back in IBM Cloud Identity & Access Management dashboard, under Service IDs, click on the service ID created earlier. Under Access policies, you should see the Writer role for your bucket.
    • Click on API keys tab and then click on Create button. In the Create API key dialog, give a name and description for the API key and click on Create. You should get a confirmation dialog saying API key successfully created as shown below.
    • Click on Download and save the API key as shown below. Note: This is the only time you will see the key. You cannot retrieve it later.
    • Finally click on Close.
    Create API key and download in IBM Cloud Identity and Access Management

Step 4. Create Mobile Foundation service and configure MFP CLI

In the IBM Cloud Dashboard, click on Catalog and select Mobile Foundation service under Platform -> Mobile. Click on Create as shown below.

Create IBM Mobile Foundation service

In the Mobile Foundation service overview page that gets shown, click on Service credentials. Expand View credentials and make a note of the url, user and password as shown below.

IBM Mobile Foundation service credentials

  • Back on your local machine, configure MFP CLI to work with Mobile Foundation server by running following command in console.
$ mfpdev server add
? Enter the name of the new server profile: Cloud-MFP
? Enter the fully qualified URL of this server: https://mobilefoundation-71-hb-server.mybluemix.net:443
? Enter the MobileFirst Server administrator login ID: admin
? Enter the MobileFirst Server administrator password: **********
? Save the administrator password for this server?: Yes
? Enter the context root of the MobileFirst administration services: mfpadmin
? Enter the MobileFirst Server connection timeout in seconds: 30
? Make this server the default?: Yes
Verifying server configuration...
The following runtimes are currently installed on this server: mfp
Server profile 'Cloud-MFP' added successfully.

$ mfpdev server info
Name         URL
--------------------------------------------------------------------------------------
Cloud-MFP  https://mobilefoundation-71-hb-server.mybluemix.net:443        [Default]
--------------------------------------------------------------------------------------

Note: For Enter the fully qualified URL of this server:, enter the url mentioned in credentials followed by :443 (the default HTTPS port).

Step 5. Download source repo and customize

5.1 Clone repo

$ git clone https://github.com/IBM/Ionic-MFP-App.git
$ cd Ionic-MFP-App

5.2 Update App ID, Name and Description

Update IonicMobileApp/config.xml as below. Change id, name, description and author details appropriately.


<?xml version='1.0' encoding='utf-8'?>
<widget id="org.mycity.myward" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0" xmlns:mfp="http://www.ibm.com/mobilefirst/cordova-plugin-mfp">
    <name>MyWard</name>
    <description>Get your civic issues resolved by posting through this app.</description>
    <author email="[email protected]" href="https://developer.ibm.com/code/author/shivahr/">Shiva Kumar H R</author>
...

5.3 Specify Cloudant credentials in MFP adapter

Open MobileFoundationAdapters/MyWardData/src/main/adapter-resources/adapter.xml and update the following properties to point to the Cloudant database created in Step 2.

  • Update key and password with the Cloudant API key as generated in Step 2.2.
  • For property account, specify the Cloudant dashboard URL portion upto (and including) -bluemix.cloudant.com as shown in the snapshot of Step 2.2.
  • For property DBName, leave the default value of myward as-is.

<mfp:adapter name="MyWardData" ...>
  <property name="account" displayName="Cloudant account" defaultValue=""/>
  <property name="key" displayName="Cloudant key" defaultValue=""/>
  <property name="password" displayName="Cloudant password" defaultValue=""/>
  <property name="DBName" displayName="Cloudant DB name" defaultValue="myward"/>
  ...
</mfp:adapter>

5.4 Specify Cloud Object Storage credentials in MFP Adapter

Open MobileFoundationAdapters/MyWardData/src/main/adapter-resources/adapter.xml and update the following properties to point to the Cloud Object Storage created in Step 3.


<mfp:adapter name="MyWardData" ...>
  ...
  <property name="endpointURL" displayName="Cloud Object Storage Endpoint Public URL" defaultValue="https://s3-api.us-geo.objectstorage.softlayer.net"/>
  <property name="bucketName" displayName="Cloud Object Storage Bucket Name" defaultValue=""/>
  <property name="serviceId" displayName="Cloud Object Storage Service ID" defaultValue=""  />
  <property name="apiKey" displayName="Cloud Object Storage API Key" defaultValue=""/>
</mfp:adapter>

Step 6. Deploy MFP Adapters and Register the App to MFP server

6.1 Build and Deploy the MFP adapters

Build and deploy UserLogin Adapter as below.

$ cd MobileFoundationAdapters/

$ cd UserLogin
$ mfpdev adapter build
$ mfpdev adapter deploy

Note: In Step 4, if you specified No to Make this server the default?, then you need to specify the name of your server profile (Cloud-MFP in our case) at the end of mfpdev adapter deploy command as shown below.

$ mfpdev adapter deploy Cloud-MFP

Build and deploy MyWardData Adapter as below.

$ cd ../MyWardData/
$ mfpdev adapter build
$ mfpdev adapter deploy

6.2 Register the MyWard app to MFP server

$ cd ../../IonicMobileApp/
$ mfpdev app register
Verifying server configuration...
Registering to server:'https://mobilefoundation-71-hb-server.mybluemix.net:443' runtime:'mfp'
Updated config.xml file located at: .../Ionic-MFP-App/IonicMobileApp/config.xml
Run 'cordova prepare' to propagate changes.
Registered app for platform: android

Note: In Step 4, if you specified No to Make this server the default?, then you need to specify the name of your server profile (Cloud-MFP in our case) at the end of mfpdev app register command as shown below.

$ mfpdev app register Cloud-MFP

Propogate changes by running cordova prepare

$ cordova prepare

6.3 Map MyWardData's protecting scope to UserLogin security check

Launch MFP Dashboard as below:

  • In the IBM Cloud dashboard, under Cloud Foundry Services, click on the Mobile Foundation service you created in Step 4. The service overview page that gets shown, will have the MFP dashboard embedded within it. You can also open the MFP dashboard in a separate browser tab by appending /mfpconsole to the url mentioned in Step 4.
  • Inside the MFP dashboard, in the list on the left, you will see the MyWard application, and MyWardData and UserLogin adapters listed.

Verify MFP Adapter configuration as below:

  • Inside the MFP dashboard, click on the MyWardData adapter. Under Configurations tab, you should see the various properties we specified in Step 5.3 and Step 5.4 for acccessing Cloudant database and Cloud Object Storage as shown below. As an alternative to specifying those property values in MobileFoundationAdapters/MyWardData/src/main/adapter-resources/adapter.xml as previously shown in Step 5.3 and Step 5.4, you can deploy the adapters with empty defaultValue, and once the adapter is deployed, change the values on this page.

Option to specify the configuration properties for accessing Cloudant NoSQL DB and Cloud Object Storage in deployed MFP Adapter

  • Click on Resources tab. You should see the various REST APIs exposed by MyWardData adapter as shown below. The Security column should show the protecting scope RestrictedData against each REST method.

The REST APIs of MyWardData adapter are protected by RestrictedData security scope

Map RestrictedData scope to UserLogin security check as below:

  • In the MFP dashboard, under Applications click on MyWard application. Click on Android and click on Security tab. Click on New button under Scope-Elements Mapping as shown below.
  • Specify Scope element as RestrictedData, and under Custom Security Checks select UserLogin as shown below. Click on Add. The new mapping should get created and shown under Scope-Elements Mapping.

The REST APIs of MyWardData adapter are protected by RestrictedData security scope

  • Repeat above steps for Applications -> MyWard -> iOS in case you add Cordova platform for iOS as well.

6.4 Test the MyWardData adapter

Create temporary credentials to test adapter REST API as below:

  • Inside the MFP dashboard, click on Runtime Settings. Click on Confidential Clients. Then click on New.
  • In the form that pops up, specify values for ID and Secret as shown in snapshot below. For Allowed Scope enter ** and click on Add. Finally click on Save.

MFP - Create Confidential Client to test Adapter REST APIs

Test adapter REST API as below:

  • Inside the MFP dashboard, click on the MyWardData adapter. Click on Resources and then click on View Swagger Docs. The Swagger UI for adapter REST APIs will get shown in a new window/tab.
  • Inside the Swagger UI, click on Expand Operations.
  • To test the GET / API, first click on OFF toggle button to enable authentication. Select Default Scope and click on Authorize as shown below. Enter the ID and Secret created above against Username and Password. Click OK. If authentication is successful, the toggle button will switch to ON position.

Authorize Swagger UI for running MFP Adapter REST APIs

  • Now click on Try it out button to run the GET / API. The API response should get shown in the Response Body as shown in snapshot below.

Swagger UI for testing MobileFirst Adapters

  • The GET API on /objectStorage should return a JSON object containing baseUrl and authorizationHeader as shown below.

Test the newly added API in MFP Adapter for getting Cloud Object Storage Authorization token

Delete the temporary credentials after testing adapter REST API as below:

  • Inside the MFP dashboard, click on Runtime Settings. Click on Confidential Clients.
  • Delete the Client ID created previously.

Step 7. Run application on Android phone

7.1 Install Android Studio and Android SDK platform

  • Download and install Android Studio from https://developer.android.com/studio/index.html
  • Install Android SDK Platform 23 (or higher)
    • Launch Android Studio.
    • Click on Configure -> SDK Manager
    • Under SDK Platforms, select Android 6.0 (Marshmallow) API Level 23. Click Apply and then click OK. This will install Android SDK Platform on your machine.

7.2 Enable developer options and USB debugging on your Android phone

  • Enable USB debugging on your Android phone as per the steps in https://developer.android.com/studio/debug/dev-options.html
    • Launch the Settings app on your phone. Select About Device -> Software Info . Tap Build number 7 times to enable developer options.
    • Return to Settings list. Select Developer options and enable USB debugging.
  • If you are developing on Windows, then you need to install the appropriate USB driver as per instructions in https://developer.android.com/studio/run/oem-usb.html.
  • Connect the Android phone to your development machine by USB cable, and accept allow access on your phone.

7.3 Enable Android platform for Ionic application

$ ionic cordova platform add [email protected]
> cordova platform add [email protected] --save
...

Note: Make sure the Cordova platform version being added is supported by the MobileFirst plug-ins. Site https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/application-development/sdk/cordova/ lists the supported levels.

$ cordova platform version
Installed platforms:
  android 6.3.0
Available platforms: 
  blackberry10 ~3.8.0 (deprecated)
  browser ~4.1.0
  ios ~4.4.0
  osx ~4.0.1
  webos ~3.7.0

Cordova Android 6.3.0 targets the latest Android API level of API 26. If you want to target API 23 instead, then edit IonicMobileApp/config.xml and add preference for android-targetSdkVersion as shown below.

  <preference name="android-minSdkVersion" value="16" />
  <preference name="android-targetSdkVersion" value="23" />

7.4 Build/Run the Ionic application on Android phone

  • Build Android application
$ ionic cordova build android
  • Run application on Android device
$ ionic cordova run android

MyWard App - Login Page

MyWard App - Home Page MyWard App - Problem Detail Page MyWard App - Report New Problem Page

7.5 Update App Logo and Splash

Reference: Automating Icons and Splash Screens https://blog.ionic.io/automating-icons-and-splash-screens/

Copy your desired app icon to IonicMobileApp/resources/icon.png and app splash to IonicMobileApp/resources/splash.png.

$ cd ../IonicMobileApp
$ ionic cordova resources

For running ionic cordova resources command, you would need to sign up on ionicframework.com and specify the credentials on the command line.

7.6 Build APK for uploading to Google Play Store

  • Add following lines at the end of IonicMobileApp/platforms/android/proguard-project-mfp.txt:
-dontwarn okhttp3.internal.huc.**
-keep class plugin.google.maps.** { *; }
  • Create release build as below:
$ cd ../IonicMobileApp
$ ionic cordova build android --prod --release
  • Zip align release build as below:
$ cd ./platforms/android/build/outputs/apk/
$ ls
android-release-unsigned.apk
$ <Android-Home>/sdk/build-tools/25.0.2/zipalign -v -p 4 android-release-unsigned.apk android-release-unsigned-aligned.apk
$ ls 
android-release-unsigned-aligned.apk	android-release-unsigned.apk

where, <Android-Home> points to the location of your Android Home directory. On Mac, this is usually /Users/<username>/Library/Android/.

  • Create self signing certificate as below:
$ keytool -genkey -v -keystore my-release-key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias my-alias
$ ls
android-release-unsigned-aligned.apk	android-release-unsigned.apk		my-release-key.jks
  • Self sign APK as below:
$ <Android-Home>/sdk/build-tools/25.0.2/apksigner sign --ks my-release-key.jks --out myward.apk android-release-unsigned-aligned.apk
Keystore password for signer #1: 
$ ls
android-release-unsigned-aligned.apk	my-release-key.jks
android-release-unsigned.apk		myward.apk
$ 
  • Distrubute myward.apk by uploading to Google Play Store or to your company's internal App store.

Troubleshooting

Debugging Android hybrid app using Chrome Developer Tools

  • Install Google Chrome

  • Open Google Chrome. Open URL chrome://inspect/#devices

  • Under Devices, click on inspect below your connected device.

    Debugging of Android app using Chrome Developer Tools

References

License

Apache 2.0

ionic-mfp-app's People

Contributors

shivahr avatar stevemart avatar

Watchers

James Cloos avatar Johny avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.