PeterStaev / nativescript-azure-mobile-apps

:cloud: NativeScript plugin for working with Microsoft Azure Mobile Apps services
Apache License 2.0
30 stars 10 forks source link
android authentication azure ios nativescript notifications

This repo only supports NativeScript pre-6.0. The latest version of the plugin supporting NS 6+ is availble as part of ProPlugins.

NativeScript Azure Mobile Apps plugin

Build Status npm downloads npm downloads npm

A NativeScript Azure Mobile Apps plugin.

Installation

Run the following command from the root of your project:

tns plugin add nativescript-azure-mobile-apps

This command automatically installs the necessary files, as well as stores nativescript-azure-mobile-apps as a dependency in your project's package.json file.

Configuration

For most of the functions the plugin you only need to know the name of your Azure mobile apps portal. The only thing that requires additional configuration is the social sign-in under iOS. For that please follow the steps explained below

Starting with version 2.0, due to updated libraries, Mircososft now reqiures the minimum SDK for Android to be 19. So you need to adjust 2 files in your app:

  1. In the app/App_Resources/Android/AndroidManifest.xml you must have android:minSdkVersion set to 19 or above.
  2. In the app/App_Resources/Android/app.gradle you must ensure that in your defaultConfig you have minSdkVersion set to the same number as the one you set in the AndroidManifest.xml file. So assuming you are setting it to 19, your file should look something like this:
    android {  
    defaultConfig {  
    generatedDensities = []
    applicationId = "......"
    minSdkVersion 19
    }  
    } 

API

MobileServiceClient

Static Methods

Methods

Properties

MobileServicePush

Methods

Properties

MobileServiceUser

Static Methods

Methods

Properties

MobileServiceTable

Methods

MobileServiceQuery

The query object provies a very easy to use chainable interface to filter, order and page through the data inside a table.

Methods

Usage

Note that there is no difference in using the plugin in Angular NativeScript apps, so the usage below is valid for Angular apps as well.

Create a client

import { MobileServiceClient } from "nativescript-azure-mobile-apps/client";
var client = new MobileServiceClient("https://<PORTAL_NAME>.azurewebsites.net");

Get a reference to a table

var todoItemTable = client.getTable("TodoItem");

Get all items in a table

todoItemTable.read<TodoItem>().then(function(results) {
    // results is array of TodoItem-s
    console.log(results.length);
    console.log(results[0].id);
});

Add an item to a table

var item = new TodoItem();
item.text = "NativeScript Rocks!";
todoItemTable.insert(item).then(function(result) {
    // result is the inserted item with the id changed
    console.log(result.id);
});

Update an item

item.text = "Changed Text";
todoItemTable.update(item).then(function(result) {
    // result is the updated item
    console.log(result);
});

Delete an item

todoItemTable.deleteItem(item).then(function() {
    console.log("Deleted!");
});

Delete an item by ID

todoItemTable.deleteById("some id").then(function() {
    console.log("Deleted!");
});

Query table

todoItemTable.where().field("completed").eq(true).read().then(function(results) {
    console.log("There are " + results.length.toString() + "completed items");
});

Sorting

import { SortDir } from "nativescript-azure-mobile-apps/query";
todoItemTable.where().field("completed").eq(true).orderBy("createdAt", SortDir.Desc).read().then(function(results) {
    // ...
});

Paging

import { SortDir } from "nativescript-azure-mobile-apps/query";
todoItemTable.where().field("completed").eq(true).orderBy("createdAt", SortDir.Asc).skip(2).top(3).read().then(function(results) {
    // Skips 2 completed tasks and returns the next 3 ordered chronologically by creation. 
});

User Authentication (Social Sign In)

iOS login requirements

In versions 1.0.0 and lower login on iOS leveraged an in-app browser. This will be banned so we needed to switch to SafariViewController which is not "in-app". So we need to be able to switch back and forth between the external browser. The main benefit is this browser can leverage cookies already set by for instance a Facebook login, so the user doesn't have to enter his credentials again.

It's a bit of work, but it's a one time effort and should take you about 5 minutes to complete these steps:

Custom URL Scheme

Switching to the external browser is not a problem, but switching back requires you to configure a 'Custom URL Scheme'. Open app/App_Resources/iOS/Info.plist and add:

<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleTypeRole</key>
    <string>Editor</string>
    <key>CFBundleURLName</key>
    <string>my.bundle.id</string>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>x-msauth-tns-azure-sample</string>
    </array>
  </dict>
</array>

Make sure the Custom URL Scheme string x-msauth-tns-azure-sample above is unique on the device of the user, so including your bundle id would be a good start (replace the dots by dashes).

Also, replace my.bundle.id by your bundle id.

