Skip to content

Instantly share code, notes, and snippets.

@amitaibu
Last active October 3, 2016 03:11
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save amitaibu/6573250 to your computer and use it in GitHub Desktop.
Save amitaibu/6573250 to your computer and use it in GitHub Desktop.
ExpressJS + AngularJS subdomain login.
# /etc/ hosts
# For local developement
127.0.0.1 app.local
127.0.0.1 api.app.local
<form data-ng-show="!user" action="http://api.app.local:3000/login" method="post">
<div>
<label>Username:</label>
<input type="text" name="username"><br>
</div>
<div>
<label>Password:</label>
<input type="password" name="password">
</div>
<div>
<input type="submit" value="Submit">
</div>
</form>
<div data-ng-show="user">
Hi {{ user.username }}
</div>
// AngularJs
'use strict';
angular.module('mainApp')
.controller('MainCtrl', function ($scope, $http) {
$scope.user = {};
$http({
method: 'GET',
url: 'http://api.app.local:3000/account',
withCredentials: true
}).
success(function(data, status, headers, config) {
$scope.user = data;
}).
error(function(data, status, headers, config) {
console.log(status);
});
});
// Express using passport-local
// This code is adaptation of examples/express3 from https://github.com/jaredhanson/passport-local
// configure Express
app.configure(function() {
// ...
app.use(express.session({
// The domain should start with a dot, as this allows the subdomain.
domain: '.app.local',
secret: 'keyboard cat'
}));
// Enable cors.
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
next();
});
// ...
});
app.get('/account', ensureAuthenticated, function(req, res){
// Return the current user's info
res.json(req.user);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment