Completed
Push — development ( f6b77e...36b1f7 )
by Ashutosh
09:19
created

HomeController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace App\Http\Controllers;
4
5
use App\Model\Order\Order;
6
use App\Model\Product\Product;
7
use Crypt;
8
use Exception;
9
use Illuminate\Http\Request;
10
11
class HomeController extends BaseHomeController
12
{
13
    /*
14
      |--------------------------------------------------------------------------
15
      | Home Controller
16
      |--------------------------------------------------------------------------
17
      |
18
      | This controller renders your application's "dashboard" for users that
19
      | are authenticated. Of course, you are free to change or remove the
20
      | controller as you wish. It is just here to get your app started!
21
      |
22
     */
23
24
    /**
25
     * Create a new controller instance.
26
     *
27
     * @return void
28
     */
29
    public function __construct()
30
    {
31
        $this->middleware('auth', ['only' => ['index']]);
32
        $this->middleware('admin', ['only' => ['index']]);
33
    }
34
35
    /**
36
     * Show the application dashboard to the user.
37
     *
38
     * @return \Response
39
     */
40
    public function version(Request $request, Product $product)
41
    {
42
        $url = $request->input('response_url');
43
44
        $title = $request->input('title');
45
        //dd($title);
46
        $id = $request->input('id');
47
        if ($id) {
48
            $product = $product->where('id', $id)->first();
49
        } else {
50
            $product = $product->where('name', $title)->first();
51
        }
52
53
        if ($product) {
54
            $version = str_replace('v', '', $product->version);
55
        } else {
56
            $version = 'Not-Available';
57
        }
58
59
        echo "<form action=$url method=post name=redirect >";
60
        echo '<input type=hidden name=_token value='.csrf_token().'>';
61
        echo "<input type=hidden name=value value=$version />";
62
        echo '</form>';
63
        echo"<script language='javascript'>document.redirect.submit();</script>";
64
    }
65
66
    public function getVersion(Request $request, Product $product)
67
    {
68
        $this->validate($request, [
69
            'title' => 'required',
70
        ]);
71
        $title = $request->input('title');
72
        $product = $product->where('name', $title)->first();
73
        if ($product) {
74
            $version = $product->version;
75
        } else {
76
            return 0;
77
        }
78
79
        return str_replace('v', '', $product->version);
80
    }
81
82
    public function serialV2(Request $request, Order $order)
83
    {
84
        try {
85
            $faveo_encrypted_order_number = self::decryptByFaveoPrivateKey($request->input('order_number'));
86
            $faveo_encrypted_key = self::decryptByFaveoPrivateKey($request->input('serial_key'));
87
            \Log::emergency(json_encode(['domain' => $request
88
                ->input('domain'), 'enc_serial' => $faveo_encrypted_key,
89
                'enc_order' => $faveo_encrypted_order_number, ]));
90
            $request_type = $request->input('request_type');
91
            $faveo_name = $request->input('name');
92
            $faveo_version = $request->input('version');
93
            $order_number = $this->checkOrder($faveo_encrypted_order_number);
94
            $domain = $request->input('domain');
95
            $domain = $this->checkDomain($domain);
96
            $serial_key = $this->checkSerialKey($faveo_encrypted_key, $order_number);
97
98
            \Log::emergency(json_encode(['domain' => $request->input('domain'),
99
             'serial'                             => $serial_key, 'order' => $order_number, ]));
100
            $result = [];
101
            if ($request_type == 'install') {
102
                $result = $this->verificationResult($order_number, $serial_key);
103
            }
104
            if ($request_type == 'check_update') {
105
                $result = $this->checkUpdate($order_number, $serial_key, $domain, $faveo_name, $faveo_version);
106
            }
107
            $result = self::encryptByPublicKey(json_encode($result));
108
109
            return $result;
110
        } catch (Exception $ex) {
111
            $result = ['status' => 'error', 'message' => $ex->getMessage()];
112
            $result = self::encryptByPublicKey(json_encode($result));
113
114
            return $result;
115
        }
116
    }
117
118
    public function serial(Request $request, Order $order)
119
    {
120
        try {
121
            $url = $request->input('url');
122
            $faveo_encrypted_order_number = self::decryptByFaveoPrivateKey($request->input('order_number'));
123
            $domain = $this->getDomain($request->input('domain'));
124
125
            //return $domain;
126
            $faveo_encrypted_key = self::decryptByFaveoPrivateKey($request->input('serial_key'));
127
            $request_type = $request->input('request_type');
128
            $faveo_name = $request->input('name');
129
            $faveo_version = $request->input('version');
130
            $order_number = $this->checkOrder($faveo_encrypted_order_number);
131
132
            $domain = $this->checkDomain($domain);
133
            $serial_key = $this->checkSerialKey($faveo_encrypted_key, $order_number);
134
            //dd($serial_key);
135
            //return $serial_key;
136
            $result = [];
137
            if ($request_type == 'install') {
138
                $result = $this->verificationResult($order_number, $serial_key);
139
            }
140
            if ($request_type == 'check_update') {
141
                $result = $this->checkUpdate($order_number, $serial_key, $domain, $faveo_name, $faveo_version);
142
            }
143
            $result = self::encryptByPublicKey(json_encode($result));
144
            $this->submit($result, $url);
145
        } catch (Exception $ex) {
146
            $result = ['status' => 'error', 'message' => $ex->getMessage()];
147
            $result = self::encryptByPublicKey(json_encode($result));
148
            $this->submit($result, $url);
149
        }
150
    }
151
152
    public static function decryptByFaveoPrivateKeyold($encrypted)
153
    {
154
        try {
155
            // Get the private Key
156
            $path = storage_path('app'.DIRECTORY_SEPARATOR.'private.key');
157
            $key_content = file_get_contents($path);
158
            if (!$privateKey = openssl_pkey_get_private($key_content)) {
159
                dd('Private Key failed');
160
            }
161
            $a_key = openssl_pkey_get_details($privateKey);
162
163
            // Decrypt the data in the small chunks
164
            $chunkSize = ceil($a_key['bits'] / 8);
165
            $output = '';
166
167
            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") {
168
                $chunk = substr($encrypted, 0, $chunkSize);
169
                $encrypted = substr($encrypted, $chunkSize);
170
                $decrypted = '';
171
                if (!openssl_private_decrypt($chunk, $decrypted, $privateKey)) {
172
                    dd('Failed to decrypt data');
173
                }
174
                $output .= $decrypted;
175
            }
176
            openssl_free_key($privateKey);
177
178
            // Uncompress the unencrypted data.
179
            $output = gzuncompress($output);
180
            dd($output);
181
            echo '<br /><br /> Unencrypted Data: '.$output;
182
        } catch (Exception $ex) {
183
            dd($ex);
184
        }
185
    }
