Satellizer Http Interceptor - angularjs

Currently I'm using satellizer library to authenticate using json web token. On the backend, I have tested the api and the authentication and everything is working. By the way Im using Twitter authentication.
While on the frontend, which the angular part,After I have authenticated with twitter and successfully redirect to home page, I couldn't get user's information whenever i go to /profile, it doesnt render the user's information and when I check the network tab on google chrome, angular doesnt even call the /api/me route from the backend.
I believe it has something to do with Http interceptor. The authorization header is set as x-access-token both on frontend and backend.
Here's the code.
app.js
angular.module('MyApp', [ 'ngMessages','ngRoute', 'ui.router','satellizer'])
.config(function($authProvider) {
// Twitter
$authProvider.authHeader = 'x-access-token';
$authProvider.httpInterceptor = true; // Add Authorization header to HTTP request
$authProvider.tokenPrefix = 'twitterAuth'; // Local Storage name prefix
$authProvider.twitter({
url: '/auth/twitter',
type: '1.0',
popupOptions: { width: 495, height: 645 }
});
})
.config(function($stateProvider, $urlRouterProvider,$locationProvider) {
$stateProvider
.state('home', {
url: '/',
templateUrl: 'app/views/home.html'
})
.state('login', {
url: '/login',
templateUrl: 'app/views/login.html',
controller: 'LoginCtrl'
})
.state('profile', {
url: '/profile',
templateUrl: 'app/views/profile.html',
controller: 'ProfileCtrl',
})
.state('logout', {
url: '/logout',
template: null,
controller: 'LogoutCtrl'
})
$urlRouterProvider.otherwise('/');
$locationProvider.html5Mode(true);
})
the controllers
login.js
angular.module('MyApp')
.controller('LoginCtrl', function($scope, $auth) {
$scope.authenticate = function(provider) {
$auth.authenticate(provider);
};
});
profile.js
angular.module('MyApp')
.controller('ProfileCtrl', function($scope, $auth, Account) {
$scope.getProfile = function() {
Account.getProfile()
.success(function(data) {
$scope.user = data;
})
};
});
services
account.js
angular.module('MyApp')
.factory('Account', function($http) {
return {
getProfile: function() {
return $http.get('/api/me');
}
};
});
Views
profile.html
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">Profile</div>
<div class="panel-body">
<form method="post">
<div class="form-group">
<label class="control-label">Profile Picture</label>
<img class="profile-picture" ng-src="{{user.picture || 'http://placehold.it/100x100'}}">
</div>
<div class="form-group">
<label class="control-label"><i class="ion-person"></i> Display Name</label>
<input type="text" class="form-control" ng-model="user.displayName" />
</div>
<div class="form-group">
<label class="control-label"><i class="ion-at"></i> Email Address</label>
<input type="email" class="form-control" ng-model="user.email" />
</div>
</form>
</div>
</div>
</div>
This is where the user's information from twitter authentication should render, on the backend everything is showing when I'm using Chrome postman.
I've been pulling my hair for the past 4 hours, so what did I do wrong over here?

I am missing a call to ProfileCtrl's $scope.getProfile. Try this:
angular.module('MyApp')
.controller('ProfileCtrl', function($scope, $auth, Account) {
Account.getProfile()
.success(function(data) {
$scope.user = data;
});
});

Related

I want to create a route to automatically redirect users to the home page upon logging in

