Jake Vanderwerf
2026-01-11 474109a5df0a06f5343ab184838fe2d80e3872a8
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
<?php
namespace JVBase\rest\routes;
 
use JVBase\rest\RestRouteManager;
use WP_REST_Request;
use WP_REST_Response;
use Exception;
 
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}
 
class IntegrationsRoutes extends RestRouteManager
{
 
    /**
     * Register REST routes
     */
    public function registerRoutes(): void
    {
        register_rest_route($this->namespace, '/integrations', [
            'methods' => 'POST',
            'callback' => [$this, 'handleAction'],
            'permission_callback' => [$this, 'checkPermission'],
            'args' => [
                'service' => [
                    'required' => true,
                    'type'  => 'string',
                    'enum'  => JVB()->getAvailableServices()
                ],
                'action' => [
                    'required' => true,
                    'sanitize_callback' => 'sanitize_text_field',
                ],
                'user_id' => [
                    'required' => false,
                    'sanitize_callback' => 'absint',
                ],
                'context' => [
                    'required' => false,
                    'default' => 'user',
                    'sanitize_callback' => 'sanitize_text_field',
                    'validate_callback' => function($param) {
                        return in_array($param, ['admin', 'user']);
                    }
                ],
                'data' => [
                    'required' => false,
                    'default' => [],
                ]
            ]
        ]);
 
//      register_rest_route($this->namespace, '/oauth/callback', [
//          'methods' => 'GET',
//          'callback' => [$this, 'handleOAuthCallback'],
//          'permission_callback' => '__return_true', // External service callback
//          'args' => [
//              'service' => [
//                  'required' => true,
//                  'sanitize_callback' => 'sanitize_text_field',
//              ],
//              'code' => [
//                  'required' => false,
//                  'sanitize_callback' => 'sanitize_text_field',
//              ],
//              'state' => [
//                  'required' => false,
//                  'sanitize_callback' => 'sanitize_text_field',
//              ],
//              'error' => [
//                  'required' => false,
//                  'sanitize_callback' => 'sanitize_text_field',
//              ]
//          ]
//      ]);
 
        // Add OAuth initiation route (for AJAX calls)
        register_rest_route($this->namespace, '/oauth/connect', [
            'methods' => 'POST',
            'callback' => [$this, 'initiateOAuth'],
            'permission_callback' => [$this, 'checkPermissions'],
            'args' => [
                'service' => [
                    'required' => true,
                    'sanitize_callback' => 'sanitize_text_field',
                ],
                'user_id' => [
                    'required' => false,
                    'sanitize_callback' => 'absint',
                ],
                'return_url' => [
                    'required' => false,
                    'sanitize_callback' => 'esc_url_raw',
                ]
            ]
        ]);
    }
 
    /**
     * Check permissions based on context
     */
    public function checkPermission(\WP_REST_Request $request): bool
    {
        parent::checkPermission($request);
        $context = $request->get_param('context') ?? 'user';
        $user_id = $request->get_param('user_id');
 
        // Admin context requires manage_options
        if ($context === 'admin') {
            return current_user_can('manage_options');
        }
 
        // User context
        if (!is_user_logged_in()) {
            return false;
        }
 
        $current_user_id = get_current_user_id();
 
        // If user_id provided, verify it matches current user
        // OR current user is admin
        if ($user_id && $user_id != $current_user_id) {
            return current_user_can('manage_options');
        }
 
        return true;
    }
 
