Checking access

In the world of Piano, we're all about access control. Piano can tell you whether or not a user has access to a resource. The length of access can last forever or can be fixed for 24 hours, 30 days, 2 weeks, etc. Piano allows publishers to define multiple ways to setup access to resources. See Creating terms.

There are only two states to think about when integrating Piano. Either the user has access or they do not have access.

Depending on your integration settings, there are multiple ways in which you can check access.

The following approaches are supported:

  • Access check via client-side javascript
  • Access check via server-side REST endpoints
  • Access check via server-side cookie
  • Access check via server-side local database

Client-Side Javascript

If you are only interested in a client-side implementation, you can perform an API call to check access in the page itself using javascript.

Be sure to read about how to initialize the Piano javascript on your pages, as this code snippet assumes that you have already embedded the tinypass.min.js javascript file on the page and properly initialized the tp.

tp.push(["init", function() {
    var params = {
        rid : "PREMIUM_ACCESS"
    };
    var callback = function(response) {
        if (response.access && response.access.granted) {
            // the user has access
        }
        else {
            // the user does not have access
        }
    }
    tp.api.callApi("/access/check", params, callback);
}]);

A client-side implementation can be easier to get up and running than setting up server-side checks. However, client-side implementations are inherently less secure due to the necessity that the browser have javascript enabled and, in most cases, the full content will be delivered to the browser before being obfuscated.

Our metered paywall product in our dashboard provides the option “Don’t track users coming directly from external sites” that when checked ensures that users that arrive at your site from an external site (such as search and social sites) will not increment the meter. We commonly refer to this as the “first click free” feature.

If you would like to replicate the “first click free” feature in a client-side implementation of a hard paywall we provide the below javascript function tpFirstClickFree() as our suggested solution. It first checks to see if the user came from one of the allowed domains (google.com, twitter.com, facebook.com) and returns “true” if that is the case. When implementing this function, call it before doing the access checking, and if the result of this function is “true” do not perform the access check and allow the browser through to the content without showing the hard paywall.

/**
 * Determine whether the content should be free based on referrer
 * @returns {boolean}
 */
function tpFirstClickFree(){
	// Specify allowed domains or referrer parameters here
	var allowedDomains = [
		/google\.com/,
		/twitter\.com/,
		/facebook\.com/
	];
	if (document.referrer.length > 0){
		for (var i in allowedDomains){
			if (document.referrer.match(allowedDomains[i])){
				return true;
			}
		}
	}
	return false;
}

Server-Side REST

Checking access via server side REST is a simple as making a REST call to Piano. See https://dashboard.tinypass.com/api-docs/dist/index.html for further reference docs.

Sending a request to /publisher/user/access/check will check if the specified user's UID has access to the resource in question.

curl https://api.tinypass.com/api/v3/publisher/user/access/check \
	-d 'aid=MODETWOAPP' \
	-d 'rid=RID' \
	-d [email protected]' \
	-d 'api_token=4uRW8r31E3giOYnGLxfKq53yOOyziodoEpi6oBWw'
{
  "code" : 0,
  "ts" : 1432145735,
  "access" : {
    "access_id" : "hgSS9tAdKmKx",
    "granted" : true,
    "expire_date" : 1434822785,
    "resource" : {
      "rid" : "RID",
      "aid" : "MODETWOAPP",
      "deleted" : false,
      "disabled" : false,
      "create_date" : 1415130054,
      "update_date" : 1418720853,
      "publish_date" : 1415130054,
      "name" : "Test Resource",
    }
  }
}

Alternatively, here's the example of the same request using the PHP SDK:

// Include Tinypass - make sure to use the correct path
include_once "/path/to/api/TinypassClient.php";
// Init configuration object. This can be omitted if configuration object was initialised earlier.
$tinypassConfig = new TPConfig( $applicationId, $apiToken, $privateKey, $isSandbox );
// Init API client
$client = new TinypassClient( $client );
// Make access check request
$access = $client->PublisherUserAccess()
                 ->checkAccessRequest()
                 ->aid( $applicationId )
                 ->rid( $resourceId )
                 ->uid( $userId )
                 ->execute();
 
if ( $access->granted ) {
	// Access is granted, content can be displayed
} else {
	// Access is denied, content should be hidden, and offer should be displayed
}

Additionally, to see a complete list of accesses for a user query the /publisher/user/access/list endpoint.

 curl https://api.tinypass.com/api/v3/publisher/user/access/list \
	-d 'aid=AIDAIDAID' \
	-d 'uid=my_user_uid' \
	-d 'api_token=4uRW8r31E3giOYnGLxfKq53yOOyziodoEpi6oBWw'
{
    "code": 0,
    "ts": 1432144388,
    "limit": 1,
    "offset": 0,
    "total": 1,
    "count": 1,
    "accesses": [
        {
            "access_id": "hgSS9tAdKmKx",
            "granted": true,
            "expire_date": 1434822785
            "resource": {
                "rid": "RID",
                "aid": "AIDAIDAID",
                "deleted": false,
                "disabled": false,
                "create_date": 1415130054,
                "update_date": 1418720853,
                "publish_date": 1415130054,
                "name": "Test Resource"
            }
        }
    ]
}

Using the Piano SDK, publisher can also check access via the Access Token List cookie, which gets set on the browser as the __tac cookie. Some integration might forbid making a server side REST call. In these situations, using the Access Token List is the best solution.

The Access Token List is an encrypted cookie, set on the publisher's domain, that contains the user's most recent access items. This secure cookie can be parsed and then access can be checked by inspecting on the lists contents.

The AccessTokenStore library provides a simple way to access the Token Access List. The SDK/libraries can be sent upon request: email us.

Below is an example of accessing the Access Token List:

// Include Tinypass - make sure to use the correct path
include_once "/path/to/api/TinypassClient.php";
// Init configuration object. This can be omitted if configuration object was initialised earlier.
$tinypassConfig = new TPConfig( $applicationId, $apiToken, $privateKey, $isSandbox );
// Init Acccess token store object with created configuration
$tokenStore = new TPAccessTokenStore( $tinypassConfig );
// Parse cookies to get tokens
$tokenStore->loadTokensFromCookie( $_COOKIE );
// Get access token for some resource
$accessToken = $tokenStore->getAccessToken( $resourceId );
 
if ( $accessToken->isAccessGranted() ) {
    // Access is granted, content can be displayed
} else {
    // Access is denied, content should be hidden, and offer should be displayed
}

Local Database

If your users are stored in a local database - either in Wordpress, Drupal, or your own identity management system - and you're not using a third-party database like Tinypass ID, Janrain, or Gigya, you can perform an access check by querying your local database for entitlements.

This type of integration involves listening to all Piano webhooks so that user access details are up-to-date locally. Since your local datastore is always up-to-date, there is no need to query Piano via a REST call or check the encrypted cookie when the page loads.

The UID that you use internally should be the UID that you provide to us on checkout. As a result, all REST endpoints are available for you to query as long as the appropriate UID is provided.