cms-frontend/app/Http/Controllers/AuthController.php

64 lines
2.1 KiB
PHP

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\RedirectResponse;
class AuthController extends Controller
{
public function showLoginForm()
{
return view('login');
}
public function login(Request $request): RedirectResponse
{
$validator = Validator::make($request->all(), [
'username' => 'required|string',
'password' => 'required|string',
]);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
}
try {
$response = Http::timeout(30)->post(config('services.backend_api.url') . '/api/cms/login_password', [
'username' => $request->username,
'password' => $request->password,
]);
$json = $response->json();
if ($response->successful()) {
if ($json['code'] === 200) {
Session::put('user', $json['data']['user'] ?? null);
return redirect('my-profile');
} else {
return redirect()->back()
->withErrors(['username' => $json['message'] ?? 'Login failed.'])
->withInput();
}
} else {
$message = $json['message'] ?? 'Login request failed. Please try again.';
return redirect()->back()
->withErrors(['username' => $message])
->withInput();
}
} catch (\Illuminate\Http\Client\ConnectionException $e) {
return redirect()->back()
->withErrors(['username' => 'Unable to connect to the server. Please try again later.'])
->withInput();
} catch (\Exception $e) {
return redirect()->back()
->withErrors(['username' => 'An error occurred: ' . $e->getMessage()])
->withInput();
}
}
}