You are here

secure_cookie_data.module in Secure Cookie Data 7

Same filename and directory in other branches
  1. 7.2 secure_cookie_data.module

secure_data_cookie.module @author António P. P. Almeida <appa@perusio.net> @date Thu Nov 21 11:45:23 2013

@brief Implements the secure cookie protocol for storing data.

File

secure_cookie_data.module
View source
<?php

/**
 * @file   secure_data_cookie.module
 * @author António P. P. Almeida <appa@perusio.net>
 * @date   Thu Nov 21 11:45:23 2013
 *
 * @brief  Implements the secure cookie protocol for storing data.
 *
 *
 */

/**
 * Sets the secure cookie with the given data.
 *
 *
 * @param string $data
 *   The JSON data to be stored in the cookie.
 * @param boolean $raw
 *   If TRUE the cookie is set so that the encryption is done
 *   in binary and then base 64 encoded.
 * @return boolean
 *   TRUE if the cookie was modified/set, FALSE if not.
 */
function secure_cookie_data_put($data) {

  // Decode the given data.
  $cookie_data = json_decode($data);

  // Compute the HMAC right away.
  $cookie_data->hmac = secureCookieBasic::create($cookie_data);

  // Now we modify or set the cookie if it doesn't exist.
  if (isset($_COOKIE[secureCookieBasic::$__cookie_name])) {
    $_COOKIE[secureCookieBasic::$__cookie_name] = secureCookieBasic::encode($cookie_data);
    return TRUE;
  }
  else {

    // Set the cookie. It expires upon closing of the browser.
    return setcookie(secureCookieBasic::$__cookie_name, secureCookieBasic::encode($cookie_data), 0, secureCookieBasic::$__cookie_path, secureCookieBasic::get_domain(), secureCookieBasic::secure_session_p(), TRUE);
  }
}

// secure_cookie_data_add

/**
 * Obtain the data stored in a secure cookie.
 *
 * @param string $data
 *   The JSON data to be stored in the cookie.
 * @return object
 *   The stored data or NULL if the cookie is missing
 *   or the HMAC doesn't validate.
 */
function secure_cookie_data_get() {

  // First thing we do is to validate the cookie.
  if (isset($_COOKIE[secureCookieBasic::$__cookie_name])) {

    // Decode the JSON.
    $cookie_data = secureCookieBasic::decode($_COOKIE[secureCookieBasic::$__cookie_name]);

    // Next we get the HMAC.
    if (isset($cookie_data->hmac)) {
      $hmac = $cookie_data->hmac;

      // Unset the hmac entry so that we get the 'raw' data only.
      unset($cookie_data->hmac);

      // Validate the cookie using the HMAC stored on the data.
      if (secureCookieBasic::validate($hmac, $cookie_data)) {

        // Return the data.
        return $cookie_data;
      }
    }
  }
  return NULL;
}

// secure_cookie_data_get

Functions

Namesort descending Description
secure_cookie_data_get Obtain the data stored in a secure cookie.
secure_cookie_data_put Sets the secure cookie with the given data.