78 lines
2.2 KiB
PHP
78 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\AdminPermission;
|
|
use App\Models\AdminUser;
|
|
use Illuminate\Contracts\Cache\Repository as Cache;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Hash;
|
|
|
|
class AuthController extends Controller
|
|
{
|
|
public function __construct(
|
|
protected Cache $cache,
|
|
) {
|
|
}
|
|
|
|
public function login(Request $request)
|
|
{
|
|
$request->validate([
|
|
'username' => 'required',
|
|
'password' => 'required',
|
|
]);
|
|
|
|
$username = $request->input('username');
|
|
|
|
$user = AdminUser::where(['username' => $username])->first();
|
|
|
|
if ($user?->banned_at) {
|
|
return $this->error('账号已封禁,请联系管理员');
|
|
}
|
|
|
|
$cacheKey = "admin_user_ban:{$username}";
|
|
|
|
if (! Hash::check($request->input('password'), (string) $user?->password)) {
|
|
if ($user) {
|
|
$this->cache->add($cacheKey, 0, 86400);
|
|
|
|
$hits = $this->cache->increment($cacheKey, 1);
|
|
|
|
if ($hits >= 3) {
|
|
// 锁定账号
|
|
$user->update([
|
|
'banned_reason' => '24小时内密码连续错误3次',
|
|
'banned_at' => now(),
|
|
]);
|
|
|
|
// 清空登录失败尝试次数
|
|
$this->cache->forget($cacheKey);
|
|
}
|
|
}
|
|
return $this->error('用户名或密码错误');
|
|
}
|
|
|
|
// 清空登录失败尝试次数
|
|
$this->cache->forget($cacheKey);
|
|
|
|
if ($user->is_enable !== 1) {
|
|
return $this->error('用户状态异常请联系管理员');
|
|
}
|
|
|
|
return $this->attemptUser($user);
|
|
}
|
|
|
|
protected function attemptUser(AdminUser $user, $name = 'api')
|
|
{
|
|
$token = $user->createToken($name)->plainTextToken;
|
|
|
|
$permissionsQuery = AdminPermission::query();
|
|
if($user->id != 1){
|
|
$permissions = $permissionsQuery->whereIn('id', $user->permissionIds());
|
|
}
|
|
$permissions = $permissionsQuery->pluck('slug')->toArray();
|
|
|
|
return $this->json(['token' => $token, 'info' => $user, 'permissions' => $user->permissionIds(), 'permissions_slug'=>$permissions]);
|
|
}
|
|
}
|