Build a blog with Areto Node.js framework

Sign in form

The login form receives a email / password and finds the appropriate user account in the database.

Sign-in form

models/SignInForm.js

'use strict';
const Base = require('areto/base/Model');
module.exports = class SignInForm extends Base {
    // place methods here
};
module.exports.init(module);
const User = require('./User');

Validation of form needed to filter invalid input values.

models/SignInForm.js

...
static getConstants () {
  return {
    RULES: [
      [['email', 'password'], 'required'],
      ['email', 'email'],
      ['rememberMe', 'boolean'],
      ['password', 'string', {min: 6, max:24}]
     ]
  };
}
...

The login method checks the form data. If there are no errors it passes control to the checkUser method that will search a user account in the database.

models/SignInForm.js

...
login (webuser, cb) {
  this.validate(err => {
    err || this.hasError() ? cb(err) : this.checkUser(webuser, cb)
  });
}
...

Look for user in checkUser by the unique login. This is the email. If the user with passed email exists, you will create a User instance. Its methods make further validate the user.

Pay attention to the same server response in cases of a non-existent user email and the wrong password. This disables the brute force of existing logins in the database.

In addition to authentication, the model checks account status. If a user is blocked, the server will return a message login error.

After successful validation webuser.login binds the current user's session to found a model. If the rememberMe flag is checked, the service's data will be added to the browser's cookies. It is required for automatic user log on to the given period (7 days).

models/SignInForm.js

...
checkUser (webuser, cb) {
  User.find({email: this.get('email')}).one((err, model)=> {
    if (model) {
      if (model.validatePassword(this.get('password'))) {
        if (model.isBanned()) {
          this.addError('email', 'This account banned');
        }
      } else {
        this.addError('password', 'Invalid authentication');
      }
    } else {
      this.addError('password', 'Invalid authentication');
    }
    this.hasError()
      ? cb()
      : webuser.login(model, this.get('rememberMe') ? 3600 * 24 * 7 : 0, cb);
  });
}
...