Auth.php
8.58 KB
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
<?php
/*
* TODO:
* Test registration/activations system
* Test injection - none was done
* Possibly create hook for login page
*/
namespace Tz\WordPress\Tools\Auth;
use Tz\WordPress\Tools;
use Tz, Tz\Common;
use Exception, LogicException, InvalidArgumentException, BadMethodCallException;
use WP_User;
// These are all WordPress hooks, I put them here for easy reference
const ACTION_LOGIN = 'wp_login';
const ACTION_LOGOUT = 'wp_logout';
const ACTION_REGISTER = 'user_register';
const ACTION_ACTIVATE = 'wpmu_activate_user';
const OPTION_NAME = 'tz_auth'; // Database lookup key (`wp_options`.`option_name`)
call_user_func(function() {
global $wpdb;
if (empty($wpdb->signups)) {
$wpdb->signups = $wpdb->prefix . 'signups';
}
Vars::$options = new Tools\WP_Option(OPTION_NAME);
if (is_admin()) {
require_once(__DIR__ . DIRECTORY_SEPARATOR . 'Settings.php');
}
if (is_array(Vars::$options['third_party'])) {
foreach (Vars::$options['third_party'] as $tp => $on) {
if ($on) {
require_once(__DIR__ . DIRECTORY_SEPARATOR . $tp . DIRECTORY_SEPARATOR . $tp . '.php');
}
}
}
Tz\import('Tz', 'trunk');
});
/**
* Attempts to login the user
* @param {String} $username
* @param {String} $password
* @param {Boolean} $remember
* @returns WP_User instance
* @throws LogicException If headers have already been passed
* @throws InvalidArgumentException If the authentication is invalid
*/
function login($username, $password, $remember = false) {
if (headers_sent()) {
throw new LogicException('Unable to login because headers have been sent');
}
$auth = _signon(Array(
'user_login' => esc_sql($username)
, 'user_password' => esc_sql($password)
, 'remember' => $remember
));
if (get_class($auth) == 'WP_User') {
// This is done to ensure the auth'd user is logged in; cookie is not yet readable, redirect needed
_set_current_user($auth->ID);
return $auth;
}
throw new InvalidArgumentException('Invalid username/password');
//$auth->get_error_message()); this would be nice except it links to a wp-page
}
/**
* NOTE: Exerciese EXTREME caution!!! This automatically logs a user user without password verification!!!
* Intended use is for third party authentication
* @param {String} $username Username of the person to login as
* @param {Boolean} $remember Longer session
* @throws
* @returns {WP_User} of the newly authenticated user
*/
function signin($username, $remember = true) {
// What happens if someone is already signed on? Throw exception?
$user = get_user_by('login', $username);
if (false === $user) {
throw new Exception('Invalid username');
}
_set_auth_cookie($user->ID, $remember);
_set_current_user($user->ID);
do_action('wp_login', $username);
return new WP_User($user->ID);
}
/**
* Attempts to log the user out
* @returns Boolean
* @throws LogicException If HTTP headers have already been sent
*/
function logout() {
if (headers_sent()) {
throw new LogicException('Unable to logout because headers have been sent');
}
_logout();
// I might need to do _set_current_user(0);
return true;
}
/**
* @param {Array} $user_data User data array, requires minimum (username, password, email)
* @throws {InvalidArgumentException} If an invalid $registration_method is passed
* @throw {BadMethodCallException} If any of the $user_data parameters are invalid
* @returns {String} Unique key to activate the account
* @uses wp-includes/registration.php
* @global $wpdb
* @see wpmu_signup_user
*/
function register($username, $email, $password, $meta = Array()) {
global $wpdb;
require_once(ABSPATH . WPINC . DIRECTORY_SEPARATOR . 'registration.php');
/**
* Check the signups database to see if there are already
* records with that email address and are not active yet.
* if there are, delete those before putting this one in.
* Purpose: To clean the database in case they user or admin
* re-registers them because they had issues validating or
* for whatever reason.
*/
$wpdb->query("DELETE FROM {$wpdb->signups} WHERE user_email='$email' AND active=0");
$user_data = Array(
'username' => $username
, 'password' => $password
, 'email' => $email
);
$meta['password'] = $password;
// array_filter($user_data, 'esc_sql');
$valid = new Validation($user_data);
if (count($valid->errors) > 0) {
throw new BadMethodCallException(implode("\n", $valid->errors));
}
global $wpdb;
$username = preg_replace( '/\s+/', '', sanitize_user($username, true));
$email = sanitize_email($email);
$key = substr(md5(time() . rand() . $email ), 0, 16);
$meta = serialize($meta);
$wpdb->insert($wpdb->signups, Array(
'domain' => '',
'path' => '',
'title' => '',
'user_login' => $username,
'user_email' => $email,
'registered' => current_time('mysql', true),
'activation_key' => $key,
'meta' => $meta
));
// do_action('ACTION_REGISTER'); ???
return $key;
}
/**
* @param {String} $key Unique key to activate account
* @global $wpdb
* @see wpmu_activate_signup
*/
function activate($key, $password_validation = null) {
global $wpdb;
$signup = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->signups} WHERE activation_key = %s", $key));
if (empty($signup)) {
throw new Exception("{$key} is not a valid registration key");
}
if ($signup->active) {
throw new Exception('Account has already been activated');
}
// Do I need to do another username_exists() call?
// Can 2 users put the same username in the signup table at the same time?
// Do I need to re-sanatize this?
$meta = unserialize($signup->meta);
if (!is_null($password_validation)) {
if ($meta['password'] != $password_validation) {
throw new Exception('Bad password match');
}
}
$id = _create_user($signup->user_login, $meta['password'], $signup->user_email);
unset($meta['password']);
if (!$id) {
throw new Exception('Unable to create user');
}
$wpdb->update($wpdb->signups, Array('active' => 1, 'activated' => current_time('mysql', true)), Array('activation_key' => $key));
// $user_site = get_site_option('dashboard_blog', $current_site->blog_id);
if (function_exists('add_user_to_blog')) {
global $current_blog;
add_user_to_blog($current_blog->blog_id, $id, get_site_option('default_user_role', 'subscriber'));
} else {
$user = new WP_User($id);
$user->set_role(get_site_option('default_role', 'subscriber'));
}
// If use these, fix variables, they're wrong
//add_new_user_to_blog( $id, $user_email, $meta );
//do_action(ACTION_ACTIVATE, $id, $password, $meta);
// If more than the password was sent in meta, have it generate user_meta for each key=>val pair
foreach($meta as $key => $val) {
update_user_meta($id, $key, $val);
}
return (int)$id;
}
class Validation extends Common\Validation {
/**
* @rule Not blank
* @rule Valid WordPress username
* @returns Boolean
*/
protected function username($val) {
if (empty($val)) {
throw new Exception('<li>Username is blank</li>');
}
require_once(ABSPATH . WPINC . DIRECTORY_SEPARATOR . 'registration.php');
if (!validate_username($val)) {
throw new Exception('<li>Username must be at least 4 characters, letters and numbers only</li>');
}
if (username_exists($val)) {
throw new Exception('<li>Username already exists</li>');
}
}
/**
* @rule Not blank
* @returns Boolean
*/
protected function password($val) {
if (empty($val)) {
throw new Exception('<li>Password can not be blank</li>');
}
}
/**
* @rule Valid email address (*@*.*)
* @returns Boolean
*/
protected function email($val) {
if (!(boolean)filter_var($val, FILTER_VALIDATE_EMAIL)) {
throw new Exception('<li>Invalid email address</li>');
}
if (false !== email_exists($val)) {
throw new Exception('<li>Email address already registered</li>');
}
}
}
class Vars {
/**
* WordPress option for this module
* @type WP_Option
*/
public static $options;
}
?>