Build a blog with Areto Framework

Sign in form

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

form


const CAPTCHA_SCENARIO = 'captcha';
const Base = require('areto/base/Model');

module.exports = class SignInForm extends Base {

const RateLimit = require('areto/security/rate-limit/RateLimit');
const PasswordAuth = require('../component/auth/PasswordAuth');

Validation of form needed to filter invalid input values.


static getConstants () {
  return {
    RULES: [
      [['email', 'password'], 'required'],
      ['email', 'email'],
      ['password', 'string', {min: 6, max:24}],
      ['rememberMe', 'boolean'],
      ['captchaCode', 'required', {on: [CAPTCHA_SCENARIO]}],
      ['captchaCode', {
        Class: require('areto/security/captcha/CaptchaValidator'),
        on: [CAPTCHA_SCENARIO]
      rememberMe: 'Remember me',
      captchaCode: 'Verification code'

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.


async login () {
  await this.validate();
  if (!this.hasError()) {
    let result = await this.createPasswordAuth().login();
    if (result.error) {
        this.addError('email', result.error);
    await this.updateRateLimit();

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).


constructor (config) {
    // user: [new WebUser]
    rateLimit: config.module.get('rateLimit'),
    rateLimitType: 'signIn',
    rememberPeriod: 7 * 24 * 3600,

createPasswordAuth () {
  return this.spawn(PasswordAuth, {
    email: this.get('email'),
    password: this.get('password'),
    rememberMe: this.get('rememberMe'),
    user: this.user

updateRateLimit () {
  if (this._rateLimitModel) {
    if (this.hasError()) {
      await this._rateLimitModel.increment();
    if (this.isCaptchaRequired()) { // captcha has been validated
      await this._rateLimitModel.reset();