Authenticating and fetching data from couchdb using jQuery - javascript

I have a web app served by cherrypy. Within this app, I would like to fetch some data from a couchdb server, preferably using jquery. I am having trouble to authenticate into the server. When using:
$.couch.login({
name: 'usename',
password: 'password',
success: function() {
console.log('Ready!');
}
});
It sends the login request to the cherrypy server, not the couchdb. According to this, I can use jquery.ajax settings and therefore I have tried using:
$.couch.login({
url: 'http://127.0.0.1:5984',
name: 'usename',
password: 'password',
success: function() {
console.log('Ready!');
}
});
but it does not seem to work.
Any ideas? In addition, can anybody point me to good tutorial or simple web app developed in a similar fashion, i.e. a "standard" web page (not a couchapp), which contains jquery that gets info from couch.

What you are currently doing is telling jquery.couch.js to login against that url. (It needs to POST to /_session)
I believe you need to set up the urlPrefix property on $.couch.
$.couch.urlPrefix = "http://localhost:5984/"; // run this before anything else with $.couch

Don't forget that inside a browser, JavaScript enforces the same origin policy. Since the HTML page is presumably not being loaded from port 5984, you'll have figure out some clever way around it, such as CORS or mod_proxy.

Related

How to POST an issue stub on GitHub using the GitHub API using the logged in user, without authentification keys?

Users of my web application are expected to provide bug reports as a GitHub issue, with a pregenerated title and body.
This works perfectly fine using GET for small bodies:
const title = getLastErrorTitle();
const body = getAllTheLogMessages();
window.open(`https://github.com/theuser/therepo/issues/new?title=${encodeURIComponent(title)}&body=${encodeURIComponent(body)}`);
If the user is logged in, GitHub presents the user with a new issue with the title and body already filled out, perfect. If not, GitHub prompts the user to log in and it works the next time.
However, if the body is too large, the GET request fails because the URL becomes too long.
After consulting the manual I tried doing the same with POST but I get a 404 from GitHub with the following test request (jQuery for brevity):
$.ajax({
type: "POST",
url: "https://api.github.com/repos/theuser/therepo/issues",
data: data = {title: "Test", body: "Test Body"},
});
My suspicion is, that the GitHub API was not designed with my use case in mind, but that POST always requires authentication and creates the full issue in one go, without letting the user change it beforehand like it is possible with GET.
How can I transfer the functionality of the GET method over to the POST method? I just want GitHub to present the user, that is currently logged in inside the browser, with a prefilled issue, without needing a token.
You can't. Otherwise, it would be a major CSRF exploit.
However, you can use OAuth authentication that will allow your application to use some features : https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/
Or simply, redirect the user to a new issue page (for exemple with a simple HTML link <a>) with some automatic content, using this pattern :
https://github.com/{theUser}/{theRepo}/issues/new?body={theContentYouWhant}&title={theTitleYouWhant}
Example : https://github.com/CristalTeam/php-api-wrapper/issues/new?body=Hi,%20this%20is%20the%20body%20you%20want&title=Hello,%20this%20is%20a%20prefill%20issue
What I would suggest here is to generate a personal_auth_token at gihub and pass this token in the headers under Authorization field.
To generate personal_auth_token, login to github.com, go to settings -> developers settings -> Personal access tokens and generate one.
Pass this token in headers under Auhtorization: token. So in your AJAX request, it could look something like this:
$.ajax({
url: *yourUrl*
...
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', *token*));
},
});
One thing to note here is each of the developers POSTing to the repo will be requiring to generate their access token and you can't push this token on to a public Github repository because of obvious security breach. If you accidentally do so, the token is revoked immediately and you'll be required to create a new one.

React ES6 App - Local API calls

