How do I connect to a Cloudant database through pure angularJS - angularjs

I've been using JSON strings to store my data and was thinking of moving to Cloudant. I've been searching long and hard for a tutorial or example code of this but one doesn't seem to exist (there are one with Node + Angular which uses the RESTAPI, but I'm a beginner in NodeJS and can't see a way to attach it to AngularJS)
I currently use this code to connect to my local.json file
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("data.json")
.success(function(response) {$scope.experience = response.experience;});
}
Can someone help me connect to a Cloudant database?

Based on your question found below links:
https://cloudant.com/blog/chaise-blog-building-a-diary-with-angular-js-grunt-js-and-cloudant/#.VjuuD6QT2ko this article has an example code on how to connect to cloudant by:
$http({
url: [root, post._id].join('/')
, method: 'PUT'
, data: post
})
.success(function(data, status){
post._rev = data.rev;
$timeout(_autosave, 5000);
})
Accessing the DB in Cloudant with Angular refers to a cloudant article which you can apply to angularjs https://cloudant.com/for-developers/crud/#browser-update

A few things you can try:
API Keys
https://docs.cloudant.com/authorization.html
After you've read up on Cloudant API Keys, try prepending your calls with one, like this:
https://<YOUR API KEY>:<YOUR API KEY PASSWORD>#<YOUR CLOUDANT USERNAME>.cloudant.com/<YOUR DATABASE NAME>
This will, obviously, not be good for the long term, b/c you'll have your creds in your client-side code, which anyone who views your Javascript can see.
You'll probably want to dig back into Node, to avoid this. Check out Cloudant's supported library for Node: https://github.com/cloudant/nodejs-cloudant
Enable CORS in Cloudant
https://docs.cloudant.com/cors.html
This will allow your client-side code running on, say, 127.0.0.1, to make Cloudant requests. (Make sure that everyone has _reader privileges.)
There are plenty of other things you can do, too, like creating proxies, but this should get you going.

I've figured it out, finally. No idea how or why there is no clear documentation on what header values are needed at the start, figured I'd share what I found:
You first have to enable CORS settings through the cloudant website-- (Users > Cors > Enable cors) and then set withCredentials to true in your http request.
The full code to connect is available here:
https://github.com/gweennnnn/cloudantangularconnect

Related

Parsing Oauth 2.0 return parameters in angular-ui-router

I'm attempting to authenticate a user using Google's Oauth 2.0 API. When my app HREF's to the Google authentication page, it successfully passes information back to my AngularJS app. However, I'm not sure how best to handle the returned URL-encoded data.
This is the format it is returned as:
#access_token=...
&token_type=Bearer
&expires_in=3600
My main problem is that this string begins with # instead of ? as is traditionally done with URL encoded parameters.
In my stateProvider config, I've implemented the callback state as such:
.state 'auth.googlecallback',
url: '/googlecallback/#{accessToken}&token_type={tokenType}&expires_in={expiresIn}'
templateUrl: 'views/auth/googlecallback.html'
controller: 'GoogleCallbackCtrl as gVm'
The above URL is an example of what I have tried. When the url is simply /googlecallback/, the page loads successfully, even when navigated to using the Google Oauth link. But the moment I had the # symbol, the state breaks and I can't parse the state params for the data inside.
I've looked into using the angular-oauth library on GitHub, but it hasn't been updated in 2 years, and it doesn't appear to allow Oauth authentication for more than just Google (I want to use Facebook and Google).
What is the correct way to handle the the Oauth URL data in angular-ui-router?
To be frank, I don't think this will actually answer your question, but I was helping some friends with this earlier today. They were unable to handle the URI via the ui-router. Instead, they had to delegate parsing the parameters and making the appropriate request to their view controller. Using the Angular $location service and some remapping functions, we were able to get the parameters out of the # query syntax into a hash that he was able to push back to the server in his request. The code looked similarly to the following:
var paramsArray = $location.hash().split('&')
var payload = {};
angular.forEach(paramsArray, function (param) {
var arr = param.split('='),
key = param[0],
value = param[1];
payload[key] = value;
});
This could absolutely be simplified but this was what he was trying to accomplish for his strategy.
That all being said, I'm personally not a fan of trying to accomplish OAuth strategy on the client. You have private keys that usually need to get exchanged to complete the full handshake. If possible, it would be best if you did the following:
Redirect the client to the appropriate OAuth path
Have the redirect go to a server endpoint that can process the oauth request and complete the handshake.
Have the server endpoint that the oauth request redirected to, redirect to your success landing page with any additional response
objects required by your application.
Doing this would protect your private keys and most web frameworks have modules/packages/gems/plugins/etc. for implementing oauth for all the mainstream providers. Hope this helps you in the right direction.

AngularJs + Django RESTful: session based authentication

