82 lines
2.5 KiB
PHP
82 lines
2.5 KiB
PHP
|
<?php
|
||
|
|
||
|
namespace app\controller\admin\api\v1;
|
||
|
|
||
|
use support\Request;
|
||
|
use App\Utils\ApiResponse;
|
||
|
use App\model\Admin;
|
||
|
use hg\apidoc\annotation as Apidoc;
|
||
|
use Intervention\Image\ImageManagerStatic as Image;
|
||
|
use Exception;
|
||
|
use support\exception\BusinessException;
|
||
|
use Tinywan\Jwt\JwtToken;
|
||
|
|
||
|
/**
|
||
|
* @Apidoc\Title("用户控制器")
|
||
|
*/
|
||
|
class AccountController
|
||
|
{
|
||
|
/**
|
||
|
* 不需要登录的方法
|
||
|
*/
|
||
|
protected $noNeedLogin = ['login', 'refresh'];
|
||
|
|
||
|
/**
|
||
|
* @Apidoc\Title("1.0 登录")
|
||
|
* @Apidoc\Url("admin/api/v1/account/login")
|
||
|
* @Apidoc\Method("POST")
|
||
|
* @Apidoc\Param("username", type="string",require=true, desc="用户名")
|
||
|
* @Apidoc\Param("password", type="string",require=true, desc="密码")
|
||
|
* @Apidoc\Returned("token", type="object", desc="令牌")
|
||
|
*/
|
||
|
public function login(Request $request)
|
||
|
{
|
||
|
// 获取请求数据
|
||
|
$data = $request->post();
|
||
|
|
||
|
// 根据手机号查询用户
|
||
|
$db = Admin::where('username', '=', $data['username'])->first();
|
||
|
|
||
|
// 如果未找到用户,返回错误
|
||
|
if (!$db) {
|
||
|
return ApiResponse::error(402, [], '用户未注册');
|
||
|
}
|
||
|
|
||
|
// 获取用户输入的密码
|
||
|
$password = $data['password'];
|
||
|
|
||
|
// 验证密码是否正确
|
||
|
if (password_verify($password, $db->password)) {
|
||
|
$user = [
|
||
|
'id' => $db->id,
|
||
|
'nickname' => $db->nickname,
|
||
|
'username' => $db->username
|
||
|
];
|
||
|
// 如果密码正确,生成 JWT 令牌
|
||
|
$token = JwtToken::generateToken($user);
|
||
|
|
||
|
// 返回成功响应和用户信息(可以将 token 添加到响应中)
|
||
|
return ApiResponse::success(200, [
|
||
|
'user' => $user, // 返回用户信息
|
||
|
'token' => $token // 返回生成的 token
|
||
|
]);
|
||
|
} else {
|
||
|
// 密码错误,返回错误响应
|
||
|
return ApiResponse::error(402, [], '密码错误');
|
||
|
}
|
||
|
}
|
||
|
/**
|
||
|
* @Apidoc\Title("1.0 刷新token")
|
||
|
* @Apidoc\Url("admin/api/v1/account/refresh")
|
||
|
* @Apidoc\Method("POST")
|
||
|
* @Apidoc\Param("refresh_token", type="string",require=true, desc="令牌")
|
||
|
* @Apidoc\Returned("token", type="object", desc="令牌")
|
||
|
*/
|
||
|
public function refresh(Request $request) {
|
||
|
$token = JwtToken::refreshToken();
|
||
|
return ApiResponse::success(200, [
|
||
|
'token' => $token // 返回生成的 token
|
||
|
]);
|
||
|
}
|
||
|
}
|