Skip to content

Instantly share code, notes, and snippets.

@stephenlb
Last active January 3, 2016 15:38
Show Gist options
  • Save stephenlb/8483690 to your computer and use it in GitHub Desktop.
Save stephenlb/8483690 to your computer and use it in GitHub Desktop.
UPDATE - OFFICIAL PHP PAM SDK NOW HERE - https://github.com/pubnub/php -- PubNub Access Manager (PAM) PHP Full Library for Granting and Revoking Access in Real-Time on the PubNub Real-Time Network.
<?php
// UPDATE - OFFICIAL PHP PAM SDK NOW HERE - https://github.com/pubnub/php
require('pam.php');
## PubNub Access Manager (PAM)
$manager = new access(
"pub-c-e132b7b4-0c2c-4d36-a828-1de1ea50d167",
"sub-c-f95db694-6ff9-11e3-9291-02ee2ddab7fe",
"sec-c-OWFkNWQ1NDctN2JiNy00NzJmLTk3Y2ItN2ExODZlYzkyNzY0"
);
## Grant User Access
print_r($manager->grant(
"my_channel", // CHANNEL
"gZW5jb2RlZCBmaWx", // STRING (AUTH KEY)
true, // READ
true, // WRITE
5 // TTL in MINUTES
));
## Grant User **Presence Access**
## WARNING: The PubNub Dev Console Requires Presence Access
print_r($manager->grant(
"my_channel-pnpres", // CHANNEL
"gZW5jb2RlZCBmaWx", // STRING (AUTH KEY)
true, // READ
true, // WRITE
5 // TTL in MINUTES
));
## Grant GLOBAL Access (any user)
## Exclude the authkey and you can global grant access to all.
print_r($manager->grant(
"my_channel-pnpres", // CHANNEL
"gZW5jb2RlZCBmaWx", // STRING (AUTH KEY)
true, // READ
true, // WRITE
5 // TTL in MINUTES
));
## Revoke User Access
print_r($manager->revoke(
"some-other-channel", // CHANNEL
"gZW5jb2RlZCBmaWx" // STRING (AUTH KEY)
));
## Revoke Global Access
print_r($manager->revoke(
"some-other-channel" // CHANNEL
));
?>

Include PAM and Initialize class access

UPDATE - OFFICIAL PHP PAM SDK NOW HERE - https://github.com/pubnub/php

require('pam.php');

$manager = new access(
    "pub-c-e132b7b4-0c2c-4d36-a828-1de1ea50d167",
    "sub-c-f95db694-6ff9-11e3-9291-02ee2ddab7fe",
    "sec-c-OWFkNWQ1NDctN2JiNy00NzJmLTk3Y2ItN2ExODZlYzkyNzY0"
);

Grant User Access

Grant access to user with authkey of gZW5jb2RlZCBmaWx with read and write access for 5 minute ttl.

print_r($manager->grant(
    "my_channel",        // CHANNEL
    "gZW5jb2RlZCBmaWx",  // STRING (AUTH KEY)
    true,                // READ
    true,                // WRITE
    5                    // TTL in MINUTES
));

Grant User Presence Access

Also grant access to the presence channel (required for PubNub Dev Console).

print_r($manager->grant(
    "my_channel-pnpres", // CHANNEL
    "gZW5jb2RlZCBmaWx",  // STRING (AUTH KEY)
    true,                // READ
    true,                // WRITE
    5                    // TTL in MINUTES
));

Grant GLOBAL Access (to all users)

Exclude the authkey and you can global grant access to all.

print_r($manager->grant_global(
    "my_channel", // CHANNEL
    true,         // READ
    true,         // WRITE
    5             // TTL in MINUTES
));

Forever Grant Access

You can grant access forever by setting the ttl param to 0.

print_r($manager->grant_global(
    "my_channel", // CHANNEL
    true,         // READ
    true,         // WRITE
    0             // FOREVER GRANT!!!
));

Revoke User Access

Instantly revoke access to a user.

print_r($manager->revoke(
    "some-other-channel", // CHANNEL
    "gZW5jb2RlZCBmaWx"    // STRING (AUTH KEY)
));

Revoke Global Access

You can also revoke Global Access by excluding the authkey param.

print_r($manager->revoke(
    "some-other-channel" // CHANNEL
));

Dev Console Test Link:

WARNING: PubNub Dev Console Requires Grant on Presence Channel too! You can set the presence access by granting on the suffix of -pnpres channel name.

http://www.pubnub.com/console/?channel=my_channel&sub=sub-c-f95db694-6ff9-11e3-9291-02ee2ddab7fe&pub=pub-c-e132b7b4-0c2c-4d36-a828-1de1ea50d167&sec=sec-c-OWFkNWQ1NDctN2JiNy00NzJmLTk3Y2ItN2ExODZlYzkyNzY0

