Simple sample for Users (on the PhoneGap platform)
Contents |
Quick start with Simple sample for Users
For quick start and learning the main features of using QuickBlox Users Module we recommend you to look through current tutorial for PhoneGap platform.
To start work with Simple Sample for Users:
- Repository: https://github.com/QuickBlox/SimpleSample-users-phonegap
- Download code from repository
git@github.com:QuickBlox/SimpleSample-users-phonegap.gitor zip archive https://github.com/QuickBlox/SimpleSample-users-phonegap/zipball/master - Create Android Project in Eclipse and specify path to project folder for Create from existing source field
- Run Android application
Create PhoneGap application for Android
This tutorial describes the process of creating a simple application using QuickBlox Users module for PhoneGap platform.
PhoneGap application consists of two parts. There is a code of HTML/JavaScript application and a wrapper that is implemented by Android application (or any other platforms that are supported by PhoneGap -- Android, iOS, Blackberry, WP, WebOS, Symbian).
First we should create empty PhoneGap application. In our case we are using the Android platform. You can use tutorial on the official website or read text below.
- Create Android application in Eclipse
- Download the latest copy of PhoneGap and extract its contents. We will be working with the Android directory.
- Create folder
libsin the root of the application and to there PhoneGap jar-library (in our case it'sphonegap-1.4.1.jar). - Add library to the application Build Path (go to Build Path → Configure Build Path for current application, then open tab Libraries and add new library by Add JARs).
- Then you need to add the following files
- Change the code in
src/com/quickblox/sample/SimpleSampleUsersPhoneGap.java - Add following code to
AndroidManifest.xmlinside root elementmanifest - Add file
assets/www/index.html - If all is right, the project should have the following structure
- Run project on the device or emulator
res/xml/phonegap.xml
<?xml version="1.0" encoding="utf-8"?> <phonegap> <access origin="http://127.0.0.1*"/> <log level="DEBUG"/> </phonegap>
and
res/xml/plugins.xml
<?xml version="1.0" encoding="utf-8"?> <plugins> <plugin name="Device" value="com.phonegap.Device" /> </plugins>
package com.quickblox.sample; import android.os.Bundle; import com.phonegap.*; public class SimpleSampleUsersPhoneGap extends DroidGap { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.loadUrl("file:///android_asset/www/index.html"); } }
<supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" /> <uses-permission android:name="android.permission.INTERNET" />
Add android:configChanges="orientation|keyboardHidden" to the activity tag and add new activity
<activity android:name="com.phonegap.DroidGap" android:configChanges="orientation|keyboardHidden" android:label="@string/app_name" > <intent-filter> </intent-filter> </activity>
Result file AndroidManifest.xml should look like this:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.quickblox.samples" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="7" /> <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" /> <uses-permission android:name="android.permission.INTERNET" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name="com.quickblox.sample.SimpleSampleUsersPhoneGap" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.phonegap.DroidGap" android:configChanges="orientation|keyboardHidden" android:label="@string/app_name" > <intent-filter> </intent-filter> </activity> </application> </manifest>
<!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>Hello, PhoneGap!</title> </head> <body> Hello, PhoneGap! </body> </html>
Using of QuickBlox Users Module in HTML/JavaScript application
This par describes the process of development HTML/JavaScript application as part of PhoneGap infrastructure. All code is situated in assets/web folder.
Application contains following files
index.html-- code of application pagemain.js-- JavaScript code of applicationjquery.min.js-- jQuery libphonegap-1.4.1.js-- PhoneGap lib, that you can find in archive, that was downloaded from official website
JavaScript code
Data initialization for connecting to QuickBlox application. All these parameters you can find on QuickBlox application page in the admin panel.
// QuickBlox application settings var QB = { appId : '203', ownerId : '4431', authKey : '5a-YN-8saK8-yTs', authSecret : 'ttwUEV7rGGaOrnV' }
Function init() runs already after the body tag was downloaded in index.html.
Function document.addEventListener("deviceready", main, true); adds listener for deviceready event. When deviceready event is done the main() function will run.
// Script runs main() when when PhoneGap is fully loaded. // http://docs.phonegap.com/en/1.4.1/phonegap_events_events.md.html#deviceready function init() { document.addEventListener("deviceready", main, true); // $(document).ready(main); }
Function main() shows QuickBlox application settings on the html page and runs authentication function authApp(appHasToken, errorCallback)
function main() { $('#phoneGapStatus').html("it's working"); // Show QuickBlox application parameters. $('#appId').html(QB.appId); $('#ownerId').html(QB.ownerId); $('#authKey').html(QB.authKey); $('#authSecret').html(QB.authSecret); authApp(appHasToken, errorCallback); }
Function authApp(successCallback, errorCallback) sends POST request to https://admin.quickblox.com/auth with following parameters
-
app_id -
auth_key -
nonce-- random value -
timestamp-- unix timestamp -
signature
The most interesting parameter is signature that calculates following way -- parameters app_id, auth_key, nonce, timestamp together with values should be sorted by alphabet, e.g.
app_id=203&auth_key=5a-YN-8saK8-yTs&nonce=0×tamp=1325016104
and encrypt with HMAC-SHA, where encryption key is authorization secret from application settings.
There is function getSignature() that makes all specified calculations.
See more documentation on the wiki -- Authentication_and_Authorization#API_Session_Creation
// Authenticate specified QuickBlox application. // Calls successCallback if finished successfully, and errorCallback if not. function authApp(successCallback, errorCallback) { var s = getSignature(); // gets signature // See more documentation on the wiki -- http://wiki.quickblox.com/Authentication_and_Authorization#API_Session_Creation var url = 'https://admin.quickblox.com/auth'; var data = 'app_id=' + QB.appId + '&auth_key=' + QB.authKey + '&nonce=' + s.nonce + '×tamp=' + s.timestamp + '&signature=' + s.signature; console.log('[DEBUG] Authenticate specified application: POST ' + url + '?' + data); $.ajax({ type: 'POST', url: url, data: data, success: successCallback, error: errorCallback }); }
appHasToken(xml) runs if application authentication is successful.
// Calls when QuickBlox application authorize. function appHasToken(xml) { // Finds token in retrieved xml response. var token = $(xml).find('token').text(); console.log('[DEBUG] Your token: ' + token); $('#auth').unbind('click'); $('#auth').click(function(){ authUser(token); }); $('#register').unbind('click'); $('#register').click(function(){ addUser(token); }); $('#users a').die('click'); $('#users a').live('click', function(){ var userId = $(this).attr('id'); deleteUser(token, userId); }); getAllUsers(token); }
getAllUsers(token) gets all application users. It sends GET request to https://users.quickblox.com/users.json
See more documentation on the wiki -- Retrieve_API_Users_for_current_application
// Gets all users of QuickBlox application and prints them into the page. function getAllUsers(token) { // See more documentation on the wiki -- http://wiki.quickblox.com/Users#Retrieve_API_Users_for_current_application var url = 'https://users.quickblox.com/users.json' var data = 'token=' + token; console.log('[DEBUG] Getting all users: GET ' + url + '?' + data); $.ajax({ type: 'GET', url: url, data: data, success: function(response) { console.log('[DEBUG] Server response:'); console.log(response); // Prints users list into the #users container. $('#users').html(''); $('#usersCount').html(' (' + response.items.length + ')'); $(response.items).each(function(index, current){ var element = '<li>[<a href="#" id="' + current.id + '">delete</a>] (' + current.id + ') ' + current.login + '</li>'; $('#users').append(element); }); if (response.items.length == 0) { $('#users').append('<li><i>There are no users in application.</i></li>'); } }, error: errorCallback }); }
.json format means that result will be presented using JSON, e.g.
{ "page": 1, "page_size": 10, "total_pages": 6, "items": [ { "blob_id": null, "created_at": "2011-12-27T20:10:43Z", "custom_parameters": null, "device_id": null, "email": "user@injoit.com", "external_user_id": null, "facebook_id": null, "full_name": null, "id": 343, "last_request_at": "2012-02-08T13:35:52Z", "login": "batman", "owner_id": 4342, "phone": null, "twitter_id": null, "updated_at": "2012-02-08T13:35:52Z", "website": null }, ... }
Some actions with data (editing, deleting) can be done only when user has been authenticated.
Thats why we should authenticate user.
See more documentation on the wiki -- Authentication_and_Authorization#API_User_Sign_In
// Authenticates user. function authUser(token) { var login = $('#login').val(); var password = $('#password').val(); // See more documentation on the wiki -- http://wiki.quickblox.com/Authentication_and_Authorization#API_User_Sign_In var url = 'https://users.quickblox.com/users/authenticate.json' var data = 'user[owner_id]=' + QB.ownerId + '&login=' + login + '&password=' + password + '&token=' + token; console.log('[DEBUG] Authenticate existing user: POST ' + url + '?' + data); $.ajax({ type: 'POST', url: url, data: data, success: function(response) { console.log('[DEBUG] User has been successfully authenticated. Server response:'); alert('[DEBUG] User has been successfully authenticated, user id = ' + response.id); console.log(response); }, error: errorCallback }); }
Adding new user.
See more documentation on the wiki -- Users#API_User_Sign_Up
// Adds new user. function addUser(token) { var login = $('#new_login').val(); var password = $('#new_password').val(); // See more documentation on the wiki -- http://wiki.quickblox.com/Users#API_User_Sign_Up var url = 'https://users.quickblox.com/users.json' var data = 'user[owner_id]=' + QB.ownerId + '&user[login]=' + login + '&user[password]=' + password + '&token=' + token; console.log('[DEBUG] Add new user: POST ' + url + '?' + data); $.ajax({ type: 'POST', url: url, data: data, success: function(response) { console.log('[DEBUG] User has been successfully added, server response:'); console.log(response); alert('User has been successfully added, user id = ' + response.id); getAllUsers(token); }, error: errorCallback }); }
Deleting an existing user (before deleting user should be authenticated).
See more documentation on the wiki -- Users#Delete_API_User_by_identifier
// Deletes existing user by id. function deleteUser(token, id) { // See more documentation on the wiki -- http://wiki.quickblox.com/Users#Delete_API_User_by_identifier var url = 'https://users.quickblox.com/users/' + id + '.json'; var data = 'token=' + token; console.log('[DEBUG] Delete user: DELETE ' + url + '?' + data); $.ajax({ type: 'DELETE', url: url, data: data, complete : function(jqXHR, textStatus) { console.log(jqXHR); alert(jqXHR.statusText + ' ' + jqXHR.status + ' : ' + jqXHR.responseText); if (jqXHR.status == 200) { authApp(appHasToken, errorCallback); } } }); }
Getting signature for making application authentication.
// Gets signature. Signature uses for application authentication. function getSignature() { var nonce = Math.floor(Math.random() * 1000); // Gets random number (0;1000) var timestamp = Math.round((new Date()).getTime() / 1000); // Gets unix timestamp (http://en.wikipedia.org/wiki/Unix_time) // Creating message where parameters are sorted by alphabetical order. var message = 'app_id=' + QB.appId + '&auth_key=' + QB.authKey + '&nonce=' + nonce + '×tamp=' + timestamp; var secret = QB.authSecret; // Encrypting message with secret key from QuickBlox application parameters. var hmac = Crypto.HMAC(Crypto.SHA1, message, secret); var signatureObj = { nonce : nonce, timestamp : timestamp, signature : hmac }; return signatureObj; }




