Giter Site home page Giter Site logo

mesmin / hello.js Goto Github PK

View Code? Open in Web Editor NEW

This project forked from mrswitch/hello.js

0.0 2.0 0.0 649 KB

A Javascript RESTFUL API library for connecting with OAuth2 services, such as Google+ API, Facebook Graph and Windows Live Connect

Home Page: http://adodson.com/hello.js/

hello.js's Introduction

hello.js

A client-side Javascript SDK for authenticating with OAuth2 (and OAuth1 with a oauth proxy) web services and querying their REST API's. HelloJS Standardizes paths and responses to common API's like Google Data Services, Facebook Graph and Windows Live Connect. Its modular so that list is growing. No more spaghetti code!

Features

Looking for more? HelloJS supports a lot more actions than just getting the users profile. Like, matching users with a users social friends list, sharing events with the users social streams, accessing and playing around with a users photos. Lets see if these whet your appetite ...

Windows FaceBook Google More..
Profile: name, picture (email)
Friends/Contacts: name, id (email)
Albums, name, id, web link
Photos in albums, names, links
Photo file: url, dimensions
Create a new album
Upload a photo
Delete an album
Status updates
Update Status

Items marked with a ✓ are fully working and can be tested here. Items marked with a ✗ aren't provided by the provider at this time. Blank items are work in progress, but there is good evidence that they can be done. Anything not listed i have no knowledge of and would appreciate input.

Quick Start

Quick start shows you how to go from zero to loading in the name and picture of a user, like in the demo above.

Register your app domain Include hello.js script Create the signin buttons Setup listener for login and retrieve user info. Initiate the client_ids and all listeners

1. Register

Register your application with atleast one of the following networks. Ensure you register the correct domain as they can be quite picky

2. Include Hello.js script in your page

<script class="pre" src="./dist/hello.all.min.js"></script>

3. Create the signin buttons

Just add onclick events to call hello.login(network). Style your buttons as you like, i've used zocial css, but there are many other icon sets and fonts

&lt;button onclick="hello.login('windows')"&gt;windows&lt;/button&gt;

4. Add listeners for the user login

Lets define a simple function, which will load a user profile into the page after they signin and on subsequent page refreshes. Below is our event listener which will listen for a change in the authentication event and make an API call for data.

hello.subscribe('auth.login', function(auth){
	
	// call user information, for the given network
	hello.api( auth.network + '/me', function(r){
		if(!r.id || !!document.getElementById(r.id) ){
			return;
		}
		var target = document.getElementById("profile_"+ auth.network );
		target.innerHTML = '<img src="'+ r.picture +'" /> Hey '+r.name;

	});
});

5. Configure hello.js with your client_id's and initiate all listeners

Now let's wire it up with our registration detail obtained in step 1. By passing a [key:value, ...] list into the hello.init function. e.g....

hello.init({ 
	facebook : FACEBOOK_CLIENT_ID,
	windows  : WINDOWS_CLIENT_ID,
	google   : GOOGLE_CLIENT_ID
},{redirect_uri:'redirect.html'});

That's it. The code above actually powers the demo at the start so, no excuses.

Core Methods

hello.init()

Initiate the environment. And add the application credentials

hello.init( {facebook: id, windows: id, google: id, .... } )

nametype
credentials object( key => value, ...  )
nametypeexampledescription argumentdefault
keystringwindows, facebook or google App name'srequiredn/a
valuestring 0000000AB1234ID of the service to connect to requiredn/a
options set's default options, as in hello.login()

Example:

hello.init({
	facebook : '359288236870',
	windows : '000000004403AD10'
});

hello.login()

If a network string is provided: A consent window to authenticate with that network will be initiated. Else if no network is provided a prompt to select one of the networks will open. A callback will be executed if the user authenticates and or cancels the authentication flow.

hello.login( [network] [,options] [, callback() ] )

nametypeexampledescription argumentdefault
networkstringwindows, facebookOne of our services. required null
options object
nametypeexampledescription argumentdefault
displaystringpopup, page or none How the signin flow should work, "none" is used to refresh the access_token in the background optional popup
scopestringemail, publish or photos Comma separated list of scopes optional null
redirect_uristringhttp://domain.com/hello.html A full URI of a page which includes this script file hello.js optional window.location.href
response_typestringtoken, code Mechanism for authentication optional token
callbackfunctionfunction(){alert("Logged in!");} A callback when the users session has been initiated optional null

Examples:

hello.login(&#39;facebook&#39;, function(){
	alert("You are signed in to Facebook");
});

hello.logout()

Remove all sessions or individual sessions.

hello.logout( [network] [, callback() ] )

nametypeexampledescription argumentdefault
networkstringwindows, facebookOne of our services. optional null
callbackfunctionfunction(){alert("Logged in!");} A callback when the users session has been initiated optional null

Example:

hello.logout(&#39;facebook&#39;, function(){
	alert("Signed out");
});

hello.getAuthResponse()

Get the current status of the session, this is an synchronous request and does not validate any session cookies which may have expired.

hello.getAuthResponse( network );

nametypeexampledescription argumentdefault
networkstringwindows, facebookOne of our services. optional current

Examples:

alert((hello.getAuthResponse(&#39;facebook&#39;)?&quot;Signed&quot;:&#39;Not signed&#39;) + &#39; into FaceBook, &#39; +( hello.getAuthResponse(&#39;windows&#39;)?&quot;Signed&quot;:&#39;Not signed&#39;)+&quot;into Windows Live&quot;);

hello.api()

Make calls to the API for getting and posting data

hello.api( [ path ], [ method ], [ data ], [ callback(json) ] )

nametypeexampledescription argumentdefault
pathstring/me, /me/friendsPath or URI of the resource. See REST API, Can be prefixed with the name of the service requirednull
methodget, post, delete, putSee typeHTTP request method to use. optionalget
dataobject{name: Hello, descrition: Fandelicious} A JSON object of data, FormData, HTMLInputElement, HTMLFormElment to be sent along with a get, post or put request optional null
callbackfunctionfunction(json){console.log(json);} A function to call with the body of the response returned in the first parameter as an object, else boolean false optional null

Examples:

hello.api("me", function(json){
	if(!json||json.error){
		alert("Whoops!");
		return;
	}
	alert("Your name is "+ json.name);
});

Event subscription

hello.subscribe()

Bind a callback to an event. An event maybe triggered by a change in user state or a change in some detail.

hello.subscribe( event, callback );

event description
auth Triggered whenever session changes
auth.login Triggered whenever a user logs in
auth.logout Triggered whenever a user logs out
auth.update Triggered whenever a users credentials change

Example:

var sessionstart =  function(){
	alert("Session has started");
};
hello.subscribe("auth.login",sessionstart);

hello.unsubscribe()

Remove a callback, both event name and function must exist

hello.unsubscribe( event, callback );

hello.unsubscribe("auth.login",sessionstart);

Scope and Permissions

Scopes define what services your asking the user to grant your app permission to. As you can gather these can be quite intrusive so only ask permission for scopes which are obvious to your app. You may always request more from the user later.

Update scope settings

The table shows how the providers have different scopes, however HelloJS sync's the names, so you only have to ever know what HelloJS calls them.

Select the scopes you want to use and update the current session.

scopeFacebookWindows LiveGoogle
default wl.signin, wl.basichttps://www.googleapis.com/auth/plus.me
emailemailwl.emails
birthdayuser_birthdaywl.birthday
eventsuser_eventswl.calenders
photos
videos
user_photos,user_videoswl.photos
friendshttps://www.google.com/m8/feeds
publishpublish_streamswl.share
create_eventcreate_eventwl.calendars_update,wl.events_create
offline_accessoffline_accesswl.offline_access

google facebook windows

REST API

Path Translation

hello.js translates paths if there are common paths across services.

hello.jsFacebookWindows LiveGoogle
OAuth2 endpointhttp://www.facebook.com/dialog/oauth/https://oauth.live.com/authorizehttps://accounts.google.com/o/oauth2/auth
REST API basehttps://graph.facebook.com/https://apis.live.net/v5.0/https://www.googleapis.com/
mememeplus/v1/people/me?pp=1
me/friendsme/friendsme/friendshttps://www.google.com/m8/feeds/contacts/default/full?alt=json&max-results=1000
me/shareme/feedme/sharen/a
me/albumsme/albumsme/albumsn/a

Paths

These are some of the paths you can use with hello.api( path, callback ). e.g. hello.api("me", function(json){console.log(json);}) Below is a REST playground, clicking the paths on the left will return the results on the right

Play Ground

Windows FaceBook Google

e.g...

  • /me
  • /me/friends
  • /me/feed
  • /me/home
  • /me/photos
  • /me/albums
  • /me/videos
  • /me/events

Runclear update your scopes and permissions

Error handling

For hello.api([path], [callback]) the first parameter of callback upon error will be either boolean (false) or be an error object as described below.

Error Object

nametype
errorobject
nametypeexampledescription argumentdefault
codestring request_token_unauthorizedCode requiredn/a
messagestringThe provided access token.... Error messagerequiredn/a

Extending the services

Services are added to HelloJS as "modules" for more information about creating your own modules and examples, go to Modules

OAuth Proxy

OAuth 1.0 and OAuth 1.0a require a server side handshake with the secret key. OAuth 1 does not use the redirect_uri to verify the application, unlike OAuth2. Making HelloJS work with OAuth1 therefore requires a proxy server to sign requests.

By default the service uses http://auth-server.herokuapp.com/ as its proxy. Developers may add their own network registration AppID/client_id and secret to this service thus supporting OAuth1.0 and OAuth1.0a web services.

Browser Support

Browser
IE10
IE9
IE8
IE7
FF
CR
SA
OP
Mob
Mini5
iOS WP 7
hello.js 1,2 3 4

IE7: Makes beeping sounds whenever the POST, PUT or DELETE methods are used - because of the XD, IFrame+Form+hack.

  • IE7: Requires JSON.js and localStorage shims
  • Opera Mini: Supports inline consent only, i.e. reloads original page.
  • WP7: Supports inline consent only, i.e. reloads original page.

hello.js's People

Contributors

mrswitch avatar

Watchers

James Cloos avatar  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.