Duplicate requests - angularjs

I am new to Ionic and angularjs. Getting duplicate Http requests for the controllers and services having http request. The following is one of the service I have created using ionic. I am not getting what's causing duplicate request in my code. This is only happening to the tabs with http requests.
login.html
<ion-view view-title="Login" name="login-view">
<ion-content>
<img src="img/epass.png" class="center" style="width: 20em; height: 18em">
<div class="list list-inset">
<label class="item item-input">
<input type="text" placeholder="Username" ng-model="data.username">
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="data.password">
</label>
<button class="button button-block button-calm" ng-click="login()">Login</button>
</div>
</ion-content>
</ion-view>
app.js
angular.module('starter', ['ionic','ngCordova', 'starter.controllers', 'starter.services'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
// Ionic uses AngularUI Router which uses the concept of states
// Learn more here: https://github.com/angular-ui/ui-router
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider
.state('splash', {
url: '/splash',
templateUrl: 'templates/splash.html'
})
// setup an abstract state for the tabs directive
.state('tab', {
url: '/tab',
abstract: true,
templateUrl: 'templates/tabs.html'
})
//Login functionality
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
})
});
contoller
.controller('LoginCtrl', function($scope, User, LoginService, $ionicPopup, $state) {
$scope.data = {};
$scope.login = function() {
LoginService.loginUser($scope)
.success(function(data) {
//TODO What is in the data object?
console.log('response.data.token_id in controllers:'+LoginService.res);
console.log('login success. ' + $scope.data.token );
console.log('$scope.data.username: '+$scope.data.username);
User.cwusername=$scope.data.username;
User.updateToken($scope.data.token);
var token=$scope.data.token;
//User.update(data);
$state.go('tab.dash');
})
.error(function(data) {
const alertPopup = $ionicPopup.alert({
title: 'Login failed!',
template: 'Please check your credentials!'
});
});
}
})
service
.factory('User', function(){
var user ={};
var token = 0;
var updateToken = function(id) {
this.token = id;
};
var getToken = function() {
return token;
};
return {
loggedIn: function() {
return user;
},
updateToken: updateToken,
update: function(user) {
this.user = user;
},
getToken: getToken
};
})
.service('LoginService', function($q, $http) {
var url = 'hardcoded url';
var id = 0;
return {
loginUser: function($scope) {
var deferred = $q.defer();
var promise = deferred.promise;
console.log('scope data.username=' + $scope.data.username );
console.log('scope data.password=' + $scope.data.password );
var dataobj = {'username': $scope.data.username, 'login_pwd': $scope.data.password};
var restRespond = "";
console.log('calling for json');
var res = $http.get(url + '/' + $scope.data.username + '/' + $scope.data.password)
.then(function(response) {
console.log('response.data.id in service:'+response.data.id);
id = response.data.id;
restRespond = response.data.response_msg;
console.log(restRespond);
if (id != 0) {
$scope.data.token = id;
console.log('Welcome ' + name + '!');
deferred.resolve('Welcome ' + name + '!');
} else {
console.log('Wrong credentials.' + id);
deferred.reject('Wrong credentials.' + id);
}
});
promise.success = function(fn) {
promise.then(fn);
return promise;
}
promise.error = function(fn) {
promise.then(null, fn);
return promise;
}
return promise;
},
loginToken: function() {
return id;
}
}
})

Related

$scope variable is not getting updated on view which rendered using $state

Below is app.js file contain myApp module. I am facing issue with $scope variable not updated on view file which is rendered using $state.
I am calling showArticles function on ng-change event from one of view file which got rendered using $state.go statement. This view rendered after user login. All code snap given below. Also facing same issue after AJAX success response $scope not getting updated on view file.
var myApp = angular.module('myApp', ['ui.router']);
myApp.config(function($stateProvider, $urlRouterProvider){
$stateProvider.state('settings', {
url: '/settings',
templateUrl: 'templates/setting.html',
controller: 'adminCtrl',
})
.state('profile', {
url: '/profile',
templateUrl: 'templates/profile.html',
controller: 'adminCtrl',
})
.state('account', {
url: '/account',
templateUrl: 'templates/account.html',
controller: 'adminCtrl',
cache: false
})
.state('articleList', {
url: '/articles',
controller: 'adminCtrl',
cache: false,
templateUrl: 'templates/articleList.html',
})
.state('addArticle', {
url:'/addArticle',
templateUrl : 'templates/addArticle',
controller: 'adminCtrl',
cache: false
})
$urlRouterProvider.otherwise('/settings');
});
myApp.run(function($rootScope, $state, $location, AuthenticationService){
//array of route that dont need authentication
var routeThatDontNeedAuth = ['/settings'];
var routeClean = function(route)
{
//alert(route); alert();
if(routeThatDontNeedAuth.indexOf(route) !== -1){ alert('aaa');
return false;
}
else{
return true;
}
}
$rootScope.$on('$stateChangeStart', function(event, next, current){
if(routeThatDontNeedAuth.indexOf($location.url()) < 0)
{
if(!AuthenticationService.isLoggedIn()){
//$state.go('settings');
//alert('not logged in and page is not login page');
}
}
});
});
myApp.factory('AuthenticationService', ['$http', '$state', function($http, $state){
return{
isLoggedIn: function(){ alert('Aut ser called');
$http({
url: 'http://127.0.0.1:8081/cUlI',
method: 'GET'
}).then(function(response){
alert('testtt');console.log(response);
if(!response.data.loggedIn)
{
$state.go('settings');
}
})
}
};
}]);
myApp.controller('adminCtrl', ['$scope', '$http', '$state', 'getArticleData', function($scope, $http, $state, getArticleData){
$scope.addArticle = function(){
$state.go('addArticle');
}
// get website list
$scope.showArticles = function(){
/*$scope.articleList = 'this is default article scope value';
alert($scope.articleList)
$scope.$applyAsync(function() {
$scope.articleList = "Another value rest"; alert($scope.articleList)
});*/
$http({
method: "GET",
url: "http://127.0.0.1:8081/articleList",
params: {
website:$scope.website
}
}).then(function(responseData){
if(responseData.data.status == 'success')
{
console.log('test dataaa');
console.log(responseData);
alert('page should modified')
alert('This is test');
$scope.articleList = {id:'test', name: 'article list'};//responseData.data.data;
$scope.artLs = "I am testt model";
$state.go('articleList', 'cache: false');
}
})
}
$scope.adminLogin = function(){
var uname = $scope.username;
var pass = $scope.password ;
alert(uname+'--'+pass);
$http({
method : "GET",
url : "http://127.0.0.1:8081/adminLogin",
params: {
username : uname,
pwd: pass
}
}).then(function(response) {
console.log('succes',response);
if(response.data.status == 'success')
{
$http({
method: "GET",
url: "http://127.0.0.1:8081/webSiteList"
}).then(function(responseData){
if(responseData.data.status == 'success')
{
$scope.sara = 'testsara';
$scope.websiteData = {id : 'a', name: 'test'}; // responseData.data.data;
console.log('scope website data', $scope.websiteData);
$state.go('account', 'cache: false');
}
});
}
else
{
}
}, function(response) {
console.log('error',response)
});
}
}]);
showArticles functions get called on ng-change event from account view:
<div id="main-container" class="col-md-12 container" >
<div class="col-md-1"></div>
<div class="col-md-10">
<div class="main-body">
<div class="content">
<div class="col-md-2"></div>
<div class="col-md-8">
<h2 class="text-center">Article Listing page modified</h2>
<div class="vt-add-article">
<button type="button" ="btn btn-default text-center" ng-click="addArticle();">Add</button>
</div>
<div class="vt-article-list">
{{articleList}}
<br>
{{artLs}} -- exp value
</div>
</div>
<div class="col-md-2"></div>
</div>
</div>
</div>
<div class="col-md-1"></div>
</div>
Main Index .html file :
<html>
<head>
<meta charset="utf-8">
<title>Welcome to Vidarbha Tigers Content Panel</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="/angularp/router/css/admin.css" />
<script src="/angularp/router/js/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script src="/angularp/router/js/app.js"></script>
</head>
<body ng-app="myApp" ng-controller="adminCtrl">
<header>
<div class="col-md-12">
<div class="col-md-1"></div>
<div class="vt-header-content col-md-10">
<div class="vt-header-logo">
<!--<img src="/images/logo.jpg" class="img-rounded" alt="Vidarbha Tiger"> -->
</div>
<div class="vt-header-tag"><h2><!--Vidarbha Tigers--></h2></div>
</div>
<div class="col-md-1"></div>
</div>
<hr/>
</header>
<div ui-view></div>
</body>
</body>
</html>
Kindly let me know if I am missing anything in my code. I am new to angular js and facing few issues which are unknown to me
ok, I understand your issue. Your $scope variable is getting reset everytime you call a view. Hence, you dont see any value. You will have to save the value and then retrieve it when your view gets loaded. I have updated your code below, try and let me know if it works or not
SOLUTION 1:
Create one more factory:
myApp.factory('persistService', ['$rootScope', function($rootScope){
var articleList = '';
return{
saveArticleList: function(data) {
articleList = data;
},
getArticleList: function() {
return articleList;
}
};
}]);
Then in your controller include the above service and save the articleList and when you go to your new view, intialize your articleList using the 'persistService' as below :
myApp.controller('adminCtrl', ['$scope', '$http', '$state', 'persistService', 'getArticleData', function($scope, $http, $state, getArticleData, persistService){
//Initialize your articleList
$scope.articleList = persistService.getArticleList();
$scope.addArticle = function(){
$state.go('addArticle');
}
// get website list
$scope.showArticles = function(){
/*$scope.articleList = 'this is default article scope value';
alert($scope.articleList)
$scope.$applyAsync(function() {
$scope.articleList = "Another value rest"; alert($scope.articleList)
});*/
$http({
method: "GET",
url: "http://127.0.0.1:8081/articleList",
params: {
website:$scope.website
}
}).then(function(responseData){
if(responseData.data.status == 'success')
{
console.log('test dataaa');
console.log(responseData);
alert('page should modified')
alert('This is test');
//Save your data
persistService.setArticleList('This is a test');
//$scope.articleList = {id:'test', name: 'article list'};//responseData.data.data;
$scope.artLs = "I am testt model";
$state.go('articleList', 'cache: false');
}
})
}
$scope.adminLogin = function(){
var uname = $scope.username;
var pass = $scope.password ;
alert(uname+'--'+pass);
$http({
method : "GET",
url : "http://127.0.0.1:8081/adminLogin",
params: {
username : uname,
pwd: pass
}
}).then(function(response) {
console.log('succes',response);
if(response.data.status == 'success')
{
$http({
method: "GET",
url: "http://127.0.0.1:8081/webSiteList"
}).then(function(responseData){
if(responseData.data.status == 'success')
{
$scope.sara = 'testsara';
$scope.websiteData = {id : 'a', name: 'test'}; // responseData.data.data;
console.log('scope website data', $scope.websiteData);
$state.go('account', 'cache: false');
}
});
}
else
{
}
}, function(response) {
console.log('error',response)
});
}
}]);
Let me know if this helps!
EDIT::
SOLUTION 2:
There is another way you can accomplish the same just by making a change in your controller code. See below code:
myApp.controller('adminCtrl', ['$scope', '$http', '$state', 'getArticleData', function($scope, $http, $state, getArticleData){
//Initialize your articleList
$scope.articleList = $scope.articleList || {};
$scope.addArticle = function(){
$state.go('addArticle');
}
// get website list
$scope.showArticles = function(){
/*$scope.articleList = 'this is default article scope value';
alert($scope.articleList)
$scope.$applyAsync(function() {
$scope.articleList = "Another value rest"; alert($scope.articleList)
});*/
$http({
method: "GET",
url: "http://127.0.0.1:8081/articleList",
params: {
website:$scope.website
}
}).then(function(responseData){
if(responseData.data.status == 'success')
{
console.log('test dataaa');
console.log(responseData);
alert('page should modified')
alert('This is test');
//Save your data
$scope.articleList = {id:'test', name: 'article list'};//responseData.data.data;
$scope.artLs = "I am testt model";
$state.go('articleList', 'cache: false');
}
})
}
$scope.adminLogin = function(){
var uname = $scope.username;
var pass = $scope.password ;
alert(uname+'--'+pass);
$http({
method : "GET",
url : "http://127.0.0.1:8081/adminLogin",
params: {
username : uname,
pwd: pass
}
}).then(function(response) {
console.log('succes',response);
if(response.data.status == 'success')
{
$http({
method: "GET",
url: "http://127.0.0.1:8081/webSiteList"
}).then(function(responseData){
if(responseData.data.status == 'success')
{
$scope.sara = 'testsara';
$scope.websiteData = {id : 'a', name: 'test'}; // responseData.data.data;
console.log('scope website data', $scope.websiteData);
$state.go('account', 'cache: false');
}
});
}
else
{
}
}, function(response) {
console.log('error',response)
});
}
}]);
is the alert that you have put printing the correct value?
Based on my understanding I think you set the articleList on ng-change called in one view file. After that you change state and go to another view file where you expect to see the updated articleList value which you set in the previous view. But, I think what may be happening is that when you navigate to the second view your controller might be getting reloaded and your $scope.articleList gets reset. Try printing the value of articleList before and after you change view.
To prevent this you can try using angular services to save the articleList value

