Search code examples
javascriptmeteormeteor-blaze

Custom validation in Meteor.loginWithPassword


I have created a custom login page and used the Meteor.loginWithPassword(user, password, [callback]) function to login to the app. Js file is like this:

  Template.login.events({
    'submit form': function(event) {
        event.preventDefault();
        var emailVar = event.target.loginEmail.value;
        var passwordVar = event.target.loginPassword.value;
        Meteor.loginWithPassword(emailVar, passwordVar, function(error) {
            if (error) {

                Bert.alert(error.reason, 'danger', 'growl-top-right');
            } else {
                Router.go('/dashboard');
            }
        });
    }
})

And my HTML file is like this:

<template name="login">

          <div class="input-group">
            <span class="input-group-addon"><i class="fa fa-envelope"></i></span>
            <input type="email" name="loginEmail" class="form-control" placeholder= {{getLanguageValue "profile_email"}}>
          </div>
          <br>
          <div class="input-group">
            <span class="input-group-addon"><i class="fa fa-lock"></i></span>
            <input type="password" name="loginPassword" class="form-control" placeholder= {{getLanguageValue "myprofile_password"}}>
          </div>
          <button type="submit" class="btn btn-block btn-default"> Submit</button>

I need another validation in error.reason for checking blocked users. How can I do that?


Solution

  • The correct way of checking if a user is blocked is on the server. If he's blocked he shouldn't login at all.

    Once loginWithPassword is called in the client, validateLoginAttempt is called on the server. This way you can perform checks on the server and abort login by throwing an error or continue login by returning true.

    This is how I would do it:

    On the client (login.js)

    Template.login.events({
      'submit form': function(event) {
        event.preventDefault();
        var emailVar = event.target.loginEmail.value;
        var passwordVar = event.target.loginPassword.value;
        Meteor.loginWithPassword(emailVar, passwordVar, function(error) {
          if (error) {
            if (error.reason === 'Your account is blocked') {
              Bert.alert("This user is blocked by admin and can not login", 'danger', 'growl-top-right');
            } else {
              Bert.alert(error.reason, 'danger', 'growl-top-right');
            }
          } else {
            Router.go('/dashboard');
          }
        });
      },
    });
    

    On the server (server.js)

    Accounts.validateLoginAttempt((info) => {
      const user = info && info.user;
    
      if (user && user.profile && user.profile.isBlocked == 1) {
        throw new Meteor.Error(403, 'Your account is blocked');
      }
    
      return true;
    });