lcly-data-admin/app/Http/Controllers/CaptchaController.php

72 lines
1.8 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Services\CaptchaService;
use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class CaptchaController extends Controller
{
/**
* 创建图形验证码
*/
public function store(Request $request, CaptchaService $captchaService)
{
$request->validate([
'key' => ['bail', 'filled', 'string', 'max:32'],
'w' => ['bail', 'int'],
'h' => ['bail', 'int'],
]);
$builder = $this->builder();
$builder->build($request->input('w', 150), $request->input('h', 40));
$captchaService->put(
$key = $request->input('key', Str::random(16)),
$builder->getPhrase()
);
return response()->json([
'key' => $key,
'img' => $builder->inline(),
]);
}
/**
* 查看图形验证码
*
* @param string $key
* @param \Illuminate\Http\Request $request
* @param \App\Services\CaptchaService $captchaService
* @return \Illuminate\Http\Response
*/
public function show($key, Request $request, CaptchaService $captchaService)
{
$builder = $this->builder();
$builder->build(
(int) $request->query('w', 150),
(int) $request->query('h', 40),
);
if (strlen($key) <= 32) {
$captchaService->put($key, $builder->getPhrase());
}
return response($builder->get())
->header('Content-Type', 'image/jpeg')
->header('Cache-Control', 'no-cache');
}
/**
* 图形验证码生成器
*
* @return \Gregwar\Captcha\CaptchaBuilder
*/
protected function builder(): CaptchaBuilder
{
return new CaptchaBuilder(Str::random(5));
}
}