2FAuth/app/Http/Controllers/QrCodeController.php

82 lines
2.0 KiB
PHP
Raw Normal View History

2020-01-03 17:25:56 +01:00
<?php
namespace App\Http\Controllers;
use Validator;
use Zxing\QrReader;
2020-01-10 22:52:47 +01:00
use OTPHP\TOTP;
use OTPHP\Factory;
use Assert\AssertionFailedException;
2020-01-03 17:25:56 +01:00
use Illuminate\Http\File;
use Illuminate\Http\Request;
2020-01-03 17:25:56 +01:00
use Illuminate\Support\Facades\Storage;
class QrCodecontroller extends Controller
{
/**
* Handle uploaded qr code image
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function decode(Request $request)
{
// input validation
$messages = [
'qrcode.image' => 'Supported format are jpeg, png, bmp, gif, svg, or webp'
];
2020-01-03 17:25:56 +01:00
$validator = Validator::make($request->all(), [
'qrcode' => 'required|image',
], $messages);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 400);
}
2020-01-03 17:25:56 +01:00
// qrcode analysis
$path = $request->file('qrcode')->store('qrcodes');
$qrcode = new QrReader(storage_path('app/' . $path));
2020-01-10 22:52:47 +01:00
$uri = urldecode($qrcode->text());
2020-01-03 17:25:56 +01:00
// delete uploaded file
Storage::delete($path);
2020-01-03 17:25:56 +01:00
2020-01-10 22:52:47 +01:00
// return the OTP object
try {
2020-01-03 17:25:56 +01:00
2020-01-10 22:52:47 +01:00
$otp = Factory::loadFromProvisioningUri($uri);
2020-01-10 22:52:47 +01:00
if(!$otp->getIssuer()) {
$otp->setIssuer($otp->getLabel());
$otp->setLabel('');
}
2020-01-03 17:25:56 +01:00
2020-01-10 22:52:47 +01:00
// returned object
$twofaccount = (object) array(
'service' => $otp->getIssuer(),
'account' => $otp->getLabel(),
'uri' => $uri,
'icon' => '',
'options' => $otp->getParameters()
);
2020-01-03 17:25:56 +01:00
2020-01-10 22:52:47 +01:00
return response()->json($twofaccount, 200);
2020-01-03 17:25:56 +01:00
}
2020-01-10 22:52:47 +01:00
catch (AssertionFailedException $exception) {
2020-01-03 17:25:56 +01:00
2020-01-10 22:52:47 +01:00
return response()->json([
'error' => [
'qrcode' => 'No valid TOTP resource in this QR code'
]
], 400);
2020-01-03 17:25:56 +01:00
}
}
2020-01-03 17:25:56 +01:00
}