Jake Vanderwerf
2026-07-10 f94860aacd6200fb24c9e7431eb379a368cb392d
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
<?php
namespace JVBase\integrations;
 
use JVBase\managers\CustomTable;
 
if (!defined('ABSPATH')) {
    exit;
}
 
class CredentialsManager
{
    private static ?CredentialsManager $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().' NOT NULL',
            'integration'   => "ENUM('bluesky','cloudflare','facebook','google-maps','gmb','helcim','instagram','postmark','square','umami') NOT NULL",
            'credentials'   => 'varchar(255) DEFAULT NULL',
            'created_at'    => 'datetime DEFAULT CURRENT_TIMESTAMP',
            'updated_at'    => 'datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'
        ]);
 
        $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(): CredentialsManager
    {
        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);
        $update = [
            'credentials'   => $this->encrypt(json_encode($credentials))
        ];
        return (bool)$this->table->findOrCreate($find, $update);
    }
 
    /**
     * 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'   => is_null($userID) ? 0 : $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]);
    }
}