Is it possible to grab the cookie from the view in AngularJS? - javascript

I was just wondering if it's possible, I was looking to grab the cookie to see if it's an admin user, and I'm not sure how to do that.

you can use $cookies for reading and writing into cookies...
example from angular docs
function ExampleController($cookies) {
// Retrieving a cookie
var favoriteCookie = $cookies.myFavorite;
// Setting a cookie
$cookies.myFavorite = 'oatmeal';
}
UPDATE
you should add angular-cookies.js script and inject ngCookies into you application module
angular.module('app', ['ngCookies']);

Related

How to Cache Angular scope

What is the best technique to cache Angular Scope from last browser session to a newly loaded one?
Is that possible?
Including to control the next time to create a cache of the complete scope?
And override the loaded cached scope, when new data is loaded from the back-end?
This is more related to how to cache data in the browser using javascript.
There are some solutions you can look into for angular specifically:
ngStorage: Local and session storage the angular way
angular-local-storage: Simple local storage with a cookies fallback
$cookies: Angular provided service wrapping cookies access
Angular services can be used to share the scope between routes within the same session. But if you close the browser, you'll need one of local/session storage, cookies, or a server-side solution.
$cookies
Cookies is a straightforward key-value storage. Easy to use for a quick way to save data.
angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
// Retrieving a cookie
var favoriteCookie = $cookies.get('myFavorite');
// Setting a cookie
$cookies.put('myFavorite', 'oatmeal');
}]);
Don't use cookies to store extensive data and limit this to data which should be sent on every request, like a authentication token.
ngStorage
An AngularJS module that makes Web Storage working in the Angular Way.
Contains two services: $localStorage and $sessionStorage.
bower install ngstorage
Pass $localStorage (or $sessionStorage) by reference to a hook
under $scope in plain ol' JavaScript:
$scope.$storage = $localStorage;
And use it like you-already-know:
<body ng-controller="Ctrl">
<button ng-click="$storage.counter = $storage.counter + 1">{{$storage.counter}}</button>
</body>
Optionally, specify default values using the $default() method:
$scope.$storage = $localStorage.$default({
counter: 42
});
With this setup, changes will be automatically sync'd between
$scope.$storage, $localStorage, and localStorage - even across
different browser tabs!
local storage demo
The angular-local-storage module provides multiple ways to store your data. It's feature rich and provides advanced options and customisation.
window.angular.module('demoModule', ['LocalStorageModule'])
.config(function(localStorageServiceProvider) {
localStorageServiceProvider.setPrefix('demoPrefix');
// localStorageServiceProvider.setStorageCookieDomain('example.com');
// localStorageServiceProvider.setStorageType('sessionStorage');
})
.controller('DemoCtrl',
function($scope, localStorageService) {
$scope.localStorageDemo = localStorageService.get('localStorageDemo');
$scope.$watch('localStorageDemo', function(value) {
localStorageService.set('localStorageDemo', value);
$scope.localStorageDemoValue = localStorageService.get('localStorageDemo');
});
$scope.storageType = 'Local storage';
if (localStorageService.getStorageType().indexOf('session') >= 0) {
$scope.storageType = 'Session storage';
}
if (!localStorageService.isSupported) {
$scope.storageType = 'Cookie';
}
$scope.$watch(function() {
return localStorageService.get('localStorageDemo');
}, function(value) {
$scope.localStorageDemo = value;
});
$scope.clearAll = localStorageService.clearAll;
}
);
Additional information
How to access cookies in AngularJS
How to set expiration date for cookie in AngularJS
How to persist data in AngularJS

Sails.js create Index(root) Controller

I was wondering if there is a way to have an index controller with an index action. my root is a login page and I wanted to detect if the users session is already authenticated and if so redirect them to another page.
Is there specific notation for how the controller is named? I have already tried IndexController.js and MainController.js. I can't seem to find anything in the documentation about this.
Sails.js Ver: 0.11.0
You need to make the controller and action yourself. From there, set up a Policy to define access.
To make the controller, run sails generate controller Index in console.
Then, open api/controllers/IndexController.js, make it look something like this:
module.exports = {
index: function (req, res) {
// add code to display logged in view
}
};
Set up config/routes.js to look like this:
module.exports.routes = {
'get /': 'IndexController.index',
};
Afterwards, define a policy which has your authentication logic. Alternatively, you can use the included session authentication located at api/policies/sessionAuth.js assuming that your login action sets req.session.authenticated = true;. See the docs on policies for more info.
Lastly, connect the policy to the action in config/policies.js:
module.exports.policies = {
IndexController: {
'*': false, // set as default for IndexController actions
index: 'sessionAuth' // or the name of your custom policy
}
}

Angularjs: maintain http body after redirect

