Satellizer error - angularjs

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.

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;

Getting Error: [$injector:unpr] error in angularjs but i have added my dependencies correcty?

this is how my factory looks like
app.factory('AuthenticationService',['$http', function ($http, $localStorage) {
var AuthenticationService = {};
var api = 'http://del1-vm-kohls:8080/Survey' ;
AuthenticationService.Login = function(username,password,callback){
$http.post('http://del1-vm-kohls:8080/Survey/user/login',{userId: username, password: password})
.success(function(response){
if(response.token) {
// storing token in localstorage if user refreshes
$localStorage.currentUser = {userId : username , token: response.token };
// adding token of authentication for futher use in getting data
authentication.token = response.token;
callback(true);
}
else{
callback(false);
}
});
}
AuthenticationService.getSurvey = function(token){
}
return AuthenticationService;
}]);
this is how my controller looks like
var app = angular.module('myApp',[]);
app.controller('myCtrl', ['$scope', '$localStorage', '$http', 'AuthenticationService', function($scope, $localStorage, $http, AuthenticationService){
$scope.username = "";
$scope.password = "";
$scope.login = false;
$scope.checkLogin = function(){
AuthenticationService.Login($scope.username, $scope.password, function(result){
if(result === true)
{
console.login("Logindone");
$scope.login = true;
$localStorage.setItem('auth', 'true');
location.href = "../../application/content/index.html";
}
else{
$scope.login = false;
$localStorage.setItem('auth', 'false');
sweetAlert("", "Invalid Username or Password", "error");
}
});
}
}]);
You are missing $localStorage in factory dependency declaration.
It should be like :
app.factory('AuthenticationService',['$http','$localStorage', function ($http, $localStorage) {

Angularjs, value coming in token from backend not working in client side

What is wrong with the code it's not working, I am trying to request call web service from backend written in spring, the value passing from backend is token wrapped, I am trying to run the code on client side but form is not passing any value.
auth.js
'use strict';
angular. module('app')
.factory('Auth', [ '$http', '$rootScope', '$window', 'Session', 'AUTH_EVENTS',
function($http, $rootScope, $window, Session, AUTH_EVENTS) {
var authService = {};
this.isLoggedIn = function isLoggedIn(){
return session.getUser() !== null;
};
//the login function
authService.login = function(user, success, error) {
$http.post('URL: http://xxx.xxx.x.xx:xxxx/xxxx/authenticateUser').success(function(authData) {
//user is returned with his data from the db
var users = data.users;
if(users[user.username]){
var loginData = users[user.username];
//insert your custom login function here
if(user.username == loginData.username && user.password == loginData.username){
localStorageService.set(['userInfo'],
{ token: result.access_token, userName: loginData.userName });
//delete password no/t to be seen clientside
delete loginData.password;
//update current user into the Session service or $rootScope.currentUser
//whatever you prefer
Session.create(loginData);
//or
$rootScope.currentUser = loginData;
//fire event of successful login
$rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
//run success function
success(loginData);
} else{
//OR ELSE
//unsuccessful login, fire login failed event for
//the according functions to run
$rootScope.$broadcast(AUTH_EVENTS.loginFailed);
error();
}
}
});
};
//check if the user is authenticated
authService.isAuthenticated = function() {
return !!Session.user;
};
//check if the user is authorized to access the next route
//this function can be also used on element level
//e.g. <p ng-if="isAuthorized(authorizedRoles)">show this only to admins</p>
authService.isAuthorized = function(authorizedRoles) {
if (!angular.isArray(authorizedRoles)) {
authorizedRoles = [authorizedRoles];
}
return (authService.isAuthenticated() &&
authorizedRoles.indexOf(Session.userRole) !== -1);
};
//log out the user and broadcast the logoutSuccess event
authService.logout = function(){
Session.destroy();
localStorageService.removeItem("userInfo");
$rootScope.$broadcast(AUTH_EVENTS.logoutSuccess);
}
return authService;
} ]);
authInterceptor
(function () {
'use strict';
var app = angular.module('app');
var factoryId = 'authInterceptor';
app.factory(factoryId, authInterceptor);
authInterceptor.$inject = ['$q', '$location', 'localStorageService', $rootScope, $http];
function authInterceptor($q, $location, localStorageService) {
var service = {
request: request,
responseError: responseError,
};
return service;
function request(config) {
config.headers = config.headers || {};
var authData = localStorageService.get('authorizationData');
if (authData) {
config.headers.Authorization = 'Bearer ' + authData.token;
}
return config;
}
function responseError(error) {
var loggedIn = false;
var authData = localStorageService.get('authorizationData');
if (authData) {
loggedIn = true;
}
//We only want to go to the login page if the user is not
//logged in. If the user is logged in and they get a 401 is
//because they don't have access to the resource requested.
if (error.status === 401 && !loggedIn) {
$location.path('/login').replace();
}
return $q.reject(error);
}
}
})();

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

Angular jwt authentication fails when reloads the page

I'm trying to authenticate user through token. if i login then token will be created and stored in local storage. whenever there is a change in route I'm hitting the api which is built in express js , gives me decoded user value. everything works without refresshing page. Once I refresh the page I'm not able to hit the API. in order to get decoded user value i suppose to click on login button which is there in header , which triggers the route change then again everything works fine. Please help me out .
.controller('mainController', function($rootScope, $location, $window ,Auth){
var vm = this;
$rootScope.loggedIn = Auth.isLoggedIn();
$rootScope.$on('$locationChangeStart', function(){
$rootScope.loggedIn = Auth.isLoggedIn();
Auth.getUser()
.then(function(data){
$rootScope.user = data.data;
});
});
vm.login = function(){
......
}
vm.logout = function(){
......
}
})
Service
.factory('Auth', function($http, $q, AuthToken){
var authFactory = {};
authFactory.login = function(username, password){
return $http.post('/api/login', {
username: username,
password: password
})
.success(function(data){
AuthToken.setToken(data.token);
return data;
});
};
authFactory.logout = function(){
AuthToken.setToken();
};
authFactory.isLoggedIn = function(){
if(AuthToken.getToken()){
return true;
} else {
return false;
}
};
authFactory.getUser = function(){
if(AuthToken.getToken()){
return $http.get('/api/me');
} else {
return $q.reject({ message: "User has no token"});
}
};
return authFactory;
})
factory for setting token and interceptor code
.factory('AuthToken', function($window){
var authTokenFactory = {};
authTokenFactory.getToken = function(){
return $window.localStorage.getItem('token');
};
authTokenFactory.setToken = function(token){
if(token){
$window.localStorage.setItem('token', token);
} else {
$window.localStorage.removeItem('token');
}
};
return authTokenFactory;
})
.factory('AuthInterceptor', function($q, $location, AuthToken){
var interceptorFactory = {};
interceptorFactory.request = function(config){
var token = AuthToken.getToken();
if(token){
config.headers['x-access-token'] = token;
}
return config;
};
interceptorFactory.responseError = function(response){
if(response.status == 403){
$location.path('/login');
}
return $q.reject(response);
};
return interceptorFactory;
});
It may be that you have to reset the $http default headers on refresh. Using cookies in my case, I make a call to the following function at the beginning of $on('$stateChangeStart'):
service.RefreshGlobalVars = function () {
if ($http.defaults.headers.common.RefreshToken == null) {
$http.defaults.headers.common.Authorization = "Bearer " + $cookieStore.get('_Token');
$http.defaults.headers.common.RefreshToken = $cookieStore.get('_RefreshToken');
}
};
edit- to clarify, since I haven't seen your setToken() function, your implementation may vary, but that's pretty much the gist of it.
I got answer, solved it by checking route change in the main app.js, inside run block.
MyApp.run(function ($rootScope, $location, Auth){
$rootScope.loggedIn = Auth.isLoggedIn();
$rootScope.$on('$locationChangeStart', function(){
$rootScope.loggedIn = Auth.isLoggedIn();
Auth.getUser()
.then(function(data){
$rootScope.user = data.data;
});
});

Resources