How to use $q service in angular js for login?

I am new in angular js. i have making ionic app useing angular js and ionic framework,
This is my service.js file.
In this i have create LoginService for Login control. but its not working.
angular.module('starter.services', ['ngCookies'])
.service('LoginService', function ($q, $http, $cookies, $rootScope) {
return {
loginUser: function (name, pw) {
var deferred = $q.defer();
var promise = deferred.promise;
var user_data = $http.get("http://vanhalterenwatersport.nl/van/webservice/appc/login.php");
user_data.then(function (result) {
var user = result.data;
log(user);
console.log($rootScope.session);
})
function log(user) {
var i;
var isloggedin = false;
for (i = 0; i < user.length; i++) {
if (name == user[i].user_email && pw == user[i].password) {
isloggedin = true;
id = user[i].iduser;
$rootScope.session = id;
break;
}
}
if (isloggedin) {
deferred.resolve('Welcome ' + name + '!');
} else {
deferred.reject('Wrong credentials.');
}
}
promise.success = function (fn) {
promise.then(fn);
return promise;
}
promise.error = function (fn) {
promise.then(null, fn);
return promise;
}
return promise;
}
}
})
This is my controllers.js file
angular.module('starter.controllers', ['ngRoute','ngCookies'])
.controller('AppCtrl', function($scope, $ionicModal, $timeout) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//$scope.$on('$ionicView.enter', function(e) {
//});
})
.controller('LoginCtrl', function($scope, LoginService, $ionicPopup, $state, $cookies, $rootScope) {
$scope.data = {};
$scope.create = function () {
$state.go('signup');
}
$scope.forgot = function () {
$state.go('forgotpassword');
}
$scope.login = function () {
console.log($scope.data.user_email);
LoginService.loginUser($scope.data.user_email, $scope.data.password).success(function (data) {
var wat = $rootScope.session;
console.log(wat);
$state.go('app.dashboard');
}).error(function (data) {
var alertPopup = $ionicPopup.alert({
title: 'Login failed!',
template: 'Please check your credentials!'
});
});
}
})
This is my login.html
<ion-view view-title="Login" hide-nav-bar="true" name="login-view">
<ion-content ng-controller="LoginCtrl">
<div class="bar-header padding">
<h1 class="title vanimage"><img src='img/logo.png'></h1>
</div>
<div class="list">
<label class="item item-input">
<span class="input-label">Username</span>
<input type="text" name="username" ng-model="data.user_email">
</label>
<label class="item item-input">
<span class="input-label">Password</span>
<input type="password" name="password" ng-model="data.password">
</label>
<label class="item">
<button class="button button-block button-positive" ng-click="login()">Log in</button>
</label>
</div>
<div class="padding">
<button class="button button-block button-positive" ng-click="create()">Registeer hier</button>
<button class="button button-block button-positive" ng-click="forgot()">Password Vergeten?</button>
</div>
</ion-content>
</ion-view>
You should put the auth logic in the backend, more secure and efficent.
This is the code I use for login in a service of a Ionic app:
login: function( loginEmail, loginPassword ) {
var deferred = $q.defer();
$http({
method: 'POST',
url: backend_url + '/auth',
// --- change content-type if needed (default = application/json)
// headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: { email: loginEmail, password: loginPassword }
}).then( function( result ) {
if( typeof result.data.token !== 'undefined' ) deferred.resolve( { token: result.data.token } );
else deferred.reject( { error: 'invalid_response' } );
}, function( result ) {
if( typeof result.data.error !== 'undefined' ) deferred.reject( { error: result.data.error, status: result.status } );
else deferred.reject( { error: 'invalid_login' } );
});
return deferred.promise;
},
$http always return a promice, so if you want to do it correctly in your service, using $q try smth like this:
var fn = function (method, url) {
var deferred = $q.defer();
$http(method, url)
.success(function (data) {
deferred.resolve(data);
}
.error(function (data, status) {
deferred.reject({
data: data,
status: status
});
});
return deferred.promise;
}
And if you want to call this function you should do
fn(method, url)
.then(
function(result){
... do if ok (resolve)
},
function( error) {
... do if error (reject)
}
)
You forgot to return the deferred object in your service..
This probably results in the following error:
Cannot read property then of undefined
I've made a basic example to demonstrate the $q service:
Controller - Login function
$scope.login = function login() {
LoginService.loginuser($scope.data.user_email, $scope.data.password)
.then(function onLoginSuccess(response) {
// response should contain 'success' data
$state.go('app.dashboard');
}, function onLoginFailed(error) {
var alertPopup = $ionicPopup.aler({
title: 'Login failed!',
template: 'Please check your credentials!'
});
});
}
Service
var API = {};
function loginUser(email, password) {
var deferred = $q.defer();
$http.get("http://vanhalterenwatersport.nl/van/webservice/appc/login.php")
.then(function onUserLoggedIn(response) {
deferred.resolve(response);
}, function onLoginFailed(error) {
deffered.reject(error);
});
// Make sure to return your promise!
return deferred.promise;
}
API.loginUser = loginUser;
Sidenote: You're also using GET in your login function. For this type of operations, you would typically POST a data-object to your back-end which on his turn will return you a result.

How to get specific state in AngularJS by local-storage?

I want to change state by local-storage in my application after page refresh. How to get the state?.
HTML:
<body ng-app="sampleApp">
<div class="container" ng-controller="Registration" ng-init ="temp()">
<div ui-view></div>
</div>
Controller:
var sampleApp = angular.module('sampleApp',
['ui.router','angularFileUpload','ngStorage']);
sampleApp.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('settings', {
url: '/settings',
templateUrl: '/ui/step1.htm'
.state('settings/Personal_Info', {
url: '/Personal_Info',
templateUrl: '/ui/step2.htm',
//controller: 'ProfileController'
})
.state('settings/Personal_Info_1', {
url: '/Personal_Info_1',
templateUrl: '/ui/step3.htm',
//controller: 'AccountController'
})
.state('settings/P_Info_Affiliations', {
url: '/P_Info_Affiliations',
templateUrl: '/ui/step4.htm',
//controller: 'ProfileController'
});
$urlRouterProvider.otherwise('/settings');
});
sampleApp.controller("Registration",
function ($scope, $location, $http, $state, $localStorage){
$scope.currentstep = 1;
$scope.formData = {};
$scope.temp = function()
{ alert($localStorage.currentstep);
if($localStorage.currentstep > 0) {
$scope.currentstep = $localStorage.currentstep;
$scope.getStepUrl();
}
}
$scope.next = function(formData){
console.log($scope.currentstep);
//console.log($scope.formData);
if (formData.check == 1) {
$scope.currentstep = $scope.currentstep + 1;
$localStorage.currentstep = $scope.currentstep;
alert("Everything is validated. We can go ahead");
$http({
method : 'POST',
url : 'addstep?step'+ $scope.currentstep,
data : $scope.formData,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
if (data.errors) {
$scope.errorName = data.errors.name;
$scope.errorUserName = data.errors.username;
$scope.errorEmail = data.errors.email;
} else {
$scope.message = data.message;
}
});
$scope.getStepUrl();
}
else {
alert("Some issues in input data.");
}
}
$scope.getStepUrl = function() {
if($scope.currentstep == 1){
$state.go('settings');
}
else if($scope.currentstep == 2){
$state.go('settings/Personal_Info');
alert("i am step 2");
}
else if($scope.currentstep == 3){
$state.go('settings/Personal_Info_1');
}
}
});
I am not geting state properly.
how to solve this issue?
Thank you for your help in advance.
You can get the current state via $state provider and state.current.name
So you can ask for current state in each controller or service you would like to use
Remove the default state
$urlRouterProvider.otherwise('/settings');
Use the else statment in a function
if($localStorage.currentstep > 0) {
$scope.currentstep = $localStorage.currentstep;
$scope.getStepUrl();
}else{
$state.go('settings');
}

Authenticating the Ionic app with a backend server

I try to create with angularjs based Ionic app an authentication mechanism. The system looks like this:
mobile users are created by administrators on the backend server. The created mobile user can login into the app.
I get an Example and implemented it for my app.
constants.js
angular.module('starter')
.constant('AUTH_EVENTS', {
notAuthenticated: 'auth-not-authenticated',
notAuthorized: 'auth-not-authorized'
})
.constant('USER_ROLES', {
admin: 'admin_role',
public: 'public_role'
});
dashController.js
myApp.controller('DashCtrl', function ($scope, $state, $http, $ionicPopup, AuthService, $location, $window) {
$scope.logout = function () {
AuthService.logout();
$window.location.href = '/index.html';
};
$scope.performValidRequest = function () {
$http.get('http://localhost:8100/valid').then(
function (result) {
$scope.response = result;
});
};
$scope.performUnauthorizedRequest = function () {
$http.get('http://localhost:8100/notauthorized').then(
function (result) {
// No result here..
}, function (err) {
$scope.response = err;
});
};
$scope.performInvalidRequest = function () {
$http.get('http://localhost:8100/notauthenticated').then(
function (result) {
// No result here..
}, function (err) {
$scope.response = err;
});
};
});
loginAppController.js
myApp.controller('LoginAppCtrl', function ($scope, $state, $ionicPopup, AuthService, AUTH_EVENTS, $location, $window) {
$scope.username = AuthService.username();
$scope.$on(AUTH_EVENTS.notAuthorized, function (event) {
var alertPopup = $ionicPopup.alert({
title: 'Unauthorized!',
template: 'You are not allowed to access this resource.'
});
});
$scope.$on(AUTH_EVENTS.notAuthenticated, function (event) {
AuthService.logout();
$window.location.href = '/loginPage.html';
var alertPopup = $ionicPopup.alert({
title: 'Session Lost!',
template: 'Sorry, You have to login again.'
});
});
$scope.setCurrentUsername = function (name) {
$scope.username = name;
};
})
loginController.js
myApp.controller('LoginCtrl', function ($scope, $state, $ionicPopup, AuthService, $location, $window) {
$scope.data = {};
$scope.login = function (data) {
AuthService.login(data.username, data.password).then(function (authenticated) {
$window.location.href = '/index.html';
$scope.setCurrentUsername(data.username);
}, function (err) {
var alertPopup = $ionicPopup.alert({
title: 'Login failed!',
template: 'Please check your credentials!'
});
});
};
})
loginService.js
angular.module('starter')
myApp.service('AuthService', function ($q, $http, USER_ROLES) {
var LOCAL_TOKEN_KEY = 'yourTokenKey';
var username = '';
var isAuthenticated = false;
var role = '';
var authToken;
function loadUserCredentials() {
var token = window.localStorage.getItem(LOCAL_TOKEN_KEY);
if (token) {
useCredentials(token);
}
}
function storeUserCredentials(token) {
window.localStorage.setItem(LOCAL_TOKEN_KEY, token);
useCredentials(token);
}
function useCredentials(token) {
username = token.split('.')[0];
isAuthenticated = true;
authToken = token;
if (username == 'admin') {
role = USER_ROLES.admin
}
if (username == 'user') {
role = USER_ROLES.public
}
// Set the token as header for your requests!
$http.defaults.headers.common['X-Auth-Token'] = token;
}
function destroyUserCredentials() {
authToken = undefined;
username = '';
isAuthenticated = false;
$http.defaults.headers.common['X-Auth-Token'] = undefined;
window.localStorage.removeItem(LOCAL_TOKEN_KEY);
}
var login = function (name, pw) {
return $q(function (resolve, reject) {
if ((name == 'admin' && pw == '1') || (name == 'user' && pw == '1')) {
// Make a request and receive your auth token from your server
storeUserCredentials(name + '.yourServerToken');
resolve('Login success.');
} else {
reject('Login Failed.');
}
});
};
var logout = function () {
destroyUserCredentials();
};
var isAuthorized = function (authorizedRoles) {
if (!angular.isArray(authorizedRoles)) {
authorizedRoles = [authorizedRoles];
}
return (isAuthenticated && authorizedRoles.indexOf(role) !== -1);
};
loadUserCredentials();
return {
login: login,
logout: logout,
isAuthorized: isAuthorized,
isAuthenticated: function () {
return isAuthenticated;
},
username: function () {
return username;
},
role: function () {
return role;
}
};
})
app.js
var myApp = angular.module('starter', ['ionic', 'ngMockE2E'])
.run(function($ionicPlatform, $ionicPopup) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.run(function($httpBackend) {
$httpBackend.whenGET('http://localhost:8100/valid')
.respond({message: 'This is my valid response!'});
$httpBackend.whenGET('http://localhost:8100/notauthenticated')
.respond(401, {message: "Not Authenticated"});
$httpBackend.whenGET('http://localhost:8100/notauthorized')
.respond(403, {message: "Not Authorized"});
$httpBackend.whenGET(/.*/).passThrough();
})
.run(function ($rootScope, $state, AuthService, AUTH_EVENTS, $location, $window) {
$rootScope.$on('$stateChangeStart', function (event,next, nextParams, fromState) {
if ('data' in next && 'authorizedRoles' in next.data) {
var authorizedRoles = next.data.authorizedRoles;
if (!AuthService.isAuthorized(authorizedRoles)) {
event.preventDefault();
$state.go($state.current, {}, {reload: true});
$rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
}
}
if (!AuthService.isAuthenticated()) {
if (next.name !== 'login') {
event.preventDefault();
$window.location.href = '/loginPage.html';
}
}
});
})
HTML:
<ion-content style="text-align: left" ng-controller="LoginCtrl">
<span class="item item-input item-stacked-label"
style="font-weight: bold">Name and password:</span>
<label class="item item-input">
<span class="input-label">Name:</span>
<input name="name" placeholder="Name!" autofocus="true" required="true"
type="text"
ng-model="data.username"/>
</label>
<label class="item item-input">
<span class="input-label">Password:</span>
<input name="password" placeholder="Password!" required="true" type="password"
ng-model="data.password"/>
</label>
<button id="button-1" class="button button-block button-positive" ng-click="login(data)">Login</button>
</ion-content>
In a related article I get these steps as an answer:
1) Send username password to server using $http.post();
2) Server authenticates the credentials. and returns a token in return
is credentials are correct.
3) App stores this token locally and passes it to server for later
request as a mean of identification of logged in user.
Ideally you should implement SOAP or REST based services on your
server and consume those services in your app.
The example works localy. But where should change, so that I can authenticate with a user and password which stored on the backen server?

