Ionic logout not clearing http service data - angularjs

when I click logout button, its changing the state, but not refreshing the page, because of this, my login page text boxes still having entered data. and If i loggIn with new data, Property details http request not pulling the new data.
I tried, $location.path , $state.go but no use,
can any one help me please.
Login controller
.controller('LoginCtrl', function($scope, $rootScope, AuthenticationService,ClientDetails, $ionicPopup, $state) {
$scope.data = { clientId: '', lastName: '', email: ''};
$scope.login = function () {
AuthenticationService.Login($scope.data.clientId, $scope.data.lastName, $scope.data.email, function(response) {
if(response.success) {
ClientDetails.setDetails(response.data);
$state.go('app.home');
console.log(response);
} else {
$scope.error = response.message;
var alertPopup = $ionicPopup.alert({
title: 'Login failed!',
template: $scope.error
});
}
});
};
})
getting properties through service:
.factory('PropertyDetails',
['$http', '$rootScope',
function ( $http, $rootScope) {
var clientId = $rootScope.globals.clientDetails.ClientId;
var service = {};
service.getProperties = function(callback){
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
var data = ''; var status = ''; var message = '';
var response = {};
var Request = $http({
method: 'GET',
url: 'http://example.com/'+clientId,
data: data
})
Request.success(function(jdata, headers) {
if( headers === 200 ){
if(typeof jdata == 'object'){
status = jdata.Status;
message = jdata.Message;
data = jdata.Data;
$rootScope.globals.properties = data;
}else{
status = false;
message = "Response data is not a object!";
}
}else{
status = false;
message = "Something went wrong!";
}
//response = { success : status, message : message, data: data };
response = { success : status, message : message, data: $rootScope.globals.properties };
callback(response);
//callback($rootScope.globals.properties);
})
Request.error(function(data, headers){
if(typeof data == 'object'){
message = data.Message;
}else{
message = "Client not found.";
}
response = { success : false, message : message };
callback(response);
});
};
service.clearDetails = function(){
$rootScope.globals.properties = {};
};
return service;
}])
My logout controller:
.controller('menuCtrl', function($scope, $rootScope, ClientDetails, PropertyDetails,$timeout,$ionicHistory, $state,$location){
$scope.logOut = function(){
ClientDetails.clearDetails();
PropertyDetails.clearDetails();
$timeout(function () {
$ionicHistory.clearCache();
$ionicHistory.clearHistory();
$ionicHistory.nextViewOptions({ disableBack: true, historyRoot: true });
$state.go('login');
}, 30);
}
})
Thank you

Many Way to clear textbox first of controller call one time to load in ionic if you want to reload again data you used
$scope.$on('$ionicView.enter', function() {
//here some code
});
above code when you open page this code is running every time[load controller].
its simple way.

Related

angularjs redircet to login page if not login

I am using Laravel angularjs
I am using this package https://github.com/andbet39/tokenAuth
it's working fine but my problem is without login i can go to any page also once i reload the page user name is disabled
I don't know what is the problem here
app.js
var app = angular.module('todoApp', ['ui.router', 'satellizer'])
.config(function($stateProvider, $urlRouterProvider, $authProvider,$provide) {
$authProvider.loginUrl = '/api/authenticate';
$urlRouterProvider.otherwise('/login');
$stateProvider
.state('login', {
url: '/login',
templateUrl: '/js/tpl/login.html',
controller: 'AuthController'
})
.state('register', {
url: '/register',
templateUrl: '/js/tpl/register.html',
controller: 'AuthController'
})
.state('todo', {
url: '/todo',
templateUrl: '/js/tpl/todo.html',
controller: 'TodoController'
});
function redirectWhenLoggedOut($q, $injector) {
return {
responseError: function (rejection) {
var $state = $injector.get('$state');
var rejectionReasons = ['token_not_provided', 'token_expired', 'token_absent', 'token_invalid'];
angular.forEach(rejectionReasons, function (value, key) {
if (rejection.data.error === value) {
localStorage.removeItem('user');
$state.go('login');
}
});
return $q.reject(rejection);
}
}
}
$provide.factory('redirectWhenLoggedOut', redirectWhenLoggedOut);
});
TodoController.js
app.controller('TodoController', function($state,$http,$rootScope, $scope,$auth) {
$scope.todos=[];
$scope.newTodo={};
$scope.init = function (){
$http.get('/api/todo').success(function(data){
$scope.todos=data;
})
};
$scope.save = function(){
$http.post('/api/todo',$scope.newTodo).success(function (data) {
$scope.todos.push(data);
$scope.newTodo={};
});
};
$scope.update = function(index){
$http.put('/api/todo/'+ $scope.todos[index].id,$scope.todos[index]);
};
$scope.delete = function(index){
$http.delete('/api/todo/'+ $scope.todos[index].id).success(function(){
$scope.todos.splice(index,1);
});
};
$scope.logout = function() {
$auth.logout().then(function() {
localStorage.removeItem('user');
$rootScope.authenticated = false;
$rootScope.currentUser = null;
});
}
$scope.init();
});
AuthController.js
app.controller('AuthController', function($auth, $state,$http,$rootScope, $scope) {
$scope.email='';
$scope.password='';
$scope.newUser={};
$scope.loginError=false;
$scope.loginErrorText='';
$scope.login = function() {
var credentials = {
email: $scope.email,
password: $scope.password
}
$auth.login(credentials).then(function() {
return $http.get('api/authenticate/user');
}, function(error) {
$scope.loginError = true;
$scope.loginErrorText = error.data.error;
}).then(function(response) {
// var user = JSON.stringify(response.data.user);
// localStorage.setItem('user', user);
$rootScope.authenticated = true;
$rootScope.currentUser = response.data.user;
$scope.loginError = false;
$scope.loginErrorText = '';
$state.go('todo');
});
}
$scope.register = function () {
$http.post('/api/register',$scope.newUser)
.success(function(data){
$scope.email=$scope.newUser.email;
$scope.password=$scope.newUser.password;
$scope.login();
})
};
});
I want to redirect to login page if authandicate is falied
How to fix this ?
In angularjs 1.4+ there is no
$http.get('/api/todo').success(function(data){
$scope.todos=data;
})
What you should do instead
$http.get('/api/todo').then(function(data){
$scope.todos=data;
})
And same with this $http.post which you have below.
Also after refreshing page rootScope is deleted and that is why nickname is blank after refresh.
You probably want to store nickname in localStorage or async promise based localForage.
If you chose async localForage on login you can emit custom event with rootScope and execute some function on this event which gather nickname from localForage. You might want to execute this function in some external controller which would wrap all app so when you assign $scope.nick you will have access to it across entire app. Same with $scope.auth = true, you will be able to build your app basing on this boolean for logged in using ng-if directive.
Inject $location to your controller as function parameter and try to redirect like so
$location.path('/todo' );
or
$location.url(YOUR_URL);
Also I don't really understand why you are doing two backend call for login, one inside another. You probably should do one $http.post which would return token in response. Then you could fix and simplify your function code to
$scope.login = function() {
var credentials = {
email: $scope.email,
password: $scope.password
}
$auth.login(credentials).then(function(response) {
$rootScope.authenticated = true;
$rootScope.currentUser = response.data.user;
$scope.loginError = false;
$scope.loginErrorText = '';
}, function(error) {
$scope.loginError = true;
$scope.loginErrorText = error.data.error;
$location.path('/todo' );
});
}
However I don't know your code from $auth service.
Remember to inject $location service.
redirectWhenLoggedOut seems to be an http interceptor.
I think the idea is that you redirect when the http call was not successful. So you need to add an http interceptor that catches the http error and redirects to the login page.
$httpProvider.interceptors.push('redirectWhenLoggedOut');
Don't forget to inject the $httpProvider;

How to do automatic login in angular js?