Add ALLOWED EXTERNAL REDIRECT URLS

Add x-msauth-tns-azure-sample://easyauth.callback to the 'ALLOWED EXTERNAL REDIRECT URLS' field in these screenshots of your Azure backend.

Make sure to replace x-msauth-tns-azure-sample by your own Custom URL Scheme.

App Delegate wiring

Now that your app can be called from the external party it still can't switch back to the foreground unless you wire up a method in the App Delegate. Don't worry, this plugin takes care of that for you, the only thing you need to do is add this line just before app.start() in app.js / app.ts:

// add this
require("nativescript-azure-mobile-apps/client").MobileServiceClient.configureClientAuthAppDelegate();

// something like this is already there
application.start({ moduleName: "main-page" });
Passing the URL Scheme to login

Note that calling login has changed a bit; you now need to pass a second parameter to this function to use the new login mechanism. Failing to do so will fall back to the deprecated in-app browser authentication method. Make sure to replace x-msauth-tns-azure-sample by the scheme you configured in Info.plist before. You can leave it out if you only target Android.

import { AuthenticationProvider } from "nativescript-azure-mobile-apps/user";
client.login(AuthenticationProvider.Google, "x-msauth-tns-azure-sample").then((user) => {  
    console.log(`Logged In! UserID:${user.userId}`);
}, (e) => {
    console.log("Error Logging in!", e);
});

Once authenticated the userId and token are cached so you can login by simply calling:

client.loginFromCache(); // Will return true if there are cached credentials and will setup the client accordingly

If you want to get additional information about the user (like provider token, name, email, profile photo etc.) you can do this by calling getProviderCredentials():

client.user.getProviderCredentials().then((result) => {
    console.log(`Surname: ${result.surname}`);
    console.log(`Given Name: ${result.givenName}`);
    console.log(`Name: ${result.name}`);
});

Note: Since each provider provides different amount of details (also depends on what you have authorized in the Azure portal), if you are looking for some specific information, you should check the claims property of the result. It is a dictionary containing all the information that is returned from Azure.

If you want to remove the cached authentication info you should use:

import { MobileServiceUser } from "nativescript-azure-mobile-apps/user";
MobileServiceUser.clearCachedAuthenticationInfo();

Push Notifications

NOTE: In order to work with push notifications you also need to install the nativescript-plugin-firebase plugin. You can do this by running the following command:

tns plugin add nativescript-plugin-firebase

When prompted answer Yes to use the plugin in Push Only setup (in case you won't be using anything from the Firebase plugin) You can read more on how to use the firebase push only setup here.

Register

You need to call the push register with Azure in the onPushTokenReceivedCallback by passing the registration token returned by the plugin.

import { messaging } from "nativescript-plugin-firebase/messaging";

messaging.registerForPushNotifications({
    onPushTokenReceivedCallback: (token) => {
        client.push.register(token)
            .then(() => { console.log("Azure Register OK!", client.push.installationId); })
            .catch((e) => { console.error(e); });
    }
});

Register with a template

If you want to use a custom template for the notifications, you can use the registerWithTemplate method to pass your template name and body.

import { messaging } from "nativescript-plugin-firebase/messaging";

let pushTemplates = {};
pushTemplates[platform.platformNames.android] = "{\"data\":{\"message\":\"$(param)\"}}";
pushTemplates[platform.platformNames.ios] = "{\"aps\":{\"alert\":\"$(param)\"}}";

messaging.registerForPushNotifications({
    onMessageReceivedCallback: (message) => {
        console.log(message);
    },
    onPushTokenReceivedCallback: (token) => {
        client.push.registerWithTemplate(token, "MyTemplate", pushTemplates[platform.device.os])
            .then(() => { console.log("Azure Register OK!", client.push.installationId); })
            .catch((e) => { console.error(e); });
    },
});

Unregister

import { messaging } from "nativescript-plugin-firebase/messaging";

messaging.unregisterForPushNotifications()
    .then(() => {
        console.log("Device Unregister OK!");
        client.push.unregister()
            .then(() => console.log("Azure Unregister OK!"))
            .catch((e) => console.log(e));
    })
    .catch((e) => { console.error(e); });

Demos

This repository includes a plain NativeScript demo. In order to run it execute the following in your shell:

$ git clone https://github.com/peterstaev/nativescript-azure-mobile-apps
$ cd nativescript-azure-mobile-apps
$ npm install
$ npm run demo-ios

This will run the plain NativeScript demo project on iOS. If you want to run it on Android simply use the -android instead of the -ios sufix.

Donate

Donate

bitcoin:14fjysmpwLvSsAskvLASw6ek5XfhTzskHC

Donate