<?php
// UPDATE - OFFICIAL PHP PAM SDK NOW HERE - https://github.com/pubnub/php
class access {
function __construct( $pubkey, $subkey, $seckey ) {
$this->publish_key = $pubkey;
$this->subscribe_key = $subkey;
$this->secret_key = $seckey;
}
function grant_global( $channel, $read=True, $write=True, $ttl=5 ) {
/** Grant GLOBAL Access on a Channel. **/
return $this->_auth(array(
"channel" => $channel,
"r" => $read ? 1 : 0,
"w" => $write ? 1 : 0,
"ttl" => $ttl
));
}
function grant( $channel, $authkey=False, $read=True, $write=True, $ttl=5 ) {
/** Grant Access on a Channel. **/
return $this->_auth(array(
"channel" => $channel,
"auth" => $authkey,
"r" => $read ? 1 : 0,
"w" => $write ? 1 : 0,
"ttl" => $ttl
));
}
function revoke( $channel, $authkey=False, $read=False, $write=False, $ttl=1 ) {
/** Revoke Access on a Channel.**/
return $this->_auth(array(
"channel" => $channel,
"auth" => $authkey,
"r" => $read ? 1 : 0,
"w" => $write ? 1 : 0,
"ttl" => $ttl
));
}
function _sign($message) {
/** Calculate a signature by secret key and message. **/
return strtr( base64_encode(hash_hmac(
'sha256',
utf8_encode($message),
utf8_encode($this->secret_key),
true
)), '+/', '-_' );
}
function _auth($query) {
/** Issue an authenticated request.**/
if (!array_key_exists( 'timestamp', $query )) {
$query['timestamp'] = time();
}
## Global Grant?
if ((array_key_exists('auth',$query)) && !$query['auth']) {
unset($query['auth']);
}
## Construct String to Sign
$params = array();
$sorted_keys = array_keys($query);
sort($sorted_keys);
foreach ($sorted_keys as $key) array_push(
$params,
$key . "=" . $query[$key]
);
$string_to_sign =
$this->subscribe_key . "\n" .
$this->publish_key . "\n" .
"grant" . "\n" .
implode( "&", $params );
$signature = $this->_sign($string_to_sign);
$url = (
"https://pubsub.pubnub.com/v1/auth/grant/sub-key/" .
$this->subscribe_key . "?" .
implode( "&", $params ) .
"&signature=" . $signature
);
$workspace_curl = curl_init();
curl_setopt( $workspace_curl, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $workspace_curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $workspace_curl, CURLOPT_URL, $url );
$result = curl_exec($workspace_curl);
return $workspace_details =json_decode( $result, true );
}
}
?>
Array
(
[status] => 200
[message] => Success
[payload] => Array
(
[channels] => Array
(
[some-other-channel] => Array
(
[r] => 0
[w] => 0
)
)
[subscribe_key] => sub-c-f95db694-6ff9-11e3-9291-02ee2ddab7fe
[ttl] => 1
[level] => channel
)
[service] => Access Manager
)
@maronin
Copy link

maronin commented Jun 22, 2014

This doesn't work. I am using php 5.5.12 and WAMP server.
When I do print_r($manager->grant(...)); it doesn't do anything. My app keeps getting a 403 error. I checked my dev console as well.

{"status":403,"service":"Access Manager","error":true,"message":"Forbidden","payload":{"channels":["my_channel"]}}

I also get {"status":403,"service":"Access Manager","error":true,"message":"Forbidden","payload":{"channels":["pn_myUserID"]}}

if I do a pubnub init with the public key, sub key, auth key and my own uuid in my javscript file.

If i grant permission through the dev console, everything works fine. Therefore, I think the php grant doesn't work. Unless I am running it in the wrong place.

Please fix it!

@maronin
Copy link

maronin commented Jun 23, 2014

The pam.php file is missing curl_setopt($workspace_curl, CURLOPT_SSL_VERIFYPEER, false); after line 87. Curl doesn't work with https.

So I fixed my problem!

@stephenlb
Copy link
Author

@maronin Hi! I'm reviewing your inquiry. Thank you for the fix!

@javaguirre
Copy link

Hello,

When trying to grant permission for a channel, I always get this.

This is the request sent:

Array
(
[channel] => my_channel
[auth] => 9f1fad32b54cf388b5d915a5af3a14db
[r] => 1
[w] => 1
[ttl] => 5
[timestamp] => 1404392170
)

I get:

Array
(
[status] => 400
[message] => Invalid Timestamp
[service] => Access Manager
[error] => 1
)

The timestamp is just php's core time(), so I don't know what is pubnub api expecting?

Thank you!

@javaguirre
Copy link

$pubnub->time() didn't solve the issue either, I will post my solution when I have it.

@javaguirre
Copy link

My mistake, the timestamp must be very accurate, you could use ntp to set it and check the value against http://www.unixtimestamp.com/index.php (for example).

@SuperDaimyo
Copy link

Hi thank you for this repo, I have an angular app and I am trying to grant with php and then subscribe with angular. I get a response with the php script but when I try to subscribe with the token through angular I get 403s. Like maronin it works fine in the dev console.
I ajax post to my php script, on success init and subscribe in js. Any ideas?

Edit: Figured out that I was calling init again in the js and overwriting the first init, i have stopped the 403s.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment