90 lines
2.4 KiB
PHP
90 lines
2.4 KiB
PHP
<?php
|
|
/**
|
|
* Plugin Name: Dabestaniha Authenticate Bridge
|
|
* Description: Authenticate WordPress user via json web token from Mahakiha Application.
|
|
* Version: 1.0
|
|
* Author: Dabestaniha
|
|
*
|
|
* Example: https://wordpress.test/dabestaniha/login/?token=eyJ0...
|
|
*/
|
|
|
|
require_once __DIR__.'/vendor/autoload.php';
|
|
|
|
use Firebase\JWT;
|
|
use Dabestaniha\AuthenticateBridge\App\Http\Requests\DabestanihaAuthenticateRequest;
|
|
|
|
add_action('init', function () {
|
|
$request = DabestanihaAuthenticateRequest::make();
|
|
|
|
if (!$request->shouldContinue()) {
|
|
return;
|
|
}
|
|
|
|
$request->validate();
|
|
$token = $request->string('token');
|
|
|
|
$payload = decrypt_jwt_token($token);
|
|
|
|
$identifier_name = get_configured_option('user-identifier');
|
|
$identifier_value = $payload[$identifier_name] ?? null;
|
|
|
|
$name = $payload['name'] ?? config('da.translates.new-user');
|
|
$user_id = find_or_create_user($identifier_name, $identifier_value, $name);
|
|
|
|
login_user($user_id);
|
|
|
|
$redirect_path = get_configured_option('after-login-route');
|
|
wp_redirect(home_url($redirect_path));
|
|
|
|
exit();
|
|
});
|
|
|
|
require_once 'settings-page.php';
|
|
|
|
function decrypt_jwt_token(string $token): array
|
|
{
|
|
$jwt_secret = get_configured_option('jwt-secret');
|
|
|
|
try {
|
|
$decoded = (array) JWT\JWT::decode($token, new JWT\Key($jwt_secret, 'HS256'));
|
|
return (array) $decoded['data'];
|
|
} catch (\Exception $e) {
|
|
wp_die(view('invalid-token'), 'Invalid Token', ['response' => 500]);
|
|
}
|
|
}
|
|
|
|
function find_or_create_user(string $identifier_name, string $identifier_value, string $name): int
|
|
{
|
|
$user = get_user_by($identifier_name, $identifier_value);
|
|
|
|
if ($user) {
|
|
return $user->ID;
|
|
}
|
|
$random_password = wp_generate_password(12, true);
|
|
$username = $identifier_value;
|
|
|
|
if (username_exists($username)) {
|
|
$username .= '_'.wp_generate_password(4, false);
|
|
}
|
|
|
|
$user_id = wp_create_user($username, $random_password);
|
|
|
|
if (is_wp_error($user_id)) {
|
|
wp_die(view('invalid-token'), 'Invalid Token', ['response' => 500]);
|
|
}
|
|
|
|
wp_update_user([
|
|
'ID' => $user_id,
|
|
'display_name' => $name,
|
|
]);
|
|
|
|
return $user_id;
|
|
}
|
|
|
|
function login_user(int $user_id): bool
|
|
{
|
|
wp_set_auth_cookie($user_id);
|
|
wp_set_current_user($user_id);
|
|
do_action('wp_login', get_userdata($user_id)->user_login, get_userdata($user_id));
|
|
return true;
|
|
} |