login works

This commit is contained in:
armiejean 2025-05-12 19:27:17 +08:00
parent 56579c8583
commit b881ff4774
5 changed files with 88 additions and 55 deletions

View File

@ -5,8 +5,8 @@ namespace App\Http\Controllers;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session; use Illuminate\Support\Facades\Session;
class AuthController extends Controller class AuthController extends Controller
{ {
protected $apiBaseUrl = 'http://192.168.100.6:8081/api'; protected $apiBaseUrl = 'http://192.168.100.6:8081/api';
@ -22,30 +22,14 @@ class AuthController extends Controller
/** /**
* Handle login form submission by calling the API * Handle login form submission by calling the API
*/ */
// public function login(Request $request) public function login(Request $request)
// {
// $credentials = $request->only('username', 'password');
// if (Auth::attempt($credentials)) {
// $request->session()->regenerate();
// $user = Auth::user();
// // Always redirect to my-profile route, let the route's controller handle the user
// return redirect()->route('my-profile');
// }
// return redirect()->back()->with('error', 'Invalid username or password');
// }
public function login(Request $request)
{ {
// Validate input
$request->validate([ $request->validate([
'username' => 'required|string', 'username' => 'required|string',
'password' => 'required|string', 'password' => 'required|string',
]); ]);
try { try {
// Send HTTP request to external API
$response = Http::post(config('services.backend_api.url') . '/api/cms/login_password', [ $response = Http::post(config('services.backend_api.url') . '/api/cms/login_password', [
'username' => $request->username, 'username' => $request->username,
'password' => $request->password, 'password' => $request->password,
@ -53,57 +37,81 @@ class AuthController extends Controller
$json = $response->json(); $json = $response->json();
Log::info('Login API Response: ', $json);
if ($response->successful()) { if ($response->successful()) {
if ($json['code'] == 200) { if ($json['code'] == 200) {
// Store user data in session $userData = [
Session::put('user', [
'admin' => $json['data']['admin'] ?? null, 'admin' => $json['data']['admin'] ?? null,
'access_token' => $json['data']['token'] ?? null, 'access_token' => $json['data']['token'] ?? null,
]); 'admin_uuid' => $json['data']['admin']['uuid'] ?? null,
// dd(Session::get('user')); ];
Session::put('user', $userData);
Session::save();
// Redirect to profile page Log::info('Session data after login: ', Session::get('user'));
return redirect('my-profile');
// Redirect to my-profile if access_token is present
if (isset($userData['access_token']) && !empty($userData['access_token'])) {
Log::info('Access token present, redirecting to my-profile from login');
return redirect()->route('my-profile');
}
$isPasswordChanged = $json['data']['admin']['is_passwordChanged'] ?? 0;
Log::info('Login: is_passwordChanged from API = ' . $isPasswordChanged);
if ($isPasswordChanged == 1) {
Log::info('Redirecting to my-profile from login');
return redirect()->route('my-profile');
} else {
Log::info('Redirecting to change-password from login');
return redirect()->route('change-password')->with('info', 'You must change your password before accessing your profile.');
}
} else { } else {
// Handle login failure from API
return back()->withErrors(['username' => $json['message'] ?? 'Login failed.']); return back()->withErrors(['username' => $json['message'] ?? 'Login failed.']);
} }
} else { } else {
// Handle failed HTTP response return back()->withErrors(['username' => $json['message'] ?? 'Login request failed.']);
return back()->withErrors(['username' => $json['message'] ?? 'Login request failed. Please try again.']);
} }
} catch (\Exception $e) { } catch (\Exception $e) {
// Handle unexpected errors
Log::error('Login error: ' . $e->getMessage()); Log::error('Login error: ' . $e->getMessage());
return back()->withErrors(['username' => 'An error occurred: ' . $e->getMessage()]); return back()->withErrors(['username' => 'An error occurred: ' . $e->getMessage()]);
} }
} }
public function showMyProfile() /**
* Show the my-profile page
*/
public function showMyProfile()
{ {
// Fetch the authenticated user $user = Session::get('user');
$user = Auth::user();
// If no user is authenticated, redirect to login if (!$user || !isset($user['access_token'])) {
if (!$user) { Log::info('No user session or access token, redirecting to login from my-profile');
return redirect()->route('login')->with('error', 'Please log in to view your profile.'); return redirect()->route('login')->with('error', 'Please log in to view your profile.');
} }
// Pass the user to the view if (!isset($user['admin']) || !is_array($user['admin'])) {
Log::error('Invalid admin data in session: ', $user);
return redirect()->route('login')->with('error', 'Invalid user data. Please log in again.');
}
Log::info('Session data in my-profile: ', $user);
Log::info('Rendering my-profile page');
return view('pages.my-profile', compact('user')); return view('pages.my-profile', compact('user'));
} }
/** /**
* Show the change password form * Show the change password form
*/ */
public function showChangePasswordForm() public function showChangePasswordForm()
{ {
if (!session()->has('admin_uuid')) { if (!session()->has('user.admin_uuid')) {
Log::info('No admin_uuid in session, redirecting to login from change-password form');
return redirect()->route('login')->withErrors(['error' => 'Unauthorized access']); return redirect()->route('login')->withErrors(['error' => 'Unauthorized access']);
} }
Log::info('Rendering change-password form');
return view('change-password'); return view('change-password');
} }
@ -112,6 +120,11 @@ public function showMyProfile()
*/ */
public function changePassword(Request $request) public function changePassword(Request $request)
{ {
$request->validate([
'admin_uuid' => 'required|string',
'password' => 'required|string|min:8|confirmed',
]);
$url = "{$this->apiBaseUrl}/cms/login_changePassword"; $url = "{$this->apiBaseUrl}/cms/login_changePassword";
$csrfToken = $request->session()->token(); $csrfToken = $request->session()->token();
@ -119,7 +132,7 @@ public function showMyProfile()
$response = Http::withHeaders([ $response = Http::withHeaders([
'X-CSRF-TOKEN' => $csrfToken, 'X-CSRF-TOKEN' => $csrfToken,
'Accept' => 'application/json', 'Accept' => 'application/json',
'Authorization' => 'Bearer ' . session('token'), 'Authorization' => 'Bearer ' . session('user.access_token'),
])->post($url, [ ])->post($url, [
'admin_uuid' => $request->input('admin_uuid'), 'admin_uuid' => $request->input('admin_uuid'),
'password' => $request->input('password'), 'password' => $request->input('password'),
@ -127,18 +140,34 @@ public function showMyProfile()
$data = $response->json(); $data = $response->json();
Log::info('Change Password API Response: ', [$data]); Log::info('Change Password API Response: ', $data);
if ($response->successful() && isset($data['code']) && $data['code'] === 200) { if ($response->successful() && isset($data['code']) && $data['code'] === 200) {
if (isset($data['data']['access_token'])) { $user = Session::get('user');
session(['token' => $data['data']['access_token']]);
} elseif (isset($data['data']['token'])) { // Update access token from API response
session(['token' => $data['data']['token']]); if (isset($data['token'])) {
$user['access_token'] = $data['token'];
} elseif (isset($data['data']['access_token'])) {
$user['access_token'] = $data['data']['access_token'];
} }
session()->forget('admin_uuid');
// Update admin data with the latest from API
if (isset($data['admin'])) {
$user['admin'] = $data['admin'];
}
Session::put('user', $user);
Session::save();
Log::info('Updated Session after password change: ', Session::get('user'));
Log::info('Redirecting to my-profile from changePassword');
// Immediately redirect to my-profile
return redirect()->route('my-profile')->with('success', $data['message'] ?? 'Password changed successfully'); return redirect()->route('my-profile')->with('success', $data['message'] ?? 'Password changed successfully');
} }
Log::info('Change password failed, redirecting back');
return redirect()->back()->withErrors(['error' => $data['message'] ?? 'Failed to change password']); return redirect()->back()->withErrors(['error' => $data['message'] ?? 'Failed to change password']);
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Change Password Exception: ' . $e->getMessage()); Log::error('Change Password Exception: ' . $e->getMessage());
@ -158,10 +187,11 @@ public function showMyProfile()
Http::withHeaders([ Http::withHeaders([
'X-CSRF-TOKEN' => $csrfToken, 'X-CSRF-TOKEN' => $csrfToken,
'Accept' => 'application/json', 'Accept' => 'application/json',
'Authorization' => 'Bearer ' . session('token'), 'Authorization' => 'Bearer ' . session('user.access_token'),
])->post($url); ])->post($url);
session()->flush(); session()->flush();
Log::info('Logged out, redirecting to login');
return redirect()->route('login')->with('success', 'Logged out successfully'); return redirect()->route('login')->with('success', 'Logged out successfully');
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Logout Exception: ' . $e->getMessage()); Log::error('Logout Exception: ' . $e->getMessage());
@ -169,6 +199,4 @@ public function showMyProfile()
return redirect()->route('login')->with('success', 'Logged out successfully'); return redirect()->route('login')->with('success', 'Logged out successfully');
} }
} }
} }

View File

@ -24,10 +24,15 @@
{{ session('success') }} {{ session('success') }}
</div> </div>
@endif @endif
@if (session('info'))
<div class="alert alert-info">
{{ session('info') }}
</div>
@endif
<form method="POST" action="{{ route('password.change') }}"> <form method="POST" action="{{ route('password.change') }}">
@csrf @csrf
<input type="hidden" name="admin_uuid" value="{{ session('admin_uuid') }}"> <input type="hidden" name="admin_uuid" value="{{ session('user.admin_uuid') }}">
<div class="mb-3"> <div class="mb-3">
<label for="password" class="form-label fw-semibold" style="font-size: 13px; color: #003366;">New Password</label> <label for="password" class="form-label fw-semibold" style="font-size: 13px; color: #003366;">New Password</label>

View File

@ -230,7 +230,7 @@
<li class="nav-item dropdown"> <li class="nav-item dropdown">
<a class="nav-link dropdown-toggle d-flex align-items-center gap-2" href="#" <a class="nav-link dropdown-toggle d-flex align-items-center gap-2" href="#"
role="button" data-toggle="dropdown"> role="button" data-toggle="dropdown">
<span style="margin-right:5px">{{ $user->username }}</span> <span style="margin-right:5px">{{ $user['admin']['username'] ?? 'N/A' }}</span>
<i class="fa-solid fa-user-circle" style="padding-right:5px"></i> <i class="fa-solid fa-user-circle" style="padding-right:5px"></i>
</a> </a>
<ul class="dropdown-menu dropdown-menu-end dropdown-menu-sm"> <ul class="dropdown-menu dropdown-menu-end dropdown-menu-sm">

View File

@ -9,7 +9,7 @@
<div class="banner-icon me-3"> <div class="banner-icon me-3">
<i class="fas fa-user-circle" style="font-size: 40px; color: #6c757d;"></i> <i class="fas fa-user-circle" style="font-size: 40px; color: #6c757d;"></i>
</div> </div>
<h4 class="fw-bold text-primary mb-0" style="margin-left:10px">{{ $user->name ?? 'User' }}</h4> <h4 class="fw-bold text-primary mb-0" style="margin-left:10px">{{ $user['admin']['username'] ?? 'N/A' }}</h4>
</div> </div>
<!-- Profile Section --> <!-- Profile Section -->
@ -20,15 +20,15 @@
<h3 class="fw-bold mb-3" style="font-size: 20px; font-weight:400">My Information</h3> <h3 class="fw-bold mb-3" style="font-size: 20px; font-weight:400">My Information</h3>
<div class="mb-2"> <div class="mb-2">
<span class="fw-bold text-dark">Username: </span> <span class="fw-bold text-dark">Username: </span>
<span>{{ $user->username }}</span> <span>{{ $user['admin']['username'] ?? 'N/A' }}</span>
</div> </div>
<div class="mb-2"> <div class="mb-2">
<span class="fw-bold text-dark">Email: </span> <span class="fw-bold text-dark">Email: </span>
<a href="mailto:{{ $user->email }}" class="text-primary">{{ $user->email }}</a> <a href="mailto:{{ $user['admin']['email'] ?? 'N/A' }}" class="text-primary">{{ $user['admin']['email'] ?? 'N/A' }}</a>
</div> </div>
<div> <div>
<span class="fw-bold text-dark">Access Role: </span> <span class="fw-bold text-dark">Access Role: </span>
<span>{{ $user->role ?? 'System Admin' }}</span> <span>{{ $user['admin']['role'] ?? 'N/A' }}</span>
</div> </div>
</div> </div>
</div> </div>

View File

@ -14,9 +14,9 @@ Route::get('/', function () {
Route::get('/login', [AuthController::class, 'showLoginForm'])->name('login'); Route::get('/login', [AuthController::class, 'showLoginForm'])->name('login');
Route::post('/login', [AuthController::class, 'login'])->name('login'); Route::post('/login', [AuthController::class, 'login'])->name('login');
Route::get('/change-password', [AuthController::class, 'showChangePasswordForm'])->name('password.change.form'); Route::get('/change-password', [AuthController::class, 'showChangePasswordForm'])->name('change-password');
Route::post('/change-password', [AuthController::class, 'changePassword'])->name('password.change'); Route::post('/change-password', [AuthController::class, 'changePassword'])->name('password.change');
Route::get('/my-profile', [AuthController::class, 'showMyProfile'])->name('my-profile')->middleware('auth'); Route::get('/my-profile', [AuthController::class, 'showMyProfile'])->name('my-profile');
Route::post('/logout', [AuthController::class, 'logout'])->name('logout'); Route::post('/logout', [AuthController::class, 'logout'])->name('logout');