Question

I have a form that when you click submit it goes to the path /signin no matter what, even if you don't enter anything into the form. However I want it to check if there is a user with the email entered and if their password is correct before going to /signin. If the email is not known or the password is not correct then I want it to display an error (and stay on the log in page). I've been trying to get this to work but I'm not sure how to do it. Does anyone know how to do this? This is the code I have so far:

html:

<div id="topbar">
  <h1><strong>chattly</strong></h1>
        {{#unless currentUser}}
            {{> signIn}}
            {{> alert}}
        {{else}}
            {{> signOut}}
        {{/unless}}
    </div>

javascript:

// Sign In Template
Template.signIn.events({
    'submit #signInForm': function(e, t) {
        e.preventDefault();

        var signInForm = $(e.currentTarget),
            email = trimInput(signInForm.find('.email').val().toLowerCase()),
            password = signInForm.find('.password').val();

        if (isNotEmpty(email) && isEmail(email) && isNotEmpty(password) && isValidPassword(password)) {
            Meteor.loginWithPassword(email, password, function(err) {
                if (err) {
                    Session.set('alert', 'We\'re sorry but these credentials are not valid.');
                } else {
                    Sesson.set('alert', 'Welcome back New Meteorite!');
                }
            });
        }
        return false;
    },
});
Was it helpful?

Solution

You tagged this with iron-router so I assume you are using the iron router package.

You could prevent un-authenticated users from getting to any page beyond your login page by using before hooks on all the routes for restricted pages. The before hook would check Meteor.user() if it doesn't return an object there is no user logged in and it could re-route to the login page.

Checkout the iron-router documentation, here is the section on before and after hooks. It even shows using a before hook as a filter to prevent un-authenticated users from going to a route.

https://github.com/EventedMind/iron-router/#before-and-after-hooks

It looks something like this:

Router.map(function () {
  this.route('postShow', {
    path: '/posts/:_id',

    before: function () {
      if (!Meteor.user()) {
        // render the login template but keep the url in the browser the same
        this.render('login');

        // stop the rest of the before hooks and the action function 
        this.stop();
      }
    },

    action: function () {
      // render the main template
      this.render();

      // combine render calls
      this.render({
        'myCustomFooter': { to: 'footer' },
        'myCustomAside': { to: 'aside' }
      });
    },

    after: function () {
      // this is run after our action function
    }
  });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top