58 lines
2.2 KiB
PHP
58 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\admin;
|
|
use Illuminate\Support\Facades\Cookie;
|
|
use App\Http\Controllers\Controller;
|
|
use App\Models\User;
|
|
use Carbon\Carbon;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Auth;
|
|
use Illuminate\Support\Facades\Log;
|
|
class LoginController extends Controller
|
|
{
|
|
//
|
|
public function index()
|
|
{
|
|
return view("administrator.pages.auth.login");
|
|
}
|
|
public function store(Request $request)
|
|
{
|
|
try {
|
|
$request->validate([
|
|
'username' => 'required|min:3',
|
|
'password' => 'required|min:3'
|
|
]);
|
|
|
|
$user = User::where('username', $request->username)->first();
|
|
if (!$user)
|
|
return back()->withErrors('Không tìm thấy thông tin người dùng');
|
|
|
|
if (Auth::guard('admins')->attempt(['username' => $request->username, 'password' => $request->password], $request->remember)) {
|
|
if (\auth()->user()->status) {
|
|
$token = \auth()->user()->createToken('access_token', ['*'], Carbon::now()->addDay())->plainTextToken;
|
|
Cookie::queue('accessToken', $token, 24 * 60);
|
|
|
|
if (Cookie::has('admin_prev_url')) {
|
|
Cookie::queue(Cookie::forget('admin_prev_url'));
|
|
return redirect(Cookie::get('admin_prev_url'));
|
|
}
|
|
return redirect()->route('dashboard')->with('success', 'Đã đăng nhập thành công!');
|
|
}
|
|
auth('admins')->logout();
|
|
return back()->withErrors('Tài khoản bị khoá, vui lòng liên hệ quản trị viên');
|
|
}
|
|
|
|
return back()->withErrors('Thông tin đăng nhập không hợp lệ');
|
|
} catch (\Exception $e) {
|
|
// Log the error for debugging
|
|
Log::error('Login error: ' . $e->getMessage(), [
|
|
'username' => $request->username,
|
|
'ip' => $request->ip(),
|
|
'user_agent' => $request->userAgent()
|
|
]);
|
|
|
|
return back()->withErrors('Có lỗi xảy ra trong quá trình đăng nhập. Vui lòng thử lại sau.');
|
|
}
|
|
}
|
|
}
|