Initial commit

This commit is contained in:
2026-01-25 21:03:33 +01:00
commit 8d8e213f1c
2570 changed files with 479666 additions and 0 deletions
@@ -0,0 +1,56 @@
<?php
namespace Vanguard\Http\Controllers\Web\Auth;
use Illuminate\Contracts\Auth\PasswordBroker;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Vanguard\Http\Controllers\Controller;
class ForgotPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset emails and
| includes a trait which assists in sending these notifications from
| your application to your users. Feel free to explore this trait.
|
*/
use SendsPasswordResetEmails;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* {@inheritDoc}
*/
protected function sendResetLinkResponse(Request $request, $response): RedirectResponse
{
return back()->with('success', trans($response));
}
/**
* {@inheritDoc}
*/
protected function sendResetLinkFailedResponse(Request $request, $response): RedirectResponse
{
$messages = ['email' => trans($response)];
$httpResponse = back()->withInput($request->only('email'));
return $response === PasswordBroker::INVALID_USER
? $httpResponse->withSuccess($messages)
: $httpResponse->withErrors($messages);
}
}
@@ -0,0 +1,197 @@
<?php
namespace Vanguard\Http\Controllers\Web\Auth;
use Auth;
use Illuminate\Contracts\Auth\Authenticatable as BaseAuthenticatable;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Vanguard\Events\User\LoggedIn;
use Vanguard\Events\User\LoggedOut;
use Vanguard\Http\Controllers\Controller;
use Vanguard\Http\Requests\Auth\LoginRequest;
use Vanguard\Repositories\Session\SessionRepository;
use Vanguard\Repositories\User\UserRepository;
use Vanguard\Services\Auth\ThrottlesLogins;
use Vanguard\User;
use Vanguard\Models\School;
class LoginController extends Controller
{
use ThrottlesLogins;
public function __construct(private readonly UserRepository $users)
{
$this->middleware('guest')->except('logout');
$this->middleware('auth')->only('logout');
}
/**
* Show the application login form.
*/
public function show($school = null): View
{
// Debug: aggiungiamo un log per verificare se arriviamo qui
\Log::info('LoginController::show chiamato con school = ' . ($school ?? 'null'));
// Cerca la scuola in base allo slug
$schoolData = null;
if ($school) {
$schoolData = School::where('slug', $school)->first();
}
return view('auth.login', [
'socialProviders' => config('auth.social.providers'),
'school_slug' => $school,
'school_logo' => $schoolData ? $schoolData->logo : null,
]);
}
public function login(LoginRequest $request, SessionRepository $sessions): Response|RedirectResponse
{
// Debug: aggiungiamo un log per verificare se arriviamo qui
\Log::info('LoginController::login chiamato con input: ' . json_encode($request->all()));
// In case that request throttling is enabled, we have to check if user can perform this request.
$throttles = (bool) setting('throttle_enabled');
// Redirect URL that can be passed as hidden field.
$to = $request->has('to') ? '?to=' . $request->get('to') : '';
if ($throttles && $this->hasTooManyLoginAttempts($request)) {
return $this->sendLockoutResponse($request);
}
// Validazione del campo school
$schoolSlug = $request->input('school');
if ($schoolSlug) {
$school = School::where('slug', $schoolSlug)->first();
if ($school) {
// Se presente e valida → salva in sessione
$request->session()->put('school_id', $school->id);
}
// ⚠️ se non esiste → NON blocchiamo il login
}
// ⚠️ se è vuota → NON facciamo nulla
$credentials = $request->getCredentials();
if (! Auth::validate($credentials)) {
if ($throttles) {
$this->incrementLoginAttempts($request);
}
return redirect()->to('login' . $to)
->withErrors(trans('auth.failed'));
}
$user = Auth::getProvider()->retrieveByCredentials($credentials);
if ($user->isBanned()) {
return redirect()->to('login' . $to)
->withErrors(trans('auth.banned'));
}
$maxSessions = setting('max_active_sessions');
if ($maxSessions && $sessions->getActiveSessionsCount($user->id) >= $maxSessions) {
return redirect()->to('login' . $to)
->withErrors(trans('auth.max_sessions_reached'));
}
Auth::login($user, setting('remember_me') && $request->get('remember'));
return $this->authenticated($request, $throttles, $user);
}
/**
* Send the response after the user was authenticated.
*/
protected function authenticated(
Request $request,
bool $throttles,
BaseAuthenticatable $user,
): Response|RedirectResponse {
if ($throttles) {
$this->clearLoginAttempts($request);
}
// Redirezione basata sul ruolo
if ($user->hasRole('Admin')) {
return redirect()->to('userarea/admin.php');
} elseif ($user->hasRole('User')) {
return redirect()->to('userarea/select_school.php');
} elseif ($user->hasRole('teacher')) {
return redirect()->to('userarea/teacher.php');
} elseif ($user->hasRole('school_owner')) {
return redirect()->to('userarea/school_dashboard.php');
}
return redirect()->intended('userarea/default.php');
}
protected function logoutAndRedirectToTokenPage(Request $request, $user, ?string $redirectPage): RedirectResponse
{
Auth::logout();
$request->session()->put('auth.2fa.id', $user->id);
if ($redirectPage) {
$request->session()->put('auth.redirect_to', $redirectPage);
}
return redirect()->route('auth.token');
}
/**
* Log the user out of the application.
*/
public function logout(Request $request): RedirectResponse
{
event(new LoggedOut);
// 1) Logout Laravel
Auth::logout();
// 2) Pulisci + invalida session Laravel (NON solo forget)
$request->session()->forget(['school_id', 'school_name', 'school_selected']);
$request->session()->invalidate();
$request->session()->regenerateToken();
// 3) Pulisci anche la session PHP nativa usata in userarea (PHPSESSID)
if (session_status() !== PHP_SESSION_ACTIVE) {
@session_start();
}
unset(
$_SESSION['school_id'],
$_SESSION['school_name'],
$_SESSION['school_selected']
);
// Se vuoi essere ancora più “definitivo”, distruggi tutta la PHP session:
$_SESSION = [];
if (ini_get('session.use_cookies')) {
$params = session_get_cookie_params();
setcookie(
session_name(),
'',
time() - 42000,
$params['path'],
$params['domain'],
$params['secure'],
$params['httponly']
);
}
@session_destroy();
return redirect('login');
}
}
@@ -0,0 +1,47 @@
<?php
namespace Vanguard\Http\Controllers\Web\Auth;
use Illuminate\Auth\Events\Registered;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Vanguard\Http\Controllers\Controller;
use Vanguard\Http\Requests\Auth\RegisterRequest;
use Vanguard\Repositories\Role\RoleRepository;
use Vanguard\Repositories\User\UserRepository;
use Vanguard\Role;
class RegisterController extends Controller
{
public function __construct(private readonly UserRepository $users)
{
$this->middleware('registration')->only('show', 'register');
}
public function show(): View
{
return view('auth.register', [
'socialProviders' => config('auth.social.providers'),
]);
}
public function register(RegisterRequest $request, RoleRepository $roles): RedirectResponse
{
$user = $this->users->create(
array_merge(
$request->validFormData(),
['role_id' => $roles->findByName(Role::DEFAULT_USER_ROLE)->id],
)
);
event(new Registered($user));
$message = setting('reg_email_confirmation')
? __('Your account is created successfully! Please confirm your email.')
: __('Your account is created successfully!');
\Auth::login($user);
return redirect('/')->with('success', $message);
}
}
@@ -0,0 +1,58 @@
<?php
namespace Vanguard\Http\Controllers\Web\Auth;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Contracts\Auth\CanResetPassword;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Support\Str;
use Vanguard\Http\Controllers\Controller;
class ResetPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Where to redirect users after resetting their password.
*
* @var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* {@inheritDoc}
*/
protected function resetPassword(CanResetPassword $user, string $password)
{
$user->password = $password;
$user->setRememberToken(Str::random(60));
$user->save();
event(new PasswordReset($user));
$this->guard()->login($user);
}
}
@@ -0,0 +1,97 @@
<?php
namespace Vanguard\Http\Controllers\Web\Auth;
use Auth;
use Illuminate\Http\RedirectResponse;
use Laravel\Socialite\Contracts\User as SocialUser;
use Socialite;
use Vanguard\Events\User\LoggedIn;
use Vanguard\Http\Controllers\Controller;
use Vanguard\Repositories\User\UserRepository;
use Vanguard\Services\Auth\Social\SocialManager;
use Vanguard\User;
class SocialAuthController extends Controller
{
public function __construct(private readonly UserRepository $users, private readonly SocialManager $socialManager)
{
$this->middleware('guest');
}
/**
* Redirect user to specified provider in order to complete the authentication process.
*/
public function redirectToProvider(string $provider): RedirectResponse
{
if (strtolower($provider) == 'facebook') {
return Socialite::driver('facebook')->with(['auth_type' => 'rerequest'])->redirect();
}
return Socialite::driver($provider)->redirect();
}
/**
* Handle response authentication provider.
*/
public function handleProviderCallback(string $provider): RedirectResponse
{
if (request()->get('error')) {
return redirect('login')
->withErrors(__('Something went wrong during the authentication process. Please try again.'));
}
$socialUser = $this->getUserFromProvider($provider);
$user = $this->users->findBySocialId($provider, $socialUser->getId());
if (! $user) {
if (! setting('reg_enabled')) {
return redirect('login')
->withErrors(__('Only users who already created an account can log in.'));
}
if (! $socialUser->getEmail()) {
return redirect('login')
->withErrors(__('You have to provide your email address.'));
}
$user = $this->socialManager->associate($socialUser, $provider);
event(new \Illuminate\Auth\Events\Registered($user));
}
return $this->loginAndRedirect($user);
}
/**
* Get user from authentication provider.
*/
private function getUserFromProvider(string $provider): SocialUser
{
return Socialite::driver($provider)->user();
}
/**
* Log provided user in and redirect him to intended page.
*/
private function loginAndRedirect(User $user): RedirectResponse
{
if ($user->isBanned()) {
return redirect()->to('login')
->withErrors(__('Your account is banned by administrator.'));
}
if (setting('2fa.enabled') && $user->twoFactorEnabled()) {
session()->put('auth.2fa.id', $user->id);
return redirect()->route('auth.token');
}
Auth::login($user);
event(new LoggedIn);
return redirect()->intended('/');
}
}
@@ -0,0 +1,63 @@
<?php
namespace Vanguard\Http\Controllers\Web\Auth;
use Auth;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Vanguard\Events\User\LoggedIn;
use Vanguard\Http\Controllers\Controller;
use Vanguard\Http\Requests\TwoFactor\TwoFactorLoginRequest;
use Vanguard\Repositories\User\UserRepository;
use Vanguard\Services\Auth\ThrottlesLogins;
class TwoFactorTokenController extends Controller
{
use ThrottlesLogins;
public function __construct(private readonly UserRepository $users)
{
}
/**
* Show Two-Factor Token form.
*/
public function show(): View|RedirectResponse
{
return session('auth.2fa.id') ? view('auth.token') : redirect('login');
}
/**
* Handle Two-Factor token form submission.
*/
public function update(TwoFactorLoginRequest $request): RedirectResponse
{
$this->validate($request, ['code' => 'required']);
if (! session('auth.2fa.id')) {
return redirect('login');
}
$user = $this->users->find(
$request->session()->pull('auth.2fa.id')
);
if (!$user) {
throw new NotFoundHttpException;
}
$customRedirect = $request->session()->pull('auth.redirect_to') ?: '';
if (!$request->hasValidCode($user)) {
return redirect()->to('login' . ($customRedirect ? "?to={$customRedirect}" : ''))
->withErrors(trans('auth.2fa.invalid_token'));
}
Auth::login($user);
event(new LoggedIn);
return redirect()->intended($customRedirect ?: '/');
}
}
@@ -0,0 +1,41 @@
<?php
namespace Vanguard\Http\Controllers\Web\Auth;
use Illuminate\Foundation\Auth\VerifiesEmails;
use Vanguard\Http\Controllers\Controller;
class VerificationController extends Controller
{
/*
|--------------------------------------------------------------------------
| Email Verification Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling email verification for any
| user that recently registered with the application. Emails may also
| be re-sent if the user didn't receive the original email message.
|
*/
use VerifiesEmails;
/**
* Where to redirect users after verification.
*
* @var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
$this->middleware('signed')->only('verify');
$this->middleware('throttle:6,1')->only('verify', 'resend');
}
}
@@ -0,0 +1,235 @@
<?php
session_start();
include('include/headscript.php');
if (!isset($_SESSION['iduserlogin'])) {
header('Location: login.php');
exit;
}
$iduserlogin = $_SESSION['iduserlogin'];
$dbHandler = DBHandlerSelect::getInstance();
$pdo = $dbHandler->getConnection();
// === DATI UTENTE ===
$stmt = $pdo->prepare("SELECT first_name, last_name, avatar FROM auth_users WHERE id = ?");
$stmt->execute([$iduserlogin]);
$user = $stmt->fetch();
$avatar = $user['avatar'] ? '../upload/users/' . $user['avatar'] : '../assets/images/default-avatar.png';
$first_name = htmlspecialchars($user['first_name'] ?? '');
// === PROCESSA SELEZIONE SCUOLA (POST) ===
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['school_id'])) {
$school_id = (int)$_POST['school_id'];
$stmt = $pdo->prepare("SELECT id, name, logo FROM schools WHERE id = ? AND status = 'active'");
$stmt->execute([$school_id]);
$school = $stmt->fetch();
if ($school) {
// Iscrivi automaticamente se non era già iscritto
$stmtCheck = $pdo->prepare("SELECT 1 FROM user_schools WHERE user_id = ? AND school_id = ?");
$stmtCheck->execute([$iduserlogin, $school_id]);
if (!$stmtCheck->fetch()) {
$pdo->prepare("INSERT INTO user_schools (user_id, school_id, status) VALUES (?, ?, 'active')")
->execute([$iduserlogin, $school_id]);
}
// Imposta sessione
$_SESSION['school_id'] = $school['id'];
$_SESSION['school_name'] = $school['name'];
// Reindirizza alla dashboard finale
header('Location: user_dashboard.php');
exit;
}
}
// === RECUPERA SCUOLE DELL'UTENTE ===
$stmt = $pdo->prepare("
SELECT s.id, s.name, s.slug, s.logo, s.address_city
FROM user_schools us
JOIN schools s ON us.school_id = s.id
WHERE us.user_id = ? AND us.status = 'active' AND s.status = 'active'
ORDER BY s.name
");
$stmt->execute([$iduserlogin]);
$userSchools = $stmt->fetchAll();
// Caso 1: ha esattamente 1 scuola → vai diretto
if (count($userSchools) === 1) {
$school = $userSchools[0];
$_SESSION['school_id'] = $school['id'];
$_SESSION['school_name'] = $school['name'];
header('Location: user_dashboard.php');
exit;
}
// Caso 2: ha più scuole → mostra selezione
// Caso 3: nessuna scuola → mostra tutte le scuole pubbliche
if (empty($userSchools)) {
$stmt = $pdo->prepare("
SELECT id, name, slug, logo, address_city
FROM schools
WHERE status = 'active'
ORDER BY name
");
$stmt->execute();
$schools = $stmt->fetchAll();
$title = "Benvenuto! Scegli la tua scuola di yoga";
$subtitle = "Seleziona la scuola dove vuoi prenotare le lezioni";
} else {
$schools = $userSchools;
$title = "Ciao $first_name!";
$subtitle = "Seleziona la scuola in cui vuoi entrare oggi";
}
?>
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Scegli la scuola - Yogiboook</title>
<?php include('cssinclude.php'); ?>
<?php include('siteinfo.php'); ?>
<style>
:root {
--pastel-blue: #94bacc;
--pastel-green: #a3d9b1;
--pastel-pink: #f8bbd0;
--pastel-yellow: #fff8c4;
}
.hero-header {
background: linear-gradient(135deg, #94bacc, #a3d9b1);
color: white;
border-radius: 20px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}
.school-card {
transition: all 0.3s ease;
border: 2px solid transparent;
border-radius: 20px;
overflow: hidden;
cursor: pointer;
}
.school-card:hover {
transform: translateY(-10px);
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
border-color: var(--pastel-blue);
}
.school-logo {
height: 120px;
object-fit: contain;
background: #f8f9fa;
padding: 15px;
}
.btn-select {
background: linear-gradient(135deg, var(--pastel-blue), var(--pastel-green));
border: none;
color: white;
font-weight: bold;
border-radius: 15px;
padding: 12px;
}
.btn-select:hover {
transform: scale(1.05);
color: white;
}
</style>
</head>
<body>
<div class="wrapper">
<?php include('include/navbar.php'); ?>
<?php include('include/topbar.php'); ?>
<div class="page-wrapper">
<div class="page-content" style="background: linear-gradient(to bottom, #f0f8ff, #f8f9fa); min-height: 100vh;">
<div class="container-fluid px-4 pt-5">
<!-- Header Benvenuto -->
<div class="card hero-header mb-5 shadow-lg">
<div class="card-body text-center py-5">
<h1 class="display-5 fw-bold mb-3"><?php echo $title; ?></h1>
<p class="fs-5 opacity-90"><?php echo $subtitle; ?></p>
</div>
</div>
<!-- Griglia Scuole -->
<?php if (empty($schools)): ?>
<div class="text-center py-5">
<i class="bx bx-building-house bx-lg text-muted"></i>
<h4 class="mt-3 text-muted">Nessuna scuola disponibile al momento</h4>
</div>
<?php else: ?>
<form method="POST" id="schoolForm">
<?= csrf_field() ?> <!-- se usi CSRF, altrimenti rimuovi -->
<div class="row g-4 justify-content-center">
<?php foreach ($schools as $school): ?>
<div class="col-md-6 col-lg-4">
<div class="school-card card h-100 shadow-sm" onclick="selectSchool(<?= $school['id'] ?>)">
<div class="text-center">
<?php
$logoPath = !empty($school['logo']) && file_exists("photoschool/" . $school['logo'])
? "photoschool/" . $school['logo']
: null;
?>
<?php if ($logoPath): ?>
<img src="<?= htmlspecialchars($logoPath) ?>"
class="school-logo w-100"
alt="<?= htmlspecialchars($school['name']) ?>">
<?php else: ?>
<div class="school-logo d-flex align-items-center justify-content-center">
<i class="bx bx-building-house display-4 text-muted"></i>
</div>
<?php endif; ?>
</div>
<div class="card-body text-center pb-4">
<h5 class="card-title mb-2"><?= htmlspecialchars($school['name']) ?></h5>
<?php if (!empty($school['address_city'])): ?>
<p class="text-muted small mb-0">
<i class="bx bx-map me-1"></i><?= htmlspecialchars($school['address_city']) ?>
</p>
<?php endif; ?>
</div>
<div class="card-footer bg-transparent border-0 pt-0">
<button type="submit" class="btn btn-select w-100 shadow-sm">
<i class="bx bx-check me-2"></i>Seleziona questa scuola
</button>
</div>
</div>
<input type="radio" name="school_id" value="<?= $school['id'] ?>" id="school_<?= $school['id'] ?>" class="d-none" required>
</div>
<?php endforeach; ?>
</div>
</form>
<?php endif; ?>
</div>
</div>
</div>
<?php include('include/footer.php'); ?>
</div>
<?php include('jsinclude.php'); ?>
<script>
function selectSchool(id) {
document.getElementById('school_' + id).checked = true;
document.getElementById('schoolForm').submit();
}
</script>
</body>
</html>