Reputation: 647
Using Angular and Node.js / Express, is there a way to prevent a direct access to my partial .html files whilst still allowing the following route handling:
My Angular routes look like this:
$stateProvider.state('albums', {
url: '/albums',
templateUrl: '/public/albums',
controller: 'AlbumsCtrl'
});
then my express app does the following:
app.get('/public/albums', function(req, res){
res.sendfile('views/partials/albums.html');
});
This all works ok, but typing "mysite.com/public/albums" allows an access to the partial .html file. There still wouldn't be anything to see as the contents is loaded seperately and the user would need to be signed in for that, but I would still like to somehow prevent an access to this file.
Upvotes: 6
Views: 5769
Reputation: 1407
You probably found an answer or a different method yourself, but if you want to do something like that there's actually a workaround:
You can use the httpRequestInterceptor to add a custom header on all the requests that are coming from angular. On the server side, you can just check if the request contains that header. If it doesn't, than you can redirect or send an error message.
Create an interceptor:
myApp.factory('httpRequestInterceptor', function () {
return {
request: function (config) {
config.headers['x-custom-header-name'] = 'something'
return config
}
}
});
Add the interceptor to the $httpProvider interceptors:
myApp.config( function ($httpProvider) {
$httpProvider.interceptors.push('httpRequestInterceptor')
});
At the point when you want to start avoiding direct access, just put this code:
app.use(function (req, res, next) {
if (!req.headers['x-custom-header-name']) {
res.redirect('/'); //Or just do what you want to
}
next();
});
Or if you want to avoid the access on just one or some routes, you can modify the code changing
app.use(function (req, res, next) ...
with
app.use( 'route/no-direct-access', function (req, res, next) ...
The code for the interceptor came from this stackoverflow question:
Setting application wide HTTP headers in AngularJS
Hope that this can help someone! Bye!
Upvotes: 4
Reputation: 11228
Making a request in AngularJS for the path /foo/bar
is the same as entering the URL domain.com/foo/bar
.
You cannot prevent one and allow the other because in the end - they are requests to the server.
What you however can do is prevent unauthorized requests using a middleware. For example, only if user is administrator or only if user has logged in.
So, in your server you can write a code such as:
function ensureAuthenticated (request, response, next) {
//Custom code - If request is authenticated
return next();
//if Not
res.send(403, "Forbidden");
};
app.get('/public/albums', ensureAuthenticated, function (req, res) {
//res.sendfile(filepath);
});
Upvotes: 2