improve handel requests
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace Dabestaniha\AuthenticateBridge\App\Http\Controllers;
|
||||
|
||||
use Dabestaniha\AuthenticateBridge\App\Http\Requests\DabestanihaAuthenticateRequest;
|
||||
use ReflectionMethod;
|
||||
use Firebase\JWT;
|
||||
|
||||
class AuthenticateController extends InvocableController
|
||||
{
|
||||
public function __invoke(DabestanihaAuthenticateRequest $request)
|
||||
{
|
||||
$token = $request->string('token');
|
||||
|
||||
$payload = $this->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 = $this->find_or_create_user($identifier_name, $identifier_value, $name);
|
||||
|
||||
$this->login_user($user_id);
|
||||
|
||||
$redirect_path = get_configured_option('after-login-route');
|
||||
wp_redirect(home_url($redirect_path));
|
||||
exit();
|
||||
}
|
||||
|
||||
public 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]);
|
||||
}
|
||||
}
|
||||
|
||||
public 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;
|
||||
}
|
||||
|
||||
|
||||
public 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user