Understanding Angular JS promises

Promises are one of the most powerful concepts for Angular and JavaScript. They enable your application to perform other tasks while waiting for the result of another operation. According to the official documentation, A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.

When do we use promises?

When we need to make a request, load some data or perform some other sort of operation, but we don’t know when / if we get the result.

There are three possible outcomes to making a promise request. First two are a promise that was fulfilled : Success, we get the expected result OR Error, we get a false of some sort.

The final option is the promise was rejected, an error was thrown.

This is all fine, but personally I’ve had a few issues first understanding promises, so let’s try to explain these in a simple way:

Promises and your tax return

Since the new fiscal year started, let’s do a tax return story.

We need to submit our tax returns, so we do this by using an accountant.

We get all our documents and then we give them to our accountant. She promises she will get the outcome in 3 working days.

That’s our request done and since we don’t just hang around the accountant’s office, we can do all sorts of other things, since the request is asynchronous.

So a few days later we get one of the possible outcomes from the accountant:

  1. The accountant says all documents are there, your tax return has been submitted, so we have a success.
  2. He tells us not all documents are here, some are missing and we need to fix it first, so we have an error, but a proper response from our request.
  3. The accountant has taken all our documents and those of other clients, emptied their bank accounts (not ours, phew…) and left to a third party unnamed tropical country without an extradition treaty to enjoy the illegal proceeds and have a relaxing life ūüôĀ ohhh…. So we don’t even get a reply to our request… plus… we don’t have copies of our receipts! Ouch…

Hopefully that clears it up a bit. But let’s look at some actual code.

Here are the controller and the service:

Controller:

//function in accountantController.js
var startAccountantPromise = function() {
    //Imagine we have an accountantService somewhere that handles the requests and other operations.
    //This function returns a promise which we will deal with here    
    accountantService.submitTaxReturn()
        // then() - this function is always called when we get a response
        .then(function(data) {
            // our promise was fulfilled. We don't know which of the possible outcomes though, so we need to check
            if (data.taxReturn === 'accepted') {
                //weeeee, all good, so we... get on with our lives
                enjoyLifeAndRelax();
            } else {
                // since the status is not 'accepted' it can be other stuff so... we need to check for missing documents
                checkMissingTaxReturnDocuments();
            }
        }, function(error) {
            //the final option is the promise was rejected, caused by some sort of error
            //we can log to the console like this : console.log('error', error);
            startPanicking();
        });
};

So that’s the controller, but that uses some functions that we need to see.

Service

app.factory('accountantService', function ($http, $q) {
    return {
        submitTaxReturn: function() {            
            //the $http API is based on the deferred/promise APIs exposed by the $q service and it returns a promise by default
            //documentation here : https://docs.angularjs.org/api/ng/service/$http
            return $http.get('http://honest-accountant-api-service.com/submit-your-tax-return')
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        //oops, invalid response...
                        return $q.reject(response.data);
                    }
                }, function(response) {
                    //something went wrong, where is our accountant?!?!?
                    return $q.reject(response.data);
                });
        }
    };
});

Summary

Hopefully this little story demonstrated the asynchronous nature of the request we make. We don’t need to wait at the accountant’s office, we can perform other operations in the meantime.

When we give our documents we immediately get a promise, so we expect to hear back at some point.

The accountant is dealing with our request and all the operations on that end are abstracted from us as financial stuff is wizardry. We don’t need to know how the stuff is resolved, we only need to hear back the result.

ūüôā


Fail2ban : Block WordPress brute force attacks

The Internet is a dangerous place so you might find yourself on the receiving end of a brute force attack.¬†WordPress’ popularity virtually guarantees that will happen to your (WordPress) site, sooner or later.

My sites get hit at least once a week and I have clients who are constantly under attack.

Once you are getting brute forced, you could easily block the offender by IP address, with iptables, like this

iptables -A INPUT -s 111.222.111.222 -j DROP

That will work, however doing this manually every time gets quite tricky, next to impossible.

A good solution is to automate this, using fail2ban (there are other options of course, but outside of the scope of this article).