i have a login screen and i am doing login by using some hard cord data.
angular.module('starter.controllers', [])
.controller('AppCtrl', function($scope, $rootScope, $window, $ionicModal, $timeout, authService, $state, $http, $ionicLoading, $location) {
//$window.location.reload();
$scope.loginSubmitted = false;
$scope.myflag = false;
$scope.User = {};
$scope.toast = function() {
$ionicLoading.show({
template: 'wrong credentials'
});
$timeout(function() {
$ionicLoading.hide();
}, 1000);
}
$scope.footerflag = true;
$scope.hidefooter = function() {
$timeout(function() {
$scope.footerflag = false;
},1)
}
$scope.showfooter = function() {
$timeout(function() {
$scope.footerflag = true;
},1)
}
$scope.doLogin = function() {
console.log("trying login");
// // var res = $http.post('http://login.com/postLogin', $scope.user);
// authService.postdetails($scope.User).success(function(data, status, headers, config) {
// $scope.message = data;
// console.log("succesfn");
// console.log(status);
//
// })
// .error(function(data, status, headers, config) {
// alert("failure message: " + JSON.stringify({
// data: data
// }));
// console.log(fail);
// });
$scope.loginSubmitted = true;
$scope.loginstatus = 0;
authService.GetByUsername().success(function(data) {
$scope.UserData = data;
// console.log($scope.UserData);
for (var i = 0; i < $scope.UserData.length; i++) {
if ($scope.UserData[i].UserName == $scope.User.UserName && $scope.UserData[i].Password == $scope.User.Password) {
authService.currentuser = $scope.User.UserName;
//console.log(authService.currentuser);
$scope.loginstatus = 1;
break;
}
}
if ($scope.loginstatus == 1) {
// var lastVal = $cookieStore.get($scope.User.UserName);
// console.log(lastVal);
//$location.path('/app/playlists');
$scope.loginstatus = 0;
$state.go('app.playlists', null, {
reload: true
});
} else {
console.log('wrong credentials');
$scope.toast();
}
}).error(function(err) {
console.log(err);
});
}
});
So i want to enable automatic login, till the user clicks logout button. How it can be done?
I'm simply redirecting to another page when username and password matches.
You can check if the user is logged in in the module.run() method. Here is an example:
http://arthur.gonigberg.com/2013/06/29/angularjs-role-based-auth/
It might help you.
Please following below links.
How to check authentication and automatically redirect to login state with ui-router?
angular js returning user autologin

Satellizer error

angular.module('starter')
.controller('LoginCtrl', function($scope, $location, $stateParams, $ionicHistory, $http, $state, $auth, $rootScope) {
$scope.loginForm = {}
$scope.loginError = false;
$scope.loginErrorText;
$scope.login = function() {
var credentials = {
email: $scope.loginForm.email,
password: $scope.loginForm.password
}
console.log(credentials);
$auth.login(credentials).then(function() {
console.log('im in login function' );
// Return an $http request for the authenticated user
$http.get('http://localhost:8000/api/v1/auth/user').success(function(response){
// Stringify the retured data
var user = JSON.stringify(response.user);
// Set the stringified user data into local storage
localStorage.setItem('user', user);
// Getting current user data from local storage
$rootScope.currentUser = response.user;
// $rootScope.currentUser = localStorage.setItem('user');;
$ionicHistory.nextViewOptions({
disableBack: true
});
$state.go('app.jokes');
})
.error(function(){
$scope.loginError = true;
$scope.loginErrorText = error.data.error;
console.log($scope.loginErrorText);
})
});
}
});
When i call the login function i get this error
POST http://localhost:8100/auth/login 404 (Not Found)
Is there problem with the satellizer?
I was also suffering from same issue. I just added
$authProvider.loginUrl = myServer+ 'oauth/token';
$authProvider.tokenName = 'access_token';
$authProvider.tokenPrefix = 'myServerAuth';
$authProvider.tokenHeader = 'Authorization';
$authProvider.tokenType = 'Bearer';
in my config and it worked fine.

router.post returns error "undefined is not a function" .Using mongo and express.js

