namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
class UserController extends Controller
{
public function login(Request $request){
$validated = Validator::make($request->all(),[
'username'=>'required',
'password'=>'required'
]);
if($validated->fails()){
return response()->json(['msg'=>'登陆失败'],400);
}
//查看能否登陆
$user = User::query()->where('username',$request->username);
$user_data = $user->get();
//用户是否存在
if(count($user_data)===0){
return response()->json(['msg'=>'用户不存在'],400);
}
//账户的登陆时间是否大于当前时间
if($user_data[0]->canLoginTime>date('Y-m-d H:i:s')){
return response()->json(['msg'=>'账户被锁'],400);
}
//登陆
if(!Auth::attempt(['username'=>$request->username,'password'=>$request->password])){
$this->fail($user);
return response()->json(['msg'=>'登陆失败'],400);
}
$request->session()->regenerate();
return response()->json(['msg'=>'登录成功'],200);
}
public function fail($user){
$count = $user->get('fail');
//失败10次
if($count[0]->fail===9){
//禁止登陆30s
$canLoginTime = date('Y-m-d H:i:s',strtotime('+30 second'));
return $user->update(['canLoginTime'=>$canLoginTime,'fail'=>0]);
}
return $user->increment('fail');
}
public function register(Request $request){
$validated = Validator::make($request->all(),[
'username'=>'required|unique:users',
'password'=>'required',
'r_password'=>'required|same:password'
]);
if($validated->fails()){
return response()->json(['msg'=>'注册失败'],400);
}
//插入数据
User::query()->insert([
'username'=>$request->username,
'password'=>$request->password
]);
return response()->json(['msg'=>'注册成功'],200);
}
public function logout(Request $request){
Auth::logout();
$request->session()->invalidate();
return response()->json(['msg'=>'退出成功'],200);
}
}