I'm wondering how I can combine angular-ui-routing with passport. All examples I find are using the node.js routing there for.
var routerApp = angular.module('routerApp', ['ui.router']);
routerApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'partial-home.html'
})
.state('about', {
// for example just show if is loggedIn
});
How would I implement this function in the above snippet?
function isLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated())
return next();
// if they aren't redirect them to the home page
res.redirect('/');
}
Thanks for every hint
One way to start is by creating a service in Angular that uses $http to hit your endpoint in Express. $http returns a promise with success and error methods you can use to change state. If you're building a Single Page App (SPA) this is probably all you need to know. For example:
// An Angular service that talks to Express
UserService.$inject = ['$http', '$state'];
function UserService($http, $state) {
this.loginUser = function (user) {
$http.post("/api/login", user)
.success(function (data, status) {
console.log('Successful login.');
console.log('data = ' + data);
console.log('status = ' + status);
$state.go('welcome'); //
})
.error(function (data) {
console.log('Error: ' + data);
$state.go('somewhereelse');
});
};
$state.go is a UI Router convenience method that will render your defined state.
In Express you'll want to write your own callback function for Passport to control what is returned. For example:
// Express Route with passport authentication and custom callback
app.post('/api/login', function(req, res, next) {
passport.authenticate('local-login', function(err, user, info) {
if (err) {
return next(err);
}
if (user === false) {
res.status(401).send(info.message);
} else {
res.status(200).send(info.message);
}
})(req, res, next);
});
In this example, I'm using a 'local-login' Passport strategy that's working it's magic in the background. If the user is authenticated it will send a 200 back to Angular, which will in turn trigger .success. Otherwise it will send a 401 Unauthorized and fire off .error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With