The below code describe my app.js file.
(function () {
'use strict';
angular
.module('app', ['ngRoute', 'ngCookies'])
.config(config)
.run(run);
config.$inject = ['$routeProvider', '$locationProvider'];
function config($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
controller: 'HomeController',
templateUrl: 'home/home.view.html',
controllerAs: 'vm'
})
.when('/users/login', {
controller: 'LoginController',
templateUrl: 'login/login.view.html',
controllerAs: 'vm'
})
.when('/register', {
controller: 'RegisterController',
templateUrl: 'register/register.view.html',
controllerAs: 'vm'
})
.otherwise({ redirectTo: '/users/login' });
}
})();
The one below describe my login controller.js file: I wrote this route for logging in registered users to the database and creating tokens once the username and password are correct. What I want now is to create an auto route that will redirect the users to the home page once the password and username is correct.
(function () {
'use strict';
angular
.module('app')
.service('Users1', function($http) {
this.logUser = function(user) {
return $http.post("/users/login", user).
then(function(response) {
return response;
}, function(response) {
alert("Error logging in user.");
});
}
})
// .controller('RegisterController', RegisterController);
.controller("LoginController", function($scope, $location, Users1) {
$scope.back = function() {
$location.path("/users/login");
}
$scope.login = function(user) {
Users1.logUser(user).then(function(doc) {
var userUrl = "/" + doc.data.id;
$location.path(userUrl);
}, function(response) {
alert(response);
});
}
})
})();
Below is the html file for the login controller file:
<div class="col-md-6 col-md-offset-3">
<h2>Login</h2>
<form name="form" role="form">
<div class="form-group" ng-class="{ 'has-error': form.username.$dirty && form.username.$error.required }">
<label for="username">Username</label>
<input type="text" name="username" id="username" class="form-control" ng-model="user.username" required />
<span ng-show="form.username.$dirty && form.username.$error.required" class="help-block">Username is required</span>
</div>
<div class="form-group" ng-class="{ 'has-error': form.password.$dirty && form.password.$error.required }">
<label for="password">Password</label>
<input type="password" name="password" id="password" class="form-control" ng-model="user.password" required />
<span ng-show="form.password.$dirty && form.password.$error.required" class="help-block">Password is required</span>
</div>
<div class="form-actions">
<button type="submit" ng-disabled="form.$invalid || vm.dataLoading" class="btn btn-primary" ng-click="login(user)">Login</button>
Register
</div>
</form>
$scope.login = function(user) {
Users1.logUser(user).then(function(
$location.path("/");
}, function(response) {
alert(response);
});
}
If you just want to redirect user to the home page. and if you want the userid as urlParams then you should go with this
.when('/:id', {
controller: 'HomeController',
templateUrl: 'home/home.view.html',
controllerAs: 'vm'
})
and the controller
$scope.login = function(user) {
Users1.logUser(user).then(function(doc) {
var userUrl = "/" + doc.data.id;
$location.path(userUrl);
}, function(response) {
alert(response);
});
}
you can use run method to redirect user to home on landing.
You can check when even ever there is route change and redirect him to right place.
$scope.$on('$routeChangeStart', function (event, next, current) {
//add your logic here. if user next contains next route.
});

AngularJS change location is not working

