aboutsummaryrefslogtreecommitdiff
path: root/apps/web/controllers/api/Key.php
blob: 4e9a3834fcdb33b745048998a4689dab2b609019 (plain)
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
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH . '/libraries/REST_Controller.php';

/**
 * Keys Controller
 * This is a basic Key Management REST controller to make and delete keys
 *
 * @package         CodeIgniter
 * @subpackage      Rest Server
 * @category        Controller
 * @author          Phil Sturgeon, Chris Kacerguis
 * @license         MIT
 * @link            https://github.com/chriskacerguis/codeigniter-restserver
 */
class Key extends REST_Controller {

    protected $methods = [
            'index_put' => ['level' => 10, 'limit' => 10],
            'index_delete' => ['level' => 10],
            'level_post' => ['level' => 10],
            'regenerate_post' => ['level' => 10],
        ];

    /**
     * Key Create
     * Insert a key into the database
     *
     * @access    public
     * @return    void
     */
    public function index_put()
    {
        // Build a new key
        $key = self::_generate_key();

        // If no key level provided, provide a generic key
        $level = $this->put('level') ? $this->put('level') : 1;
        $ignore_limits = ctype_digit($this->put('ignore_limits')) ? (int) $this->put('ignore_limits') : 1;

        // Insert the new key
        if (self::_insert_key($key, ['level' => $level, 'ignore_limits' => $ignore_limits]))
        {
            $this->response([
                'status' => 1,
                'key' => $key
            ], 201); // 201 = Created
        }
        else
        {
            $this->response([
                'status' => 0,
                'error' => 'Could not save the key'
            ], 500); // 500 = Internal Server Error
        }
    }

    // --------------------------------------------------------------------

    /**
     * Key Delete
     * Remove a key from the database to stop it working
     *
     * @access    public
     * @return    void
     */
    public function index_delete()
    {
        $key = $this->delete('key');

        // Does this key exist?
        if (!self::_key_exists($key))
        {
            // It doesn't appear the key exists
            $this->response([
                'error' => 'Invalid API Key'
            ], 400); // 400 = Bad Request
        }

        // Destroy it
        self::_delete_key($key);

        // Respond that the key was destroyed
        $this->response([
            'status' => 1,
            'success' => 'API Key was deleted'
            ], 204); // 204 = Success, No Content
    }

    // --------------------------------------------------------------------

    /**
     * Update Key
     * Change the level
     *
     * @access    public
     * @return    void
     */
    public function level_post()
    {
        $key = $this->post('key');
        $new_level = $this->post('level');

        // Does this key exist?
        if (!self::_key_exists($key))
        {
            // It doesn't appear the key exists
            $this->response([
                'error' => 'Invalid API Key'
            ], 400); // 400 = Bad Request
        }

        // Update the key level
        if (self::_update_key($key, ['level' => $new_level]))
        {
            $this->response([
                'status' => 1,
                'success' => 'API Key was updated'
            ], 200); // 200 = OK
        }
        else
        {
            $this->response([
                'status' => 0,
                'error' => 'Could not update the key level'
            ], 500); // 500 = Internal Server Error
        }
    }

    // --------------------------------------------------------------------

    /**
     * Update Key
     * Change the level
     *
     * @access    public
     * @return    void
     */
    public function suspend_post()
    {
        $key = $this->post('key');

        // Does this key exist?
        if (!self::_key_exists($key))
        {
            // It doesn't appear the key exists
            $this->response([
                'error' => 'Invalid API Key'
            ], 400); // 400 = Bad Request
        }

        // Update the key level
        if (self::_update_key($key, ['level' => 0]))
        {
            $this->response([
                'status' => 1,
                'success' => 'Key was suspended'
            ], 200); // 200 = OK
        }
        else
        {
            $this->response([
                'status' => 0,
                'error' => 'Could not suspend the user'
            ], 500); // 500 = Internal Server Error
        }
    }

    // --------------------------------------------------------------------

    /**
     * Regenerate Key
     * Remove a key from the database to stop it working
     *
     * @access    public
     * @return    void
     */
    public function regenerate_post()
    {
        $old_key = $this->post('key');
        $key_details = self::_get_key($old_key);

        // Does this key exist?
        if (!$key_details)
        {
            // It doesn't appear the key exists
            $this->response([
                'error' => 'Invalid API Key'
            ], 400); // 400 = Bad Request
        }

        // Build a new key
        $new_key = self::_generate_key();

        // Insert the new key
        if (self::_insert_key($new_key, ['level' => $key_details->level, 'ignore_limits' => $key_details->ignore_limits]))
        {
            // Suspend old key
            self::_update_key($old_key, ['level' => 0]);

            $this->response([
                'status' => 1,
                'key' => $new_key
            ], 201); // 201 = Created
        }
        else
        {
            $this->response([
                'status' => 0,
                'error' => 'Could not save the key'
            ], 500); // 500 = Internal Server Error
        }
    }

    // --------------------------------------------------------------------

    /* Helper Methods */

    private function _generate_key()
    {
        do
        {
            // Generate a random salt
            $salt = $this->security->get_random_bytes(64);
            
            // If an error occurred, then fall back to the previous method
            if ($salt === FALSE)
            {
				$salt = hash('sha256', time() . mt_rand());
            }
            $new_key = substr($salt, 0, config_item('rest_key_length'));
        }
        while (self::_key_exists($new_key));
        // Already in the DB? Fail. Try again

        return $new_key;
    }

    // --------------------------------------------------------------------

    /* Private Data Methods */

    private function _get_key($key)
    {
        return $this->db->where(config_item('rest_key_column'), $key)->get(config_item('rest_keys_table'))->row();
    }

    // --------------------------------------------------------------------

    private function _key_exists($key)
    {
        return $this->db->where(config_item('rest_key_column'), $key)->count_all_results(config_item('rest_keys_table')) > 0;
    }

    // --------------------------------------------------------------------

    private function _insert_key($key, $data)
    {
        $data[config_item('rest_key_column')] = $key;
        $data['date_created'] = function_exists('now') ? now() : time();

        return $this->db
            ->set($data)
            ->insert(config_item('rest_keys_table'));
    }

    // --------------------------------------------------------------------

    private function _update_key($key, $data)
    {
        return $this->db
            ->where(config_item('rest_key_column'), $key)
            ->update(config_item('rest_keys_table'), $data);
    }

    // --------------------------------------------------------------------

    private function _delete_key($key)
    {
        return $this->db
            ->where(config_item('rest_key_column'), $key)
            ->delete(config_item('rest_keys_table'));
    }
}