You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.5 KiB

<?php
namespace App\Http\Controllers\Api\Admin;
use App\Http\Controllers\Controller;
use App\Models\AdminUser;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
class AuthController extends Controller
{
public function login(Request $request): JsonResponse
{
$data = $request->validate([
'username' => ['required', 'string', 'max:64'],
'password' => ['required', 'string', 'max:255'],
]);
$admin = AdminUser::query()->where('username', $data['username'])->first();
if (! $admin || $admin->status !== 'active') {
throw ValidationException::withMessages([
'username' => ['账号不存在或不可用'],
]);
}
$hash = $admin->getAuthPassword();
if ($hash === null || $hash === '') {
throw ValidationException::withMessages([
'username' => ['该账号未配置密码'],
]);
}
if (! Hash::check($data['password'], $hash)) {
throw ValidationException::withMessages([
'username' => ['账号或密码错误'],
]);
}
$admin->forceFill(['last_login_at' => now()])->save();
$token = $admin->createToken('admin')->plainTextToken;
$adminPayload = [
'id' => $admin->id,
'username' => $admin->username,
'name' => $admin->name,
];
return response()->json([
'token_type' => 'Bearer',
'access_token' => $token,
'token' => $token,
'admin' => $adminPayload,
'user' => $adminPayload,
]);
}
public function changePassword(Request $request): JsonResponse
{
$data = $request->validate([
'current_password' => ['required', 'string', 'max:255'],
'password' => ['required', 'string', 'min:6', 'max:255', 'confirmed'],
]);
/** @var AdminUser $admin */
$admin = $request->user();
$hash = $admin->getAuthPassword();
if ($hash === null || $hash === '' || ! Hash::check($data['current_password'], $hash)) {
throw ValidationException::withMessages([
'current_password' => ['当前密码不正确'],
]);
}
$admin->forceFill(['password_hash' => $data['password']])->save();
return response()->json(['message' => '密码已更新']);
}
}