I'm new in ionic
I'm trying to do a simple switch between two views in a login app:
index.html
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic Login App</h1>
</ion-header-bar>
<ion-content>
<div class="list list-inset">
<label class="item item-input">
<input type="text" placeholder="Email" ng-model="data.email">
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="data.password">
</label>
</div>
<button class="button button-block button-calm" ng-click="postLogin()">Login</button>
</ion-content>
</ion-pane>
logincontroller.js
app.controller('loginCtrl', function ($scope,$http,$location)
{
$scope.data = {};
$scope.postLogin = function ()
{
var data =
{
email: $scope.data.email,
password: $scope.data.password
};
console.log('bonjour');
$http.post("http://localhost/authproject/public/api/auth/login", data)
.then(
function(response){
// success callback
console.log('success');
$location.path('/map');
},
function(response){
// failure callback
console.log('error');
$location.path('/index');
}
);
}
When I click on a button Login the url change but the page doesn't change
Could someone tell me how do I solve this ? Thanks in advance :)
In your app.js add a state for map like this (with your own templateUrl and controller value). Make sure to add $stateProvider in the config(). Also, include ui.router to your dependencies. Something like this:
angular.module('starter', ['ionic', 'starter.controllers', 'starter.directives', 'ui.router'])
.config(function($stateProvider, $urlRouterProvider, $httpProvider, $locationProvider){
$stateProvider
.state('map', {
url: '/map',
templateUrl: 'app/views/map.html',
controller: 'MapController'
});
...
And in your index.html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.min.js"></script>
Try this
app.controller('loginCtrl', function ($scope,$http,$location,$state) {
$scope.data = {};
$scope.postLogin = function ()
{
var data =
{
email: $scope.data.email,
password: $scope.data.password
};
console.log('bonjour');
$http.post("http://localhost/authproject/public/api/auth/login", data)
.then(
function(response){
// success callback
console.log('success');
$location.path('/map');
},
function(response){
// failure callback
console.log('error');
$state.go('main');
});
})
Add a state in app.js
.config(function($stateProvider,$urlRouterProvider){
.state('main', {
url:'/main',
templateUrl:'templates/main.html',
controller:'yourCtrl'
})
$urlRouterProvider.otherwise('/index');
})
Now make in template folder make a page for named main.html

ui-router $stateProvider.state.controller don't work

The SignupCtrl controller is not binding to signup view. Even when i press the submit button it don't work. But when i place ng-controller=SignupCtrl in the form tag it works. Just wondering why ui-router state parameter controller was not working.
index.html
<html class="no-js" ng-app="mainApp" ng-controller="MainCtrl">
<head> ....
</head>
<body class="home-page">
<div ui-view="header"></div>
<div ui-view="content"></div>
<div ui-view="footer"></div>
...
signup.html
<div class="form-container col-md-5 col-sm-12 col-xs-12">
<form class="signup-form">
<div class="form-group email">
<label class="sr-only" for="signup-email">Your email</label>
<input id="signup-email" type="email" ng-model="user.email" class="form-control login-email" placeholder="Your email">
</div>
<!--//form-group-->
<div class="form-group password">
<label class="sr-only" for="signup-password">Your password</label>
<input id="signup-password" type="password" ng-model="user.password" class="form-control login-password" placeholder="Password">
</div>
<!--//form-group-->
<button type="submit" ng-click="createUser()" class="btn btn-block btn-cta-primary">Sign up</button>
<p class="note">By signing up, you agree to our terms of services and privacy policy.</p>
<p class="lead">Already have an account? <a class="login-link" id="login-link" ui-sref="login">Log in</a>
</p>
</form>
</div><!--//form-container-->
app.js
angular
.module('mainApp', [
'services.config',
'mainApp.signup'
])
.config(['$urlRouterProvider', function($urlRouterProvider){
$urlRouterProvider.otherwise('/');
}])
signup.js
'use strict';
/**
* #ngdoc function
* #name mainApp.signup
* #description
* # SignupCtrl
*/
angular
.module('mainApp.signup', [
'ui.router',
'angular-storage'
])
.config(['$stateProvider', function($stateProvider){
$stateProvider.state('signup',{
url: '/signup',
controller: 'SignupCtrl',
views: {
'header': {
templateUrl: '/pages/templates/nav.html'
},
'content' : {
templateUrl: '/pages/signup/signup.html'
},
'footer' : {
templateUrl: '/pages/templates/footer.html'
}
}
});
}])
.controller( 'SignupCtrl', function SignupController( $scope, $http, store, $state) {
$scope.user = {};
$scope.createUser = function() {
$http({
url: 'http://localhost:3001/users',
method: 'POST',
data: $scope.user
}).then(function(response) {
store.set('jwt', response.data.id_token);
$state.go('home');
}, function(error) {
alert(error.data);
});
}
});
There is a working plunker. Firstly, check this Q & A:
Are there different ways of declaring the controller associated with an Angular UI Router state
Where we can see, that
controller does not belong to state. It belongs to view!
This should be the state definition:
$stateProvider.state('signup',{
url: '/signup',
//controller: 'SignupCtrl',
views: {
'header': {
templateUrl: 'pages/templates/nav.html'
},
'content' : {
templateUrl: 'pages/signup/signup.html',
controller: 'SignupCtrl',
},
'footer' : {
templateUrl: 'pages/templates/footer.html'
}
}
});
Check it here
You need a template to bind a controller.
In the docs ui-router Controllers
Controllers
You can assign a controller to your template. Warning: The controller
will not be instantiated if template is not defined.

Angular, redirect from one controller to onother

I'm developing an application using angularjs starting from https://github.com/firebase/angularfire-seed project. I'm trying to redirect from a controller to another without success. I need to do this from controller because i have some controls to do before redirect. I'm using location object for do it..
Here is my code for redirect:
$scope.infostore = function() {
$location.path( 'store' );
}
Here is my route configuration:
angular.module('myApp.routes', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/home', {
authRequired: true,
templateUrl: 'partials/home.html',
controller: 'HomeCtrl'
});
$routeProvider.when('/apps', {
authRequired: true,
templateUrl: 'partials/apps.html',
controller: 'appsController'
});
$routeProvider.when('/store', {
authRequired: true,
templateUrl: 'partials/store.html',
controller: 'storeController'
});
$routeProvider.otherwise({redirectTo: '/home'});
}]);
But every time i call the method 'infostore' in appsController angular redirect me to 'home'
Why? I just try to use apply() without success on main scope.
Here is my store controller:
'use strict';
app.controller('storeController', function($location, $firebase, $modal, $scope, database, $http, $rootScope, $routeParams) {
var ref = database.returnRef("users/"+$rootScope.auth.user.uid+"/apps");
$scope.apps = $firebase(ref);
});
Here is store html:
<div class="container">
<br />
<div class="row">
<div class="col-md-12 text-center">
<h3>
<span>{{ 'myappslong' | translate }}</span>
</h3>
</div>
</div>
<br />
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-10">
store
</div>
<div class="col-md-1"></div>
</div>
</div>
Here is the URL from the first controller: http://localhost:8000/app/index.html#/apps
Solved, there was an error in my html code. Using location.path works correctly.

