Setting and getting objects in cookies with Angular 1.2 - angularjs

I'm trying to set user properties in cookies. On login, the following code is run:
$scope.$parent.session.user = response.data.user;
// Get profile information
$http.get('api/v1/profiles/' + response.data.user.id)
.then(function(response){
$scope.$parent.session.user.profile = response.data;
});
// Set cookie data
console.log($scope.$parent.session.user);
$cookieStore.put('user', $scope.$parent.session.user);
The logged data includes the profile object, so I assume that this is placed into cookies too.
When the app is loaded, I look for cookies with:
if ($cookieStore.get('user')){
$scope.session.user = $cookieStore.get('user');
}
This returns just the user object, without the profile object. What am I doing wrong here?

It's weird that you say it is logged correctly, but it still looks like a synchronity issue. You should set the cookie in the body of the $http callback..
$http.get('api/v1/profiles/' + response.data.user.id)
.then(function(response){
$scope.$parent.session.user.profile = response.data;
$cookieStore.put('user', $scope.$parent.session.user);
});

Related

Unable to get a JSON response from my express router using node-Fetch module

So I'm making a post request to my Express search router where I'm using the node-fetch module to call a remote api:
var fetch = require('node-fetch');
router.route('/search')
//Performs Job Search
.post(function(req, res){
var area = req.body.area;
fetch('https://api.indeed.com/ads/apisearch?publisher=*********&l=' + area)
.then(function(res) {
return res.json();
}).then(function(json) {
console.log(json);
});
})
I'm using angular 1 on the client side to call the router and parse the returned json:
$scope.search = function(){
$http.post('/api/search', $scope.newSearch).success(function(data){
if(data.state == 'success'){
//perform JSON parsing here
}
else{
$scope.error_message = data.message;
}
});
}
I'm just starting out with the MEAN stack and only have a vague idea of how promises work. So my issue is that my angular search function is not getting the JSON string I want to return from my remote API call. But rather the data parameter is getting set to my page html. Eventually the breakpoints I've set in the .then() clauses are hit and my json is returned. So my question is how can I use Anguular to get the JSON values when they are finally returned????
Can you try something like this?
router.route('/search')
//Performs Job Search
.post(function(req, res){
var area = req.body.area;
fetch('https://api.indeed.com/ads/apisearch?publisher=*********&l=' + area)
.then(function(result) {
res.json(result);
//or possibly res.send(result), depending on what indeed responds with
})
})
Turns out I had forgotten that I had middleware in place where if the user was not authenticated when performing the search they were redirected to the login page. So I was getting a bunch of html returned for this login page, rather then my json. What still confuses me is why my breakpoints in search function were ever hit if I was being redirected before ever reaching this function.

How is client side authentication implemented in MEAN.JS?

Can someone tell how is authentication actually working in MEAN.JS [meanjs.org] here?
When the user logs in,where is the USER json object stored. The code is
// Authentication service for user variables
angular.module('users').factory('Authentication', [
function() {
var _this = this;
_this._data = {
user: window.user
};
return _this._data;
}
]);
//The implementation of the service in the controller
$scope.authentication=Authentication;
// If successful we assign the response to the global user model
$scope.authentication.user = response;
but in console window.user returns null
Another question, how the app retains the user JSON object when the page is refreshed? After the page is refreshed window.user returns the user JSON object, I don't see this object in the Local Storage or Session Storage, neither do i see any ajax being made to the server to fetch this object.
Thanks

Angular $cookieStore not retaining updated cookie on refresh

