Skip to content

Instantly share code, notes, and snippets.

@creativepsyco
Created January 28, 2015 02:58
Show Gist options
  • Save creativepsyco/ae27651daaae20f2d86e to your computer and use it in GitHub Desktop.
Save creativepsyco/ae27651daaae20f2d86e to your computer and use it in GitHub Desktop.
Batch Authorizer for Pusher Java Client.
class BatchAuthorizer extends HttpAuthorizer {
private final Collection<String> channelsToSub;
private Map<String, JSONObject> cachedAuthMap = new HashMap<>();
/**
* We need the socket id to know when to refresh the batch auth data
*/
private String authSocketId = "";
/**
* An Optional string collection to manage the batch mechanism of doing pusher channel auth
*
* @param endPoint The endpoint for the pusher auth session JSON string
* @param channelsToSub the list of channels to subscribe to
*/
public BatchAuthorizer(String endPoint, Collection<String> channelsToSub) {
super(endPoint);
this.channelsToSub = channelsToSub;
}
@Override
public String authorize(String channelName, String socketId) throws AuthorizationFailureException {
batchAuthorize(socketId);
/* If we don't have a cached Auth String after this we fallback to old method */
if (!cachedAuthMap.containsKey(channelName)) {
String authString = super.authorize(channelName, socketId);
try {
cachedAuthMap.put(channelName, new JSONObject(authString));
} catch (JSONException e) {
e.printStackTrace();
}
}
return cachedAuthMap.get(channelName).toString();
}
private void batchAuthorize(String socketId) {
/**
* If the socket ID matches the authorized socket ID, then we have nothing to do
* This also works in the scenario of connection changes because the socket ID will
* automatically change and Pusher will trigger the re-auth
*/
if (this.authSocketId.equals(socketId))
return;
/** Since we are going to re-auth anyways we clear our cache */
cachedAuthMap.clear();
/* If not let's fire the authSocket ID */
// Download your auth information here from your web server API & put it into cachedAuthMap
// example:-
// cachedAuthMap.put(channelName, new JSONObject(authString));
// I am using JSON throughout you can use anything else.
this.authSocketId = socketId;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment