QrCodeController.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Validator;
  4. use Zxing\QrReader;
  5. use OTPHP\TOTP;
  6. use OTPHP\Factory;
  7. use Assert\AssertionFailedException;
  8. use Illuminate\Http\File;
  9. use Illuminate\Http\Request;
  10. use Illuminate\Support\Facades\Storage;
  11. class QrCodecontroller extends Controller
  12. {
  13. /**
  14. * Handle uploaded qr code image
  15. *
  16. * @param \Illuminate\Http\Request $request
  17. * @return \Illuminate\Http\Response
  18. */
  19. public function decode(Request $request)
  20. {
  21. // input validation
  22. $validator = Validator::make($request->all(), [
  23. 'qrcode' => 'required|image',
  24. ]);
  25. if ($validator->fails()) {
  26. return response()->json(['validation' => $validator->errors()], 400);
  27. }
  28. // qrcode analysis
  29. $path = $request->file('qrcode')->store('qrcodes');
  30. $qrcode = new QrReader(storage_path('app/' . $path));
  31. $uri = urldecode($qrcode->text());
  32. // delete uploaded file
  33. Storage::delete($path);
  34. // return the OTP object
  35. try {
  36. $otp = Factory::loadFromProvisioningUri($uri);
  37. if(!$otp->getIssuer()) {
  38. $otp->setIssuer($otp->getLabel());
  39. $otp->setLabel('');
  40. }
  41. // returned object
  42. $twofaccount = (object) array(
  43. 'service' => $otp->getIssuer(),
  44. 'account' => $otp->getLabel(),
  45. 'uri' => $uri,
  46. 'icon' => '',
  47. 'options' => $otp->getParameters()
  48. );
  49. return response()->json($twofaccount, 200);
  50. }
  51. catch (AssertionFailedException $exception) {
  52. return response()->json([
  53. 'validation' => [
  54. 'qrcode' => __('errors.response.no_valid_totp')
  55. ]
  56. ], 400);
  57. }
  58. }
  59. }