I can't for the life of me figure this out, it seems like it should be straight forward but it's just not clicking.
I have an ES6 app that I created using create-react-app. I've got all the templates and layouts set up for the project and came to trying to pull in data from an API that I want to sit inside the app - like a botched MVC where React handles the views and I run the models and controllers in PHP.
So I have a function in one of my components that I want to fetch some data. I use the fetch() function (I know this isn't yet compatible with a number of browsers but that's a problem for another day) to fetch a relative path from the component to the model I want to load, however the fetch function treats my path as a call to the base URL followed by the request. So with the site running on localhost:3000, I run the following code in my getData() function...
let test = fetch('../models/overall-stats.php').then(function(response) {
console.log(response);
return response;
});
...the URL that fetch hits is then http://localhost:3000/models/overall-stats.php which simply resolves back to the index.html file and loads the app, rather than the PHP file I'm requesting.
If I need to hit that PHP file to get my data, am I wrong in using fetch? Or am I just using it incorrectly? If I shouldn't be using fetch what's a better approach to this problem I'm having?
When I run this on an apache server (after building and deploying) I can get the fetches to work fine (apache recognizes the structure of the URL and hits it as I am expecting) and I hit the file no issues, but I need to be able to work in a local development environment and have the same functionality. The app will end up being deployed live on an apache server.
Any help would be greatly appreciated.
I knew after sleeping on this it would be very straight-forward... I simply had to move my models and controllers into the public directory for them to be accessible. I'll be putting in authentication to the models so that they can't be hit directly, but only through GET requests.
Why don't you just use something like ${baseUrl}/models/... ?
Also for solving browsers problem with fetch you can import the Polyfill or simply use axios (my choice)!
Maybe you can try to use ajax to get or post the data from server, just like this:
$.ajax({
url: '../models/overall-stats.php',
data: {
},
type: 'GET',
dataType : 'json',
success : function(res){
let obj = parseJSON(res)
}
})
or add this on top in your php file because the CORS :
header('Access-Control-Allow-Origin: *');

facebook graph api node.js invalid appsecret_proof

this is my first post so please go easy on me!
I am a beginning developer working with javascript and node.js. I am trying to make a basic request from a node js file to facebook's graph API. I have signed up for their developer service using my facebook account, and I have installed the node package for FB found here (https://www.npmjs.com/package/fb). It looks official enough.
Everything seems to be working, except I am getting a response to my GET request with a message saying my appsecret_proof is invalid.
Here is the code I am using (be advised the sensitive info is just keyboard mashing).
let https = require("https");
var FB = require('fb');
FB.options({
version: 'v2.11',
appId: 484592542348233,
appSecret: '389fa3ha3fukzf83a3r8a3f3aa3a3'
});
FB.setAccessToken('f8af89a3f98a3f89a3f87af8afnafmdasfasedfaskjefzev8zv9z390fz39fznabacbkcbalanaa3fla398fa3lfa3flka3flina3fk3anflka3fnalifn3laifnka3fnaelfafi3eifafnaifla3nfia3nfa3ifla');
console.log(FB.options());
FB.api('/me',
'GET',
{
"fields": "id,name"
},
function (res) {
if(!res || res.error) {
console.log(!res ? 'error occurred' : res.error);
return;
}
console.log(res);
console.log(res.id);
console.log(res.name);
}
);
The error I am getting reads:
{ message: 'Invalid appsecret_proof provided in the API argument',
type: 'GraphMethodException',
code: 100,
fbtrace_id: 'H3pDC0OPZdK' }
I have reset my appSecret and accessToken on the developer page and tried them immediately after resetting them. I get the same error, so I don't think that stale credentials are the issue. My
console.log(FB.options())
returns an appropriate looking object that also contains a long hash for appSecretProof as expected. I have also tried this code with a number of version numbers in the options (v2.4, v2.5, v2.11, and without any version key). Facebook's documentation on this strikes me as somewhat unclear. I think I should be using v2.5 of the SDK (which the node package is meant to mimic) and making requests to v2.11 of the graph API, but ??? In any case, that wouldn't seem to explain the issue I'm having. I get a perfectly good response that says my appSecretProof is invalid when I don't specify any version number at all.
The node package for fb should be generating this appSecretProof for me, and it looks like it is doing that. My other info and syntax all seem correct according to the package documentation. What am I missing here? Thank you all so much in advance.
looks like you have required the appsecret_proof for 2 factor authorization in the advance setting in your app.
Access tokens are portable. It's possible to take an access token generated on a client by Facebook's SDK, send it to a server and then make calls from that server on behalf of the client. An access token can also be stolen by malicious software on a person's computer or a man in the middle attack. Then that access token can be used from an entirely different system that's not the client and not your server, generating spam or stealing data.
You can prevent this by adding the appsecret_proof parameter to every API call from a server and enabling the setting to require proof on all calls. This prevents bad guys from making API calls with your access tokens from their servers. If you're using the official PHP SDK, the appsecret_proof parameter is automatically added.
Please refer the below url to generate the valid appsecret_proof,and add it to each api call
https://developers.facebook.com/docs/graph-api/securing-requests
I had to deal with the same issue while working with passport-facebook-token,
I finally released that the problem had nothing to have with the logic of my codebase or the app configuration.
I had this error just because I was adding intentionally an authorization Header to the request. so if you are using postman or some other http client just make sure that the request does not contain any authorization Header.

