Jake Vanderwerf
10 days ago de317675a8069b747cb253ba3e2b5dc394ca36ef
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
<?php
namespace JVBase\integrations;
use JVBase\managers\CustomTable;
 
if (!defined('ABSPATH')) {
    exit;
}
 
class Auth
{
    private static ?Auth $instance = null;
    private string $encryption_key;
    private CustomTable $table;
 
    private function __construct()
    {
        $this->getEncryptionKey();
        $this->defineTable();
    }
 
    protected function defineTable():void
    {
        $table = CustomTable::for('integrations');
        $table->setColumns([
            'id'            => 'bigint(20) unsigned NOT NULL AUTO_INCREMENT',
            'user_id'       => $table->getUserIDType().' DEFAULT NULL',
            'integration'   => "ENUM('bluesky','cloudflare','facebook','google-maps','gmb','helcim','instagram','postmark','square','umami') NOT NULL",
            'credentials'   => 'varchar(1000) DEFAULT NULL',
            'created_at'    => 'datetime DEFAULT CURRENT_TIMESTAMP',
            'updated_at'    => 'datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
            'last_tested'   => 'datetime DEFAULT NULL',
            'is_healthy'    => 'tinyint(1) DEFAULT 1',
            'webhook_healthy'   => 'tinyint(1) DEFAULT 1',
            'request_healthy'   => 'tinyint(1) DEFAULT 1',
            'oauth_healthy'     => 'tinyint(1) DEFAULT 1',
        ]);
 
        $table->setKeys([
            ['key' => 'PRIMARY', 'value' => '(`id`)'],
            ['key' => 'UNIQUE', 'value' => '`user_integration` (`user_id`, `integration`)'],
            '`user` (`user_id`)',
        ]);
 
        $base = BASE;
        $table->setConstraints([
            "CONSTRAINT `{$base}integrations_user` FOREIGN KEY (`user_id`)
            REFERENCES `{$table->getUserTable()}` (`ID`) ON DELETE CASCADE"
        ]);
        $table->defineTable();
        $this->table = $table;
    }
 
    public static function getInstance(): Auth
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
 
    /**
     * Store encrypted credentials
     */
    public function storeCredentials(string $service, array $credentials, ?int $userID = null): bool
    {
        $find = $this->findBy($service, $userID);
        error_log('Storing Credentials: '.print_r($credentials, true));
 
        $update = [
            'credentials'   => $this->encrypt(json_encode($credentials))
        ];
 
        error_log('Find: '.print_r($find, true));
        error_log('Update: '.print_r($update, true));
        $updated = $this->table->findOrCreate($find, $update);
        error_log('Last error: '.print_r($this->table->getLastError(), true));
        error_log('Updated: '.print_r($updated, true));
 
        return (bool)$updated;
    }
 
    /**
     * Retrieve and decrypt credentials
     */
    public function getCredentials(string $service, ?int $userID = null): array
    {
        $find = $this->findBy($service, $userID);
        $credentials = $this->table->pluck('credentials', $find);
        if (empty($credentials)) {
            return [];
        }
        $decrypted_data = $this->decrypt($credentials[0]);
        return empty($decrypted_data) ? [] : json_decode($decrypted_data, true);
    }
 
    /**
     * Delete credentials
     */
    public function deleteCredentials(string $service, ?int $userID = null): bool
    {
        $find = $this->findBy($service, $userID);
        return $this->table->delete($find);
    }
 
    protected function findBy(string $service, ?int $userID = null):array
    {
        return [
            'user_id'   => $userID,
            'integration'=> $service
        ];
    }
 
    /**
     * Check if credentials exist
     */
    public function hasCredentials(string $service, ?int $userID = null): bool
    {
        return !empty($this->getCredentials($service, $userID));
    }
 
    /**
     * Get or create encryption key
     */
    private function getEncryptionKey():void
    {
        $this->encryption_key = JVB_KEY;
    }
 
    /**
     * Encrypt data
     */
    private function encrypt(string $data): string
    {
        $iv = random_bytes(16);
        $encrypted = openssl_encrypt($data, 'AES-256-CBC', $this->encryption_key, 0, $iv);
        return base64_encode($iv . $encrypted);
    }
 
    /**
     * Decrypt data
     */
    private function decrypt(string $data): ?string
    {
        $data = base64_decode($data);
        $iv = substr($data, 0, 16);
        $encrypted = substr($data, 16);
 
        return openssl_decrypt($encrypted, 'AES-256-CBC', $this->encryption_key, 0, $iv);
    }
 
    /**
     * Get all users with credentials for a service
     */
    public function getUsersWithCredentials(string $service): array
    {
        return $this->table->pluck('user_id', ['integration' => $service]);
    }
 
    public function updateTested(string $service, ?int $userID = null):void
    {
        $find = $this->findBy($service, $userID);
        $this->table->update([
            'last_tested'   => time(),
        ], $find);
    }
 
    public function markUnhealthy(string $service, string $type = '', ?int $userID = null):void
    {
        $update = [];
        switch ($type) {
            case 'oauth':
                $update['oauth_healthy'] = 0;
                break;
            case 'request':
                $update['request_healthy'] = 0;
                break;
            case 'webhook':
                $update['webhook_healthy'] = 0;
                break;
            default:
                $update['is_healthy'] = 0;
                break;
        }
        $find = $this->findBy($service, $userID);
        $this->table->update($update, $find);
    }
}