How to Password Protect Form Pages

Public
</> CopyGet raw version
php
  1. <?php
  2. /**
  3.  * @file
  4.  * Password Require primary module file.
  5.  *
  6.  * Learning Notes *****************
  7.  * The current version of this modules as been reduced to its most basic form, only 2 functions.
  8.  *
  9.  * In this version you must set the variable password_require_forms in settings.php to array of form_id's that require validation.
  10.  * For example: $conf['password_require_forms'] = array('system_site_information_settings', 'user_admin_permissions');
  11.  */
  12. define('PASSWORD_REQUIRE_MSG', 'You are required to enter your password to perform this action.');
  13. define('PASSWORD_REQUIRE_ATTEMPTS', 3);
  14. /**
  15.  * Implements hook_form_alter().
  16.  *
  17.  * If the current form_id is in array variable password_require_forms then
  18.  * The form should be password protected.
  19.  * A password element is added to the form.
  20.  * This password element is set with a validation function which will check the password.
  21.  *
  22.  */
  23. function password_require_form_alter(&$form, $form_state, $form_id) {
  24. //check to user to see your can bypass this module - uid 1 will always bypass
  25. $protected_forms = variable_get('password_require_forms', array());
  26. if (in_array($form_id, $protected_forms)) {
  27. //this form should be pasword protected
  28. $form['user_password'] = array(
  29. '#type' => 'password',
  30. '#title' => 'Password',
  31. '#description' => t(PASSWORD_REQUIRE_MSG),
  32. '#element_validate' => array('password_require_password_validate'),
  33. '#required' => TRUE,
  34. '#weight' => -10,
  35. );
  36. }
  37. }
  38. /**
  39.  * Validates the user password that was added to the form.
  40.  * Checks how many attempts and logs the user out if over the limit
  41.  * @param $element
  42.  * @param $form_state
  43.  */
  44. function password_require_password_validate($element, &$form_state) {
  45. global $user;
  46. if (!user_authenticate($user->name, $element['#value'])) {
  47. // Increase the password attempt count
  48. if (!isset($_SESSION['password_require_attempt_count'])) {
  49. $_SESSION['password_require_attempt_count'] = 1;
  50. }
  51. else{
  52. $_SESSION['password_require_attempt_count']++;
  53. }
  54. if ( $_SESSION['password_require_attempt_count'] > PASSWORD_REQUIRE_ATTEMPTS) {
  55. // The user has gone over allowed attempts. Log them out.
  56. drupal_goto("user/logout");
  57. }
  58. // Setting the error will cause the form not to validate so the form submit functions are not called.
  59. form_set_error('user_password', t('Your password is incorrect'));
  60. }
  61. else{
  62. //user enter correct password
  63. //reset attempt count
  64. $_SESSION['password_require_attempt_count'] = 0;
  65. }
  66. }