fail2ban monitors your log files and when it matches certain rules (like too many login attempts, scanning directories etc.) it can take action by creating firewall rules (like the one above). That will block the offending IP from accessing your server in any way (ftp, http, ssh, etc.).

Installing fail2ban

If you don’t already have fail2ban installed, you can do it easily from command line:

sudo apt-get install fail2ban

or if you are using CentOS (or similar flavour) , first add the repo

rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm

Then install

yum install fail2ban

This is not a complete guide on installing fail2ban, but rather configuring a few rules specifically to protect a WordPress site.

Resources abound on the topic of installing fail2ban. Also, after setting up, make sure your install monitors your logs as they can vary depending on setup (in jail.local, in your rule files [filter.d directory]).
I run servers with individual logs per domain, shared logs and so on, so your mileage may vary. If you need some help setting it up, drop me a line.

Creating a fail2ban rule

After we have (if not already) installed fail2ban, we need to create rules (it comes with default ones too).
The rules are made up of regular expressions, called failregex that match the logs we are monitoring.

Protecting wp-login

Most of the attempts to brute force go to the wp-login page, so we are protecting this first.
The rule I have for this is saved in the file (on my setup) /etc/fail2ban/filter.d/wp-login.conf
It contains

# WP brute force attacks filter
 [Definition]
 failregex = ^<HOST> .* "POST .*wp-login.php
 ignoreregex =

This matches POST requests to wp-login.php
If there are 5 or more matches (my jail.local config is 5, defaults are found in jail.conf), it automatically blocks the offending IP.

Protecting xmlrpc.php attempts
This file is another source of trouble. Same as the wp-login rule, I create a new rule under /etc/fail2ban/filter.d/wp-xmlrpc.conf
It contains:

# WP brute force attacks filter
[Definition]
failregex = ^<HOST> .* "POST .*xmlrpc.php
ignoreregex =

As you can see, both rules are quite basic but do the job.

We created the rules, but we haven’t tested them.¬†So let’s test before we enable.¬†Testing uses the following syntax:

fail2ban-regex <logfile> <fail2ban rule to test>

For example:

fail2ban-regex /var/log/apache2/access.log /etc/fail2ban/filter.d/wp-login.conf

If there are any matches in the logfile, the test should output some matches and IP addresses.

We can clearly see the bots have been quite busy hammering this server. All quiet after adding the rule.

90146 hit(s): Day/MONTH/Year:Hour:Minute:Second
Success, the total number of match is 6532

I always test the rules before enabling them. Having rules that don’t work is not very useful.

After creating and testing these new rules, we need to enforce them.

Edit¬†/etc/fail2ban/jail.local (if file doesn’t exist, create it. Do not do your local changes in jail.conf) and add¬†the following:

[wp-login]
enabled = true
port = http,https
action = iptables-multiport[name=WP, port=http, protocol=tcp]
filter = wp-login
logpath = /var/log/apache2/access.log
maxretry = 5

[wp-xmlrpc]
enabled = true
port = http,https
action = iptables-multiport[name=WP-xmlrpc, port=http, protocol=tcp]
filter = wp-xmlrpc
logpath = /var/log/apache2/access.log
maxretry = 5
bantime=3600

What we are doing: enabling rules, specifying which logs to check and what action to take. If we do not specify things like bantime,
that setting will default to what ever your default it. As you can see, for one I did specify, for the other one, I left to default.

Ok then, so we have created and enabled our rules so now we need to restart fail2ban (fingers crossed).

Restart:

service fail2ban restart

Then let’s check it is now runing

service fail2ban status

I tend to do this, just to double check there wasn’t a silent fail start.

Checking rules work

With the fail2ban rule now active, login attempts to wp-login.php should now get blocked in the iptables firewall. Same for attempts
on xmlrpc.php

You can check the list of blocked ip adresses in iptables with this command:

iptables -L

What if fail2ban doesn’t start

Sometimes it happens that we misconfigured something. We will see no error logs when starting (and failing) so we need to diagnose:

fail2ban-client -x start

This will show us logs of what’s happening. Also we can use this to deal with any warnings, though not necessary.

Hopefully this has given you some extra information on dealing with all the nasty people out there wanting your site logins…


Angular JS, Understanding $emit, $broadcast and $on

In late 2015 I started working with Angular JS as part of a project at work (Hybrid mobile app).

Understanding the concepts is quite important to make use of it in an efficient and extendable way.

Angular JS provides us with some events that we can use to communicate between controllers.

They are $on, $emit and $broadcast.

Here is a quick schematic on the direction of the events.

$on

When using $on, Angular listens to an event of a given type. We can call it anyway we want. $on will catch any event dispatched by $emit or $broadcast.

Real life example from a hybrid app:

$scope.$on(AUTH_EVENTS.notAuthorized, function(event) {
 //do something to block the unauthorized page view attempt
 });
});

(AUTH_EVENTS is a constant we are using in our app)

So what happens and how / where does this happen?

In an authentication service, the user is checked if logged in. If he / she is not, we will emit an event which will block the unauthorized page view.

So we need to broadcast this event:

$scope.$broadcast('AUTH_EVENTS.notAuthorized', { ... });

Since we mentioned broadcast, let’s quickly go through that.

$broadcast

Broadcast dispatches an event name downwards to all child scopes (and their children) notifying the registered $rootScope.Scope listeners.

$broadcast(name, args);

The event cannot be cancelled. The event starts at the scope on which $broadcast was called. All listeners for the event get notified, all events under the scope.

$emit

 is pretty much the same thing, just in reverse (going upwards into the $scope).

It will traverse all the $scopes until the $rootScope.

Unlike the $broadcast event, this one can be cancelled by any of the listeners.

Do try to keep the $rootScope clean ūüôā


Update WordPress and plugins

As you probably already know, WordPress is a Content Management System (CMS) and as any software, it gets updates every now and then. The same applies to plugins built for WordPress. Software in general is not static.

Regardless of how many or how few plugins we have, every now and then our site (even if very static) requires a bit of care.

Why do I need to update?

WordPress and plugins (and themes) are just like software running on your computer or apps on your phone. They require updates which fix bugs or add new features. Without going into too much details, usually newer is better.

How do I know when to update?

Although important, daily life gets in the way and I am sure we can’t go around checking for updates every day. If you do find yourself in the admin, you can see if updates exist as in the image below:

Updates Available Example

You can see this site has 7 Updates (yikes). This also includes themes, plugins and WordPress itself.

Updating either of these is rather simple.

Update WordPress

As suggested and recommended practically everywhere, a good idea is to make a backup. Always always backup!

Wordpress Update Now

So, long story short, as you can see all you need to do is click the button ‘Update Now’ and WordPress will be updated.

The update will now begin and you need to wait until it finishes.¬†Sometimes we need to log back in and occasionally we need to also perform a database update. Again it’s just a butoon.

Remember, WordPress also does automatic updates, however these are only security updates (from 3.9 to 3.9.1, but not to version 4).

Other settings

It is possible to have custom settings and they require you to edit the wp-config.php file. This file is located in the root folder of WordPress.
define(‘AUTOMATIC_UPDATER_DISABLED’, true); //¬†this will deactivate all automatic¬†updates

define(‘WP_AUTO_UPDATE_CORE’, true); //¬†this will enable all automatic updates, including major releases.¬†use with care!!!Use either one or the other.

WP_AUTO_UPDATE_CORE ‚Äď you can set two values,¬†true or false. The second option is really the default, so unnecessary, but good to be aware of possibilities.

If you don’t want to touch the wp-config.php file, you can apply the same settings via filters:

add_filter('automatic_updater_disabled', '__return_true'); //deactivate automatic updates

You can use other filters, they all accept true or false values.

add_filter('allow_minor_auto_core_updates', '__return_false'); // Deactivate automatic minor / security updates
add_filter('allow_major_auto_core_updates', '__return_true'); // Activate automatic updates
add_filter('allow_dev_auto_core_updates', '__return_true'); // Activate automatic updates, dev version. Not recommended on production websites

Manually updating WordPress when automatic updates fail

I recommend you do updates automatically, however sometimes depending on server setup and other things, it’s not possible.

So… if we need to do manual updates keep this in mind: all files need be properly updated, an incomplete transfer can leave you with an unusable website.

These are the steps I take (keeping it simple is better).

Before you start, remember, backup backup backup ūüôā

  1. Download the latest version of WordPress. You can do that from wordpress.org or use the link from the Dashboard (there is a button which lets you download the archive). After download, unzip the .zip file.
  2. Optional:¬†you can delete the wp-includes¬†and¬†wp-admin folders.¬†I don’t bother, just overwrite these folders and files.
    DO NOT touch the wp-content folder
  3. I am assuming you are using FTP, but other methods work as well, but not covered here : Upload the files and overwrite all existing ones. Even if you upload wp-content,¬†the already existing files in there that you uploaded, plugins, images etc. won’t be touched.
  4. Do the same with the files at the root of the wordpress installation / unzipped folder. DO NOT touch wp-config.php.
  5. Optional, especially when things go wrong, know there is a file called .maintenance created by WordPress during the update. If it goes wrong, that file can stay there, even if you did a manual update afterwards. If you go and delete the file, your site will go off maintenance mode.
  6. Optional: sometimes your database needs updates. There is a button which says as much, so click that and that’s it.

The above steps are what I normally do if auto-updates are not possible on a setup.

Things can go wrong so be careful the first few times you do this.

Updating themes and plugins

So far you must have noticed the pattern here: everything is dead simple with WordPress.

When you have plugins or theme updates, just go to Dashboard > updates or Themes / Plugins and you cand see available updates.

There is a button called Update Themes or Update plugins

Here’s the proof ūüôā

Examplu actualizari plugin si teme

Just like WordPress itself, these updates are also done immediately as we push the button.

While the update runs, we will see a page that feeds us information regarding the update progress.

Automatically updating plugins and themes

If you like to live on the dangerous side, fear not, you can setup your site to do automatic updates for plugins and themes. Maybe not always the best idea, if something goes wrong, your site might become completely unusable.

So… by default the only automatic updates are for WordPress security releases. Just like other settings, these can also be changed from the theme functions.php (each theme has a file functions.php, ¬†in which we can add the below code snippets)

add_filter('auto_update_plugin', '__return_true'); // This will activate all automatic plugin updates

add_filter('auto_update_theme', '__return_true'); // This will activate all automatic theme updates

That’s how it’s done, we don’t use wp-config.php, with this one better stick to¬†functions.php.

Manually updating plugins or themes

Sometimes we need to do manual updates for plugins or themes, probably because your setup doesn’t allow you do automated ones. In that case you probably can’t update WordPress itself. It’s hard work, but it builds character…

What ever the reason, manual update of plugins or themes is done the same way as the WordPress manual update: overwrite the old files with the new ones.

That’s it.

Oh yes, make sure you backup… before…

Plugins are located in the wp-content/ folder

Some are just single files, most of them are in a directory.

Themes are under wp-content as well, then /themes.

Since we’re all lazy, the lazy man’s way

Maybe should’ve started with this, but¬†good things come to those who wait ūüôā

If what you read above makes you uncomfortable and you don’t want to edit settings from¬†functions.php or¬†wp-config.php all by yourself, there is the lazy man’s way.

Just like phones, there’s an app for everything, so we have a plugin called¬†WP Updates Settings. This one allows you to edit settings in the admin.

You don’t want to check for updates, take a look at my friend’s plugin:¬†WP Updates Notifier. Quite good, does what it says it does.

Other nice tools to consider are ManageWP, InfiniteWP, WP Remote, MainWP and then you have Plesk 12 WordPress Toolkit.

To sum up

It’s quite important to have the latest version and hopefully this provided you with the knowledge you need.

If you need my help, please contact me.
If not, good luck ūüôā