Build a blog with Areto Node.js framework

Security controller

The blog's user has the following actions: sign up, sign in or sign out. All of them are united in the security controller.

controller/AuthController.js

const Base = require('../component/BaseController');
module.exports = class AuthController extends Base {
  static getConstants () {}
  async actionSignUp () {}
  async actionSignIn () {}
  async actionLogout () {}
};
module.exports.init(module);

Captcha

In addition to the internal methods, controller actions can be defined as a separate class. It uses a constant ACTIONS. Name of the captcha property determines the route. Prop's value determines parameters to create a class instance. In this case, the class action is a captcha to protect our blog from automatic registration.

controller/AuthController.js

static getConstants () {
  return {
    ACTIONS: {
      'captcha': {
        Class: require('areto/captcha/CaptchaAction'),
        minLength: 3,
        maxLength: 4,
        // fixedVerifyCode: '123'
      }
    },
    BEHAVIORS: {
      'rejectSigned': {
        Class: require('areto/filter/AccessControl'),
        rules: [{
          actions: ['sign-in', 'sign-up'],
          roles: ['?']
        }],
        denyPromise: (action, user)=> {
          return action.render('signed', {
            model: user.model
          });
        }
      }
    }
  };
}

Sign up

Registration and authentication is available for anonymous (isGuest) users only. Logged user will get the name and exit link.

The SignUpForm form model is instantiated to sign up. If the current request already contains form data (isPost), the model gets these values and calls registration method. Otherwise, the blank form is displayed.

If errors occur the current form is displayed with a warning message. If successful, the guest user is redirected to the login page.

controller/AuthController.js

async actionSignUp () {
  let model = new SignUpForm({
    user: this.user
  });
  if (this.isGet()) {
    return this.render('sign-up', {model});
  }
  model.captchaAction = this.createAction('captcha');
  model.load(this.getBodyParams());
  await model.register();
  return model.hasError()
    ? this.render('sign-up', {model})
    : this.goLogin();
}

Authentication

To access the blog functionality visitors use the authentication form. After successful validation, users are forwarded to the initiated page.

controller/AuthController.js

async actionSignIn () {
  let model = new SignInForm({
    user: this.user
  });
  await model.resolveCaptchaScenario();
  if (this.isGet()) {
    return this.render('sign-in', {model});
  }
  model.captchaAction = this.createAction('captcha');
  await model.load(this.getBodyParams()).login();
  return model.hasError()
    ? this.render('sign-in', {model})
    : this.goBack();
}

Sign out

controller/AuthController.js

async actionLogout () {
  await this.user.logout();
  this.goHome();
}