How to change resource's headers in angularjs - javascript

I'm trying to set the headers of a resource (code bellow).
It happens that, when I instantiate my resource ($scope.user = new rsrUser;) angularjs fetches the cookies that aren't yet defined (an "undefined" error is fired from inside "getHMAC()"). The cookies will only be defined when "$scope.login()" is fired (it happens when the user clicks a button in the interface).
Is there a better way of doing this?
controllers.js
angularjsWebInterfaceControllers.controller('loginCtrl', ['$scope', 'rsrUser',
function($scope, rsrUser){
$cookieStore.put("username","therebedragons");
$cookieStore.put("password","therebedragons");
$scope.user = new rsrUser;
$scope.user.username = ""; //bound to input field in interface
$scope.user.password = ""; //bound to input field in interface
$scope.login = function() {
$cookieStore.put("username", $scope.user.username);
$cookieStore.put("password", $scope.user.password);
$cookieStore.put("state", "loggedOUT");
$scope.user.$logIn(
function(){
$cookieStore.put("state", "loggedIN");
}, function() {
$cookieStore.put("username","therebedragons");
$cookieStore.put("password","therebedragons");
$cookieStore.put("state", "loggedOUT");
}
)
};
}]);
services.js
angularjsWebInterfaceServices.service('rsrUser', [ '$resource', '$cookieStore',
function($resource, $cookieStore){
var req = "/login"
var timestamp = getMicrotime(true).toString();
var username = $cookieStore.get("username");
var key = $cookieStore.get("password");
return $resource(baseURL + req, {}, {
logIn: {method:'POST',
isArray:false,
headers:{
'X-MICROTIME': timestamp,
'X-USERNAME': username,
'X-HASH': getHMAC(username,timestamp,req,key)
}
}
});
}]);
EDIT: Actually, the cookies are defiend as soon as the controller is instantiated;