Html cloud storage?

I'm trying to make an app using phonegap, but what I want to know is if it is possible to store information online. For example, say there is a number variable, and it is added to when a button is pushed. Could that value be saved somewhere and then a totally different device can retrieve the variable?
I looked at databases, but I couldn't really understand it. I want something that can be accessed by any device as long as It has a key or something.
Is this possible? If so, how would I do it?
PhoneGap uses JS so you cannot connect to the database directly. You should create a Web service using server side languages like PHP on external server and make ajax request on your web service. This approach is possible using PhoneGap.
Sample Code will look somewhere near:
function FetchData() {
$.ajax({
async: false,
type: "GET",
url: "Your_WebService_URL",
dataType: "json",
success: function(data) {
$.each(data, function(i, object) {
if(i==="title"){
document.getElementById("title").InnerHTML = object;
}
if(i==="home_image"){
document.getElementById("title").InnerHTML = '<img src="'+object+'"/>';
}
});
},
error: function() {
alert("There was an error loading the feed");
}
});
The web service, in this case json will throw the variables. May me somewhere like this :
[{"title":"my application"},{"home_image":"http://link.com/image.png"}]
I think this article is useful to you: Loading external data into a PhoneGap app using the jQuery JSONP plugin for cross-domain access. Also see this similar question here:
This is entirely possible.
You essentially need two components: the client interface, and the server.
The client displays the results to the users, and, using your example, waits for a button to be pushed. On the push of that button, the client would send a request to the server to increment the stored value (possibly through a jQuery.post, or get, function call).
The server page, written in php for example, receives this request, and accesses a file, or more realistically a database, to increment the value.
With some Googling, this should be very doable, but post specific questions if you get stuck.

$ajax webservice failing on webfarm scenario

I am working on asp.net web form project.
In particular scenario I want to set some session values when user check/uncheck checkboxes in javascript.
In JavaScript session is not accessible so I developed a web service and gives call the web service method and that web method will going to set the values to session.
here is my js web service call.
$.ajax({
async: false,
url: baseUrl + '/' + "WebServices/ExtraInfoWebService.asmx/MyWebMethod",
data: { hdnValue: $("[id$='hdnCCSarray']").val() },
success: gett
});
This webservice call works perfectly on development machine having single IIS server but fails on production environment where multiple IIS boxes. I observed carefully and found that this webservice call is not working on IE browser only.
Anyone has suggestion on this please let me know.
Thanks in Advance!!!
If you are running in a Web Farm this means that you cannot use the default session store mode (InProc) because the different nodes of the farm will not be able to synchronize the session values. You will need to use an out-of-process session mode. There are 2 available:
StateServer
SQLServer
You can read more about the different session state modes in this MSDN article.
Or even better: refactor your code so that it doesn't rely on any session at all. I find it a very bad design to have a web service which is not stateless.

Categories