Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AMD support, Auto-fetch credentials from Collection/Model url #6

Merged
merged 6 commits into from Jul 22, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 1 addition & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,9 @@ Usage:

``` js
var Model = Backbone.Model.extend({
url: 'http://path/to/basic/auth/protected/resource'
url: 'http://username:password@path/to/basic/auth/protected/resource'
});

Backbone.BasicAuth.set('username', 'password');

var model = new Model();
model.fetch();
```
Expand All @@ -27,16 +25,6 @@ The access token is formed by taking the username and password, concatenating to

This plugin handles the Base64 encoding and automatically sets the `Authorization` header on every request which uses `Backbone.sync`.

## API

#### `Backbone.BasicAuth.set(username, password)`

Sets the access token which is used by all future remote requests, until `clear()` is called.

#### `Backbone.BasicAuth.clear()`

Clears the access token and restores the standard `Backbone.sync`.

## Dependencies

- [Backbone](http://backbonejs.org)
Expand Down
85 changes: 53 additions & 32 deletions backbone.basicauth.js
Original file line number Diff line number Diff line change
@@ -1,48 +1,69 @@
/*!
* backbone.basicauth.js v0.2.0
* Copyright 2013, Tom Spencer (@fiznool)
* backbone.basicauth.js v0.3.0
*
* Automatically parses the model/collection.url for http auth credentials
*
* Copyright 2013, Tom Spencer (@fiznool), Luis Abreu (@lmjabreu)
* backbone.basicauth.js may be freely distributed under the MIT license.
*/
;(function(window) {
;( function ( root, factory ) {
// AMD module if available
if ( typeof define === 'function' && define.amd ) {
// AMD
define( 'BackboneBasicAuth', [ 'Underscore', 'Backbone' ], function BackboneBasicAuthDefineCallback ( Underscore, Backbone ) {
factory( root, Underscore, Backbone );
} );
} else {
// Browser global scope
factory( root );
}
}( this, function BackboneBasicAuthFactory ( window, Underscore, BBone ) {

// Local copy of global variables
var _ = window._;
var Backbone = window.Backbone;
var _ = Underscore || window._;
var Backbone = BBone || window.Backbone;
var btoa = window.btoa;

var token = null;

var encode = function(username, password) {
/**
* Returns a base64 encoded "user:pass" string
* @param {string} username The http auth username
* @param {string} password The http auth password
* @return {string} The base64 encoded credentials pair
*/
var encode = function encodeToken ( username, password ) {
// Use Base64 encoding to create the authentication details
// If btoa is not available on your target browser there is a polyfill:
// https://github.com/davidchambers/Base64.js
return btoa(username + ':' + password);
return btoa( [ username, password ].join( ':' ) );
};

// Store a copy of the original Backbone.sync
var originalSync = Backbone.sync;

// Override Backbone.sync for all future requests.
// If a token is present, set the Basic Auth header
// before the sync is performed.
Backbone.sync = function(method, model, options) {
if (typeof token !== "undefined" && token !== null) {
/**
* Override Backbone.*.prototype.sync
*
* If a token is present, set the Basic Auth header before the sync is performed.
*
* @param {string} method Contains the backbone operation. e.g.: read, reset, set
* @param {object} context A Backbone model or collection
* @param {object} options Options to be passed over to Backbone.sync and jQuery
* @return {object} Reference to Backbone.sync for chaining
*/
Backbone.Collection.prototype.sync = Backbone.Model.prototype.sync = function backboneSyncOverride ( method, context, options ) {
// Handle both string and function urls
var remoteURL = ( _.isFunction( context.url ) ) ? context.url() : context.url ;
// Retrieve the auth credentials from the context url
var credentials = remoteURL.match( /\/\/(.*):(.*)@/ ),
token;
// Set the token if available
if ( credentials && credentials.length === 3 ) {
token = encode( credentials[ 1 ], credentials[ 2 ] );
}
// Add the token to the request headers if available
if ( typeof token !== 'undefined' && token !== null ) {
options.headers = options.headers || {};
_.extend(options.headers, { 'Authorization': 'Basic ' + token });
_.extend( options.headers, { 'Authorization': 'Basic ' + token } );
}
return originalSync.call(model, method, model, options);
};

Backbone.BasicAuth = {
// Setup Basic Authentication for all future requests
set: function(username, password) {
token = encode(username, password);
},

// Clear Basic Authentication for all future requests
clear: function() {
token = null;
}
// Perform the sync
return Backbone.sync.apply( this, arguments );
};

})(this);
} ) );
2 changes: 1 addition & 1 deletion bower.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "backbone.basicauth",
"version": "0.2.0",
"version": "0.3.0",
"description": "Sync data through your Backbone Models and Collections to resources protected by HTTP Basic Authentication.",
"main": "backbone.basicauth.js",
"dependencies": {
Expand Down