186
187
    public function createEncryptionKeys()
188
    {
189
        try {
190
            $privateKey = openssl_pkey_new([
191
                'private_key_bits' => 2048, // Size of Key.
192
                'private_key_type' => OPENSSL_KEYTYPE_RSA,
193
            ]);
194
            //dd($privateKey);
195
            // Save the private key to private.key file. Never share this file with anyone.
196
            openssl_pkey_export_to_file($privateKey, 'private.key');
197
198
            // Generate the public key for the private key
199
            $a_key = openssl_pkey_get_details($privateKey);
200
            //dd($a_key);
201
            // Save the public key in public.key file. Send this file to anyone who want to send you the encrypted data.
202
            file_put_contents('public.key', $a_key['key']);
203
204
            // Free the private Key.
205
            openssl_free_key($privateKey);
206
        } catch (\Exception $ex) {
207
            dd($ex);
208
        }
209
    }
210
211
    public function checkOrder($faveo_decrypted_order)
212
    {
213
        try {
214
            $order = new Order();
215
//            $faveo_decrypted_order = self::decryptByFaveoPrivateKey($faveo_encrypted_order_number);
216
217
            $this_order = $order->where('number', 'LIKE', $faveo_decrypted_order)->first();
218
            if (!$this_order) {
219
                return;
220
            } else {
221
                return $this_order->number;
222
            }
223
        } catch (Exception $ex) {
224
            throw new Exception($ex->getMessage());
225
        }
226
    }
