Detecting localhost - Is it safe to do this?


#1

Hi guys.

Basic question, but just need to check for sanity.

Is it safe to do this in Meteor?

if (!location.host === 'localhost:3000') {
   // Do login check
}

Thanks!


#2

Never trust the client


#3

By the way, seems like you are doing it wrong. Should be:

if (location.host !== 'localhost:3000') {
   // Do login check
}

#4

Yes sorry. Bad habit.


#5

Is it possible for someone to hack this and fake the location.host? How could it be done? Forgive my ignorance.


#6

use Meteor.absoluteUrl() instead.
And yes, anything on the client can be changed. Always do serverside validation. Why not just register a login handler on the server?

Accounts.validateLoginAttempt(function (attempt) {
  if (Meteor.absoluteUrl() === 'http://localhost:3000') {
  }
});

#7

thanks @corvid. that helps a lot.

think i need to work through implementing this for proper environment detection:
https://github.com/awatson1978/meteor-cookbook/blob/master/cookbook/environment-detection.md


#8

Meteor.absoluteUrl() uses ROOT_URL


#9

You should use Meteor.settings or explicitly set environment variables in your different project areas for this sort of thing.

This is a lot more maintainable as it essentially allows you to have predictable and server side controls for features and constraints.

Another tip would be to define what you are really asking.

If the url isn’t localhost then what does this really need to check:

  • If the app is running in a development environment
  • If the client has paid for X feature
  • If the app is running in a production environment
  • If the user is in an area where they need a login

It also makes the code easier to understand later