Query user roles in loopbacks angular sdk - javascript

I want to get all roles applied to one user using strongloops angular sdk.
I got it worked with the GET request /users/{id}/roles in my strongloop explorer and it works very well. But I can't figure out how to trigger this request in the angular SDK. I created the lb-services.js file and I it has a prototyped function what seems to intended for exactly this request.
"prototype$__get__roles": {
isArray: true,
url: urlBase + "/users/:id/roles",
method: "GET"
},
However I havn't found how to use this function in controller.
Update: it's working calling:
User.prototype$__get__roles({id:"1"});
but isn't it according to this supposed to called like getRoles() ?

Related

Confluence REST API request while not being admin ends in 401 error

I am developing confluence blueprint where a user can choose between jira projects and use them for specific jira issues report.
Both instances are connected correctly with each other and I get results but only if I am logged as an admin. With normal user I am getting this:
<status>
<status-code>401</status-code>
<message>This resource requires WebSudo.</message>
</status>
Unfortunately I have to get the information from the jira server as AJAX post request with JavaScript and here is my code:
function pickDate(e, state) {
AJS.$('#spLebenStart').datePicker({
overrideBrowserDefault: true
});
getJiraUrl();
}
function getJiraUrl(){
var appUrl = AJS.contextPath() + "/rest/applinks/1.0/applicationlink/type/jira";
$.ajax({
type: 'GET',
url: appUrl,
data: {
key: "value"
},
dataType: "xml",
success: function (xml){
jiraID = $(xml).find("id").text();
},
complete: function(){
getJiraProjects(jiraID);
},
error: function() {
alert("ERROR # getJiraUrl");
}
});
}
function getJiraProjects(applicationId){
var restUrl = AJS.contextPath() + "/rest/applinks/1.0/entities/"+applicationId+"?os_authType=any";
$.ajax({
type: 'GET',
url: restUrl,
data: {
key: "value"
},
dataType: "xml",
success: function (xml){
jiraProjectKeys = [];
$(xml).find("entity").each(function(){
jiraProjectKeys.push({id: $(this).attr("key"), text: $(this).attr("name")});
});
},
crossDomain: true,
xhrFields: {
withCredentials: true
},
error: function() {
alert("ERROR # getJiraProjects");
},
complete: function(){
AJS.$('#spSelect').auiSelect2({
placeholder: 'Projekt auswählen...',
data:jiraProjectKeys,
multiple: false
});
}
});
}
I have tried to use login information with basic authentication in AJAX but it didn't help. Of course I can hardcode the id in the code but what if it get changed? Its not the best solution imo. How can I manage the websudo problem?
I'm new here (as a contributor) so pardon my newbie bloopers.
Looks like accessing /rest/applinks/1.0/applicationlink/type/jira indeed requires admin permissions. But there's an undocumented (AFAIK) workaround and this is how I do it.
There's an Atlassian plugin called Confluence JIRA Plugin. It's bundled with Confluence (hence it should be available in your installation). It provides you with a few cool features allowing JIRA integration (e.g. JIRA and JIRA Chart macros). To provide the integration it also adds a few useful endpoints to your Confluence REST API (which don't require admin access):
/rest/jiraanywhere/1.0/servers or /rest/jira-integration/1.0/servers to list the linked JIRA servers (inlcuding applink id)
/jira-integration/1.0/servers/{INSERT APPLINK ID HERE}/projects to list JIRA projects available to the logged-in user
Now, per your requirements, I'd hit 1. to get the applink id and then 2. to get the list of the projects. Hope it works with your product versions.
BONUS - JIRA Proxy
Another nice endpoint is /plugins/servlet/applinks/proxy. It allows forwarding simple REST requests to the linked JIRA instances. For example /plugins/servlet/applinks/proxy?appId={INSERT APPLINK ID HERE}&path=%2Frest%2Fapi%2F2%2Fsearch will call JIRA's issue search REST endpoint and list issues available to the user (as in JIRA search). By "simple request" I mean that only GET and POST HTTP methods are supported in the current version (with POST limited to application/xml and multipart/form-data content types). The servlet supports both query-string and HTTP-header parameters. Check out the source of the servlet in plugin's source to get more info as I haven't found any online documentation for it.
Using this servlet you can get the projects list as well by requesting /plugins/servlet/applinks/proxy?appId={INSERT APPLINK ID HERE}&path=%2Frest%2Fapi%2F2%2Fproject
Servlets's path in the repo is confluence-jira-plugin/src/main/java/com/atlassian/confluence/plugins/jira/AppLinksProxyRequestServlet.java, but most of the important stuff is in its base class confluence-jira-plugin/src/main/java/com/atlassian/confluence/plugins/jira/AbstractProxyServlet.java

Failing to show an individual entry from an API in Angular

I'm building my first little AngularJS app.
I'm successfully able to show all entries from the API on the home page of the app.
Then I'm routing the user via ng-href to /jobs/{{job.id}} and have the appropriate controller to do that.
My console.log statement is telling me that the correct entry is being loaded via the GET request method but the template isn't actually pulling that back for display.
Here's the extent of what I have so far http://plnkr.co/QPW3lsLHfPxyYOKcVOKY (obviously my API isn't public) but wondering if there's something obvious I'm missing in my show template relating to the showController perhaps?
I've been working along with CodeSchool but I've had to make some mods to their code (for example the showController wasn't correctly defining $http or $routeParams).
Help appreciated.
So it seems there's an issue between the tutorial version of Angular 1.3.x and the one I'm using 1.4.x
However, using this works as sweet as a nut, passing $scope as a function parameter
angular.module('JobStore')
.controller('JobsShowController', function($http, $routeParams, $scope) {
$http({
method: 'GET',
url: '/jobs/' + $routeParams.id + '.json'
}).success(function(data) {
$scope.job = data;
console.log(data);
});
})

How to access HP ALM using REST and local javascript?

I just want to access ALM via local written javascript js in the browser (IE11, Firefox) via the REST API but I can not login. Here is my code for requesting the LWSSO cookie via jquery:
var auth = btoa(USER+":"+PASSWORD);
$.ajax({
type: "POST",
url: https://alm.xxx.net/qcbin/authentication-point/j_spring_security_check,
headers: {
"Authorization": "Basic " + auth
},
success : function(data) { },
});
The response header contains:
https://alm.xxx.net/qcbin/authentication-point/login.jsp;jsessionid=1gfsdk4pn525f1ur55e2x2zzte?login_error
With OTA/directX object everything works fine but I want to use the REST API via javascript. Can anyone help me?
First of all; which version of ALM are you using? Second, I think you are using the wrong URL for the authentication point. According to the documentation (for ALM 12.01) it should be https://alm.xxx.net/qcbin/authentication-point/authenticate.
Also, the HTTP method you use should be GET, not POST.
I noticed that you are using https in the URL, so I assume your instance of ALM is set up with that?

Creating a local .json file in Extjs

I want to create/save a .json file locally in Extjs with information from the DOM. Usually to POST, DELETE, GET or PUT .json query packets, the following method is used;
Ext.Ajax.request({
url: GlobalInfo.apiURL + 'api/grades/postsub',
method: 'POST',
params: {
SubjectName: newSubjectName,
SkillID: newSubjSkill
},
success: function(){
Ext.MessageBox.alert('Status', 'Success');
},
failure: function() {
Ext.Msg.alert('Status', 'You failed me! :o');
}
});
Is there a similar method I can use to create a local .json file on the hard drive of the user when they click a 'Save' button for example?
Create a store/model which uses a client proxy. Ext has a few built in client proxies.
Local storage
In memory
Session
If none of these work for your target browsers, then you will likely need to write your own.
The Sencha docs on proxies should help

Is there a Request.IsMvcAjaxRequest() equivalent for jQuery?

I prefer to use jQuery with my ASP.NET MVC apps than the Microsoft Ajax library. I have been adding a parameter called "mode" to my actions, which I set in my ajax calls. If it is provided, I return a JsonViewResult. If it isn't supplied, I assume it was a standard Http post and I return a ViewResult.
I'd like to be able to use something similar to the IsMvcAjaxRequest in my controllers when using jQuery so I could eliminate the extra parameter in my Actions.
Is there anything out there that would provide this capability within my controllers or some simple way to accomplish it? I don't want to go crazy writing code since adding a single parameter works, it just isn't ideal.
Here's an except from MVC RC1 release notes - Jan 2009
IsMvcAjaxRequest Renamed to IsAjaxRequest
The IsMvcAjaxRequest method been
renamed to IsAjaxRequest. As part of
this change, the IsAjaxRequest method
was updated to recognize the
X-Requested-With HTTP header. This is
a well known header sent by the major
JavaScript libraries such as
Prototype.js, jQuery, and Dojo.
The ASP.NET AJAX helpers were updated to send this header in
requests. However, they continue to
also send it in the body of the form
post in order to work around the issue
of firewalls that strip unknown
headers.
In other words - it was specifically renamed to be more 'compatible' with other libraries.
In addition, for anyone who hasnt read the full release notes but has been using previous versions - even as recent as the beta - I STRONGLY recommend you read them in full. It will save you time in future and most likely excite you with some of the new features. Its quite surprising how much new stuff is in there.
Important note: You will need to make sure you upgrade the .js file for MicrosoftAjax.MVC (not the exact name) if upgrading to RC1 from the Beta - otherwise this method won't work. It isn't listed in the release notes as a required task for upgrading so don't forget to.
See Simons answer below. The method I describe here is no longer needed in the latest version of ASP.NET MVC.
The way the IsMvcAjaxRequest extension method currently works is that it checks Request["__MVCASYNCPOST"] == "true", and it only works when the method is a HTTP POST request.
If you are making HTTP POST requests throug jQuery you could dynamically insert the __MVCASYNCPOST value into your request and then you could take advantage of the IsMvcAjaxRequest extension method.
Here is a link to the source of the IsMvcAjaxRequest extension method for your convenience.
Alternatively, you could create a clone of the IsMvcAjaxRequest extension method called
IsjQueryAjaxRequest that checks Request["__JQUERYASYNCPOST"] == "true" and you could dynamically insert that value into the HTTP POST.
Update
I decided to go ahead and give this a shot here is what I came up with.
Extension Method
public static class HttpRequestBaseExtensions
{
public static bool IsjQueryAjaxRequest(this HttpRequestBase request)
{
if (request == null)
throw new ArgumentNullException("request");
return request["__JQUERYASYNCPOST"] == "true";
}
}
Checking from an action if a method is a jQuery $.ajax() request:
if (Request.IsjQueryAjaxRequest())
//some code here
JavaScript
$('form input[type=submit]').click(function(evt) {
//intercept submit button and use AJAX instead
evt.preventDefault();
$.ajax(
{
type: "POST",
url: "<%= Url.Action("Create") %>",
dataType: "json",
data: { "__JQUERYASYNCPOST": "true" },
success: function(data) {alert(':)');},
error: function(res, textStatus, errorThrown) {alert(':(');}
}
);
});
Why don't you simply check the "X-Requested-With" HTTP header sent automatically by most Javascript libraries (like jQuery) ?
It has the value 'XMLHttpRequest' when a GET or POST request is sent.
In order to test it you should just need to check the "Request.Headers" NameValueCollection in your action, that is :
if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
return Json(...);
else
return View();
This way, you can simply differentiate regular browser requests from Ajax requests.
Ok, I have taken this one step farther and modified my jQuery file to load the additional parameter into the post data, so I don't have to repeat the "__JQUERYASYNCPOST: true" for every call to post. For anybody that's interested, here's what my new definition for $.post looks like:
post: function(url, data, callback, type) {
var postIdentifier = {};
if (jQuery.isFunction(data)) {
callback = data;
data = {};
}
else {
postIdentifier = { __JQUERYASYNCPOST: true };
jQuery.extend(data, postIdentifier);
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
}
I added the "postIdentifier" variable as well as the call to jQuery.extend. Now the Helper explained in spoon16's response works without having to add any thing special to my page-level jQuery code.

Categories