227
228
    public function faveoVerification(Request $request)
229
    {
230
        try {
231
            $data = $request->input('data');
232
            $json = self::decryptByFaveoPrivateKey($data);
233
            $data = json_decode($json);
234
            //return $data->url;
235
236
            $domain = $data->url;
237
238
            $faveo_encrypted_order_number = $data->order_number;
239
240
            //$domain = $data->domain;
241
242
            $faveo_encrypted_key = $data->serial_key;
243
244
            $request_type = $data->request_type;
245
246
            $faveo_name = $data->name;
247
248
            $faveo_version = $data->version;
249
250
            $order_number = $this->checkOrder($faveo_encrypted_order_number);
251
252
            $domain = $this->checkDomain($domain);
253
254
            $serial_key = $this->checkSerialKey($faveo_encrypted_key, $order_number);
255
            //dd($serial_key);
256
            //return $serial_key;
257
            $result = [];
258
            if ($request_type == 'install') {
259
                $result = $this->verificationResult($order_number, $serial_key, $domain);
260
            }
261
            if ($request_type == 'check_update') {
262
                $result = $this->checkUpdate($order_number, $serial_key, $domain, $faveo_name, $faveo_version);
263
            }
264
            $result = self::encryptByPublicKey(json_encode($result));
265
266
            return $result;
267
        } catch (Exception $ex) {
268
            $result = ['status' => 'error', 'message' => $ex->getMessage().'  
269
            file=> '.$ex->getFile().' Line=>'.$ex->getLine()];
270
            $result = self::encryptByPublicKey(json_encode($result));
271
272
            return $result;
273
        }
274
    }
275
276
    public function submit($result, $url)
277
    {
278
        echo "<form action=$url method=post name=redirect>";
279
        echo '<input type=hidden name=_token value=csrf_token()/>';
280
        echo '<input type=hidden name=result value='.$result.'/>';
281
        echo '</form>';
282
        echo"<script language='javascript'>document.redirect.submit();</script>";
283
    }
284
285
    public function checkUpdate($order_number, $serial_key, $domain, $faveo_name, $faveo_version)
286
    {
287
        try {
288
            if ($order_number && $domain && $serial_key) {
289
                $order = $this->verifyOrder($order_number, $serial_key, $domain);
290
                //var_dump($order);
291
                if ($order) {
292
                    return $this->checkFaveoDetails($order_number, $faveo_name, $faveo_version);
293
                } else {
294
                    return ['status' => 'fails', 'message' => 'this-is-an-invalid-request'];
295
                }
296
            } else {
297
                return ['status' => 'fails', 'message' => 'this-is-an-invalid-request'];
298
            }
299
        } catch (Exception $ex) {
300
            throw new Exception($ex->getMessage());
301
        }
302
    }
303
304
    public function checkFaveoDetails($order_number, $faveo_name, $faveo_version)
305
    {
306
        try {
307
            $order = new Order();
308
            $product = new Product();
309
            $this_order = $order->where('number', $order_number)->first();
310
            if ($this_order) {
311
                $product_id = $this_order->product;
312
                $this_product = $product->where('id', $product_id)->first();
313
                if ($this_product) {
314
                    $version = str_replace('v', '', $this_product->version);
315
316
                    return ['status' => 'success', 'message' => 'this-is-a-valid-request', 'version' => $version];
317
                }
318
            }
319
320
            return ['status' => 'fails', 'message' => 'this-is-an-invalid-request'];
321
        } catch (Exception $ex) {
322
            throw new Exception($ex->getMessage());
323
        }
324
    }
325
326
    public static function encryptByPublicKey($data)
327
    {
328
        $path = storage_path().DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'public.key';
329
        //dd($path);
330
        $key_content = file_get_contents($path);
331
        $public_key = openssl_get_publickey($key_content);
332
333
        $encrypted = $e = null;
334
        openssl_seal($data, $encrypted, $e, [$public_key]);
335
336
        $sealed_data = base64_encode($encrypted);
337
        $envelope = base64_encode($e[0]);
338
339
        $result = ['seal' => $sealed_data, 'envelope' => $envelope];
340
341
        return json_encode($result);
342
    }
343
344
    public function downloadForFaveo(Request $request, Order $order)
345
    {
346
        try {
347
            $faveo_encrypted_order_number = $request->input('order_number');
348
            $faveo_serial_key = $request->input('serial_key');
349
            $orderSerialKey = $order->where('number', $faveo_encrypted_order_number)
350
                    ->value('serial_key');
351
                    
352
            $this_order = $order
353
                     ->where('number', $faveo_encrypted_order_number)
354
                    ->first();
355
            if ($this_order && $orderSerialKey == $faveo_serial_key) {
356
                $product_id = $this_order->product;
357
                $product_controller = new \App\Http\Controllers\Product\ProductController();
358
                 
359
                return $product_controller->adminDownload($product_id, true);
360
            }
361
        } catch (\Exception $e) {
362
            return response()->json(['error' => $e->getMessage(), 'line' => $e->getFile()], 500);
363
        }
364
    }
365
366
    public function latestVersion(Request $request, Product $product)
367
    {
368
        $v = \Validator::make($request->all(), [
369
                    'title' => 'required',
370
        ]);
371
        if ($v->fails()) {
372
            $error = $v->errors();
373
374
            return response()->json(compact('error'));
375
        }
376
377
        try {
378
            $title = $request->input('title');
379
            $product = $product->where('name', $title)->first();
380
            if ($product) {
381
                $message = ['version' => str_replace('v', '', $product->version)];
382
            } else {
383
                $message = ['error' => 'product_not_found'];
384
            }
385
            $message = ['version' => str_replace('v', '', $product->version)];
386
        } catch (\Exception $e) {
387
            $message = ['error' => $e->getMessage()];
388
        }
389
390
        return response()->json($message);
391
    }
392
393
    /*
394
     * Check if the Product is valid For Auto Updates
395
    * @params string Serial Key in encrypted
396
    * @return array
397
    */
398
399
    public function checkUpdatesExpiry(Request $request)
400
    {
401
         $v = \Validator::make($request->all(), [
402
          'order_number' =>'required',
403
        ]);
404
        if ($v->fails()) {
405
            $error = $v->errors();
406
            return response()->json(compact('error'));
407
        }
0 ignored issues
show
Bug Best Practice introduced by
The expression return response()->json(compact('error')) also could return the type Illuminate\Http\JsonResponse which is incompatible with the documented return type array.
Loading history...
408
        try {
409
            $order_number = $request->input('order_number');
410
            $orderId = Order::where('number','LIKE',$order_number)->pluck('id')->first();
411
            if($orderId){
412
            $expiryDate = Subscription::where('order_id',$orderId)->pluck('update_ends_at')->first();
413
            if(\Carbon\Carbon::now()->toDateTimeString() < $expiryDate->toDateTimeString()){
414
                return ['status' => 'success', 'message' => 'allow-auto-update'];
415
           
416
            }
417
            }
418
           return ['status' => 'fails', 'message' => 'do-not-allow-auto-update'];
419
        } catch (\Exception $e) {
420
            $result = ['status'=>'fails','error' => $e->getMessage()];
421
            return $result;
422
            
423
        }
424
    }
425
}
426