Completed
Push — development ( c0a597...4b3f17 )
by Ashutosh
11:26
created

HomeController   B

Complexity

Total Complexity 47

Size/Duplication

Total Lines 390
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 47
eloc 202
dl 0
loc 390
rs 8.64
c 0
b 0
f 0

15 Methods

Rating   Name   Duplication   Size   Complexity  
A faveoVerification() 0 44 4
A checkFaveoDetails() 0 19 4
A submit() 0 7 1
A decryptByFaveoPrivateKeyold() 0 35 5
A serialV2() 0 30 4
A downloadForFaveo() 0 20 3
A serial() 0 31 4
A checkUpdate() 0 16 6
A latestVersion() 0 25 4
A __construct() 0 4 1
A checkOrder() 0 14 3
A getVersion() 0 14 2
A version() 0 24 3
A encryptByPublicKey() 0 16 1
A createEncryptionKeys() 0 21 2

How to fix   Complexity   

Complex Class

Complex classes like HomeController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use HomeController, and based on these observations, apply Extract Interface, too.

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