I'm trying to buld an app using files from LINK .I found that posting is where the code breaks.Has express js changed or is it syntax mistake ?
The router.post breaks once it reaches Maid.registerMaid(new Maid({... .I'm able to make it work using .save() but could anyone explain why this callback is beaking ?
Putting the code below.. sorry, i'm a beginner in M.E.A.N
API.js
var express = require('express'),
router = express.Router(),
passport = require('passport');
User = require('../models/user.js');
Maid = require('../models/maid.js');
router.post('/AddMaid', function(req, res) {
console.log(req.body, req.body.FirstName,req.body.LastName);
Maid.registerMaid(new Maid({ FirstName: req.body.FirstName }), ({LastName: req.body.LastName}), function(err, account) {
if (err) {
return res.status(500).json({err : err})
}
return res.status(200).json({status: 'Registration successful!'});
});
});
Services.js
angular.module('myApp').factory('AuthService',['$q', '$timeout', '$http', function ($q, $timeout, $http) {
var user = null;
return ({
isLoggedIn: isLoggedIn,
getUserStatus: getUserStatus,
login: login,
logout: logout,
register: register,
registerMaid: registerMaid
});
function registerMaid(Fname, Lname) {
var deferred = $q.defer();
$http.post('/maid/AddMaid', {
FirstName : Fname,
LastName : Lname
}).success(function(data, status) {
if (status === 200 && data.status) {
deferred.resolve();
} else {
deferred.reject();
}
}).error(function(data) {
debugger;
alert("Error in Services AddMaid");
deferred.reject();
});
return deferred.promise;
} }]);
Controllers.js
angular.module('myApp').controller('AddMaidController', ['$scope', '$http','$location', 'AuthService', function($scope, $http,$location, AuthService) {
console.log(AuthService.getUserStatus());
$scope.register = function () {
$scope.error = false;
$scope.disabled = true;
AuthService.registerMaid($scope.registerForm.FirstName,$scope.registerForm.LastName).then(function () {
$scope.disabled = false;
$scope.registerForm = {};
}).catch(function () {
$scope.error = true;
$scope.errorMessage = "Something went wrong!";
});
};}]);
maid.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var Maid = new Schema({
First_Name: String,
Last_Name: String
});
module.exports = mongoose.model('maids', Maid);
First of all you globally defined ur User and Maid modules, that is not a good practice.
Error occurs because your Maid module (Maid model on server side, i.e. Nodejs) doesnt have registerMaid method. You need to use Maid.create instead

First time injection doesn't instantiate

First time calling, the authenticated property is false, even the credential is OK. If I login once again with the same credential, it will be OK.
Anyway, I am not sure that my factory below is the right way in angularjs or not. Would you please give me any suggestions?
Factory:
app.factory('authenticatorService',['$resource', function($resource){
var authenticator = {};
authenticator.attempt = function(email, password){
var current = this;
$resource("/service/authentication/:id",null,{'update' : { method: 'PUT'}})
.save({'email' : email,'password': password},
//success
function(response){
current.authenticated = sessionStorage.authenticated = true;
current.userinfo = response.user;
current.authenticated = true;
},
function(response){
current.authenticated = false;
}
);
return this.authenticated;
};
authenticator.logout = function(){
delete sessionStorage.authenticated;
this.authenticated = false;
this.userinfo = null;
return true;
};
authenticator.check = function(){
if(this.userinfo && this.authenticated){
return true;
}
return false;
};
return authenticator;
}]);
Controller:
app.controller('authenCtrl',
[
'authenticatorService',
'$scope',
'$sanitize',
'$log',
'$location',
function(alert, authenticator, $scope, $sanitize, $log, $location){
$scope.login = function(){
if(authenticator.attempt($sanitize($scope.email) ,$sanitize($scope.password))){
$location.path('/dashboard');
}else{
alert.add("danger","Login fail.");
}
}
}]);
The this.authenticated in authenticator.attempt will return before the asynchronous call from $resource has completed.
You will need to wait for the promise to be resolved before returning from the factory, and before receiving in the controller.
Something like this should hopefully work:
Factory:
authenticator.attempt = function(email, password){
var current = this;
$resource("/service/authentication/:id", null, {'update' : { method: 'PUT'}})
.save({'email' : email,'password': password},
function(response){
current.authenticated = sessionStorage.authenticated = true;
current.userinfo = response.user;
current.authenticated = true;
},
function(response){
current.authenticated = false;
}
).$promise.then(function () {
return current.authenticated;
});
};
Controller:
$scope.login = function() {
var email = $sanitize($scope.email);
var password = $sanitize($scope.password);
authenticator.attempt(email, password).then(function(isAuthenticated) {
if (isAuthenticated) $location.path('/dashboard');
else alert.add("danger", "Login fail.");
});
};

Resources