Alex's Notes

CM3050 Topic 07: Integrating Cloud Services

Main Info

Description

In this topic, we discuss what are cloud services? Why are they useful and how can we download data from the cloud?

Key Reading

Cloudfare Guide to the Cloud

expo-network

expo-netinfo

Lecture Summaries

7.0 Introduction to cloud services

Cloud services are services delivered on demand over the internet. It removes the need for us to host our own infrastructure.

Benefits include scalability- the cloud service provider supplies all the necessary infrastructure, software and hardware.

This means it can scale on demand, sometimes automatically.

It can be cheaper - pay for what you use and when you use it.

It can be flexible - often you can cancel any time, just pay for when you need it and then terminate it.

Models of cloud solutions:

SaaS - an application service - dropbox, Slack, stripe - services delivered at the point of need.

Infrastructure as a Service - IaaS - provides servers, firewalls, load balancers. AWS, Azure etc.

Platform as a Service - developers build apps within a web interface without the need for databases, AWS, Azure, IBM.

Public vs. Private cloud. Private is costly.

Common to use some kind of services within apps now - eg translation service, database service, payment service etc.

7.1 Reachability

Your app has to deal with a lot of situations where it’s not possible to access the internet - dodgy signal etc.

This happens all the time as users move. If you can’t connect to a db, how do you avoid data loss?

If you want to serve different assets depending on the connection you need to rely on the device report of its connection.

We can use the expo-network library to get the network state. import using import * as Network from 'expo-network'

Then we can interrogate network state:

await Network.getNetworkStateAsync();

returns:

{ type: NetworkStateType.CELLULAR, isConnected: true, isInternetReachable: true,}

Using this we can monitor internet connection type and let the user know any issues, take measures like storing data locally etc.

We can also use the netinfo library to create event listeners to detect change in status.

Here’s how we can use the basic expo-network library to detect the internet connection:

import * as Network from 'expo-network';

export default function App() {
    const [internetConnected, setInternetConnected] = useState(true);

    // detect connection
    useEffect(() => {
	isConnected().then((isIt) => {
	    if (isIt !== internetConnected) {
		setInternetConnected(isIt);
	    }
	}).catch((err) => console.log(err);)
    });

    if (internetConnected) {
	return ( <View>...)
    else {
	return ( <View>...)
    }
}

function isConnected() {
    return new Promise(async (resolve, reject) => {

	try {
	    let networkStatus = await Network.getNetworkStateAsync();
	    if (networkStatus.isInternetReachable) {
		resolve(true);
	    } else {
		resolve(false);
	    } catch (err) {
		reject(err);
	    }
	});
}

You can see this isn’t ideal if we’re wanting to detect rapidly changing connection status.

We can use a different library to create cleaner code:

import NetInfo from '@react-native-community/netinfo';

export default function App() {
    const [internetConnected, setInternetConnected] = useState(true);

    const unsubscribe = NetInfo.addEventListener(state => {
	if (internetConnected != state.isConnected) {
	    setInternetConnected(state.isConnected);
	}
    });

    if (internetConnected) {
	return (<View...>);
    }
    else {
	return (<View...>);
    }
}

Note the isConnected property here is potentially misleading, but here it means are you connected to the protocol (cellular, wifi). Usually that’s all that matters. But sometimes you want to check whether it is internet reachable, ie can the user access the public internet. For this you use state.isInternetReachable.

7.2 Fetching Data

An http get request is a simple and straightforward way to fetch data from a server.

React native uses the fetch API, which returns a promise. Use it with the await syntax or standard promise syntax.

7.3 Posting Data

post is for changing information typically. The request usually involves a body.

We use the same fetch API, but we need a config object following the url, with the method POST, headers, and body string.

Usual stuff…

7.4 Authentication

Authentication is widely used to secure sensitive endpoints etc. There are four dominant methods:

  • Basic Auth

  • Bearer Token

  • API Key

  • OAuth

Basic Auth

We provide the username and password to access the resource in the form an HTTP request header that looks like this:

Authorization: Basic <credentials>

Here credentials are a base64 encoded string of un and password joined by a single colon: <username>:<password>.

Here’s how to do it:

const base64 = require('base-64');

fetch('https://example.com/something', {
    method: 'POST',
    headers: {
	Accept: 'application/json',
	'Content-Type': 'application/json',
	Authorization: `Basic ${base64.encode("user:pass")}`
    }
});

You can use the ‘express-basic-auth’ library for implementing server-side basic auth on the server.

app.use(basicAuth({
    users: {'username', 'password'},
    challenge: true,
    realm: "mobile",
  }));

Then basic auth is applied to all requests below it…

In react native you can install ‘react-native-base64’ to do the auth encoding.

Bearer Token

This is much more likely to be used when the user has been logged in. The basic structure is again a header:

Authorization: Bearer <token>

Typically a user has logged in, the server returns a bearer token. The user can then submit that token.

Here’s how to do it:


fetch('https://example.com/something', {
    method: 'POST',
    headers: {
	Accept: 'application/json',
	'Content-Type': 'application/json',
	Authorization: `Bearer ${token}`
    }
});

API Key

This varies widely from API to API, always check the docs.

Typically though you’ll have a header of the form key: <token>

Usually this is identifying the developer/application not the individual user.

OAuth

One of the most common authentication mechanisms. Allows integration with third party authentication providers - Facebook/Twitter.

You can grant permission scopes with Oauth. There’s a complex authentication flow, often requiring multiple steps to setup.

Links to this note