AngularJS and Spring MVC login error

var appModule = angular.module('myApp', [ 'angular-storage', 'ui.router' ]);
appModule
.controller(
'MainCtrl',
[
'mainService','$scope','$http','userFactory','$state','$rootScope','store',
function(mainService, $scope, $http, userFactory, $state,$rootScope,store) {
$scope.token = null;
$scope.error = null;
$scope.user={"emailId":"","password":""};
$scope.login = function(user) {
$scope.error = null;
mainService
.login(user)
.then(
function(token) {
$scope.token = token;
$http.defaults.headers.common.Authorization = 'Bearer '
+ token;
userFactory.setUserToken(token);
console.log("token store");
$state.go("home");
}, function(error) {
$scope.error = error
$scope.userName = '';
alert("not");
});
}
$scope.loggedIn = function() {
return store.get("token") !== null;
}
} ]);
appModule.controller('HomeCtrl',['$scope','mainService','$http','userFactory','$state',function($scope,mainService,$http,userFactory,$state){
$scope.greeting = 'Welcome to the JSON Web Token / AngularJR / Spring example!';
$scope.roleUser = false;
$scope.roleAdmin = false;
$scope.roleFoo = false;
// $scope.checkRoles = function() {
mainService.hasRole('user').then(
function(user) {
console.log(user + " user");
$scope.roleUser = user
});
mainService.hasRole('admin').then(
function(admin) {
console.log(admin + " admin");
$scope.roleAdmin = admin
});
mainService.hasRole('foo').then(function(foo) {
$scope.roleFoo = foo
});
// }
$scope.logout = function() {
$scope.userName = '';
$scope.token = null;
$http.defaults.headers.common.Authorization = '';
userFactory.removeUserToken();
$state.go("login");
}
}]);
appModule.config([ '$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/login");
$stateProvider.state('login', {
url : "/login",
templateUrl : "login.html",
controller : 'MainCtrl'
}).state('home', {
url : "/home",
templateUrl : "home.html",
controller : 'HomeCtrl'
});
} ]);
appModule.config([ '$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('myInterceptor');
} ]);
appModule.factory('myInterceptor', function(store,userFactory) {
var myInterceptor = {
request : function(request) {
if(userFactory.getUserToken() !=null){
request.headers['Authorization'] = 'Bearer '+ userFactory.getUserToken();
return request;
}
return request;
},
response : function(response) {
return response;
}
};
return myInterceptor;
});
appModule.run(function(mainService,$state,$rootScope) {
$rootScope.$on('$stateChangeStart', function (event, next) {
var is=mainService.auth();
if(is == false && next.name=="home"){
event.preventDefault();
$state.go("login");
}
});
});
appModule.factory('userFactory',['store',function(store){
var user={};
user.setUserToken=function(token){
store.set("token",token);
},
user.getUserToken=function(){
return store.get("token");
},
user.removeUserToken=function(){
store.remove("token");
}
return user;
}]);
appModule.service('mainService', function($http, userFactory) {
return {
login : function(user) {
var config={
method:'POST',
url:'http://192.168.0.5:8080/TeamAssist/camelRestlet/getLoginDetails?restletMethod=post'
};
return $http(config, user).then(function(response) {
console.log(response);
return response.data.token;
});
},
hasRole : function(role) {
return $http.get('/api/role/' + role).then(function(response) {
console.log(response);
return response.data;
});
},
auth : function() {
if (userFactory.getUserToken() == null)
return false;
else
return true;
}
};
});var appModule = angular.module('myApp', [ 'angular-storage', 'ui.router' ]);
appModule
.controller(
'MainCtrl',
[
'mainService','$scope','$http','userFactory','$state','$rootScope','store',
function(mainService, $scope, $http, userFactory, $state,$rootScope,store) {
$scope.token = null;
$scope.error = null;
$scope.user={"emailId":"","password":""};
$scope.login = function(user) {
$scope.error = null;
mainService
.login(user)
.then(
function(token) {
$scope.token = token;
$http.defaults.headers.common.Authorization = 'Bearer '
+ token;
if(token.length<=10)
{
$scope.token = '';
$http.defaults.headers.common.Authorization = '';
$state.go('login');
return;
}
userFactory.setUserToken(token);
console.log("token store");
$state.go("home");
}, function(error) {
$scope.error = error
$scope.userName = '';
alert("not");
});
}
$scope.loggedIn = function() {
return store.get("token") !== null;
}
} ]);
appModule.controller('HomeCtrl',['$scope','mainService','$http','userFactory','$state',function($scope,mainService,$http,userFactory,$state){
$scope.greeting = 'Welcome to the JSON Web Token / AngularJR / Spring example!';
$scope.roleUser = false;
$scope.roleAdmin = false;
$scope.roleFoo = false;
// $scope.checkRoles = function() {
mainService.hasRole('user').then(
function(user) {
console.log(user + " user");
$scope.roleUser = user
});
mainService.hasRole('admin').then(
function(admin) {
console.log(admin + " admin");
$scope.roleAdmin = admin
});
mainService.hasRole('foo').then(function(foo) {
$scope.roleFoo = foo
});
// }
$scope.logout = function() {
$scope.userName = '';
$scope.token = null;
$http.defaults.headers.common.Authorization = '';
userFactory.removeUserToken();
$state.go("login");
}
}]);
appModule.config([ '$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/login");
$stateProvider.state('login', {
url : "/login",
templateUrl : "login.html",
controller : 'MainCtrl'
}).state('home', {
url : "/home",
templateUrl : "home.html",
controller : 'HomeCtrl'
});
} ]);
appModule.config([ '$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('myInterceptor');
} ]);
appModule.factory('myInterceptor', function(store,userFactory) {
var myInterceptor = {
request : function(request) {
if(userFactory.getUserToken() !=null){
request.headers['Authorization'] = 'Bearer '+ userFactory.getUserToken();
return request;
}
return request;
},
response : function(response) {
return response;
}
};
return myInterceptor;
});
appModule.run(function(mainService,$state,$rootScope) {
$rootScope.$on('$stateChangeStart', function (event, next) {
var is=mainService.auth();
if(is == false && next.name=="home"){
event.preventDefault();
$state.go("login");
}
});
});
appModule.factory('userFactory',['store',function(store){
var user={};
user.setUserToken=function(token){
store.set("token",token);
},
user.getUserToken=function(){
return store.get("token");
},
user.removeUserToken=function(){
store.remove("token");
}
return user;
}]);
appModule.service('mainService', function($http, userFactory) {
return {
login : function(user) {
var config={
method:'GET',
url:'http://192.168.0.64:8080/TeamAssist/rest/service/login/'+ user.emailId + '/' + user.password,
headers: {
'Content-Type': 'application/json'
}
};
return $http(config, user).then(function(response) {
console.log(response);
return response.data;
});
},
hasRole : function(role) {
return $http.get('/api/role/' + role).then(function(response) {
console.log(response);
return response.data;
});
},
auth : function() {
if (userFactory.getUserToken() == null)
return false;
else
return true;
}
};
});
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form ng-submit="login(user)">
Username: <input type="text" ng-model="user.emailId" /><br/>
Password: <input type="text" ng-model="user.password" /><span><input
type="submit" value="Login" />
</form>
</body>
</html>
After successfully login and logout, when I do login again with correct credentials, I got "****Request header field Authorization is not allowed by Access-Control-Allow-Headers**.**" error, but if I refresh the page then I get successfully logged-IN.

Resources