-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwpAuth.php
More file actions
419 lines (387 loc) · 11.4 KB
/
wpAuth.php
File metadata and controls
419 lines (387 loc) · 11.4 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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
<?php
/*
Plugin Name: WPAuth
Plugin URI: https://github.com/orcnd
Description: A simple plugin to authenticate users against a WordPress database.
Version: 1.0
Author: orcnd
Author URI: https://github.com/orcnd
License: GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/
if (!class_exists('WP_REST_Controller')) {
include_once ABSPATH .
'wp-content/plugins/rest-api/lib/endpoints/' .
'/class-wp-rest-controller.php';
}
if (!class_exists('WP_REST_Taxonomies_Controller')) {
include_once ABSPATH .
'wp-content/plugins/rest-api/lib/endpoints/' .
'/class-wp-rest-terms-controller.php';
}
if (!function_exists('add_action')) {
echo 'Hi there! I\'m just a plugin, not much I can do when called directly.';
exit();
}
class wpAuth extends WP_REST_Controller
{
/**
* @var string $cacheTime cache time in seconds for token
*/
var $cacheTime = 30;
/**
* @var string $controlTokenExpireTime control token expire time in seconds
*/
var $controlTokenExpireTime = 20;
/**
* construct class
*
* @return void
*/
public function __construct()
{
$this->namespace = 'wpauth/v1';
}
/**
* settings for plugin
*
* @var array $registerSettings
*/
var $registerSettings = [
'key' => [
'name' => 'Key',
'type' => 'password',
'text' => 'wpAuth Access Key',
],
'usernamePrefix' => [
'name' => 'UsernamePrefix',
'type' => 'text',
'text' => 'wpAuth Username Prefix',
],
'redirectUrl' => [
'name' => 'RedirectUrl',
'type' => 'text',
'text' => 'wpAuth Redirect Url',
],
'passwordSalt' => [
'name' => 'PasswordSalt',
'type' => 'text',
'text' => 'wpAuth Password Salt',
],
];
/**
* create redirect code with shortcode
*
* @return void
*/
function shortcode()
{
@ob_end_clean();
$token = isset($_GET['token']) ? $_GET['token'] : '';
if (is_user_logged_in()) {
$this->redirectToBase();
}
if ($token !== '') {
$userData = get_transient('wpAuthByOrcnd' . $token);
if ($userData !== false) {
$userNamePrefix = get_option(
'wpAuthByOrcndSettingUsernamePrefix'
);
$existingUser = get_user_by(
'email',
(string) $userData['email'],
);
if ($existingUser === false) {
$newUser = [
'user_login' => $userNamePrefix . $userData['name'],
'user_pass' => $this->generatePass($userData['email']),
'user_email' => (string) $userData['email'],
'display_name' => (string) $userData['name'],
];
$id=wp_insert_user($newUser);
$loginData=[
'id'=> $id,
'login' => $newUser['user_login']
];
}else{
$loginData=[
'id' => $existingUser->ID,
'login' => $existingUser->user_login
];
}
//login
wp_set_current_user($loginData['id'], $loginData['login']);
wp_set_auth_cookie($loginData['id']);
// do_action('wp_login', $loginData['login']);
delete_transient('wpAuthByOrcnd' . $token);
}
}
$this->redirectToBase();
}
function redirectToBase()
{
$redirectUrl = get_option('wpAuthByOrcndSettingRedirectUrl');
wp_redirect($redirectUrl);
exit;
}
/**
* generate password for users
*
* @return string password
*/
function generatePass($e)
{
return md5(((string)$e).'qwjas;ol2l;fg94k;ljsd');
}
/**
* initialize plugin
*
* @return void
*/
function adminInit()
{
//adding settings in bulk
foreach ($this->registerSettings as $setting) {
//registering settings
register_setting(
'general',
'wpAuthByOrcndSetting' . $setting['name']
);
//adding fields
add_settings_field(
'wpAuthByOrcnd' . $setting['name'] . 'Field',
$setting['text'],
[$this, 'fieldCallback'],
'general',
'default',
['setting' => $setting]
);
}
}
/**
* field output for admin page
*
* @param array $args
* @return void
*/
function fieldCallback(array $arg)
{
echo $this->settingInput(
$arg['setting']['type'],
'wpAuthByOrcndSetting' . $arg['setting']['name'],
get_option('wpAuthByOrcndSetting' . $arg['setting']['name'])
);
}
/**
* create form input for settings
*
* @return string
*/
function settingInput($type, $name, $data)
{
$str = "<input type=\"{$type}\" name=\"{$name}\" value=\"";
$str .= (isset($data) ? esc_attr($data) : '') . '">';
return $str;
}
/**
* initialize menu items
*
* @return void
*/
function menuInit()
{
add_menu_page(
'wpAuth', // page title
'wpAuth', // menu title
'manage_options', // capability
'wpAuthByOrcnd', // menu slug
[$this, 'adminPage'] // callback function
);
}
/**
* initialize and create rest routes
*
* @return void
*/
public function restInit()
{
register_rest_route(
$this->namespace, '/token', [
'methods' => 'POST',
'callback' => [$this, 'routeToken'],
'args' => [
'email' => [
'required' => true,
],
'time' => [
'required' => true,
],
'control_token' => [
'required' => true,
],
],
]
);
register_rest_route(
$this->namespace, '/generateLogin', [
'methods' => 'POST',
'callback' => [$this, 'routeLogin'],
'args' => [
'email' => [
'required' => true,
],
'name' => [
'required' => true,
],
'access_token' => [
'required' => true,
],
],
]
);
}
/**
* check api working
*
* @param WP_REST_Request $request Full data about the request.
* @return WP_Error|WP_REST_Response
*/
public function routeToken($request)
{
$params = $request->get_params();
$controlTokenTime = strtotime($params['time']);
//check if token expired
if ($controlTokenTime > time() + $this->controlTokenExpireTime
|| $controlTokenTime < time() - $this->controlTokenExpireTime
) {
return new WP_REST_Response(
[
'error' => 'control token expired',
],
400
);
}
$controlToken = $this->createAccessToken(
$params['email'],
$params['time'],
'control_token'
);
if ($controlToken === $params['control_token']) {
$accessTime = date('c', time());
$accessToken = $this->createAccessToken(
$params['email'],
$accessTime,
'access_token'
);
set_transient(
'wpAuthByOrcnd' . $accessToken,
[$params['email'], $accessTime],
$this->cacheTime
);
return new WP_REST_Response(
['access_token' => $accessToken, 'time' => $accessTime],
200
);
} else {
return new WP_REST_Response(
[
'error' => 'invalid token',
],
400
);
}
}
/**
* create login link for user
*
* @param WP_REST_Request $request Full data about the request.
* @return WP_Error|WP_REST_Response
*/
function routeLogin($request)
{
$params = $request->get_params();
$cachedData = get_transient('wpAuthByOrcnd' . $params['access_token']);
if ($cachedData === false) {
return new WP_REST_Response(['error' => 'invalid token'], 400);
}
if ($cachedData[0] !== $params['email']) {
return new WP_REST_Response(['error' => 'invalid token'], 400);
}
if (strtotime($cachedData[1]) > time() + $this->cacheTime) {
return new WP_REST_Response(['error' => 'token expired'], 400);
}
$uniqueId = $this->uniqidReal();
set_transient(
'wpAuthByOrcnd' . $uniqueId,
['email' => $params['email'], 'name' => $params['name']],
$this->cacheTime
);
return new WP_REST_Response(
[
'login' => $uniqueId,
],
200
);
}
/**
* create access token for email
*
* @param string $email email address
* @param string $time time of token
* @param string $subject subject of token
* @return string access token
*/
function createAccessToken($email, $time, $subject = '')
{
$key = get_option('wpAuthByOrcndSettingKey');
return md5($key . $email . $time . $subject);
}
/**
* generates unique id (source: https://www.php.net/manual/en/function.uniqid.php)
*
* @param int $lenght lenght of id
* @return string
*/
function uniqidReal($lenght = 13)
{
// uniqid gives 13 chars, but you could adjust it to your needs.
if (function_exists('random_bytes')) {
$bytes = random_bytes(ceil($lenght / 2));
} elseif (function_exists('openssl_random_pseudo_bytes')) {
$bytes = openssl_random_pseudo_bytes(ceil($lenght / 2));
} else {
throw new Exception(
'no cryptographically secure random function available'
);
}
return substr(bin2hex($bytes), 0, $lenght);
}
/**
* get client ip
*
* @return string
*/
public static function getClientIP()
{
if (isset($_SERVER)) {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
return $_SERVER['HTTP_X_FORWARDED_FOR'];
}
if (isset($_SERVER['HTTP_CLIENT_IP'])) {
return $_SERVER['HTTP_CLIENT_IP'];
}
return $_SERVER['REMOTE_ADDR'];
}
if (getenv('HTTP_X_FORWARDED_FOR')) {
return getenv('HTTP_X_FORWARDED_FOR');
}
if (getenv('HTTP_CLIENT_IP')) {
return getenv('HTTP_CLIENT_IP');
}
return getenv('REMOTE_ADDR');
}
}
$wpAuth = new wpAuth();
add_action('rest_api_init', [$wpAuth, 'restInit']);
add_action('admin_init', [$wpAuth, 'adminInit']);
add_shortcode('wpAuth', [$wpAuth, 'shortcode']);