Authorization in frontend

Contents...

Webasyst framework allows app developers to implement signup and login options for website visitors.

For a working example, look at the Guestbook 2 app in which the authorization system for frontend users described below is implemented.

Enabling authorization on the website

Authorization is set up individually for each website, connected to a Webasyst account, in the Site app, which stores authorization configuration in file wa-config/auth.php:

  <?php

  return array(
      'domain1.com' => array(
            // enables authorization on the website; in design theme templates its current status is returned by function $wa->isAuthEnabled()
          'auth' => true,
            // app responsible for signup & login
            // the specified app must support authorization, i.e. its configuration file app.php must contain 'auth' => true)
          'app' => 'blog',
          // authorization adapters for external services
          'adapters' => array(
              'facebook' => array (
                  'app_id' => 'FACEBOOK_APP_ID',
                  'app_secret' => 'FACEBOOK_APP_SECRET',
              ),
              // ... other adapters
          ),
          /*
          Array defining the set of fields for the signup form
          If not specified explicitly, the following fields are used by default:
          'fields' => array(
              'firstname',
              'lastname',
              '', // separator
              'email',
              'password', //"enter password" and "re-enter password" fields
          )
          */
      ),
      'domain2.com' => array(
          // ... similar settings for some other domain2.com website
      )
  );
  

The set of signup fields is controlled by array item with key 'fields'. The following values are acceptable:

  • 'name': full name;
  • 'sex';
  • 'birthday',
  • 'phone.mobile' phone number field with a sub-field name; e.g., 'mobile', 'work', etc;
  • 'url' website URL;
  • 'address': composite field consisting of several sub-fields: street address, locality (city), region (state), country, postal ZIP code;
  • 'im.telegram' with a social media or online messenger identifier; e.g., 'telegram', 'whatsapp', 'facebook', etc.

See information about other available fields in file wa-system/contact/data/fields.php.

Authorization and signup for website visitors

The design and functionality of authorization forms is defined by a specific app; therefore, they are connected website pages not at the system level but in the source code of authorization handling apps. The framework offers ready-to-use tools for convenient connection of such forms within an app, but their specific location on a page, design, and actual content are defined solely by an app developer.

  1. In file wa-apps/[app_id]/lib/config/app.php the following entry must be added to declare that your app supports authorization:

    'auth' => true,

    Your app must also have a frontend:

    'frontend' => true,
  2. Create 3 action classes responsible for the functioning of the login form, the signup form, and the password recovery form as described below.

Authorization form

Create file wa-apps/[APP_ID]/lib/actions/[APP_ID]Login.action.php

<?php

class [APP_ID]LoginAction extends waLoginAction
{
    public function execute()
    {
        // general website page layout
        $this->setLayout(new myappFrontendLayout());

        // use login form template
        $this->setThemeTemplate('login.html');

        // execution of the parent class implementing common authorization logic
        parent::execute();
    }
}

In the design theme create file login.html with the authorization form.

{$wa->loginForm()}

Signup form

Create file wa-apps/[app_id]/lib/actions/[app_id>]Signup.action.php.

<?php

class [APP_ID]SignupAction extends waSignupAction
{
    public function execute()
    {
        // common website page layout
        $this->setLayout(new myappFrontendLayout());

        // use signup form template
        $this->setThemeTemplate('signup.html');

        // call parent class method with common signup logic
        parent::execute();
    }

    /**
    * This method is called after successful creation of a new contact.
    * You can modify it to send an greeting message to the newly registered user, for example,
    * or add the contact to the app's system category
    */
    public function afterSignup(waContact $contact)
    {
        $contact->addToCategory($this->getAppId());
    }
}

In the design theme create file signup.html with the signup form.

{$wa->signupForm($errors)}

Password recovery form

This action is responsible for the functioning of the password recovery form and for setting a new password upon a click on the password resetting link sent to the user by email.

To create those form, create action file wa-apps/[APP_ID]/lib/actions/[APP_ID]Forgotpassword.action.php

class [APP_ID]ForgotpasswordAction extends waForgotPasswordAction
{
    public function execute()
    {
        // common website page layout
        $this->setLayout(new myappFrontendLayout());

        // use signup password recovery template
        $this->setThemeTemplate('forgotpassword.html');

        // call parent class method with common password recovery logic
        parent::execute();
    }
}

Also create template file wa-apps/[APP_ID]/>themes/default/forgotpassword.html ( $set_password is equal to true, if a new password should be entered; otherwise the login form is displayed):

{if !empty($set_password)}
    {* If $set_password contains true then show the form to enter a new password *}
    {$wa->setPasswordForm()}
{else}
    {* Otherwise show the form to enter an email address *}
    {if !empty($sent)}
        <p>Password recovery instructions have been sent to your email address.</p>
        <p><a href="{$wa->loginUrl()}">I remember my password!</a></p>
    {else}
        {$wa->forgotPasswordForm()}
    {/if}
{/if}

Internal app routing

