Completed
Push — development ( 2fd849...7f23a5 )
by Ashutosh
24:05 queued 14:01
created

HomeController::checkUpdatesExpiry()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 26
rs 9.4222
c 0
b 0
f 0
cc 5
nc 8
nop 1
1
<?php
2
3
namespace App\Http\Controllers;
4
5
use App\Model\Order\Order;
6
use App\Model\Product\Product;
7
use Exception;
8
use Illuminate\Http\Request;
9
10
class HomeController extends BaseHomeController
11
{
12
    /*
13
      |--------------------------------------------------------------------------
14
      | Home Controller
15
      |--------------------------------------------------------------------------
16
      |
17
      | This controller renders your application's "dashboard" for users that
18
      | are authenticated. Of course, you are free to change or remove the
19
      | controller as you wish. It is just here to get your app started!
20
      |
21
     */
22
23
    /**
24
     * Create a new controller instance.
25
     *
26
     * @return void
27
     */
28
    public function __construct()
29
    {
30
        $this->middleware('auth', ['only' => ['index']]);
31
        $this->middleware('admin', ['only' => ['index']]);
32
    }
33
34
    /**
35
     * Show the application dashboard to the user.
36
     *
37
     * @return \Response
38
     */
39
    public function version(Request $request, Product $product)
40
    {
41
        $url = $request->input('response_url');
42
43
        $title = $request->input('title');
44
        //dd($title);
45
        $id = $request->input('id');
46
        if ($id) {
47
            $product = $product->where('id', $id)->first();
48
        } else {
49
            $product = $product->where('name', $title)->first();
50
        }
51
52
        if ($product) {
53
            $version = str_replace('v', '', $product->version);
54
        } else {
55
            $version = 'Not-Available';
56
        }
57
58
        echo "<form action=$url method=post name=redirect >";
59
        echo '<input type=hidden name=_token value='.csrf_token().'>';
60
        echo "<input type=hidden name=value value=$version />";
61
        echo '</form>';
62
        echo"<script language='javascript'>document.redirect.submit();</script>";
63
    }
64
65
    public function getVersion(Request $request, Product $product)
66
    {
67
        $this->validate($request, [
68
            'title' => 'required',
69
        ]);
70
        $title = $request->input('title');
71
        $product = $product->where('name', $title)->first();
72
        if ($product) {
73
            $version = $product->version;
74
        } else {
75
            return 0;
76
        }
77
78
        return str_replace('v', '', $product->version);
79
    }
80
81
    public function serialV2(Request $request, Order $order)
82
    {
83
        try {
84
            $faveo_encrypted_order_number = self::decryptByFaveoPrivateKey($request->input('order_number'));
85
            $faveo_encrypted_key = self::decryptByFaveoPrivateKey($request->input('serial_key'));
86
            \Log::emergency(json_encode(['domain' => $request
87
                ->input('domain'), 'enc_serial' => $faveo_encrypted_key,
88
                'enc_order' => $faveo_encrypted_order_number, ]));
89
            $request_type = $request->input('request_type');
90
            $faveo_name = $request->input('name');
91
            $faveo_version = $request->input('version');
92
            $order_number = $this->checkOrder($faveo_encrypted_order_number);
93
            $domain = $request->input('domain');
94
            $domain = $this->checkDomain($domain);
95
            $serial_key = $this->checkSerialKey($faveo_encrypted_key, $order_number);
96
97
            \Log::emergency(json_encode(['domain' => $request->input('domain'),
98
             'serial'                             => $serial_key, 'order' => $order_number, ]));
99
            $result = [];
100
            if ($request_type == 'install') {
101
                $result = $this->verificationResult($order_number, $serial_key);
102
            }
103
            if ($request_type == 'check_update') {
104
                $result = $this->checkUpdate($order_number, $serial_key, $domain, $faveo_name, $faveo_version);
105
            }
106
            $result = self::encryptByPublicKey(json_encode($result));
107
108
            return $result;
109
        } catch (Exception $ex) {
110
            $result = ['status' => 'error', 'message' => $ex->getMessage()];
111
            $result = self::encryptByPublicKey(json_encode($result));
112
113
            return $result;
114
        }
115
    }
116
117
    public function serial(Request $request, Order $order)
118
    {
119
        try {
120
            $url = $request->input('url');
121
            $faveo_encrypted_order_number = self::decryptByFaveoPrivateKey($request->input('order_number'));
122
            $domain = $this->getDomain($request->input('domain'));
123
124
            //return $domain;
125
            $faveo_encrypted_key = self::decryptByFaveoPrivateKey($request->input('serial_key'));
126
            $request_type = $request->input('request_type');
127
            $faveo_name = $request->input('name');
128
            $faveo_version = $request->input('version');
129
            $order_number = $this->checkOrder($faveo_encrypted_order_number);
130
131
            $domain = $this->checkDomain($domain);
132
            $serial_key = $this->checkSerialKey($faveo_encrypted_key, $order_number);
133
            //dd($serial_key);
134
            //return $serial_key;
135
            $result = [];
136
            if ($request_type == 'install') {
137
                $result = $this->verificationResult($order_number, $serial_key);
138
            }
139
            if ($request_type == 'check_update') {
140
                $result = $this->checkUpdate($order_number, $serial_key, $domain, $faveo_name, $faveo_version);
141
            }
142
            $result = self::encryptByPublicKey(json_encode($result));
143
            $this->submit($result, $url);
144
        } catch (Exception $ex) {
145
            $result = ['status' => 'error', 'message' => $ex->getMessage()];
146
            $result = self::encryptByPublicKey(json_encode($result));
147
            $this->submit($result, $url);
148
        }
149
    }
150
151
    public static function decryptByFaveoPrivateKeyold($encrypted)
152
    {
153
        try {
154
            // Get the private Key
155
            $path = storage_path('app'.DIRECTORY_SEPARATOR.'private.key');
156
            $key_content = file_get_contents($path);
157
            if (!$privateKey = openssl_pkey_get_private($key_content)) {
158
                dd('Private Key failed');
159
            }
160
            $a_key = openssl_pkey_get_details($privateKey);
161
162
            // Decrypt the data in the small chunks
163
            $chunkSize = ceil($a_key['bits'] / 8);
164
            $output = '';
165
166
            while ("¥IM‰``쐇Á›LVP›†>¯öóŽÌ3(¢z#¿î1¾­:±Zï©PqÊ´›7×:F௦   à•…Ä'öESW±ÉŸLÃvÈñÔs•ÍU)ÍL 8¬š‰A©·Å $}Œ•lA9™¡”¸èÅØv‘ÂOÈ6„_y5¤ì§—ÿíà(ow‰È&’v&T/FLƒigjÒZ eæaa”{©ªUBFÓ’Ga*ÀŒ×?£}-jÏùh¾Q/Ž“1YFq[͉¬òÚ‚œ½Éº5ah¶vZ#,ó@‚rOƱíVåèÜÖšU¦ÚmSΓMý„ùP") {
167
                $chunk = substr($encrypted, 0, $chunkSize);
168
                $encrypted = substr($encrypted, $chunkSize);
169
                $decrypted = '';
170
                if (!openssl_private_decrypt($chunk, $decrypted, $privateKey)) {
171
                    dd('Failed to decrypt data');
172
                }
173
                $output .= $decrypted;
174
            }
175
            openssl_free_key($privateKey);
176
177
            // Uncompress the unencrypted data.
178
            $output = gzuncompress($output);
179
            dd($output);
180
            echo '<br /><br /> Unencrypted Data: '.$output;
181
        } catch (Exception $ex) {
182
            dd($ex);
183
        }
184
    }
185
186
    public function createEncryptionKeys()
187
    {
188
        try {
189
            $privateKey = openssl_pkey_new([
190
                'private_key_bits' => 2048, // Size of Key.
191
                'private_key_type' => OPENSSL_KEYTYPE_RSA,
192
            ]);
193
            //dd($privateKey);
194
            // Save the private key to private.key file. Never share this file with anyone.
195
            openssl_pkey_export_to_file($privateKey, 'private.key');
196
197
            // Generate the public key for the private key
198
            $a_key = openssl_pkey_get_details($privateKey);
199
            //dd($a_key);
200
            // Save the public key in public.key file. Send this file to anyone who want to send you the encrypted data.
201
            file_put_contents('public.key', $a_key['key']);
202
203
            // Free the private Key.
204
            openssl_free_key($privateKey);
205
        } catch (\Exception $ex) {
206
            dd($ex);
207
        }
208
    }
209
210
    public function checkOrder($faveo_decrypted_order)
211
    {
212
        try {
213
            $order = new Order();
214
//            $faveo_decrypted_order = self::decryptByFaveoPrivateKey($faveo_encrypted_order_number);
215
216
            $this_order = $order->where('number', 'LIKE', $faveo_decrypted_order)->first();
217
            if (!$this_order) {
218
                return;
219
            } else {
220
                return $this_order->number;
221
            }
222
        } catch (Exception $ex) {
223
            throw new Exception($ex->getMessage());
224
        }
225
    }
226
227
    public function faveoVerification(Request $request)
228
    {
229
        try {
230
            $data = $request->input('data');
231
            $json = self::decryptByFaveoPrivateKey($data);
232
            $data = json_decode($json);
233
            //return $data->url;
234
235
            $domain = $data->url;
236
237
            $faveo_encrypted_order_number = $data->order_number;
238
239
            //$domain = $data->domain;
240
241
            $faveo_encrypted_key = $data->serial_key;
242
243
            $request_type = $data->request_type;
244
245
            $faveo_name = $data->name;
246
247
            $faveo_version = $data->version;
248
249
            $order_number = $this->checkOrder($faveo_encrypted_order_number);
250
251
            $domain = $this->checkDomain($domain);
252
253
            $serial_key = $this->checkSerialKey($faveo_encrypted_key, $order_number);
254
            //dd($serial_key);
255
            //return $serial_key;
256
            $result = [];
257
            if ($request_type == 'install') {
258
                $result = $this->verificationResult($order_number, $serial_key, $domain);
259
            }
260
            if ($request_type == 'check_update') {
261
                $result = $this->checkUpdate($order_number, $serial_key, $domain, $faveo_name, $faveo_version);
262
            }
263
            $result = self::encryptByPublicKey(json_encode($result));
264
265
            return $result;
266
        } catch (Exception $ex) {
267
            $result = ['status' => 'error', 'message' => $ex->getMessage().'  
268
            file=> '.$ex->getFile().' Line=>'.$ex->getLine()];
269
            $result = self::encryptByPublicKey(json_encode($result));
270
271
            return $result;
272
        }
273
    }
274
275
    public function submit($result, $url)
276
    {
277
        echo "<form action=$url method=post name=redirect>";
278
        echo '<input type=hidden name=_token value=csrf_token()/>';
279
        echo '<input type=hidden name=result value='.$result.'/>';
280
        echo '</form>';
281
        echo"<script language='javascript'>document.redirect.submit();</script>";
282
    }
283
284
    public function checkUpdate($order_number, $serial_key, $domain, $faveo_name, $faveo_version)
285
    {
286
        try {
287
            if ($order_number && $domain && $serial_key) {
288
                $order = $this->verifyOrder($order_number, $serial_key, $domain);
289
                //var_dump($order);
290
                if ($order) {
291
                    return $this->checkFaveoDetails($order_number, $faveo_name, $faveo_version);
292
                } else {
293
                    return ['status' => 'fails', 'message' => 'this-is-an-invalid-request'];
294
                }
295
            } else {
296
                return ['status' => 'fails', 'message' => 'this-is-an-invalid-request'];
297
            }
298
        } catch (Exception $ex) {
299
            throw new Exception($ex->getMessage());
300
        }
301
    }
302
303
    public function checkFaveoDetails($order_number, $faveo_name, $faveo_version)
304
    {
305
        try {
306
            $order = new Order();
307
            $product = new Product();
308
            $this_order = $order->where('number', $order_number)->first();
309
            if ($this_order) {
310
                $product_id = $this_order->product;
311
                $this_product = $product->where('id', $product_id)->first();
312
                if ($this_product) {
313
                    $version = str_replace('v', '', $this_product->version);
314
315
                    return ['status' => 'success', 'message' => 'this-is-a-valid-request', 'version' => $version];
316
                }
317
            }
318
319
            return ['status' => 'fails', 'message' => 'this-is-an-invalid-request'];
320
        } catch (Exception $ex) {
321
            throw new Exception($ex->getMessage());
322
        }
323
    }
324
325
    public static function encryptByPublicKey($data)
326
    {
327
        $path = storage_path().DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'public.key';
328
        //dd($path);
329
        $key_content = file_get_contents($path);
330
        $public_key = openssl_get_publickey($key_content);
331
332
        $encrypted = $e = null;
333
        openssl_seal($data, $encrypted, $e, [$public_key]);
334
335
        $sealed_data = base64_encode($encrypted);
336
        $envelope = base64_encode($e[0]);
337
338
        $result = ['seal' => $sealed_data, 'envelope' => $envelope];
339
340
        return json_encode($result);
341
    }
342
343
    public function downloadForFaveo(Request $request, Order $order)
344
    {
345
        try {
346
            $faveo_encrypted_order_number = $request->input('order_number');
347
            $faveo_serial_key = $request->input('serial_key');
348
            $orderSerialKey = $order->where('number', $faveo_encrypted_order_number)
349
                    ->value('serial_key');
350
351
            $this_order = $order
352
                     ->where('number', $faveo_encrypted_order_number)
353
                    ->first();
354
            if ($this_order && $orderSerialKey == $faveo_serial_key) {
355
                $product_id = $this_order->product;
356
                $product_controller = new \App\Http\Controllers\Product\ProductController();
357
358
                return $product_controller->adminDownload($product_id, true);
359
            }
360
        } catch (\Exception $e) {
361
            return response()->json(['error' => $e->getMessage(), 'line' => $e->getFile()], 500);
362
        }
363
    }
364
365
    public function latestVersion(Request $request, Product $product)
366
    {
367
        $v = \Validator::make($request->all(), [
368
                    'title' => 'required',
369
        ]);
370
        if ($v->fails()) {
371
            $error = $v->errors();
372
373
            return response()->json(compact('error'));
374
        }
375
376
        try {
377
            $title = $request->input('title');
378
            $product = $product->where('name', $title)->first();
379
            if ($product) {
380
                $message = ['version' => str_replace('v', '', $product->version)];
381
            } else {
382
                $message = ['error' => 'product_not_found'];
383
            }
384
            $message = ['version' => str_replace('v', '', $product->version)];
385
        } catch (\Exception $e) {
386
            $message = ['error' => $e->getMessage()];
387
        }
388
389
        return response()->json($message);
390
    }
391
392
    /*
393
     * Check if the Product is valid For Auto Updates
394
    * @params string Serial Key in encrypted
395
    * @return array
396
    */
397
398
399
}
400