Angularjs: ReferenceError: scope is not defined

I'm a beginner with Angularjs, and I have some difficulties understanding modules and scopes.
I keep getting the error that the scope is undefined, but I don't get why. First I had my controller linked where I set my route, but since the function inside the controller is called on submit button click I took it away. I've tried putting it back, but that didn't make any difference.
This is my js file:
var myApp = angular.module('myApp', ['ngRoute']);
// routes
myApp.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'home.html',
controller : 'mainController'
})
// route for the about page
.when('/about', {
templateUrl : 'about.html',
controller : 'aboutController'
})
// route for the login page
.when('/login', {
templateUrl : 'login.html'
});
});
myApp.controller('mainController', function($scope) {
$scope.message = 'Beginpagina';
});
myApp.controller('aboutController', function($scope) {
$scope.message = 'Informatie over deze pagina';
});
function loginCtrl($scope, $http){
$scope.doLogin = function() {
$http({
method: 'POST',
url: 'loginController.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
'username': $scope.un,
'password': $scope.pw
},
}).
success(function(data, status) {
$scope.data = data;
if(data == 'FALSE'){
$scope.errorMessage = 'Geen geldige inloggegevens';
} else {
scope.$apply(function() { $location.path("/profile"); });
}
}).
error(function(data, status) {
$scope.data = data || "FALSE";
$scope.errorMessage = 'Something went wrong';
});
};
};
And this is my login-page where I get the error, trying to log in:
<div class="span5" ng-controller="loginCtrl">
<form>
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Gebruikersnaam" ng-model="un"
type="text" autocomplete="off">
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" ng-model="pw"
type="password" value="" autocomplete="off">
</div>
<input class="btn btn-lg btn-success btn-block" type="submit"
ng-click="doLogin()" value="Login">
<div>{{errorMessage}}</div>
</fieldset>
</form>
</div>
I don't know if I should post the index-page as well, since the routing for home/about page works fine, so the problem is somewhere making the logincontroller and linking it to my submit button. I have found some similar questions, but I haven't seen anyone mix a new controller with myApp controllers, so I might be doing it completely wrong. I've also read that one html page can only have one module, so I didn't know if I could put the login controller apart. It would be nice to have some more info to be put in the right direction. Thanks in advance!
In loginCtrl, you have used scope instead of $scope
Problem is in line
scope.$apply(function()
Use
$scope.$apply(function()

Resources