summaryrefslogtreecommitdiffstats
path: root/http-authentication.php
blob: 705325939de8b05bd45a43f7b54063addb0c4f7a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
<?php
/*
Plugin Name: HTTP Authentication
Version: 1.8 

Description: Authenticate users using basic HTTP authentication
(<code>REMOTE_USER</code>). This plugin assumes users are externally
authenticated, as with <a
href="http://www.gatorlink.ufl.edu/">GatorLink</a>.  

Original author: Daniel Westermann-Clark
Author URI: http://dev.webadmin.ufl.edu/~dwc/
Patched for Wordpress MU by Simon Wilkinson, further patched by Bret
McMillan

Copyright (C) 2008, Red Hat, Inc.  (Author: Bret McMillan)

This is free software, licensed to you under the GNU General Public
License, version 2 (GPLv2). A copy of GPLv2 is available at 
http://www.gnu.org/licenses/old-licenses/gpl-2.0.html .

This software is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Copyright (C) 2008, Simon Wilkinson
Copyright (C) 2008, Daniel Westermann-Clark
*/


if (! class_exists('HTTPAuthenticationPlugin')) {



		/*
		 * Create a new WordPress account for the specified username.
		 */
		function create_remote_user($username, $password) {
			$email_domain = get_site_option('http_authentication_auto_create_email_domain');

			require_once( ABSPATH . WPINC . '/registration.php');

			if (strpos($username, '@') !== FALSE) {
				$email = $username;
			} else {
				$email = $username . '@' . $email_domain;
			}

			$userid = wpmu_create_user($username, $password, $email);
			if ( ! $userid )
			  die("Error create WPMU user; username or email address may already be in use");

			do_action('wpmu_new_user', $userid);
			do_action('wpmu_activate_user', $userid, $password);

			return new WP_User($userid);
		}



  // override this so that we're paying attention to REMOTE_USER, not the cookie
  function get_currentuserinfo () {
    global $current_user;
    
    if ( defined('XMLRPC_REQUEST') && XMLRPC_REQUEST )
      return false;

    if ( ! empty($current_user) )
      return;

    if (empty($_SERVER['REMOTE_USER'])) {
      return false;
    }

    $user = get_userdatabylogin($_SERVER['REMOTE_USER']);
    
    if ( ! $user ) {
      $user = create_remote_user($_SERVER['REMOTE_USER'], substr(md5(uniqid(microtime())), 0, 10));  // lazy, refactor this
    }

    wp_set_current_user($user->ID);
  }

  // just die here since w/ generalized http auth, not really a "login page"
  function auth_redirect() {

    $user = wp_get_current_user();

    if ( ! $user) {
      die('HTTP Authentication failure in auth_redirect');
    }
  }


	class HTTPAuthenticationPlugin {
		function HTTPAuthenticationPlugin() {
			if (isset($_GET['activate']) and $_GET['activate'] == 'true') {
				add_action('init', array(&$this, 'init'));
			}
			add_action('admin_menu', array(&$this, 'admin_menu'));
			add_action('wp_authenticate', array(&$this, 'authenticate'), 10, 2);
			add_action('wp_logout', array(&$this, 'logout'));
			add_action('lost_password', array(&$this, 'disable_function'));
			add_action('retrieve_password', array(&$this, 'disable_function'));
			add_action('password_reset', array(&$this, 'disable_function'));
			add_action('check_passwords', array(&$this, 'check_passwords'), 10, 3);
			add_filter('show_password_fields', array(&$this, 'show_password_fields'));
		}


		/*************************************************************
		 * Plugin hooks
		 *************************************************************/

		/*
		 * Add options for this plugin to the database.
		 */
		function init() {
			if (current_user_can('manage_options')) {
				add_site_option('http_authentication_logout_uri', get_option('home'), 'The URI to which the user is redirected when she chooses "Logout".');
				add_site_option('http_authentication_auto_create_user', false, 'Should a new user be created automatically if not already in the WordPress database?');
				add_site_option('http_authentication_auto_create_email_domain', '', 'The domain to use for the email address of an automatically created user.');
			}
		}

		/*
		 * Add an options pane for this plugin.
		 */
		function admin_menu() {
			$objCurrUser = wp_get_current_user();
			$objUser = wp_cache_get($objCurrUser->id, 'users');
			if (function_exists('add_submenu_page') &&
			    is_site_admin($objUser->user_login)) {
				add_submenu_page('wpmu-admin.php', 'HTTP Authentication', 'HTTP Authentication', 9, basename(__FILE__), array(&$this, 'display_options_page'));
			}
		}

		/*
		 * If the REMOTE_USER evironment is set, use it as the username.
		 * This assumes that you have externally authenticated the user.
		 */
		function authenticate($username, $password) {
			global $using_cookie;

			// Reset values from input ($_POST and $_COOKIE)
			$username = $password = '';

			if (! empty($_SERVER['REMOTE_USER'])) {
				if (function_exists('get_userdatabylogin')) {
					$username = $_SERVER['REMOTE_USER'];
					$user = get_userdatabylogin($username);

					if (! $user or $username != $user->user_login) {
						if ((bool) get_site_option('http_authentication_auto_create_user')) {
							// Create user and re-read from database for login (next step)
						        create_remote_user($username, $this->get_password());
							$user = get_userdatabylogin($username);
                                                        # If we were to create a new blog, we'd do so here...
						}
						else {
							// User is not in the WordPress database, and thus not authorized
							die("User $username does not exist in the WordPress database");
						}
					}

					// Login the user by feeding WordPress a double-MD5 hash
					$password = md5($user->user_pass);

					// User is now authorized; force WordPress to use the generated password
					$using_cookie = true;
					wp_setcookie($user->user_login, $password, $using_cookie);
				}
				else {
					die("Could not load user data");
				}
			}
			else {
				die("No REMOTE_USER found; please check your external authentication configuration");
			}
		}

		/*
		 * Logout the user by redirecting them to the logout URI.
		 */
		function logout() {
			header('Location: ' . get_site_option('http_authentication_logout_uri'));
			exit();
		}

		/*
		 * Generate a password for the user. This plugin does not
		 * require the user to enter this value, but we want to set it
		 * to something nonobvious.
		 */
		function check_passwords($username, $password1, $password2) {
			$password1 = $password2 = $this->get_password();
		}

		/*
		 * Used to disable certain display elements, e.g. password
		 * fields on profile screen.
		 */
		function show_password_fields($show_password_fields) {
			return false;
		}

		/*
		 * Used to disable certain login functions, e.g. retrieving a
		 * user's password.
		 */
		function disable_function() {
			die('Disabled');
		}


		/*************************************************************
		 * Functions
		 *************************************************************/

		/*
		 * Generate a random password.
		 */
		function get_password($length = 10) {
			return substr(md5(uniqid(microtime())), 0, $length);
		}

		/*
		 * Display the options for this plugin.
		 */
		function display_options_page() {
		    if( is_site_admin() == false ) {
		        wp_die( __('<p>You do not have permission to access this page.</p>') );
		    }

		    if ($_POST['httpOptionsSave']) {
			update_site_option('http_authentication_logout_uri', $_POST['http_authentication_logout_uri']);
			update_site_option('http_authentication_auto_create_user', $_POST['http_authentication_auto_create_user']);
			update_site_option('http_authentication_auto_create_email_domain', $_POST['http_authentication_auto_create_email_domain']);
			?>
			<div id="message" class="updated fade"><p><?php _e('Options saved!'); ?></p></div><?php
		    }
			$logout_uri = get_site_option('http_authentication_logout_uri');
			$auto_create_user = (bool) get_site_option('http_authentication_auto_create_user');
			$auto_create_email_domain = get_site_option('http_authentication_auto_create_email_domain');
?>
<div class="wrap">
  <h2>HTTP Authentication Options</h2>
  <form method="post">
    <input type="hidden" name="action" value="update" />
    <input type="hidden" name="page_options" value="http_authentication_logout_uri,http_authentication_auto_create_user,http_authentication_auto_create_email_domain" />
    <?php if (function_exists('wp_nonce_field')): wp_nonce_field('update-options'); endif; ?>

    <fieldset class="options">
      <table class="editform optiontable">
        <tr valign="top">
          <th scope="row"><label for="http_authentication_logout_uri">Logout URI</label></th>
          <td>
            <input type="text" name="http_authentication_logout_uri" id="http_authentication_logout_uri" value="<?php echo htmlspecialchars($logout_uri) ?>" size="50" /><br />
            Default is <code><?php echo htmlspecialchars(get_settings('home')); ?></code>; override to e.g. remove a cookie.
          </td>
        </tr>
        <tr valign="top">
          <th scope="row"><label for="http_authentication_auto_create_user">Automatically create accounts?</label></th>
          <td>
            <input type="checkbox" name="http_authentication_auto_create_user" id="http_authentication_auto_create_user"<?php if ($auto_create_user) echo ' checked="checked"' ?> value="1" /><br />
            Should a new user be created automatically if not already in the WordPress database?<br />
            Created users will obtain the role defined under &quot;New User Default Role&quot; on the <a href="options-general.php">General Options</a> page.
          </td>
        </tr>
        <tr valign="top">
          <th scope="row"><label for="http_authentication_auto_create_email_domain">Email address domain</label></th>
          <td>
            <input type="text" name="http_authentication_auto_create_email_domain" id="http_authentication_auto_create_email_domain" value="<?php echo htmlspecialchars($auto_create_email_domain) ?>" size="50" /><br />
            When a new user logs in, this domain is used for the initial email address on their account. The user can change his or her email address by editing their profile.
          </td>
        </tr>
      </table>
    </fieldset>
    <p class="submit">
      <input type="submit" name="httpOptionsSave" value="Update Options &raquo;" />
    </p>
  </form>
</div>
<?php
		}
	}
}

// Load the plugin hooks, etc.
$http_authentication_plugin = new HTTPAuthenticationPlugin();
?>