Token Store

In Keyring, Tokens are stored within Token Stores. Keyring implements Token Stores in an abstracted way which allows you to write a custom Store, depending on your requirements. All Token Stores must extend the provided Keyring_Store class in /store.php. As you will see, all methods in that class are abstract and thus they must all be implemented in your extending class, and must have the same call-signature as the base class.

Single Store

Bundled with core is Keyring_SingleStore which stores both Request and Access Tokens as Posts within WordPress, using Custom Post Types which are not exposed to the normal WordPress posts admin UI. Token meta is stored as Post Meta (Custom Fields). Single Store is designed to be used on a single-user/single-site configuration of WordPress and may not be appropriate for multiple users or Multi-Site installs.

Writing Your Own Token Store

You may decide that to scale your application, you need to store Tokens in a centralized blog within a multi-site install, in completely custom tables, or maybe even purely in cookies or client-based localStorage. It’s up to you. Here are some pointers on writing your own Token Store.

  • Your Token Store must be written as a class, and it must extend Keyring_Store (which means it must be loaded after Keyring’s files load).
  • The init method on your Token Store will be called to initiate the Token Store, and should do any connections/set-up required to get ready. It should also implement the Singleton pattern in some way to avoid re-doing these setup operations (it may be called more than once within a single request). See SingleStore::init() for an example of how to do this.
  • insert() and update() both take a Token and handle everything internally. Make sure that you’re handling both Request and Access Tokens in both (check $token->type() to see which type you’re working with). You may want to handle duplicates in insert() by checking for existing, matching Tokens before storing the new one.
  • If update() is called on a Token which doesn’t have a way of identifying which existing Token you’re updating, you should return false.
  • get_token() and get_tokens() both just accept an array of $args. This provides the most flexibility for working with custom Token Stores. Core Keyring operations will always use a combination of the following args: id (if known, the unique identifier for a Token), service (the service name/sluge), type (Token type, either ‘request’ or ‘access’), user_id (a WordPress user ID)
  • delete() will always be passed an id and type in the $args array, which give the unique identifier (and Token type) for the Token to delete. Depending on your custom implementation, you may also decide to pass other arguments in that array to help determine which Token to delete.

What do you think?