signalpoint / angular-drupal Goto Github PK
View Code? Open in Web Editor NEWAn Angular JS module for Drupal.
License: GNU General Public License v2.0
An Angular JS module for Drupal.
License: GNU General Public License v2.0
Hello,
I'm trying to build a mobile app using angular-drupal. After configure everything, when I call the user_login() in my controller, it shows 'NOT A VALID USER!' message.
myApp.controller("TestController", ['$scope', '$http', 'shared', 'drupal', function ($scope, $http, shared, drupal) {
var qsStoreId = 1;
drupal.user_login('Admin', 'Admin@123').then(function(data) {
console.log(data);
if (data.user.uid) {
console.log('User exists!');
}
else {
console.log('NOT A VALID USER!');
}
});
}]);
In Firefox console, I can see three calls as follows (user/login.json, session/token and connect.json )
Call : POST http://mysite/?q=drupalgap/user/login.json
Response:
{
"sessid": "SZHvoUQY76BR0EphigNuROAhlSosveXyOW17bsUD2VE",
"session_name": "SESS31bd58610f7362c1ad5ccecaf06b294e",
"token": "7Wwtz-akDJoF-4bNBbW_4w1z1EljPVRYsyXw4dh0JAE",
"user": {
"uid": "1",
"name": "Admin",
...
}
}
When it gets the token it returns a new token.
http://mysite/?q=services/session/token
Response:
lxmxpeboGGyH3hc88zZ2uj4RNKRHbqhY_hMa8yfGxIw
When it calls 'connect', session_name is same but the sessid is different.
http://mysite/?q=drupalgap/system/connect.json
Response:
{
"sessid": "ei4lHs9z8_W5i4XypOgjPJLwph8Bx_Brvh8Odk_aUaA",
"session_name": "SESS31bd58610f7362c1ad5ccecaf06b294e",
"user": {
"uid": 0,
"hostname": "127.0.0.1",
"roles": { "1": "anonymous user" },
"cache": 0,
"timestamp": 1476790053
},
"remote_addr": "127.0.0.1",
...
}
Might be because of this reason, I'm not getting user login success message.
I'm using Drupal 7 as backend. Instead of 'drupalgap' service endpoint I tried with a service called 'api' as mentioned in the tutorial(https://www.npmjs.com/package/angular-drupal) but still shows 'NOT A VALID USER!' message.
How can I fix this issue?
I have installed drupalgap 2 in my drupal site and developed an ionic/angular based app to connect the web site. But something strange happened when I call user_login() in my angular.module().run() as following:
drupal.user_login('myaccount', 'mypassword').then(function (data) { if (data.user.uid) { alert('Hello ' + data.user.name + '!'); } else { alert('login failed.'); } });
The error message shows it is a 'Access-Control-Allow-Origin' problem since I sent the request from localhost:
XMLHttpRequest cannot load http://dev-tiyogo.pantheon.io/?q=drupalgap/system/connect.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 405.
However, the error was caused by system/connect but not by user/login. So I checked the network timeline and found that:
both /?q=drupalgap/user/login.json and /?q=services/session/token calls executed successfully but failed when it try to connect system(/?q=drupalgap/system/connect.json).
Any suggestions to solve the problem? By the way, I am very sure that the web services of system and user resources are all checked.
Rebuild angular-drupal.min.js
to match recent refactor.
The Services module now includes the new token in the result of a login call, so we don't need to manually grab the token after logging in any more.
When I try to login to the Drupal site the login is failing. Any help would be appreciated.
FYI: I added console.log statements in the user_login and connect functions. Here is the output:
user_login():
config: Object
data: Object
password: "test1234"
username: "testuser"
data: Object
sessid: "tfH2bdGIwCBD4ozoPaQn06mEanYZpD6rZfW8hTKPgT0"
session_name: "SESSbf88127597425f6389f62f338f0cc5d5"
token: "d23PmNvcjVkzioxspZLTBx2WNaju0wmTOl0d0oFYWfo"
user: Object
access: "0"
created: "1435764274"
data: false
language: ""
login: 1435764297
mail: "***@******.***"
name: "testuser"
picture: null
rdf_mapping: Object
roles: Object
2: "authenticated user"
__proto__: Object
signature: ""
signature_format: "filtered_html"
status: "1"
theme: ""
timezone: "America/New_York"
uid: "14"
connect():
config: Object
headers: Object
Accept: "application/json, text/plain, */*"
X-CSRF-Token: "d23PmNvcjVkzioxspZLTBx2WNaju0wmTOl0d0oFYWfo"
data: Object
sessid: "tfH2bdGIwCBD4ozoPaQn06mEanYZpD6rZfW8hTKPgT0"
session_name: "SESSbf88127597425f6389f62f338f0cc5d5"
user: Object
cache: 0
hostname: "::1"
roles: Object
1: "anonymous user"
__proto__: Object
timestamp: 1435764298
uid: 0
Drupal Module:
Services: 7.x-3.12
Hello,
Loving your module but i can't seem to get it to play nicely with my gulp file.
I am using ng-annotate but no success...
any advice for me please?
Update examples in README
to match recent refactor.
The README
instructs to install the angular_drupal
module, but I can't find it for D8. It's not listed on the project version control page, and drush
isn't finding it.
$ drush en angular_drupal
angular_drupal was not found. [warning]
No release history available for angular_drupal 8.x. [error]
$ drush dl angular_drupal
No release history available for angular_drupal 8.x. [error]
Could not download requested project(s).
Please advise on the steps to getting this working. Thanks!
As the title states the anonymous user is always returned when trying to log in.
angular.module('angular-drupal').config(function($provide) {
$provide.value('drupalSettings', {
sitePath: 'http://api.circuit-territory.vm'
});
});
drupal.userLogin('test', 'test!').then(function(data) {
console.log(data);
var user = drupal.currentUser();
var msg = user.isAuthenticated() ?
'Hello ' + user.getAccountName() : 'Hello Anonymous User';
console.log(msg);
});
You can see my drupal configuration here. I wanted to make sure that permissions weren't the issue so I opened them up.
Any help on the matter would be greatly appreciated.
@signalpoint Thank you for helping me solve the last problem. I have found the answer.
I have a new problem, when I create node with entity field always gave error, I think it should be the format problem.
var node = { type: 'article', title: 'Hello world', language: 'und', body: { und: [ { value: 'How are you?' }] } };
I change them to
var node = { type: 'article', title: 'Hello world', language: 'und', fiele_engtity: { und: [ { entity_id : *** }] } };
Pleas give me some tips. thank you very much.
Hopefully it will not take you too much time.
I've been looking at jDrupal 8.x-1.x, which appears much more full-featured & functional for interaction with D8 REST, and I've gotten a basic bridge working to turn jDrupal into an AngularJS service.
Am I correct in understanding that jDrupal has more support for D8 REST than angular-drupal does? Would you consider merging them (like, making angular-drupal a wrapper around jDrupal)? I would be glad to contribute what I've done so far on that front.
Hello, there are questions to ask you.
When I create a node using node_save, I want to change the created time. I use "created: 1322428031" to set the value of the created, but it does not work. How do I set it up?
Thank you.
Hi,
We were using the login web services via angular drupal and found that when using ios/safari users were not able to log in.
After a bit of research we found this issue on stack overflow:
https://stackoverflow.com/questions/34620703/error-syntaxerror-dom-exception-12-setrequestheadernative-code
Going through the code we isolated the problem to line 49 of aungular-drupal.js:
drupalToken = result.data;
The issue as described in the link to stack overflow above was resolved by changing the above code to:
drupalToken = result.data.trim(); // remove white space from beginning and end of token
Just thought we'd make you aware. This might be an issue better fixed in Drupal core (from the brief look we gave it -- sorry we had a deadline to hit -- it appears drupal_get_token is returning the token with a space tacked on to the front of it), but the fix above was a quick and easy win and we thought you guys would like to know.
Very good tools!
When I update user or node how to get success message and error message.I saw jDruapl api there are success message, but I could not read it. Please give me a help!
Thank you!
In drupal you can set the cookie domain in your settings.php.
Can you authenticate using that?
Very strange behavior.
jdrupal runs perfectly on iOS 10.3 but does nothing on iOS9.x
Problem with angular support by safari? I don't have debug tools for mac to investigate it properly, i just put alerts directly to jdrupal.js and none is called on an iphone running iOS9
I'm using node.js and browserSync to spin up a static server at localhost:3000 which runs my angular application. I then have a Drupal 8.3.3 site setup using MAMP at a vhost "example.com." I'm using the following call in my applications run function and it (Drupal) properly returns me the correct response.
Function call:
drupal.userLogin('username', 'password').then(function() {
alert('Logged in!');
alert(jDrupal.currentUser().id());
}, function() {
alert('Not logged in');
});
When I load my app I get an alert saying "Logged in!" and I see the response in chrome dev tools below:
{"current_user":{"uid":"1","roles":["authenticated"],"name":"username"},"csrf_token":"wtP7auf0MyDqoiR4j6htpGqSIfAYKgmnKVzZVD3kvDA","logout_token":"MSFu1mBZ7mFuy65pOauuA15FjFTqth8Q5QLEHjIMxjU"}
However, when I alert using this alert(jDrupal.currentUser().id());
I still get 0, or Anonymous user. Any ideas what could be causing this? Is it a CORS issue?
Further background: After looking at the code it looks like jDrupal calls jDrupal.connect() after the login, and the response from that is where I get the anonymous user.
Hello again,
When trying to edit any field on a user, i get a 403 forbidden on the PATCH to update that user, with the detailed error message:
{"error":"Access denied on updating field 'name'."}
Strange thing is, i'm not even updating/changing that field's value.
The code sample on which I get this error is the following:
var user = drupal.currentUser();
user.entity.field_hobbies[0].value = "Programming, cooking, sports,...";
user.save().then(function(){
console.log("user saved successfully");
});
My permissions in D8 are set up like this:
Am I missing something here? I have no idea why i get the error on the 'name' field, even when I try to update the user without even changing any fields.
When enabling Language module in Drupal 8.4.4 I get 403 PUT/PATCH error on user register/update
Hi Tyler, Grt Job with this module. I myself learned a lot. I was trying to node_index(query) from drupal when I discovered the code doesn't have sort & direction parameter in "drupal_entity_index_build_query_string()" if you can see that in 7.x version. Thanks. !!
Attached is a screenshot of Drupal Services Entity module with its additional parameters.
If you place "main" in the bower.js then you can use grunt and wiredep to auto add the js file to your index.
I am using yeoman and when installing this module using bower it never ends up saving the script with out it which makes it kind of a standalone js file which is not what I want.
i download module angular_drupal but this no content any service. is it in development?
I was attempting to load a menu entity. I get:
angular.js:13920 TypeError: this[this.ucfirst(...)] is not a constructor
at Object.jDrupal.entityLoad (http://localhost:9000/bower_components/jdrupal/jdrupal.js:452:16)
at menuLoad (http://localhost:9000/scripts/services/menu.js:14:21)
at new <anonymous> (http://localhost:9000/scripts/controllers/main-menu.js:18:24)
at Object.invoke (http://localhost:9000/bower_components/angular/angular.js:4718:19)
at $controllerInit (http://localhost:9000/bower_components/angular/angular.js:10354:34)
at nodeLinkFn (http://localhost:9000/bower_components/angular/angular.js:9263:34)
at compositeLinkFn (http://localhost:9000/bower_components/angular/angular.js:8620:13)
at publicLinkFn (http://localhost:9000/bower_components/angular/angular.js:8500:30)
at Object.link (http://localhost:9000/bower_components/angular/angular.js:26734:38)
at http://localhost:9000/bower_components/angular/angular.js:1247:18 <div ng-include="'views/main-menu.html'" class="ng-scope" data-ng-animate="1">
It looks like loading other entities besides comments users and nodes is not supported using the jDrupal api?
I am new to angularJS. I added code in angular-drupal.js (image of code attached
) to check username available to take or not. I am checking on blur of input field. It returns ok in my first call. As i blur again the same field it gives error "$q is not a function".
I am confused something wrong with my code ?
Not sure at this point what is going on. All my other app calls work but when I call logout there is no response.
Running D8. There is also some redirect action going on after the logout call. Which I think is because my "frontpage" is set to "user".
I'm encountering this strange issue on D8 when i try to authenticate a user via the following method:
drupal.user_login('bob', 'secret').then(function(data) {
//returned data here
});
I've enabled users as a REST resource like this:
I've also changed the permissions so that the "User" resource is available for anonymous users:
When I try to authenticate a user I get this in chrome console:
I've been able to fetch other data like nodes and views with angular-drupal on this installation of D8, but authentication is not working for me...
I've been banging my head on this for a while now, any suggestions on what I can try?
drupal.comment_save(comment).then(function (data) {
console.log('Created comment: ' + data.cid + data.nid);
});
where comment is:
var commment = {
nid: 12
//author: 'BOBBOOB',
subject: 'Songs About Animals',
comment_body: {
und: [{
value: 'ttttttttttt test'
}]
}
};
I get a messagew from drupal_angular noting the token is grabbed from memory.
I get POST http://data.songsaboutanimals.co.uk/?q=api/comment.json 500 (Internal Server Error : An error occurred (0): A nid must be provided) in the console.
Ive also tried altering the json to be 'nid' : '12' single quotes around everything, just single quotes around the values, the raw integer..
Happens logged in as administrator.
Anonymous users also have the post comment permission on.
using the basic get
drupal.comment_load(1).then(function (comment) {
console.log("Comment:");
console.dir(comment);
});
I get comment 1 back and structure of json is as expected, with an nid.
SO far in my application,
ive used the views_json get several times with success/
Request payload in network tab of console is {} no properties .... is this correct?
Hi
Does this keeps user info safe on page refresh?
This is quite interesting library I found Angular + Drupal. I am developing an app, will raise an issue here if I find anything buggy. Grt module. Thanks.
Hi @signalpoint,
I build a app with angular and ionic,I want to use cordova plugin to upload images to image field.Please give me some advice on how to implement this process. If you have the relevant demo code is better.
Thank you very much.
Really need help!
For all requests, using token, I get
example:
drupal.user_logout().then(function(data) {
if (!data.user.uid) {
alert('Logged out!');
}
});
return:
Error: drupal.token (...).then is not a function
Please HELP!
Hi,
I needed to use the 'attach files to node resource' targeted action provided by services but didn't find that capability in this module. I got something working & thought I'd share it.
Here's the code for the Angular Drupal module:
// Attach file(s) to node
this.file_attach = function(nid, data) {
var options = {
method: 'POST',
url: this.restPath + '/node/' + nid + '/attach_file',
transformRequest: angular.identity,
headers: {'Content-Type': undefined, 'Accept': 'application/json'},
data: data,
};
return this.token().then(function(token) {
options.headers['X-CSRF-Token'] = token;
return $http(options).then(function(result) {
if (result.status == 200) { return result.data; }
});
});
};
Setting Content-Type: undefined, & transformRequest: angular.identity are essential to making the browser send the data with the proper Content-Type: multipart/form-data & correct boundaries.
Since this targeted action (for some obscure reason) requires multipart/form-data Content-Type POSTs rather than a more REST API/Angular friendly JSON, it requires some fiddling. In my Angular controller I created a FormData() object that gets passed in above as the parameter 'data'. To wit:
$scope.sendFile = function(nid) {
var data = {
'files[anything1]': $scope.loadedImage,
'field_values[anything1][alt]': $scope.imageAlt,
'field_values[anything1][title]': $scope.imageAlt,
field_name: 'field_i4l_page_images',
};
var fd = new FormData();
angular.forEach(data, function(value, key) {
fd.append(key, value);
});
drupal.file_attach(nid, fd)
.catch(function(response) {
toaster.pop('error', 'Could not save the file.', response.statusText);
// Or some other error handling.
})
.then(function(data) {
console.log(data);
// Or some other cool action
});
}
According to comments in Services code: 'The name="files[anything]" format is required to use file_save_upload().'
In my example above, $scope.loadedImage is the ng-model set on my file element. According to this article, ng-model doesn’t work on inputs with type=“file”, so I used the custom directive described there to make it work:
.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
&
<input type="file" file-model="loadedImage"/>
Hope this helps, & feel free to include it in Angular Drupal! 🐫
Hi, I keep getting an authentication popup window, if user is already logged on or passing wrong user details.
If i click cancel i get: Failed to load resource: the server responded with a status of 401 (Unauthorized : CSRF validation failed)
If i click cancel on wrong credentials it console logs after i click cancel, meaning i can't show users its a wrong username or password.
My Drupal site is located in a subfolder, while the site is created with Angular as frontend.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.