These classes for the authorization, signup and password recovery forms must then be settled in the app’s internal routing system — specify their addresses in configuration file wa-apps/[app_id>]/lib/config/routing.php.

<?php

return [
    // authorization form
    'login/' => 'login', // when URL login/ is requested then class myappLoginAction will be called

    // password recovery form
    'forgotpassword/' => 'forgotpassword',

    // signup form
    'signup/' => 'signup',

    //... other routing rules for your app’s frontend ...
];

Now only have to settle your app to one of your websites using the Site app, enable authorization for that website, and select your app for handling authorization.


Methods of the $wa object

For convenient access to authorization and signup functions, the $wa object in Smarty templates offers the following methods:

  • isAuthEnabled

    Returns the status of the authorization setting for the current website.

  • signupUrl

    Returns the signup page URL.

  • loginUrl

    Returns the authorization page URL.

  • forgotPasswordUrl

    Returns the password recovery page URL.

  • signupForm

    Returns the signup form’s HTML code.

  • loginForm

    Returns the authorization form’s HTML code.

  • forgotPasswordForm

    Returns the password recovery form’s HTML code.

  • setPasswordForm

    Returns the HTML code of the form for entering a new password during the password recovery.

  • authAdapters

    Returns information about the setup third-party authorization adapters.

isAuthEnabled()

Returns the status of the authorization setting for the current website.

Example

{if $wa->isAuthEnabled()}
      <!-- Authorization is enabled on this website! -->
  {/if}

signupUrl ($absolute = false)

Returns the signup page URL.

Parameters

  • $absolute

    Flag denoting the necessity to return an absolute URL.

Example

{$relative_signup_page_url = $wa->signupUrl()}
  {$absolute_signup_page_url = $wa->signupUrl(true)}

loginUrl ($absolute = false)

Returns the authorization page URL.

Parameters

  • $absolute

    Flag denoting the necessity to return an absolute URL.

Example

{$relative_login_page_url = $wa->loginUrl()}
  {$absolute_login_page_url = $wa->loginUrl(true)}

forgotPasswordUrl ($absolute = false)

Returns the password recovery page URL.

Parameters

  • $absolute

    Flag denoting the necessity to return an absolute URL.

Example

{$relative_password_recovery_page_url = $wa->forgotPasswordUrl()}
  {$absolute_password_recovery_page_url = $wa->forgotPasswordUrl(true)}

signupForm ($errors = [], $options = [])

Returns the signup form’s HTML code.

Parameters

  • $errors

    Array of error messages which must be displayed in the form. In a Smarty template, this array is available via the $errors variable.

  • $options

    Array of form’s appearance and behavior parameters with the following keys:

    • show_title: Flag denoting the necessity to display the form title. The default value is false.
    • namespace: Common request parameter name via which all form fields’ values can be accessed in the server-side code. By default no value is specified.
    • show_oauth_adapters: Flag denoting the necessity to display third-party authorization services’ buttons in the form. The default value is false.
    • need_redirects: Flag denoting the necessity to redirect a user upon the signup to the page from the user proceeded to the signup. The default value is true.
    • need_placeholders: Flag denoting the necessity to show the values of placeholder attributes for text fields. The default value is true.
    • include_css: Flag denoting the necessity to include default CSS styles in the HTML code of the form. The default value is true.
    • contact_type: The type with which a new contact must be saved during the signup:
      • person (default),
      • company

Example

{$wa->signupForm([], [
      'show_title'          => true,
      'show_oauth_adapters' => true,
      'namespace'           => 'fields',
      'need_redirects'      => false,
      'need_placeholders'   => false,
      'contact_type'        => 'company'
  ])}

loginForm ($errors = [], $options = [])

Returns the authorization form’s HTML code.

Parameters

  • $errors

    Array of error messages which must be displayed in the form. In a Smarty template, this array is available via the $errors variable.

  • $options

    Array of form’s appearance and behavior parameters with the following keys:

    • title: Custom text title to replace the default form title.
    • sub_title: Custom text subtitle to be displayed under the main form title.
    • show_title: Flag denoting the necessity to display the form title. The default value is false.
    • show_sub_title: Flag denoting the necessity to display the form subtitle. The default value is false.
    • namespace: Common request parameter name via which all form fields’ values can be accessed in the server-side code. By default no value is specified.
    • show_oauth_adapters: Flag denoting the necessity to display third-party authorization services’ buttons in the form. The default value is false.
    • need_redirects: Flag denoting the necessity to redirect a user upon the authorization to the page from the user proceeded to the authorization. The default value is true.
    • need_placeholders: Flag denoting the necessity to show the values of placeholder attributes for text fields. The default value is true.
    • include_css: Flag denoting the necessity to include default CSS styles in the HTML code of the form. The default value is true.
    • url: Custom URL, instead of the default one, to which authorization form data must be sent.

Example

{$wa->loginForm([], [
      'show_title'          => true,
      'title'               => 'My title',
      'show_sub_title'      => true,
      'sub_title'           => 'My subtitle',
      'show_oauth_adapters' => true,
      'namespace'           => 'fields',
      'need_redirects'      => false,
      'need_placeholders'   => false,
      'include_css'         => false
  ])}

forgotPasswordForm ($errors = [], $options = [])

Returns the password recovery form’s HTML code.

Parameters

  • $errors

    Array of error messages which must be displayed in the form. In a Smarty template, this array is available via the $errors variable.

  • $options

    Array of form’s appearance and behavior parameters with the following keys:

    • title: Custom text title to replace the default form title.
    • sub_title: Custom text subtitle to be displayed under the main form title.
    • show_title: Flag denoting the necessity to display the form title. The default value is false.
    • show_sub_title: Flag denoting the necessity to display the form subtitle. The default value is false.
    • namespace: Common request parameter name via which all form fields’ values can be accessed in the server-side code. By default no value is specified.
    • show_oauth_adapters: Flag denoting the necessity to display third-party authorization services’ buttons in the form. The default value is false.
    • need_redirects: Flag denoting the necessity to redirect a user upon the password recovery to the page from the user proceeded to the password recovery. The default value is true.
    • need_placeholders: Flag denoting the necessity to show the values of placeholder attributes for text fields. The default value is true.
    • include_css: Flag denoting the necessity to include default CSS styles in the HTML code of the form. The default value is true.

Example

{$wa->forgotPasswordForm([], [
      'show_title'          => true,
      'title'               => 'My title',
      'show_sub_title'      => true,
      'sub_title'           => 'My subtitle',
      'show_oauth_adapters' => true,
      'namespace'           => 'fields',
      'need_redirects'      => false,
      'need_placeholders'   => false,
      'include_css'         => false
  ])}

setPasswordForm ($errors = [], $options = [])

Returns the HTML code of the form for entering a new password during the password recovery.

Parameters

  • $errors

    Array of error messages which must be displayed in the form. In a Smarty template, this array is available via the $errors variable.

  • $options

    Array of form’s appearance and behavior parameters with the following keys:

    • title: Custom text title to replace the default form title.
    • sub_title: Custom text subtitle to be displayed under the main form title.
    • show_title: Flag denoting the necessity to display the form title. The default value is false.
    • show_sub_title: Flag denoting the necessity to display the form subtitle. The default value is false.
    • namespace: Common request parameter name via which all form fields’ values can be accessed in the server-side code. By default no value is specified.
    • show_oauth_adapters: Flag denoting the necessity to display third-party authorization services’ buttons in the form. The default value is false.
    • need_redirects: Flag denoting the necessity to redirect a user upon the password recovery completion to the page from the user proceeded to the password recovery. The default value is true.
    • need_placeholders: Flag denoting the necessity to show the values of placeholder attributes for text fields. The default value is true.
    • include_css: Flag denoting the necessity to include default CSS styles in the HTML code of the form. The default value is true.

Example

{$wa->setPasswordForm([], [
      'show_title'          => true,
      'title'               => 'My title',
      'show_sub_title'      => true,
      'sub_title'           => 'My subtitle',
      'show_oauth_adapters' => true,
      'namespace'           => 'fields',
      'need_redirects'      => false,
      'need_placeholders'   => false,
      'include_css'         => false
  ])}

authAdapters ($return_array = false, $options = [])

Returns information about the setup third-party authorization adapters.

Parameters

  • $return_array

    Flag denoting the necessity to return an array with third-party authorization adapters’ parameters. If true is not specified then the method returns the HTML code of authorization buttons to be displayed on the website.

  • $options

    Array of parameters of third-party authorization forms’ display and behavior parameters with the following keys:

    • width: Width of a popup window, in pixels, which will open during the authorization via any third-party service.
    • height: Height of a popup window, in pixels, which will open during the authorization via any third-party service.
    • [authorization adapter identifier]: Array with keys width and height containing custom width and height of a popup window displayed during the authorization with the specified service. Its own sub-array with these keys can be added for each of the authorization services if they must be different from common dimensions.

Example

{* Show third-party services’ authorization buttons *}
  {$wa->authAdapters(false, [
      'width'  => 700,
      'height' => 600,
      'google' => [
          'width'  => 750,
          'height' => 650
      ]
  ])}

Authorization via external services (social networks)

Webasyst framework offers an option to set up authorization for website visitors via third-party services (social media). This functionality is implemented with the use of authorization adapters. You can show buttons for this authorization option with the use of the {$wa->authAdapters()}) method or by passing a parameter with the 'show_oauth_adapters' key when using methods displaying authorization-related forms.

How to verify user authorization

You can hide certain content on website pages and show it only to registered clients by checking user’s authorization as described below.

PHP

In actions/controllers:

// in actions & controllers
if ($this->getUser()->getId()) {
    // user is authorized
}

// in other places
if (wa()->getUser()->getId()) {
    // user is authorized
}

Smarty

{if $wa->userId()}
    {* user is authorized *}
{/if}