refactor: restructure API authentication system and remove legacy files

- Updated API routes to use a unified versioning scheme under `/api/v1/auth`.
- Implemented new authentication controller for login, registration, and token management.
- Removed legacy user and index controllers, along with associated models and validation files.
- Updated documentation to reflect new API endpoints and usage.
- Cleaned up unused service and middleware files to streamline the application structure.
This commit is contained in:
nepiedg
2026-04-02 03:05:44 +00:00
parent b56df15c2b
commit e0733cf672
22 changed files with 130 additions and 681 deletions
-22
View File
@@ -1,22 +0,0 @@
<?php
declare (strict_types = 1);
namespace app;
use think\Service;
/**
* 应用服务类
*/
class AppService extends Service
{
public function register()
{
// 服务注册
}
public function boot()
{
// 服务启动
}
}
-94
View File
@@ -1,94 +0,0 @@
<?php
declare (strict_types = 1);
namespace app;
use think\App;
use think\exception\ValidateException;
use think\Validate;
/**
* 控制器基础类
*/
abstract class BaseController
{
/**
* Request实例
* @var \think\Request
*/
protected $request;
/**
* 应用实例
* @var \think\App
*/
protected $app;
/**
* 是否批量验证
* @var bool
*/
protected $batchValidate = false;
/**
* 控制器中间件
* @var array
*/
protected $middleware = [];
/**
* 构造方法
* @access public
* @param App $app 应用对象
*/
public function __construct(App $app)
{
$this->app = $app;
$this->request = $this->app->request;
// 控制器初始化
$this->initialize();
}
// 初始化
protected function initialize()
{}
/**
* 验证数据
* @access protected
* @param array $data 数据
* @param string|array $validate 验证器名或者验证规则数组
* @param array $message 提示信息
* @param bool $batch 是否批量验证
* @return array|string|true
* @throws ValidateException
*/
protected function validate(array $data, string|array $validate, array $message = [], bool $batch = false)
{
if (is_array($validate)) {
$v = new Validate();
$v->rule($validate);
} else {
if (strpos($validate, '.')) {
// 支持场景
[$validate, $scene] = explode('.', $validate);
}
$class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
$v = new $class();
if (!empty($scene)) {
$v->scene($scene);
}
}
$v->message($message);
// 是否批量验证
if ($batch || $this->batchValidate) {
$v->batch(true);
}
return $v->failException(true)->check($data);
}
}
-58
View File
@@ -1,58 +0,0 @@
<?php
namespace app;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Response;
use Throwable;
/**
* 应用异常处理类
*/
class ExceptionHandle extends Handle
{
/**
* 不需要记录信息(日志)的异常类列表
* @var array
*/
protected $ignoreReport = [
HttpException::class,
HttpResponseException::class,
ModelNotFoundException::class,
DataNotFoundException::class,
ValidateException::class,
];
/**
* 记录异常信息(包括日志或者其它方式记录)
*
* @access public
* @param Throwable $exception
* @return void
*/
public function report(Throwable $exception): void
{
// 使用内置的方式记录异常日志
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* @access public
* @param \think\Request $request
* @param Throwable $e
* @return Response
*/
public function render($request, Throwable $e): Response
{
// 添加自定义异常处理机制
// 其他错误交给系统处理
return parent::render($request, $e);
}
}
-8
View File
@@ -1,8 +0,0 @@
<?php
namespace app;
// 应用请求对象类
class Request extends \think\Request
{
}
-22
View File
@@ -1,22 +0,0 @@
<?php
declare (strict_types = 1);
namespace app\api;
use think\Service;
/**
* API 应用服务
*/
class AppService extends Service
{
public function register()
{
// 注册服务
}
public function boot()
{
// 启动服务
}
}
-37
View File
@@ -1,37 +0,0 @@
<?php
declare (strict_types = 1);
namespace app\api\controller;
/**
* API 示例控制器
*/
class Index extends BaseController
{
/**
* 首页接口
* @return \think\response\Json
*/
public function index()
{
$data = [
'name' => 'ThinkPHP API',
'version' => app()->version(),
'message' => 'Welcome to ThinkPHP API Application',
];
return $this->success($data);
}
/**
* 健康检查接口
* @return \think\response\Json
*/
public function health()
{
return $this->success([
'status' => 'ok',
'timestamp' => date('Y-m-d H:i:s'),
]);
}
}
-81
View File
@@ -1,81 +0,0 @@
<?php
declare (strict_types = 1);
namespace app\api\controller;
/**
* 用户控制器示例
*/
class User extends BaseController
{
/**
* 用户登录
* @return \think\response\Json
*/
public function login()
{
$data = $this->request->post();
// 验证数据
$this->validate($data, [
'username' => 'require',
'password' => 'require',
], [
'username.require' => '用户名不能为空',
'password.require' => '密码不能为空',
]);
// TODO: 实际的登录逻辑
return $this->success([
'token' => 'example_token_' . md5($data['username']),
'username' => $data['username'],
], '登录成功');
}
/**
* 获取用户信息
* @return \think\response\Json
*/
public function info()
{
// TODO: 从 token 或 session 中获取用户信息
$userInfo = [
'id' => 1,
'username' => 'demo_user',
'nickname' => '演示用户',
'avatar' => '',
'email' => 'demo@example.com',
'created_at' => date('Y-m-d H:i:s'),
];
return $this->success($userInfo);
}
/**
* 用户注册
* @return \think\response\Json
*/
public function register()
{
$data = $this->request->post();
// 验证数据
$this->validate($data, [
'username' => 'require|length:3,20',
'password' => 'require|length:6,20',
'email' => 'require|email',
], [
'username.require' => '用户名不能为空',
'username.length' => '用户名长度3-20位',
'password.require' => '密码不能为空',
'password.length' => '密码长度6-20位',
'email.require' => '邮箱不能为空',
'email.email' => '邮箱格式不正确',
]);
// TODO: 实际的注册逻辑
return $this->success([
'user_id' => rand(1000, 9999),
], '注册成功');
}
}
@@ -1,49 +1,43 @@
<?php
declare(strict_types=1);
namespace app\api\controller;
namespace app\api\controller\v1;
use app\api\common\Jwt;
use app\api\common\Response;
use app\api\controller\BaseController;
use app\api\service\AuthService;
use think\App;
use think\exception\ValidateException;
/**
* 认证控制器 (v1版本)
* 处理用户登录、注册、Token 刷新等
* v1 认证控制器
*/
class Auth extends BaseController
{
/**
* @var AuthService
*/
protected AuthService $authService;
public function __construct()
public function __construct(App $app)
{
parent::__construct();
parent::__construct($app);
$this->authService = new AuthService();
}
/**
* 用户登录
* POST /api/v1/auth/login
* @return \think\response\Json
*/
public function login()
{
try {
$data = $this->request->post();
// 验证参数
validate($data, [
validate([
'username' => 'require',
'password' => 'require',
], [
'username.require' => '用户名不能为空',
'password.require' => '密码不能为空',
]);
])->check($data);
$result = $this->authService->login(
$data['username'],
@@ -61,15 +55,13 @@ class Auth extends BaseController
/**
* 用户注册
* POST /api/v1/auth/register
* @return \think\response\Json
*/
public function register()
{
try {
$data = $this->request->post();
// 验证参数
validate($data, [
validate([
'username' => 'require|length:3,20|alphaNum',
'password' => 'require|length:6,20',
'email' => 'email',
@@ -80,7 +72,7 @@ class Auth extends BaseController
'password.require' => '密码不能为空',
'password.length' => '密码长度6-20位',
'email.email' => '邮箱格式不正确',
]);
])->check($data);
$result = $this->authService->register(
$data['username'],
@@ -100,7 +92,6 @@ class Auth extends BaseController
/**
* 刷新 Token
* POST /api/v1/auth/refresh
* @return \think\response\Json
*/
public function refresh()
{
@@ -122,7 +113,6 @@ class Auth extends BaseController
/**
* 获取当前用户信息
* GET /api/v1/auth/me
* @return \think\response\Json
*/
public function me()
{
@@ -143,19 +133,15 @@ class Auth extends BaseController
/**
* 退出登录
* POST /api/v1/auth/logout
* @return \think\response\Json
*/
public function logout()
{
// JWT 无状态,退出只需客户端删除 Token
// 如果需要服务端失效,可以将 Token 加入黑名单(需要 Redis 支持)
return Response::success([], '退出成功');
}
/**
* 修改密码
* POST /api/v1/auth/password
* @return \think\response\Json
*/
public function password()
{
@@ -167,7 +153,7 @@ class Auth extends BaseController
$data = $this->request->post();
validate($data, [
validate([
'old_password' => 'require',
'new_password' => 'require|length:6,20|confirm:confirm_password',
], [
@@ -175,7 +161,7 @@ class Auth extends BaseController
'new_password.require' => '新密码不能为空',
'new_password.length' => '新密码长度6-20位',
'new_password.confirm' => '两次密码输入不一致',
]);
])->check($data);
$this->authService->changePassword(
$payload['userid'],
-48
View File
@@ -1,48 +0,0 @@
<?php
declare (strict_types = 1);
namespace app\api\model;
use think\Model;
/**
* 用户模型
*/
class User extends Model
{
// 表名
protected $name = 'user';
// 自动写入时间戳
protected $autoWriteTimestamp = true;
// 类型转换
protected $type = [
'id' => 'integer',
'status' => 'integer',
];
// 隐藏字段
protected $hidden = ['password', 'delete_time'];
/**
* 密码加密
* @param string $value
* @return string
*/
public function setPasswordAttr(string $value): string
{
return password_hash($value, PASSWORD_DEFAULT);
}
/**
* 验证密码
* @param string $password 明文密码
* @param string $hash 加密后的密码
* @return bool
*/
public static function verifyPassword(string $password, string $hash): bool
{
return password_verify($password, $hash);
}
}
+9 -24
View File
@@ -2,35 +2,20 @@
declare(strict_types=1);
use think\facade\Route;
use app\api\controller\Index;
use app\api\controller\User;
use app\api\controller\V1Auth;
use app\api\controller\v1\Auth;
/**
* API 应用路由
*/
// ==================== v1 版本接口 ====================
// v1 认证接口(公开)
Route::post('v1/auth/login', [Auth::class, 'login']);
Route::post('v1/auth/register', [Auth::class, 'register']);
Route::post('v1/auth/refresh', [Auth::class, 'refresh']);
// 健康检查 (公开)
Route::get('v1/health', [Index::class, 'health']);
// 认证接口 (公开)
Route::post('v1/auth/login', [V1Auth::class, 'login']);
Route::post('v1/auth/register', [V1Auth::class, 'register']);
Route::post('v1/auth/refresh', [V1Auth::class, 'refresh']);
// 认证接口 (需登录)
// v1 认证接口(需登录)
Route::group('v1/auth', function () {
Route::get('me', [V1Auth::class, 'me']);
Route::post('logout', [V1Auth::class, 'logout']);
Route::post('password', [V1Auth::class, 'password']);
Route::get('me', [Auth::class, 'me']);
Route::post('logout', [Auth::class, 'logout']);
Route::post('password', [Auth::class, 'password']);
})->middleware(\app\api\middleware\Auth::class);
// ==================== 兼容旧版路由 ====================
Route::get('index', [Index::class, 'index']);
Route::get('health', [Index::class, 'health']);
Route::post('user/login', [V1Auth::class, 'login']);
Route::post('user/register', [V1Auth::class, 'register']);
Route::get('user/info', [V1Auth::class, 'me'])->middleware(\app\api\middleware\Auth::class);
-47
View File
@@ -1,47 +0,0 @@
<?php
declare (strict_types = 1);
namespace app\api\validate;
use think\Validate;
/**
* 用户验证器
*/
class User extends Validate
{
/**
* 验证规则
*/
protected $rule = [
'username' => 'require|length:3,20|chsDash',
'password' => 'require|length:6,20',
'email' => 'require|email',
'phone' => 'mobile',
'nickname' => 'length:2,20',
];
/**
* 验证提示信息
*/
protected $message = [
'username.require' => '用户名不能为空',
'username.length' => '用户名长度3-20位',
'username.chsDash' => '用户名只能是汉字、字母、数字和下划线_及破折号-',
'password.require' => '密码不能为空',
'password.length' => '密码长度6-20位',
'email.require' => '邮箱不能为空',
'email.email' => '邮箱格式不正确',
'phone.mobile' => '手机号格式不正确',
'nickname.length' => '昵称长度2-20位',
];
/**
* 验证场景
*/
protected $scene = [
'login' => ['username', 'password'],
'register' => ['username', 'password', 'email'],
'update' => ['email', 'phone', 'nickname'],
];
}
-2
View File
@@ -1,2 +0,0 @@
<?php
// 应用公共文件
-18
View File
@@ -1,18 +0,0 @@
<?php
namespace app\controller;
use app\BaseController;
class Index extends BaseController
{
public function index()
{
return '<style>*{ padding: 0; margin: 0; }</style><iframe src="https://www.thinkphp.cn/welcome?version=' . \think\facade\App::version() . '" width="100%" height="100%" frameborder="0" scrolling="auto"></iframe>';
}
public function hello($name = 'ThinkPHP8')
{
return 'hello,' . $name;
}
}
-17
View File
@@ -1,17 +0,0 @@
<?php
// 事件定义文件
return [
'bind' => [
],
'listen' => [
'AppInit' => [],
'HttpRun' => [],
'HttpEnd' => [],
'LogLevel' => [],
'LogWrite' => [],
],
'subscribe' => [
],
];
-10
View File
@@ -1,10 +0,0 @@
<?php
// 全局中间件定义文件
return [
// 全局请求缓存
// \think\middleware\CheckRequestCache::class,
// 多语言加载
// \think\middleware\LoadLangPack::class,
// Session初始化
// \think\middleware\SessionInit::class
];
-9
View File
@@ -1,9 +0,0 @@
<?php
use app\ExceptionHandle;
use app\Request;
// 容器Provider定义文件
return [
'think\Request' => Request::class,
'think\exception\Handle' => ExceptionHandle::class,
];
-9
View File
@@ -1,9 +0,0 @@
<?php
use app\AppService;
// 系统服务定义文件
// 服务在完成全局初始化之后执行
return [
AppService::class,
];