Skip to content

Commit

Permalink
Added support to Drupal 8 and maintain version for Drupal 7
Browse files Browse the repository at this point in the history
  • Loading branch information
enzolutions committed Sep 5, 2014
1 parent 2f609ea commit fd392fc
Show file tree
Hide file tree
Showing 6 changed files with 155 additions and 49 deletions.
35 changes: 30 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,17 +37,40 @@ Enable to have Drupal as Backend in a Domain backend.com and the Backbone/Marion

##### Drupal 8

Because the mode https://www.drupal.org/project/cors doesn't have a version for Drupal 8 yet I recommend use Apache 2 and enable CORS using .htaccess using the following command
Because the mode https://www.drupal.org/project/cors doesn't have a version for Drupal 8 yet and Drupal Core still doesn't have a solution for that I did a <a href="https://www.drupal.org/files/issues/core-cors-headers-1869548-26.patch">patch</a> for .htacces to enable CORS request using jQuery documented in issue # https://www.drupal.org/node/1869548#comment-9120317

```
Header set Access-Control-Allow-Origin "*"
diff --git a/.htaccess b/.htaccess
index c32b182..b0bf563 100644
--- a/.htaccess
+++ b/.htaccess
@@ -118,6 +118,10 @@ DirectoryIndex index.php index.html index.htm
RewriteCond %{REQUEST_URI} !core
RewriteRule ^ %1/core/%2 [L,QSA,R=301]
+ # Intercept OPTIONS calls
+ RewriteCond %{REQUEST_METHOD} OPTIONS
+ RewriteRule .* / [R=200,L]
+
# Pass all requests not referring directly to files in the filesystem to
# index.php.
RewriteCond %{REQUEST_FILENAME} !-f
@@ -165,3 +169,7 @@ DirectoryIndex index.php index.html index.htm
</FilesMatch>
</IfModule>
</IfModule>
+
+Header always set Access-Control-Allow-Origin "*"
+Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, PATCH, DELETE"
+Header always set Access-Control-Allow-Headers: Authorization
```
When issues https://www.drupal.org/node/1869548 and https://www.drupal.org/node/2237231 get resolved this implementation will be updated.

More information at http://enable-cors.org/server_apache.html

##### Drupal 7

In your Drupal Server you must setup <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS" target="_blank">HTTP Access Control</a> to enable connection, below and example.
In your Drupal Server you must setup <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS" target="_blank">HTTP Access Control</a> to enable connection, below an example.

````
Access-Control-Allow-Credentials:true
Expand Down Expand Up @@ -87,12 +110,14 @@ var Property = Backbone.Drupal.Models.Node.extend({

<ul>
<li>Implement Collections for Taxonomies and Search</li>
<li>Create integration with module Restws</li>
<li>Create version of plugin for Drupal 8.</li>
<li>Create integration with module Restws in Drupal 7</li>
<li>Test Drupal 8 POST method and Views integrations.</li>
</ul>

### Usage

Check **test/index.html** for Drupal 8 example and **indexd7.html** for Drupal 7 example.

````
<!DOCTYPE html>
<html lang="en">
Expand Down
92 changes: 62 additions & 30 deletions backbone.drupal.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ Backbone.Drupal.Auth = (function(Backbone, $, _){

// Set defaults. These are the only attributes allowed.
function defaults() {
return { crossDomain: false };
return { crossDomain: false, drupal8: true };
}

// Set attributes
Expand Down Expand Up @@ -53,37 +53,64 @@ Backbone.Drupal.Auth = (function(Backbone, $, _){
var status = false;
var restEndpoint = Backbone.Drupal.restEndpoint.root + (Backbone.Drupal.restEndpoint.root.charAt(Backbone.Drupal.restEndpoint.root.length - 1) === '/' ? '' : '/');

jQuery.ajax({
async: false,
url : restEndpoint + 'user/login' + Backbone.Drupal.restEndpoint.dataType,
type : 'post',
data : 'username=' + encodeURIComponent(username) + '&password=' + encodeURIComponent(password),
//dataType : 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
return false;
},
success : function(data) {

var settings = {
beforeSend: function (request) {
request.setRequestHeader("X-CSRF-Token", data.token);
}
};
if(attributes.drupal8) {
// Prepare further calls to use Basic Auth againt drupal 8 and set a cookie
var settings = {
beforeSend: function (request) {
request.setRequestHeader ('Authorization', 'Basic ' + btoa(username + ':' + password));
//request.setRequestHeader ('Accept', 'application/json');
request.setRequestHeader ( "Content-type", "application/x-www-form-urlencoded" );
}
};

if(attributes.crossDomain) {
settings.xhrFields = {
withCredentials: true
if(attributes.crossDomain) {
/*settings.xhrFields = {
withCredentials: true
};*/

//settings.crossDomain = true;
}

// Define specific parametres to be used in all future request.
$.ajaxSetup(settings);

console.log(btoa(username + ':' + password));
status=true;
}
else if(attributes.drupal8 === false) {
// Call user/login end point to get CSR token an use in following calls
jQuery.ajax({
async: false,
url : restEndpoint + 'user/login' + Backbone.Drupal.restEndpoint.dataType,
type : 'post',
data : 'username=' + encodeURIComponent(username) + '&password=' + encodeURIComponent(password),
//dataType : 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
return false;
},
success : function(data) {

var settings = {
beforeSend: function (request) {
request.setRequestHeader("X-CSRF-Token", data.token);
}
};

settings.crossDomain = true;
}
if(attributes.crossDomain) {
settings.xhrFields = {
withCredentials: true
};

settings.crossDomain = true;
}

// Define specific parametres to be used in all future request.
$.ajaxSetup(settings);
// Define specific parametres to be used in all future request.
$.ajaxSetup(settings);

status=true;
}
});
status=true;
}
});
}

return status;
}.bind(this),
Expand All @@ -110,7 +137,6 @@ Backbone.Drupal.Auth = (function(Backbone, $, _){
return Auth;
})(Backbone, jQuery, _);


Backbone.Drupal.Models = {};


Expand Down Expand Up @@ -197,8 +223,14 @@ Backbone.Drupal.Models.Base = Backbone.Model.extend({
var base = restEndpoint + this.urlSource;

if (this.isNew()) { return base; }
// Add .json for format here.
return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.get(this.idAttribute)) + Backbone.Drupal.restEndpoint.dataType;
var url_endpoint = base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.get(this.idAttribute));

if(Backbone.Drupal.restEndpoint.drupal8 == false) {
// Add .json for format here.
url_endpoint = url_endpoint + urlBackbone.Drupal.restEndpoint.dataType;
}

return url_endpoint;
},

// TODO: evaluate moving all of this to Views.Base
Expand Down
4 changes: 2 additions & 2 deletions bower.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@
"backbone.drupal.js",
"backbone.drupal.services.js"
],
"version": "0.1.0-beta",
"version": "0.2.0-alpha",
"homepage": "http://enzolutions.com/projects/backbone_drupal/",
"author": {
"name": "enzo - Eduardo Garcia",
"email": "[email protected]"
},
"description": "Backbone.drupal extension provides Drupal compatible using Services module",
"description": "Backbone.drupal extension provides connection to Drupal 7/8",
"keywords": [
"backbone",
"marionette",
Expand Down
14 changes: 2 additions & 12 deletions test/index.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
Expand All @@ -14,8 +15,7 @@
$(function() {
// Set API Information
Backbone.Drupal.restEndpoint = {
root: 'http://onthisday/api',
dataType: '.json'
root: 'http://drupal8'
};
// Define auth object, set crossDomain if is necessary
var Auth = new Backbone.Drupal.Auth({crossDomain: true});
Expand All @@ -36,16 +36,6 @@
console.log(user.attributes.mail);
}
});
/*
Check users retrive
*/
var Users = new Backbone.Drupal.Collections.UserIndex();
Users.fetch({
success: function (users) {
// Check information retrived, could be used directly in a template
console.log(users.models[0].attributes.uri);
}
});
});

</script>
Expand Down
55 changes: 55 additions & 0 deletions test/indexd7.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Backbone Drupal Library</title>
</head>
<body>
<script src="./jquery.js"></script>
<script src="./underscore.js"></script>
<script src="./backbone.js"></script>
<script src="../backbone.drupal.js"></script>
<script src="../backbone.drupal.services.js"></script>
<script>
$(function() {
// Set API Information
Backbone.Drupal.restEndpoint = {
root: 'http://onthisday/api',
dataType: '.json'
};
// Define auth object, set crossDomain if is necessary
var Auth = new Backbone.Drupal.Auth({crossDomain: true, drupal8: false});
// Request executed in sync mode
// If status is token further ajax will use the proper token
var status = Auth.login('admin', 'admin');

console.log(status);

/*
Check user retrieve
*/

var User = new Backbone.Drupal.Models.User({uid: 1});
User.fetch({
success: function (user) {
// Check information retrived, could be used directly in a template
console.log(user.attributes.mail);
}
});
/*
Check users retrive
*/
var Users = new Backbone.Drupal.Collections.UserIndex();
Users.fetch({
success: function (users) {
// Check information retrived, could be used directly in a template
console.log(users.models[0].attributes.uri);
}
});
});

</script>

</body>
</html>
4 changes: 4 additions & 0 deletions test/jquery.js
Original file line number Diff line number Diff line change
Expand Up @@ -9656,13 +9656,17 @@ if ( xhrSupported ) {
// To keep consistent with other XHR implementations, cast the value
// to string and ignore `undefined`.
if ( headers[ i ] !== undefined ) {
//console.log(i);
//console.log(headers[ i ]);
xhr.setRequestHeader( i, headers[ i ] + "" );
}
}

// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
console.log(options);
console.log(options.hasContent && options.data);
xhr.send( ( options.hasContent && options.data ) || null );

// Listener
Expand Down

0 comments on commit fd392fc

Please sign in to comment.