I'm having issues with $cookieStore retaining a cookie value after updating it. Here are two methods of a UserService that deals with the cookie:
var getCurrentUser = function () {
return $cookieStore.get('currentUser');
};
var updateCurrentUser = function () {
return $http.get(baseUrl + 'api/session').then(function (response) {
$cookieStore.put('currentUser', response.data);
$rootScope.$broadcast('currentUser', response.data);
}, function (response) {
$cookieStore.remove('currentUser');
$rootScope.$broadcast('currentUser', null);
});
};
Throughout my app, after an action is executed that would affect the current user's meta data, I call UserService.updateCurrentUser() which retrieves the latest user data from the server and updates that cookie. Then, in places that display the user data, I have the following code that will update the user model in that particular controller:
$scope.$on('currentUser', function (event, data) {
$scope.user = data;
});
As I step through the code, everything appears to be working correctly. After the $cookieStore.put('currentUser', response.data); line runs, the updated value can be confirmed by checking $cookieStore.get('currentUser'). When I check the actual cookie using a browser tool, however, the cookie value is not updated. I'm not sure if the browser tool requires a refresh to show the new data. But when I refresh the page, the updated cookie value is also no where to be seen. What is going on?
Thanks in advance.
Check out the documentation adding a cookie using $cookie service:
put(key, value, [options]);
The third argument allows additional options:
path (string)
domain (string)
expires (date)
secure (boolean)
You should set "expires" to define when the cookie should expire, otherwise the cookie will expire when you refresh or leave the site.
$cookies.put("id", 1, {
expires: new Date(2016, 1, 1)
});
Also the service is now called $cookies. Since Angular 1.4 you can now set expiry. Until then it wasn't possible.
http://docs.angularjs.org/api/ngCookies/service/$cookies

cookies does not work correctly in angularjs

I read a lot of articles but still can't make cookies work. I have a controller for login page, and this controller basicaly calls service that make a login. In service callback vunstion I set cookies:
$cookieStore.uid = response.ui;
$cookieStore.email = response.email;
$cookieStore.auth = response.cookie;
$location.path('/');
After that I make a redirect on my index view. In controller for index view, I try to check cookies in the cookie chacker service.
var email = $cookieStore.email;
var auth = $cookieStore.auth;
if (typeof email !== 'undefined' && typeof auth !== 'undefined') {
success("");
}
And this works only for the moment when I was redirected to the page from login. When I moved to different view or reload page my cookies lost.
Adding records to the cookiestore is like so.
$cookieStore.put("KEY", value);
And to retrieve:
$cookieStore.get("KEY");

$cookieStore.get() return undefined in angularjs

I'm writing a cookie from a server through the response and it's fine the problem is when I try to read the same cookie using angularJs $cookieStore.get() returns always 'undefined', I have debugged with the developer tools using chrome and the cookie is there,
console.log($cookieStore.get("r"));
the $cookieStore seems to be injected and running ok, I'm just wondering why angularJs can't read the cookie.
Edit:
I tried with $cookies service and I get undefined as well.
I send the cookie in the server side without any problem, I'm getting the cookie in chrome developer tools
I'm using Service Stack and the code is the following:
public override object Logout(IServiceBase service, ServiceStack.ServiceInterface.Auth.Auth request)
{
var resp = service.RequestContext.Get<IHttpResponse>();
resp.Cookies.AddCookie(new Cookie { Name = "r", Path = "/", Value = "from server", HttpOnly = false, Discard = false, Expires = DateTime.Now.AddHours(12) });
return base.Logout(service, request);
}
I think $cookieStore is only meant to be used by itself, was 'r' set somewhere else? The docs say it provides a key/value store backed by cookies, not direct access to cookies. When I set 'myValue' to 'jason' it stores %22jason%22 (fiddle). This means you can set values to javascript objects if you want and the cookieStore will serialize and deserialize them for you.
Try using $cookies instead where you can just set properties and the values aren't encoded (fiddle):
$scope.setValue = function() {
$cookieStore.put("myValue", $scope.value);
};
$scope.getValue = function() {
$scope.value = $cookieStore.get('myValue');
};
$scope.setCookieValue = function() {
$cookies.otherValue = $scope.value;
};
$scope.getCookieValue = function() {
$scope.value = $cookies.otherValue;
};
Yes #Pedro is right in .NET ,for example, when doing an authentication with HttpCookie by default the attribute HttpOnly is true and in javscript -> document.cookie cant find the cookie you just saved to the browser.
It worked for me by setting to false HttpOnly when saving the cookie.

Resources