Using Pusher Channels to remotely update an application's configuration
You will need React Native 0.5+ installed on your machine. Some knowledge of React Native development will be helpful.
In this tutorial, I will describing how to remotely update the configuration of a mobile app.
Sometimes the unexpected happens - a public API key was swapped, a new logo was created. While these are not really terrible things, the major issue is how to inform older clients of this change.
For web applications, this is relatively easy but the same cannot be said for mobile applications as it will require the app store approval process and hoping the user updates their app.
The app basically functions as a search client for users of the GitHub platform. Users enter a particular username and it displays the user’s information in a simple card. We will bundle a personal access token key in the app but will later create a newer one and revoke the older one in the GitHub’s dashboard, then create a new key and use Pusher Channels to notify all users of the change.
Searching for a user via the GitHub API can be done without authentication but the user’s email will not be provided. If the request is authenticated, the email address is returned in the response.
This makes it interesting for our usecase as requests with the revoked keys will actually still resolve but the user card will not contain the email address while clients that have gotten the new key will get email addresses.
Prerequisites
- Yarn
- React Native ( >= 0.50)
- A Pusher Channels application. Create one here.
- A GitHub account.
Building the application
We will need to create a new React-Native app before proceeding with anything. To do that, we will need to run the following command:
react-native init pusherchannelsconfig
If an error that says
command not found: react-native
. You will need to install thereact-native
toolchain. That can be done byyarn global add react-native
Once the application has been created, we will then proceed to building the user interface. We will need two screens to complete the user story of this app:
- A search screen
- A result screen
We will build the search screen first. You will need to create a file called Search.js
in your application root. Since we will be making HTTP
requests, we will need a library that can help with that, I have settled on axios
. The following command will create the Search.js
file and install the axios
library.
$ touch Search.js
$ yarn add axios
Once the above succeeds, you need to paste the following code into the newly created Search.js
file.
// pusherchannelsconfig/Search.js
import React, { Component } from 'react';
import { Alert, Button, TextInput, View, Text, StyleSheet } from 'react-native';
import axios from 'axios';
const USERNAME = 'adelowo';
class Search extends Component {
state = {
useKey: true,
};
fetchProfile = () => {
const config = this.state.useKey
? { auth: { username: USERNAME, password: this.props.authKey } }
: {};
return axios.get(`https://api.github.com/users/${this.state.text}`, config);
};
render() {
return (
<View>
<TextInput
style={{ height: 40 }}
placeholder="Type here to search for a GitHub user!"
onChangeText={text => this.setState({ text })}
/>
<Button
onPress={() => {
this.fetchProfile()
.then(res => {
this.props.cb(res.data);
})
.catch(err => {
if (err.response) {
if (err.response.data.message === 'Bad credentials') {
this.setState({ useKey: false });
this.fetchProfile().then(res => {
this.props.cb(res.data);
});
return;
}
}
Alert.alert(
'an error occurred while fetching the user profile'
);
});
}}
title="Press Me"
/>
</View>
);
}
}
export default Search;
In the above code, we create a React Native search component. It houses the search bar and whenever the button titled Search is clicked, it connects to the GitHub API to fetch the user’s profile.
The next step of action is to build the result page. The result page will be a simple card that contains the profile information of the user.
The only dependency we need here is a library called react-native-simple-card
. To install it, run the following command in the root directory.
$ yarn add react-native-simple-card
You will also need to create a file named UserView.js
. That can be done with:
$ touch UserView.js
In the newly created UserView.js
. paste the following contents:
// pusherchannelsconfig/UserView.js
import React, { Component } from 'react';
import { Button, Image, StyleSheet, Text, View } from 'react-native';
import SingleCardView from 'react-native-simple-card';
class UserView extends Component {
render() {
console.log(this.props);
return (
<View>
<SingleCardView
elevation={1}
shadowColor="rgb(50,50,50)"
shadowOpacity={1}
marginTop={150}
height={200}
>
<Text style={{ padding: 10, fontSize: 18 }}>
Username : {this.props.user.login}
</Text>
<Text style={{ padding: 10, fontSize: 18 }}>
Bio : {this.props.user.bio}
</Text>
<Text style={{ padding: 10, fontSize: 18 }}>
Email: {this.props.user.email}
</Text>
</SingleCardView>
<Button title="Go back" onPress={this.props.clear} />
</View>
);
}
}
export default UserView;
This is as simple as can be. The user’s information is passed to this component and the relevant fields are picked and displayed.
You will need to create an access token on GitHub by visiting this URL. Make sure to select user scope as shown below:
The next thing will be to connect the components we have created above together. You will need to edit the App.js
file. Delete all of it’s contents and replace it with the following:
// pusherchannelsconfig/App.js
import React, { Component } from 'react';
import { Alert, Button, TextInput, View, Text, StyleSheet } from 'react-native';
import Search from './Search';
import UserView from './UserView';
const appKey = 'PUSHER_CHANNELS_APP_KEY';
const cluster = 'eu';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
text: '',
key: 'GITHUB_PERSONAL_TOKEN',
showUserProfile: false,
user: null,
};
}
onCallBack = user => {
this.setState({ user: user, showUserProfile: true });
};
onReset = () => {
this.setState({ user: null, showUserProfile: false });
};
render() {
return (
<View style={styles.container}>
<View style={{ padding: 10 }}>
{this.state.showUserProfile ? (
<UserView clear={this.onReset} user={this.state.user} />
) : (
<Search cb={this.onCallBack} authKey={this.state.key} />
)}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
Remember to use your credentials.
You can run the application by running the following command in the root directory.
$ react-native run-ios
$ ## OR
$ react-native run-android
You can go ahead to search for a user - If you don’t know any username, you can go ahead to make use of adelowo
or fabpot.
Updating the personal access token
If you were following. you will notice that in the App.js
file, we kept a reference of our access token in this.state.key.
In the following steps, we will need to revoke the current key and create a new one.
Navigate to GitHub to create an access token. Feel free to revoke the older key as the app will be aware of revoked keys and make the request without any key. Remember that in this instance the only advantage authenticating with the personal access key is the email address that is returned in the response.
You will need to visit your Channels dashboard and navigate to the Debug console. You will use the Debug console to send the new key to all mobile clients. Once the application receives it, it will replace the previous key with what was gotten from Pusher Channels.
There is one more step we need to take which is update our app to be aware of Pusher Channels. We will need to install the pusher-js
library.
$ yarn add pusher-js
You will also need to update App.js
with the following:
// pusherchannelsconfig/App.js
// New import statement
import Pusher from 'pusher-js/react-native';
const channelName = 'gh-key-swap';
constructor(props) {
// Update the constructor to look like this
super(props);
this.state = {
text: '',
key: 'GITHUB_PERSONAL_ACCESS_TOKEN',
showUserProfile: false,
user: null,
};
this.pusher = new Pusher(appKey, { cluster });
this.listenForChanges();
}
// Here is a newer method
listenForChanges = () => {
const channel = this.pusher.subscribe(channelName);
channel.bind('key-change', data => {
Alert.alert('Reloading Authentication key', 'Press ok to continue');
this.setState({ user: null, showUserProfile: false, key: data.key });
});
};
Once that has been added, verify your App.js
is similar to the code below:
// pusherchannelsconfig/App.js
import React, { Component } from 'react';
import { Alert, Button, TextInput, View, Text, StyleSheet } from 'react-native';
import Search from './Search';
import UserView from './UserView';
import Pusher from 'pusher-js/react-native';
const appKey = 'PUSHER_CHANNELS_APP_KEY'
const cluster = 'PUSHER_CHANNELS_CLUSTER';
const channelName = 'gh-key-swap';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
text: '',
key: 'GITHUB_PERSONAL_ACCESS_TOKEN',
showUserProfile: false,
user: null,
};
this.pusher = new Pusher(appKey, { cluster });
this.listenForChanges();
}
listenForChanges = () => {
const channel = this.pusher.subscribe(channelName);
channel.bind('key-change', data => {
Alert.alert('Reloading Authentication key', 'Press ok to continue');
this.setState({ user: null, showUserProfile: false, key: data.key });
});
};
onCallBack = user => {
this.setState({ user: user, showUserProfile: true });
};
onReset = () => {
this.setState({ user: null, showUserProfile: false });
};
render() {
return (
<View style={styles.container}>
<View style={{ padding: 10 }}>
{this.state.showUserProfile ? (
<UserView clear={this.onReset} user={this.state.user} />
) : (
<Search cb={this.onCallBack} authKey={this.state.key} />
)}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
Input a new username in the search box and make the request. Remember to revoke the previous access token that was initially created as that will be the way to test the application. You will notice that the search requests still resolves with the newer token.
If you will like to test this further, revoke all tokens from your GitHub dashboard and try searching for a user. This will still go through but you will notice that the user’s email address is not included in the card.
This can be taken further by storing the newer key in some form of persistent storage system.
Conclusion
In this tutorial, we have leveraged Pusher Channels as a way to remotely update an application’s configuration. This can be useful when it takes a long time for users to update to a newer version.
The entire source code of this tutorial can be found on GitHub.
4 March 2019
by Lanre Adelowo