The value for a header can be a function that returns a string (see arguments here: http://docs.angularjs.org/api/ng/service/$http#usage). That way the cookie isn't accessed in your resource until the logIn method is called.
return $resource(baseURL + req, {}, {
logIn: {method:'POST',
isArray:false,
headers: {
'X-MICROTIME': timestamp,
'X-USERNAME': function() {
return $cookieStore.get("username");
},
'X-HASH': function() {
var username = $cookieStore.get("username");
return getHMAC(username,timestamp,req,key)
}
}
}
});

Related

JavaScript local storage value from Service to Controller in AngularJS

I am setting a local storage value in a AngularJS Service and trying to get the value in a AngularJS controller. But In the controller, getting null value instead of the value I have set in the service.
Here is the service where I have set the local storage value:
app.factory('accountService', ['$http', '$q', 'serviceBasePath', 'userService', '$window', function ($http, $q, serviceBasePath, userService, $window) {
var fac = {};
fac.login = function (user) {
var obj = { 'username': user.username, 'password': user.password, 'grant_type': 'password' };
Object.toparams = function ObjectsToParams(obj) {
var p = [];
for (var key in obj) {
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
}
var defer = $q.defer();
$http({
method: 'post',
url: serviceBasePath + "/token",
data: Object.toparams(obj),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function (response) {
userService.SetCurrentUser(response.data);
// The local storage value I have set
localStorage.setItem('IsAuthenticated', true);
localStorage.setItem('userName', response.username);
defer.resolve(response.data);
}, function (error) {
defer.reject(error.data);
})
return defer.promise;
}
fac.logout = function () {
userService.CurrentUser = null;
userService.SetCurrentUser(userService.CurrentUser);
}
return fac;
}])
Here is the controller where I am trying to get the previously set local storage value:
app.controller('indexController', ['$scope', 'accountService', '$location', '$window', function ($scope, accountService, $location, $window) {
$scope.message = localStorage.getItem("IsAuthenticated");
console.log($scope.message);
$scope.logout = function () {
accountService.logout();
$location.path('/login');
}
}])
Problem is I am getting null value instead of the value I have set in the service.
Any Help Please!
Best way to deal with browser storage using angular is:
1) Create a service that deals with localStorage, sessionStorage, cookie with generic methods that exposed through service.
2) This service will consumed by controller specific service, this service also handles keys that going to used to store in storage.
3) This service will expose more specific methods that consumed by controller.
eg:
UserController:
userService.setUserSession(session)
UserService:
var SESSION_KEY = 'userSession';
setUserSession() {
storageService.sessionStorageProvider.set(SESSION_KEY, session)
}
StorageService:
// here you need to create generic method using inheritance which will expose sessionStorage and loacalStorage and cookieStorage.
First try to get this in factory itself..after setting it...if you are able to get there then surely you will get in controller as well. Because local Storage nothing to relate with factory or controller.
Try like this , Use $window.
$window.localStorage.setItem('userName', response.username);
I believe you need to inject the dependency into your factory:
app.factory('accountService', ['$http', '$q', 'serviceBasePath', 'userService', '$window', '$localStorage', function ($http, $q, serviceBasePath, userService, $window, $localStorage) {
var fac = {};
fac.login = function (user) {
var obj = { 'username': user.username, 'password': user.password, 'grant_type': 'password' };
Object.toparams = function ObjectsToParams(obj) {
var p = [];
for (var key in obj) {
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
}
var defer = $q.defer();
$http({
method: 'post',
url: serviceBasePath + "/token",
data: Object.toparams(obj),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function (response) {
userService.SetCurrentUser(response.data);
// The local storage value I have set
$localStorage.IsAuthenticated = true;
$localStorage.userName = response.username;
//localStorage.setItem('IsAuthenticated', true);
//localStorage.setItem('userName', response.username);
defer.resolve(response.data);
}, function (error) {
defer.reject(error.data);
})
return defer.promise;
}
fac.logout = function () {
userService.CurrentUser = null;
userService.SetCurrentUser(userService.CurrentUser);
}
return fac;
}])

AngularJS - Checking if a user is authenticated and then routing them to the correct page

What I am looking to do I when a user comes to the index.html page I need the login module to do 2 things:
I need this to check if a user is authenticated ( which I think I already started with the "function authService" ) if the user has a valid token then change the ui-view to dashboard/dashboard.html and if the key is not valid or there is no key at all then load login/login.html into ui-view.
Once they have successfully logged in I want them to be routed to "dashboard/dashboard.html"
Here is my login script:
function authInterceptor(API) {
return {
request: function(config) {
if(config.url.indexOf(API) === 0) {
request.headers = request.headers || {};
request.headers['X-PCC-API-TOKEN'] = localStorage.getItem('token');
}
return config;
}
}
}
function authService(auth) {
var self = this;
self.isAuthed = function() {
localStorage.getItem('token');
}
}
function userService($http, API) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;';
$http.defaults.transformRequest = [function(data) {
return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
}];
var self = this;
self.login = function(username, pwd, ctrl) {
ctrl.requestdata = API + '/winauth' + '; with ' + username;
return $http.post(API + '/winauth', {
username: username,
pwd: pwd
})
};
var param = function(obj) {
var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
for(name in obj) {
value = obj[name];
if(value instanceof Array) {
for(i=0; i<value.length; ++i) {
subValue = value[i];
fullSubName = name + '[' + i + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if(value instanceof Object) {
for(subName in value) {
subValue = value[subName];
fullSubName = name + '[' + subName + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if(value !== undefined && value !== null)
query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
}
return query.length ? query.substr(0, query.length - 1) : query;
};
}
function LoginCtrl(user) {
var self = this;
function handleRequest(res) {
self.responsedata = res;
self.message = res.data.message;
var authToken = res.data.auth_token;
localStorage.setItem('token', authToken);
}
self.login = function() {
this.requestdata = 'Starting request...';
user.login(self.username, self.pwd, self)
.then(handleRequest, handleRequest)
}
}
// Login Module
var login = angular.module('login', ["ui.router"])
login.factory('authInterceptor', authInterceptor)
login.service('user', userService)
login.service('auth', authService)
login.constant('API', 'http://myserver.com/api')
EDIT - I added this into my login controller to provide the login routes
login.config(function($httpProvider, $stateProvider, $urlRouterProvider) {
$httpProvider.interceptors.push('authInterceptor');
$urlRouterProvider.otherwise('/login');
$stateProvider
// HOME STATES AND NESTED VIEWS ========================================
.state('login', {
url: '/login',
templateUrl: 'login/login.html',
controller: "mainLogin",
controllerAs: "log"
})
// nested list with just some random string data
.state('dashboard', {
url: '/dashboard',
templateUrl: 'dashboard/dashboard.html',
})
})
login.controller('mainLogin', LoginCtrl)
Here is my index.html:
EDIT - I removed "ng-include" and added "ng-view" to control the routes.
<body ng-app="login" ng-controller="mainLogin as log" class="loginPage">
<div class="main" ui-view></div>
</body>
As you can see I have a function that is checking for the token in the users local storage:
function authService(auth) {
var self = this;
self.isAuthed = function() {
localStorage.getItem('token');
}
}
And I am loading it in the module as a service:
login.service('auth', authService)
This is where I am stuck. I don't know where to go from here. I don't even know if I am using my authService function properly. I am still learning a lot about AngularJS so its easy for me to get stuck. :)
Another thing you will notice is in my index.html file I am just loading the "login/login.html" partial as default. I need it to load either login.html or dashboard.html depending if they are logged in or not. And then also route them to dashboard.html once they have successfully logged in.
The script works great as far as hitting the auth API, authenticating the user and then storing a valid auth key on their local storage.
Anyone know how I can accomplish this?
There are two separate concerns that you are dealing with. The first, is to be able to determine if you are logged in. Assuming the user needs to be logged in for any state except the login state, you would implement it like so by listening for $stateChangeState events and verifying that the user is logged in:
login.run(function($state, authService) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
var authToken = authService.isAuthed();
if (!authToken && toState !== 'login') {
//not logged in, so redirect to the login view instead of the view
//the user was attempting to load
event.preventDefault();
$state.go('login');
}
})
});
This will put them on the login state if they haven't already logged in.
The second part is to redirect to the correct view after they login, which you would do in your login controller:
function LoginCtrl(user, $state) {
var self = this;
function handleRequest(res) {
self.responsedata = res;
self.message = res.data.message;
var authToken = res.data.auth_token;
localStorage.setItem('token', authToken);
//after successful login, redirect to dashboard
$state.go('dashboard');
}
self.login = function() {
this.requestdata = 'Starting request...';
user.login(self.username, self.pwd, self)
.then(handleRequest, handleRequest)
}
}
ok I see you are using ui.router so let's work within this framework.
You want to
check if a user is logged in
redirect user to a view
What you're looking for is resolve:{loggedIn: checkLoggedInFn}
so your route for dashboard could be something like
.state('dashboard', {
url: '/dashboard',
templateUrl: 'dashboard/dashboard.html',
resolve: {
loggedIn: function(){
//do your checking here
}
}
})
what this does basically is that the controller will not instantiate until every resolve is resolved (so you can use a promise here for example), and then the value is passed into the controller as a parameter, so you could then do something like:
if(!loggedIn){
$state.go('login');
}
You would handle the logic inside your login controller specifically here:
self.login = function() {
this.requestdata = 'Starting request...';
user.login(self.username, self.pwd, self)
.then(handleRequest, handleRequest)
}
Inside the callback for the success on login, you would simple do a state change to send the user to the correct state.
In authInterceptor add code for response. So:
return {
request: function(config) {
if(config.url.indexOf(API) === 0) {
request.headers = request.headers || {};
request.headers['X-PCC-API-TOKEN'] = localStorage.getItem('token');
}
return config;
},
response: function(response) {
//ok response - code 200
return response;
},
responseError: function(response){
//wrong response - different response code
}
};
On server side check http header X-PCC-API-TOKEN and if is wrong ( no authentication) response should have different code like 403. So responseError method will run in interceptor.
responseError: function(response){
//wrong response - different response code
if (response.status === 403) {
alert("No rights to page");//your code for no auth
//redirect to different route
$injector.get('$state').transitionTo('login');//use injector service
return $q.reject(response);//return rejection - use $q
}
}
Your service is fine and it's on the loginModule but you are not using it anywhere where i can see. You need to inject your service into controller to do stuff you want. In your authService you are getting item from localstorage but you are not returning anything for example you have your login service
function authService(auth) {
var self = this;
self.isAuthed = function() {
return localStorage.getItem('token');
}
}
//here you can inject your auth service to get it work as you want
function LoginCtrl(user, auth) {
var self = this;
function handleRequest(res) {
self.responsedata = res;
self.message = res.data.message;
var authToken = res.data.auth_token;
localStorage.setItem('token', authToken);
}
self.login = function() {
this.requestdata = 'Starting request...';
user.login(self.username, self.pwd, self)
.then(handleRequest, handleRequest)
}
}
login.service('auth', authService)
function authService(auth) {
var self = this;
self.isAuthed = function() {
**localStorage.getItem('token');**
}
}
Where are you getting the localstorage item into? The LValue is missing.
At the most basic level, you could handle a check for this item - token - in the Dashboard page, at the time of loading the page and if it is null ie. empty, then redirect/route the user to the login page. Btw, use the sessionStorage rather than the localStorage as the former will flush as soon as the browser session is closed.
There are more elegant and simpler ways of accomplishing it like Passport. Have you checked it? It is as simple as this:
app.post('/login', passport.authenticate('local', { successRedirect: '/',
failureRedirect:'/login'}));
Your code isn't checking on url changes or affecting routes in a cross-cutting way.
Remember that authentication and authorization are cross-cutting concerns. That being said, Angular has a way for you to intercept routing calls by listening on $routeChangeStart. Your "interceptor" should be added there. You can then redirect the router to the required view by manually routing there. Have a look as the solution from a previous stack overflow thread.
There is a simple way you can achieve what you want for your application, using PassportJs.
The documentation is pretty simple and easy to implement.
You can also refer this tutorial to implement authentication using Passport. This tutorial teaches in very simple way, how to do authentication for your application.
Simple way to do that is just use https://github.com/Emallates/ng-enoa-auth package. You just need to include it in your app, nothing else.

Dynamic domain URL Rest factory AngularJS

I want change dynamic REST URL (for example if is stage or production) with a simple change in a server, but the URL don't change:
I have tried this:
.factory('Auth', ['$resource', 'Config', function($resource, Config) {
var URL = function(){
var random = Math.floor((Math.random() * 100) + 1);
window.localStorage.setItem("REST", "http://dynamic"+random+".com/");
return window.localStorage.getItem("REST");
}
return $resource(_url, {url:"url"}, {
login: { method:'POST', url: URL()},
})
}])
And this
// Generate random URL in the controller
.factory('Auth', ['$resource', 'Config', function($resource, Config) {
var URL = window.localStorage.getItem("REST");
return $resource(_url, {url:"url"}, {
login: { method:'POST', url: URL},
})
}])
But when I change the url ( I check this url in local storage and its change) the domain is the same anywhere unless that I reload the page, in this case works.
Thanks
You can do something like that:
Add a 2 new constant:
.constant('HOST_CDN', {
development: {
api: 'http://YOUR_LOCAL_DOMAIN',
},
production: {
api: 'http://YOUR_PRODUCTION_DOMAIN',
}
})
.constant('ENV', 'development')
Create new service:
var domain = null;
(function getDomains() {
domain = HOST_CDN[ENV];
if (!domain) {
throw 'Could not get domains';
}
domain.api = domain.api.concat('/')
.replace(/\/\/$/, '/');
})();
return {
api : domain.api
};

Parse/AngularJS - Input data with user id

I'm working on a Parse App with AngularJS, and reworking a controller to point to the logged in user when posting. On my database table, I've set a column "author" to point to the users. I made a separate service.js file which I call with Squeeg. When I click create, it does not input the data with the user.id. It works fine without it. How would I fix this to ensure that the user objectId is a part of the data is added to the database?
$scope.create=function(){
var user = Parse.User.current();
console.log(user.id);
Squeeg.create({ author:user.id, eventname:$scope.events.title, eventDescription:$scope.events.description}).success(function(data){
alert("done");
});
}
Since I need 50 reputation to comment, this needs to be asked here, have you accessed authfactory/authserverice to get the current user from there? Assuming you have login?
Then in authFactory you could have something like this.
app.factory('authFactory', ['$http', '$window', function ($http, $window) {
var authFactory = {};
authFactory.logIn = function (user) {
return $http.post('/login', user).success(function (data) {
authFactory.saveToken(data.token);
});
};
authFactory.saveToken = function (token) {
$window.localStorage['appToken'] = token;
};
authFactory.getToken = function () {
return $window.localStorage['appToken'];
};
authFactory.logOut = function () {
$window.localStorage.removeItem('appToken');
};
authFactory.currentUser = function () {
if(authFactory.isLoggedIn()){
var token = authFactory.getToken();
var payload = JSON.parse($window.atob(token.split('.')[1]));
return payload.username; // or return payload.id ..... / return payload
}
};
authFactory.isLoggedIn = function () {
var token = authFactory.getToken();
if(token){
var payload = JSON.parse($window.atob( token.split('.')[1]) );
return payload.exp > Date.now() / 1000;
} else {
return false;
}
};
return authFactory;
}]);
Then all you need to do is binding it with your controller to access it.
app.controller('AnyCtrl', ['$scope', 'authFactory',
function ($scope, authFactory) {
$scope.currentUser = authFactory.currentUser;
}
]);

AngularJS pass service variable to controller

I built a simple app with user authentication base on this: link
Basically, I have a userAccountService, responsible for communicating with server and login controller handling the login process.
From other controller I want to check if user is already logged in (to hide LogIn button, and show user profile instead).
So I have a navController
function navCtrl ($scope, $modal, userAccountService) {
$scope.IsUserLoggedIn = function () {
return userAccountService.isUserLoggedIn;
}
}
So in HTML I use this ng-hide="isUserLoggedIn()
my userAccountService:
app.factory('userAccountService', ['$http', '$q', userAccountService]);
function userAccountService($http, $q) {
var service = {
registerUser: registerUser,
loginUser: loginUser,
logOut: logOut,
getValues: getValues,
isUserLoggedIn: false,
accessToken: ""
};
// code ommited
function loginUser(userData) {
var tokenUrl = serverBaseUrl + "/Token";
if (!userData.grant_type) {
userData.grant_type = "password";
}
var deferred = $q.defer();
$http({
method: 'POST',
url: tokenUrl,
data: userData,
})
.success(function (data,status,headers,cfg) {
// save the access_token as this is required for each API call.
accessToken = data.access_token;
isUserLoggedIn = true;
// check the log screen to know currently back from the server when a user log in successfully.
console.log(data);
deferred.resolve(data);
})
.error(function (err, status) {
console.log(err);
deferred.reject(status);
});
return deferred.promise;
}
}
What am I doing wrong? Here's another interesting read I took inspiration from: link
You can't return a variable, but you can return a function, so create a function that returns that variable.
Try something like this, it returns your service object (you might want to put a $watch on it):
Service
function userAccountService($http, $q) {
function getData() {
return service;
}
...
}
Controller
$scope.IsUserLoggedIn = userAccountService.getData().isUserLoggedIn;
Also, you're not correctly updating the state variable from your success callback - you're creating global variables instead of using the service object properties. So, for example:
isUserLoggedIn = true;
should be:
service.isUserLoggedIn = true;

Categories

Resources