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.
57 lines
1.6 KiB
57 lines
1.6 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;
|
|
|
|
return response()->json([
|
|
'token_type' => 'Bearer',
|
|
'access_token' => $token,
|
|
'admin' => [
|
|
'id' => $admin->id,
|
|
'username' => $admin->username,
|
|
'name' => $admin->name,
|
|
],
|
|
]);
|
|
}
|
|
}
|