I'm developing an angular web application that will replace the current website that we have. The current website uses session based authentication. At the moment, I can't access the hosted API with get or post requests.
I'm developing the angular application on my local computer using a python simple server, whereas the api is hosted online.
I would prefer to find a fix that's completely in angular since I can't change the API without help (it was written by my boss a while ago, and is now used in the production version). I don't have a login page so I'm just trying to provide the authentication information in my headers and requests.
My angular application was written independent of django. I just want to access the django backend
So far I'm trying the following to set the headers:
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$httpProvider.defaults.headers.common = {'username': btoa('myUsername'), 'password': btoa('myPassword')
};
}]);
And in my service:
app.factory('Test', ['$resource', function($resource) {
return $resource('https://www.phonywebsite.org/en/api/test/')
};
I consistently get 301, 400 and 403 errors. Lately it's been mostly 301 errors and I get no response from the api. I'm using the Allow CORS chrome extension as a temporary fix to try to get to the api without getting a CORS policy error.
My questions
How can I fix the CORS errors without using the chrome extension?
How do I provide my authentication to my django backend that uses session based authentication making sure the csrf cookie its looking for is in the header?
To answer your first question, using the cors extension is a temporary solution and should mostly never be used cause your clients might not use it. To handle CORS, you need to understand how cross site API calls work. In short CORS is a mechanism that allows AJAX requests to circumvent their same origin limits. To handle such situations you need to update your backend and add
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
. Once you add this your settings.py should stop getting CORS issues.
To answer your second question, angular already provides you with support for CSRF so half of your battle is already won. What you need to do is add a patch on your module to start accepting csrf tokens (The name is a bit different in angular). You have already done this and done a good job of it as well:
var app = angular.module('app', ['...']);
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}]);
What this would do is make sure that whenever you make a $http call your csrf token is set as well.
As a learning oppurtunity, you could also try using ng-cookies as well. To go further to explain this, whenever you make a call in angular , your request in bundled with cookies as well so you can easily access them in request.COOKIES.
You need to change how you are calling your API as well, something like:
app.factory('APIService', function ($http) {
return $http({url: 'https://www.phonywebsite.org/en/api/test/',
method: 'GET'})
}
You can obviously make modifications to this but I think this shows the $http usage to make you understand the general gist.
You can try to add some more authentication around your application here as well (or replace django auth with your own custom auth), but that is on your use case.
Hope this helps.

Which is the right method to handle oauth2.0 done in server using Ionic framework?

I am creating an Ionic app which has multiple 3rd party integration. I already have a java server which does the oauth2 authentication for the 3rd parties and redirect to the callback url in the server itself.
Now my task is to open back the app page after the server callback url is done.
I have tried the following method:
monitoring the url changes in app using ionic and redirect after the successful callback.
Which is the best way to handle this sitn.
Thanks.
Frankly, I haven't done anything like this. But to my mind, you can check ngcordova oauth implementation for ideas.
var browserRef = window.open(your_url);
browserRef.addEventListener("loadstart", function(event) {
//your code
});
browserRef.addEventListener('exit', function(event) {
deferred.reject("The sign in flow was canceled");
});
Check oauth.js source for more details.
Moreover, you can find the sample of using this implementation on this page.
http://mcgivery.com/using-custom-url-schemes-ionic-framework-app/
Above link may help you. If I am thinking correctly what you want?

Angular $resource.save() not working?

I am trying to create a web app with Angular, and I need some help. I need to POST data to an api. Rather than using $http (which works), I'd like to use $resource, and save().
I've also used GET and query so far, and they work fine. But when I try to call save(), I never get a response. I also don't see a POST request go through when I check on the server side.
Here's my code for the $resource factory (normally with my actual API url, of course)
.factory('ExamplePosts', function($resource) {
return {
all: $resource('http://my.website.com/api/')
};
});
In my controller, I can run ExamplePosts.all.query() or .get(), and retrieve the results. (I also see the request in my server logs.)
I then tried running ExamplePosts.all.save(), and I did not see a POST request on the server logs. I can post to it through forms and it works, but there seems to be a problem with Angular.
Appreciate any help I can get, thanks!
You actually need to add a prefix "$" to the save method as .$save() not .save() read this for more on those that need the $prefix read more

Accessing Session values in Angular.js

I am unable to access the session values which is set by node.js in Angular.js controller. I am using the Express framework. How to resolve it? Here is my code.
app.use(express.cookieParser());
app.use(express.session({
secret: '1234567890QWERTY',
cookie: { httpOnly: false }
}));
//setting the values
cookies.set('username',username);
req.session.username=username;
Presumably you want to do something like show the username in your angular app. As I mentioned in this answer, the hard part to Angular is not thinking about what data the server has, but thinking about data the server should provide to the browser via API.
My general model is to have the angular page start up without any data and have a low-level controller invoke a service (say AuthenticationService or IdentityService) that requests relevant data from the server, e.g. HTTP GET /api/identity. That will return a block of JSON that the page can then store in that low-level controller. Any deeper controller can then access the identity (or whatever) data loaded in that first request.

Resources