A little trick to authenticate our users in WordPress

Lately in Nannuka we had a need for an internal website for our emploee announcements and documentation.

We had three options:

  • Buy a license to a platform (like Confluece) and connect it to our backend to handle the authentication – That’s a very elegant solution, but with a cost
  • Create a new section in our administration panel and post everything we want there – That would require development resources (and it’s like reinventing the wheel)
  • Setup an open source solution and just create an authentication bridge

Since our favorite platform for anouncements etc. is WordPress, we decided to go for the third option.

Our “trick” to authenticate our users was so simple that we decided to post it here for anyone that might need something similar.

To begin, we found a wordpress theme that we liked and fits our needs. Let’s say it was twentyseventeen. We created a child theme based on it (let’s call it “Nannuka Docs”). So, we have a style.css file looking like this:

/*
Theme Name: Nannuka Docs
Theme URI: https://techblog.nannuka.com
Description: Our child theme
Author: Nannuka
Author URI: https://techblog.nannuka.com
Template: twentyseventeen
Version: 1.000
*/

@import url("../twentyseventeen/style.css");

and just like that we have our own theme.

The next step is to handle the authentication. We created a functions.php file similar to this:

<?php
/**
 * Nannuka Docs Functions
 *
 * @since 1.0
 */
session_start();

define (URL, 'Here is a URL in our administration panel');
require_once ('Here is the path to the class that handles authentication in our administration panel');


if (!isset($_SESSION['user'])) {
    header('location: ' . URL);
    die();
}
if ($_SESSION['user']->usertype < 90) {
    header('location: ' . URL);
    die();
}

if ( Various other checks on the object ) {
    header('location: ' . URL);
    die();
}

In other words, we just loaded the authentication class from our codebase, we didn’t make any modifications on it. When we load the theme, we check if an instance of that class is loaded in $_SESSION, and if it is we do some additional tests to see if the user can actually see the content. If any of the checks fail, we redirect the user to our administration panel, to a (very simple) special endpoint that helps with the authentication: If the user is not logged in, it displays a login form. If the user is logged in, it just inserts the authentication object to $_SESSION and redirects the user to the blog. What we actually share with our users is the url of that endpoint.

This trick is not a real secure authentication system, but it’s really simple and quick to setup. And it can be extended, depending on the needs.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.