Hi everybody and sorry for the English (if you found some mistakes),
I have the next question: I am in the page A and I call a web service that returns a JSON in the body, after this I redirect to another page B.
My question: after the redirection, body is kept ? In oder words, can I get or access to the body (if the body contains the JSON)?
Example
The web service:
app.service('LoginService', ['$http', function($http) {
this.retrieveUser = function(username, password) {
var url = app.baseURI + username+"/"+password;
return $http.get(url);
};
...
JS redirect
self.login = function(username, password){
LoginService.retrieveUser(username, password)
.success(function (data) {
if(data.usuario.rol == "G")
window.location.href="http://localhost:8080/Natureadventure/html/gerente/gestionarActividades.html";
}).error(function(data){
$scope.loginForm.password.$setValidity("password", false);
});
};
Thanks!
Angular is completely client-sided, so, aside from setting something in localStorage, cookies or sessionStorage, no, you will not be able to do this.
The way around it is to turn your Angular application into a single-page application; you never really change the page of the website as such, but Angular can emulate the changing of your web page (i.e the content and the layout) through a library like ui-router or ngRoute.
The downside to this is that if you are either stuck with ugly hashbang URLs or you enable html5Mode, which breaks if you refresh the page. The way to fix that is to either a) stick with hashbang URLs or b) make your server redirect any unknown request to your index.html and let angular do the routing for you.

The ui-router for angular seems to be cacheing the resolve. When I don't want it to

The Background:
I am using ui-router for my Angular page routing needs. It's working great so far, however I'm running into an issue. When I load a state and I resolve my user object. I use restangular to make the call to the database and it returns a promise. Everything works great. If I then log out, and log in as another user. Then navigate back to that same page it shows the previous user object.
Things that I've discovered:
The rest api call is being made every time when the state loads, and
it is the correct information.
If I place a break point inside my controller the user object that the resolve passes is the cached
information.
Theories:
The rest API end point is /users/me/, which is the same end point for
every user. We just deliver different information based off of the
JWT token we pass. Somewhere must things since it's the same call
don't bother delivering the goods it already got.
Things I've tried:
I've confirmed that the API call isn't cached, and it is delivering
the correct information to angular
I've tried grabbing the
$cacheFactory of $http and .removeAll.
Sample code:
angular.module('services.user', [ ])
.factory('User', function(Restangular) {
return Restangular.service('users');
});
angular.module('settings.profile', [
'ui.router',
'services.user'
])
.config(function($stateProvider){
$stateProvider
.state('settings.profile',{
url: '/profile',
templateUrl: 'app/settings/profile/settings.profile.html',
controller: 'SettingsProfileCtrl',
authenticate: true,
resolve: {
user: function(User) {
var user = User.one('me').get()
return user;
}
}
});
})
.controller('SettingsProfileCtrl',
function($scope, $location, user, $http, apiUrl){
$scope.user = user;
}
I had the same problem, however in my case the data requested in the resolve property wasn't coming from an API so HTTP caching definitely wasn't the problem.
I added {reload: true} for the options property in the troublesome $state.go call and this seems to have forced ui-router to refresh the resolve property. I no longer get the previous user's roles and permissions, which is nice :)
Your REST API parameter does not change i.e. it stays the same /users/me/ in all the requests. While the browser may not cache - which is why you see different correct information the cache.
You can try configuring Restangular to validate the theory by doing as below:-
RestangularProvider.setDefaultHttpFields({cache: true});
However I advise you to use URLs and REST API in the spirit of REST style i.e. use something like...
/users/me/username
where username changes based on the user OR if you have some constraints do the following
/users/me/?t=timestamp
Try adding cache: false to the state configuration object. But I also recommend adding a different parameter to the requests like userId for example.

AngularJS and REST resources naming wondering

So in my angular js app in service called 'authService' I have the following resources:
var userAreaLogin = $resource('/api/user_area/login');
var userAreaSignup = $resource('/api/user_area/signup');
var session = $resource('/api/user_area/getSession');
var userAreaLogout = $resource('/api/user_area/logout');
but this doesn't feel quite right, I'm using only the get methods, for example:
this.login = function(credentials) {
var user = userAreaLogin.get(credentials, function() {
...
});
};
this.signup = function(userInfo) {
var signup = userAreaSignup.get(userInfo, function() {
...
});
};
I'm confused about what resources to use, should I have something like this?
var session = $resource('/api/user/session');
var userArea = $resource('/api/user');
userArea.get(credentials); //should login the user?
userArea.post(credentials); //should signup the user?
session.delete(); //should logout the user?
session.get(); //should get the sessions of the logged user if any?
By REST sessions are maintained by the client and not by the service. You should use HTTPS and send the username and password with every request (for example with HTTP basic auth headers) instead of using session cookies... (stateless constraint)
Ofc. on the client side you can have login and logout which will change the content of the auth headers sent via AJAX.
You are going to the right direction.
In a well designed REST API you should have something like this.
POST /users/sign_in # Create a user session (signs in)
DELETE /users/sign_out # Delete a user session (signs out)
POST /users # Create a new user resource
GET /users/:id # Get the user resource
Based on these API you can then define your services. I also suggest to use $http which is cleaner, although you'll write few lines of code more.
# Session related methods
Session.create
Session.delete
# User related methods
User.create
User.get
Hope this makes things clearer.

Categories