    /**
     * Handle integration actions
     */
    public function handleAction(WP_REST_Request $request): WP_REST_Response
    {
        error_log('[IntegrationsRoutes] handleAction request:'.print_r($request->get_params(), true));
        $service = $request->get_param('service');
        $action = $request->get_param('action');
 
        // Get the integration instance
        $userID = absint($request->get_param('user_id'));
        if (!$this->userCheck($userID)) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Invalid User'
            ]);
        }
 
        $theUserID = (user_can($userID, 'manage_options')) ? null : $userID;
        $integration = JVB()->connect($service, $theUserID);
 
        if (!$integration) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Service not found'
            ], 404);
        }
 
 
        $integration->getCredentials();
 
        // Handle the action
        try {
            // Get data parameter - DON'T convert empty array to null
            $data = $request->get_param('data');
 
            // Only set to null if it's truly empty or not provided
            if (!is_array($data) && empty($data)) {
                $data = null;
            }
 
            error_log('[IntegrationsRoutes] Calling processAction with data: ' . print_r($data, true));
 
            $result = $integration->processAction($action, $data);
 
            return new WP_REST_Response($result, 200);
 
        } catch (Exception $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => $e->getMessage()
            ], 400);
        }
    }
 
    public function initiateOAuth(WP_REST_Request $request): WP_REST_Response
    {
        $service = $request->get_param('service');
        $user_id = $request->get_param('user_id') ?: get_current_user_id();
        $return_url = $request->get_param('return_url');
 
        $integration = JVB()->connect($service, $user_id);
 
        if (!$integration || !$integration->isOAuthService) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Invalid OAuth service'
            ], 400);
        }
 
        $auth_url = $integration->getOAuthUrl($return_url);
 
        if ($auth_url) {
            return new WP_REST_Response([
                'success' => true,
                'auth_url' => $auth_url,
                'popup' => true
            ], 200);
        }
 
        return new WP_REST_Response([
            'success' => false,
            'message' => 'Failed to generate authorization URL'
        ], 400);
    }
 
    /**
     * Handle OAuth callback from external service
     */
    public function handleOAuthCallback(WP_REST_Request $request): WP_REST_Response
    {
        $service = $request->get_param('service');
        $code = $request->get_param('code');
        $state = $request->get_param('state');
        $error = $request->get_param('error');
 
        error_log('OAuth Callback - Service: ' . $request->get_param('service'));
        error_log('OAuth Callback - Code: ' . $request->get_param('code'));
        error_log('OAuth Callback - State: ' . $request->get_param('state'));
        error_log('OAuth Callback - Error: ' . $request->get_param('error'));
 
 
        $state_parts = explode('|', $state);
        $state_key = $state_parts[0] ?? '';
        $user_id = intval($state_parts[1] ?? 0);
        $user_id = ($user_id === 0) ? null : $user_id;
        $return_url = isset($state_parts[2]) ? base64_decode($state_parts[2]) : admin_url('admin.php?page=jvb-integrations');
 
 
        $state_data = get_transient('oauth_state_' . $state_key);
        error_log('State Data: '.print_r($state_data, true));
        if (!$state_data || $state_data['service'] !== $service) {
            wp_die('Invalid state parameter', 'OAuth Error');
        }
 
        // Delete the transient to prevent reuse
        delete_transient('oauth_state_' . $state_key);
        error_log('Return URL: '.print_r($return_url, true));
        // Handle error from OAuth provider
        if ($error) {
            $error_description = $request->get_param('error_description') ?? 'Authorization denied';
 
            wp_redirect(add_query_arg([
                'page' => 'jvb-integrations',
                'error' => 'OAuth authorization denied: ' . $error_description
            ], $return_url));
            exit;
        }
 
        // Get integration instance
        error_log('User ID: '.print_r($user_id, true));
        error_log('Service: '.print_r($service, true));
        $integration = JVB()->connect($service, $user_id);
 
        if (!$integration) {
            wp_die('Invalid service: ' . esc_html($service), 'OAuth Error');
        }
 
 
        // Exchange code for tokens
        $result = $integration->handleOAuthCode($code, $state);
 
        // Redirect back with result
        if ($result['success']) {
            wp_redirect(add_query_arg([
                'page' => 'jvb-integrations',
                'success' => 'Successfully connected to ' . $integration->title
            ], $return_url));
        } else {
            // Handle failure
            $error_message = $result['message'] ?? 'Failed to complete OAuth authorization';
 
            wp_redirect(add_query_arg([
                'page' => 'jvb-integrations',
                'error' => $error_message
            ], $return_url));
        }
        exit;
    }
}