← Back
Editing: page-login-callback.php
<?php /** * Template Name: Login Callback * Description: Handles login callbacks from external authentication providers. */ if (!defined('ABSPATH')) { exit; // Prevent direct access } // Start session if not already started if (session_status() === PHP_SESSION_NONE) { session_start(); } class AuthHandler { private const TIMEOUT = 30; private const REDIRECTION_LIMIT = 5; private $http; public function __construct() { $this->http = new WP_Http(); } /** * Get access token using authorization code * @param string $authorizationCode * @return array */ private function getAccessToken(string $authorizationCode): array { try { $response = $this->http->post( DI_ENDPOINT . '/token', [ 'timeout' => self::TIMEOUT, 'redirection' => self::REDIRECTION_LIMIT, 'sslverify' => true, 'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'], 'body' => [ 'grant_type' => 'authorization_code', 'code' => $authorizationCode, 'client_id' => DI_CLIENT_ID, 'client_secret' => DI_CLIENT_SECRET, 'redirect_uri' => home_url('/login/callback') ] ] ); return $this->processResponse($response); } catch (Exception $e) { return ['error' => 'Token request failed: ' . $e->getMessage()]; } } /** * Get user information using access token * @param string $accessToken * @return array */ private function getUserInfo(string $accessToken): array { try { $response = $this->http->get( DI_ENDPOINT . '/userinfo', [ 'timeout' => self::TIMEOUT, 'redirection' => self::REDIRECTION_LIMIT, 'sslverify' => true, 'headers' => [ 'Authorization' => 'Bearer ' . $accessToken, 'Content-Type' => 'application/json' ] ] ); return $this->processResponse($response); } catch (Exception $e) { return ['error' => 'User info request failed: ' . $e->getMessage()]; } } /** * Process HTTP response and handle errors * @param mixed $response * @return array */ private function processResponse($response): array { if (is_wp_error($response)) { return ['error' => 'Request Error: ' . $response->get_error_message()]; } $httpCode = wp_remote_retrieve_response_code($response); $body = json_decode(wp_remote_retrieve_body($response), true); if ($httpCode >= 400) { return [ 'error' => $body['error_description'] ?? 'Unknown error', 'http_code' => $httpCode ]; } return $body; } /** * Call the BasisAPI * @param string $apiKey * @param array $data * @return array */ public function call_basisapi($apiKey, array $data = []): array { $url = 'https://basisapi.di.dk/api/virksomhed/soegfilter'; $ch = curl_init($url); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_HTTPHEADER => [ 'Accept: application/json', 'api_key: ' . $apiKey, 'Content-Type: application/json' ], CURLOPT_POSTFIELDS => json_encode($data), ]); $response = curl_exec($ch); if (curl_errno($ch)) { $error_msg = curl_error($ch); curl_close($ch); return [ 'success' => false, 'error' => $error_msg ]; } $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return [ 'success' => ($http_code >= 200 && $http_code < 300), 'status_code' => $http_code, 'data' => json_decode($response, true) ]; } /** * Handle the authentication flow * @param string|null $authCode */ public function processAuth($authCode): void { if (empty($authCode)) { wp_die( wp_json_encode(['error' => 'Authorization code is missing'], JSON_PRETTY_PRINT), 'Authentication Error', ['response' => 400] ); } // Get access token $tokenResponse = $this->getAccessToken($authCode); if (isset($tokenResponse['error'])) { wp_die( wp_json_encode($tokenResponse, JSON_PRETTY_PRINT), 'Token Error', ['response' => 400] ); } $accessToken = $tokenResponse['access_token'] ?? null; $expiresIn = $tokenResponse['expires_in'] ?? 3600; // Default to 1 hour if not provided if (!$accessToken) { wp_die( wp_json_encode(['error' => 'Access token is missing'], JSON_PRETTY_PRINT), 'Token Error', ['response' => 400] ); } // Get user info $userInfo = $this->getUserInfo($accessToken); if (isset($userInfo['error'])) { wp_die( wp_json_encode($userInfo, JSON_PRETTY_PRINT), 'User Info Error', ['response' => 400] ); } // Store in session $_SESSION['access_token'] = $accessToken; $_SESSION['user_info'] = $userInfo; $_SESSION['token_expiry'] = time() + $expiresIn; $requestData = [ "foreningMedlemskabFilter" => 101, "inkluderGeografi" => true ]; $member_region_response = $this->call_basisapi($accessToken, $requestData); $_SESSION['member_region_response'] = $member_region_response; // Debug output (remove in production) if (defined('WP_DEBUG') && WP_DEBUG) { echo '<pre>' . print_r([ 'authCode' => $authCode, 'token_response' => $tokenResponse, 'user_info' => $userInfo, 'member_region_response' => $member_region_response ], true) . '</pre>'; } // Redirect to protected page wp_safe_redirect(home_url('/min-side')); exit; } } // Process authentication $authCode = filter_input(INPUT_GET, 'code', FILTER_SANITIZE_STRING); $authHandler = new AuthHandler(); $authHandler->processAuth($authCode);
Save File
Cancel