Laravel后台控制台认证开发:含重试计数等需求实现求助
Laravel Eloquent Authentication with Custom Validation & Session Handling
Hey there! Let's tackle your authentication requirements one by one. I'll modify your existing login code and explain each part so you can follow along easily.
First, let's set up the necessary relationship in your User model to connect with the role mapping table. Add these methods to your App\Models\User class:
// App\Models\User.php // Direct relationship to the user_role_mapping table public function userRoleMappings() { return $this->hasMany(UserRoleMapping::class, 'user_id'); } // Optional: If you have a Role model, use this many-to-many relationship instead public function roles() { return $this->belongsToMany(Role::class, 'user_role_mapping', 'user_id', 'role_id') ->wherePivot('status', 1); // Filter only active role associations }
Now let's update your submitLogin method to cover all four requirements:
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Session; use App\Models\User; public function submitLogin(Request $request) { // Step 1: Validate input fields $this->validate($request, [ 'username' => 'required|max:50', 'password' => 'required|max:100', ]); // Step 2: Fetch user by username $user = User::where('username', $request->username)->first(); // Handle case where username doesn't exist if (!$user) { return redirect()->back() ->withInput($request->only('username', 'remember')) ->withErrors(['Invalid Username or password.']); } // Step 3: Check if user account is locked if ($user->retry_count >= 5) { return redirect()->back() ->withInput($request->only('username', 'remember')) ->withErrors(['用户账户已被锁定']); } // Step 4: Check if user account is inactive if ($user->status != 1) { // Increment retry count as per requirement $user->increment('retry_count'); return redirect()->back() ->withInput($request->only('username', 'remember')) ->withErrors(['用户账户未激活']); } // Step 5: Verify password credentials if (!Auth::attempt(['username' => $request->username, 'password' => $request->password])) { // Increment retry count on password failure $user->increment('retry_count'); return redirect()->back() ->withInput($request->only('username', 'remember')) ->withErrors(['Invalid Username or password.']); } // Step 6: Post-success actions // Reset retry count to 0 $user->update(['retry_count' => 0]); // Fetch user's active roles (choose one option below) // Option 1: Get only role IDs $roleIds = $user->userRoleMappings()->where('status', 1)->pluck('role_id')->toArray(); // Option 2: Get full Role objects (if using the Role model relationship) // $roles = $user->roles()->get(); // Store roles in session for permission checks Session::put('user_roles', $roleIds); // If using full Role objects: Session::put('user_roles', $roles); // Redirect to the intended dashboard page return redirect()->intended(route('home')); }
Handling Logout (Requirement 4)
Update your logout method to fully clear all session data:
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Session; public function logout(Request $request) { Auth::logout(); // Clear all session data Session::flush(); // Invalidate the current session $request->session()->invalidate(); // Regenerate CSRF token for security $request->session()->regenerateToken(); return redirect('/login'); }
Quick Breakdown of Key Parts:
- Pre-validation checks: We fetch the user first to verify their status and lock state before checking passwords, ensuring we return accurate error messages right away.
- Retry count management: We increment the count for all valid failed attempts (inactive user, wrong password) to enforce the lock rule.
- Role storage: After successful login, we pull the user's active roles and store them in the session for easy access in permission checks later.
- Full session cleanup on logout:
Session::flush()removes all stored data, and we invalidate the session + regenerate the CSRF token to keep things secure.
内容的提问来源于stack exchange,提问作者Suraj KV
相关产品推荐
相关产品推荐

