genpass.module 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. <?php
  2. define('GENPASS_REQUIRED', 0);
  3. define('GENPASS_OPTIONAL', 1);
  4. define('GENPASS_RESTRICTED', 2);
  5. define('GENPASS_DISPLAY_NONE', 0);
  6. define('GENPASS_DISPLAY_ADMIN', 1);
  7. define('GENPASS_DISPLAY_USER', 2);
  8. define('GENPASS_DISPLAY_BOTH', 3);
  9. /**
  10. * Defines default characters allowed for passwords.
  11. */
  12. function _GENPASS_REQUIRED_entropy() {
  13. return 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789!#$%&()*+,-./:;<=>?@[]^_{|}~';
  14. }
  15. /**
  16. * Generate a new password using the preferred password generation algorithm.
  17. *
  18. * @return a fresh password.
  19. */
  20. function genpass_generate() {
  21. return module_invoke(genpass_algorithm_module(), 'password');
  22. }
  23. /**
  24. * Generates random password.
  25. *
  26. * @see user_password()
  27. *
  28. * @return string
  29. * The random string.
  30. */
  31. function genpass_password() {
  32. $pass = '';
  33. $length = variable_get('genpass_length', 12);
  34. $allowable_characters = variable_get('genpass_entropy', _GENPASS_REQUIRED_entropy());
  35. // Zero-based count of characters in the allowable list:
  36. $len = strlen($allowable_characters) - 1;
  37. // Loop the number of times specified by $length.
  38. for ($i = 0; $i < $length; $i++) {
  39. do {
  40. // Find a secure random number within the range needed.
  41. $index = ord(drupal_random_bytes(1));
  42. } while ($index > $len);
  43. // Each iteration, pick a random character from the
  44. // allowable string and append it to the password:
  45. $pass .= $allowable_characters[$index];
  46. }
  47. return $pass;
  48. }
  49. /**
  50. * Helper function to find a item in the user form, since its position
  51. * within the form-array depends on the profile module (account-category).
  52. */
  53. function &_genpass_get_form_item(&$form, $field) {
  54. if (isset($form['account'][$field])) {
  55. return $form['account'][$field];
  56. }
  57. else {
  58. return $form[$field];
  59. }
  60. }
  61. /**
  62. * Implementation of hook_form_alter()
  63. */
  64. function genpass_form_alter(&$form, $form_state, $form_id) {
  65. switch ($form_id) {
  66. // User admin settings form at admin/config/people/accounts
  67. case 'user_admin_settings':
  68. $form['registration_cancellation']['genpass_mode'] = array(
  69. '#type' => 'radios',
  70. '#title' => t('Password handling'),
  71. '#default_value' => variable_get('genpass_mode', GENPASS_REQUIRED),
  72. '#options' => array(
  73. GENPASS_REQUIRED => t('Users <strong>must</strong> enter a password on registration. This is disabled if e-mail verification is enabled above.'),
  74. GENPASS_OPTIONAL => t('Users <strong>may</strong> enter a password on registration. If left empty, a random password will be generated. This always applies when an administer is creating the account.'),
  75. GENPASS_RESTRICTED => t('Users <strong>cannot</strong> enter a password on registration; a random password will be generated. This always applies for the regular user registration form if e-mail verification is enabled above.'),
  76. ),
  77. '#description' => t('Choose a password handling mode for new users.'),
  78. );
  79. $form['registration_cancellation']['genpass_length'] = array(
  80. '#type' => 'textfield',
  81. '#title' => t('Generated password length'),
  82. '#default_value' => variable_get('genpass_length', 12),
  83. '#size' => 2,
  84. '#maxlength' => 2,
  85. '#description' => t('Set the length of generated passwords here. Allowed range: 5 to 32.'),
  86. );
  87. $form['registration_cancellation']['genpass_entropy'] = array(
  88. '#type' => 'textfield',
  89. '#title' => t('Generated password entropy'),
  90. '#size' => 100,
  91. '#default_value' => variable_get('genpass_entropy', _GENPASS_REQUIRED_entropy()),
  92. '#description' => t('Give a list of possible characters for a generated password. Note that the list must contain at least X different characters where X is defined by the length you have given above.'),
  93. );
  94. // Provide a selection mechanism to choose the preferred algorithm for
  95. // generating passwords. Any module which implements hook_password() is
  96. // displayed here.
  97. $form['registration_cancellation']['genpass_algorithm'] = array(
  98. '#type' => 'radios',
  99. '#title' => t('Password generation algorithm'),
  100. '#default_value' => genpass_algorithm_module(),
  101. '#options' => genpass_add_samples(genpass_algorithm_modules()),
  102. '#description' => t('If third party modules define a password generation algorithm, you can select which one to use. Note that algorithms other than genpass will ignore the preferred entropy and password length. The currently selected algorithm produced the password @pw.', array('@pw' => genpass_generate())),
  103. );
  104. $form['registration_cancellation']['genpass_display'] = array(
  105. '#type' => 'radios',
  106. '#title' => t('Generated password display'),
  107. '#default_value' => variable_get('genpass_display', GENPASS_DISPLAY_BOTH),
  108. '#options' => array(
  109. GENPASS_DISPLAY_NONE => t('Do not display.'),
  110. GENPASS_DISPLAY_ADMIN => t('Display when site administrators create new user accounts.'),
  111. GENPASS_DISPLAY_USER => t('Display when users create their own accounts.'),
  112. GENPASS_DISPLAY_BOTH => t('Display to both site administrators and users.'),
  113. ),
  114. '#description' => t('Whether or not the generated password should display after a user account is created.'),
  115. );
  116. $form['#validate'][] = 'genpass_user_admin_settings_validate';
  117. // Move the "When cancelling a user account" field down.
  118. $form['registration_cancellation']['user_cancel_method']['#weight'] = 1;
  119. break;
  120. // User registration form at admin/people/create
  121. case 'user_register_form':
  122. $mode = variable_get('genpass_mode', GENPASS_REQUIRED);
  123. // Add validation function, where password may get set
  124. $form['#validate'][] = 'genpass_register_validate';
  125. // Administrator is creating the user
  126. if ($_GET['q'] == 'admin/people/create') {
  127. // Switch to optional mode
  128. $mode = GENPASS_OPTIONAL;
  129. // Help avoid obvious consequence of password being optional
  130. $notify_item =& _genpass_get_form_item($form, 'notify');
  131. $notify_item['#description'] = t('This is recommended when auto-generating the password; otherwise, neither you nor the new user will know the password.');
  132. }
  133. // Pass mode to validation function
  134. $form['genpass_mode'] = array(
  135. '#type' => 'value',
  136. '#value' => $mode,
  137. );
  138. $pass_item =& _genpass_get_form_item($form, 'pass');
  139. switch ($mode) {
  140. // If password is optional, don't require it, and give the user an
  141. // indication of what will happen if left blank
  142. case GENPASS_OPTIONAL:
  143. $pass_item['#required'] = FALSE;
  144. $pass_item['#description'] = (empty($pass_item['#description']) ? '' : $pass_item['#description'] . ' ') . t('If left blank, a password will be generated for you.');
  145. break;
  146. // If password is restricted, remove access
  147. case GENPASS_RESTRICTED:
  148. $pass_item['#access'] = FALSE;
  149. $pass_item['#required'] = FALSE;
  150. break;
  151. }
  152. break;
  153. }
  154. }
  155. /**
  156. * User settings validation.
  157. */
  158. function genpass_user_admin_settings_validate($form, &$form_state) {
  159. // Validate length of password
  160. $length = $form_state['values']['genpass_length'];
  161. if (!is_numeric($length) || $length < 5 || $length > 32) {
  162. form_set_error('genpass_length', t('The length of a generated password must be between 5 and 32.'));
  163. return;
  164. }
  165. // Validate allowed characters
  166. $chars = array_unique(preg_split('//', $form_state['values']['genpass_entropy'], -1, PREG_SPLIT_NO_EMPTY));
  167. if (count($chars) < $length) {
  168. form_set_error('genpass_entropy', t('The list of possible characters is not long or unique enough.'));
  169. return;
  170. }
  171. return $form;
  172. }
  173. /**
  174. * User registration validation.
  175. */
  176. function genpass_register_validate($form, &$form_state) {
  177. if (empty($form_state['values']['pass'])) {
  178. // Generate and set password.
  179. $pass = genpass_generate();
  180. $pass_item =& _genpass_get_form_item($form, 'pass');
  181. form_set_value($pass_item, $pass, $form_state);
  182. if (!form_get_errors()) {
  183. $display = variable_get('genpass_display', GENPASS_DISPLAY_BOTH);
  184. // Administrator created the user.
  185. if ($_GET['q'] == 'admin/people/create') {
  186. $message = t('Since you did not provide a password, it was generated automatically for this account.');
  187. if (in_array($display, array(GENPASS_DISPLAY_ADMIN, GENPASS_DISPLAY_BOTH))) {
  188. $message .= ' ' . t('The password is: <strong class="nowrap">@password</strong>', array('@password' => $pass));
  189. }
  190. }
  191. // Optional - User did not provide password, so it was generated
  192. elseif ($form_state['values']['genpass_mode'] == GENPASS_OPTIONAL) {
  193. $message = t('Since you did not provide a password, it was generated for you.');
  194. if (in_array($display, array(GENPASS_DISPLAY_USER, GENPASS_DISPLAY_BOTH))) {
  195. $message .= ' ' . t('Your password is: <strong class="nowrap">@password</strong>', array('@password' => $pass));
  196. }
  197. }
  198. // Restricted - User was forced to receive a generated password
  199. elseif ($form_state['values']['genpass_mode'] == GENPASS_RESTRICTED && in_array($display, array(GENPASS_DISPLAY_USER, GENPASS_DISPLAY_BOTH))) {
  200. $message = t('The following password was generated for you: <strong class="nowrap">@password</strong>', array('@password' => $pass));
  201. }
  202. if (!empty($message)) {
  203. drupal_set_message($message);
  204. }
  205. }
  206. }
  207. return $form;
  208. }
  209. /**
  210. * Return an array of all modules which implement hook_password.
  211. *
  212. * @return array of module names.
  213. */
  214. function genpass_algorithm_modules() {
  215. // Fetch a list of all modules which implement the password generation hook.
  216. // To be in this list, a module must implement a hook, and return random
  217. // passwords as strings.
  218. $return = array();
  219. foreach (module_implements('password') as $module) {
  220. $return[$module] = $module;
  221. }
  222. return $return;
  223. }
  224. /**
  225. * Return the currently activated module for generating passwords. Does some
  226. * validation to make sure the variable contains a valid module name.
  227. *
  228. * @return the name of the module whose implementation of hook_password is
  229. * currently the preferred implementation.
  230. */
  231. function genpass_algorithm_module() {
  232. $modules = genpass_algorithm_modules();
  233. $module = variable_get('genpass_algorithm', 'genpass');
  234. if (in_array($module, array_keys($modules))) {
  235. return $module;
  236. }
  237. else {
  238. return 'genpass';
  239. }
  240. }
  241. /**
  242. * Adds some sample passwords to each module in an array.
  243. */
  244. function genpass_add_samples($array) {
  245. $return = array();
  246. foreach ($array as $module => $name) {
  247. $return[$module] = $module . ' (' . t('examples') . ': <strong>' . htmlentities(module_invoke($module, 'password')) . '</strong>, <strong>' . htmlentities(module_invoke($module, 'password')) . '</strong>)';
  248. }
  249. return $return;
  250. }