Skip to main content

How to declare an use a custom marker?

Vasyl MartyniukLess than 1 minute

AAM plugin and its premium add-on offers plethora of markers already that can cover most of the use-cases we are aware of. However, in some cases you might want to introduce a custom marker to enhance access policy functionality. A good example of a custom marker is IPSTACK that is declared by a premium add-on.

Let's take an example where you would like to allow visitors to access a certain page only if stock prices for company XYZ is higher than $40/share and redirect to a different page if below $40/share.

The policy may look like this:

{
    "Statement": [
        {
            "Effect": "deny",
            "Resource": "Post:page:company-xyz-stocks-rock",
            "Action": "Read",
            "Metadata": {
                "Redirect": {
                    "Type": "page",
                    "Slug": "company-xyz-stocks-suck",
                    "Code": 307
                }
            },
            "Condition": {
                "Less": {
                    "(*int)${TRADE_API.companyXYZ.price}": 40
                }
            }
        }
    ]
}

The statement above denies access to the page "Company XYZ Stocks Rock" by redirecting to a different page "Company XYZ Stocks Suck" only if the condition meets - price per share is less than $40.

Now, because AAM does not understand what the TRADE_API is, you have to declare this marker end explain how to process it. The following PHP code will do the trick:

add_filters('aam_policy_token_value_filter', function($value, $source, $path, $args) {
    // This function receives following values:
    // - $value  = null
    // - $source = "TRADE_API"
    // - $path   = "companyXYZ.price"
    // - $args   = array or inline arguments. To learn more, refer to the
    //             https://aamportal.com/reference/json-access-policy/marker/args

    if ($source === 'TRADE_API') {
        list($company, $property) = explode('.', $path);

        // Call the Stock Exchange API of your choice and pull the information about
        // the company XYZ. Update the returning $value with numeric price.
    }

    return $value;
}, 10, 4)
Virtual Assistant