Skip to content

Commit 356829c

Browse files
committed
refactor: miglioria gestione login per utente già connesso con classe User
1 parent e36a1bc commit 356829c

6 files changed

Lines changed: 99 additions & 41 deletions

File tree

index.php

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,8 @@
6262
} else {
6363
$status = auth_osm()->getCurrentStatus();
6464

65-
flash()->error(AuthOSM::getStatus()[$status]['message']);
65+
// Salva il messaggio di errore in una variabile di sessione separata
66+
$_SESSION['login_error'] = AuthOSM::getStatus()[$status]['message'];
6667

6768
redirect_url(base_path_osm().'/index.php');
6869
exit;
@@ -185,10 +186,12 @@ function brute() {
185186
}
186187
</script>';
187188
}
188-
$error_message = flash()->getMessage('error');
189+
// Recupera il messaggio di errore dalla variabile di sessione
190+
$error_message = $_SESSION['login_error'] ?? null;
189191
if (!empty($error_message)) {
190-
// Recupera il primo messaggio di errore
191-
$error_text = is_array($error_message) ? reset($error_message) : $error_message;
192+
// Rimuovi il messaggio dalla sessione dopo averlo recuperato
193+
unset($_SESSION['login_error']);
194+
192195
echo '
193196
<script>
194197
$(document).ready(function(){
@@ -198,8 +201,8 @@ function brute() {
198201
// Add error styling to password field
199202
$(".password-field").addClass("is-invalid");
200203
201-
// Add error message under password field (usando il messaggio reale dal flash)
202-
$(".password-field-container").append(\'<div class="invalid-feedback d-block"><i class="fa fa-exclamation-circle mr-1"></i>'.addslashes($error_text).'</div>\');
204+
// Add error message under password field
205+
$(".password-field-container").append(\'<div class="invalid-feedback d-block"><i class="fa fa-exclamation-circle mr-1"></i>'.addslashes($error_message).'</div>\');
203206
204207
// Focus on password field
205208
$("input[name=password]").focus();

log.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,9 @@
6969
} elseif ($log['stato'] == $status['unauthorized']['code']) {
7070
$type = 'warning';
7171
$stato = $status['unauthorized']['message'];
72+
} elseif ($log['stato'] == $status['already_logged_in']['code']) {
73+
$type = 'warning';
74+
$stato = $status['already_logged_in']['message'];
7275
} else {
7376
$type = 'danger';
7477
$stato = $status['failed']['message'];

src/AuthOSM.php

Lines changed: 9 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ class AuthOSM extends Util\Singleton
4949
],
5050
'already_logged_in' => [
5151
'code' => 6,
52-
'message' => 'Questo utente è già connesso al gestionale. Chiudere la sessione precedente o riprovare più tardi.',
52+
'message' => 'Utente già connesso al gestionale.',
5353
],
5454
];
5555

@@ -144,17 +144,11 @@ public function attempt($username, $password, $force = false)
144144
// Verifica se l'utente è già connesso (ha un token di sessione attivo)
145145
if (!empty($user['session_token'])) {
146146
// Verifica se ci sono operazioni recenti per l'utente (sessione attiva)
147-
$session_timeout = 10; // minuti
148-
149-
$recent_operations = $database->fetchArray('SELECT COUNT(*) as count FROM zz_operations
150-
WHERE id_utente = :user_id
151-
AND DATE_ADD(created_at, INTERVAL :timeout MINUTE) >= NOW()', [
152-
':user_id' => $user['id'],
153-
':timeout' => $session_timeout,
154-
]);
155-
147+
$user_model = User::find($user['id']);
148+
$is_online = $user_model ? $user_model->isOnline() : 0;
149+
156150
// Se ci sono operazioni recenti, la sessione è ancora attiva -> blocca il login
157-
if (!empty($recent_operations) && $recent_operations[0]['count'] > 0) {
151+
if ($is_online == 1) {
158152
$status = 'already_logged_in';
159153
$this->current_status = $status;
160154

@@ -1229,18 +1223,11 @@ protected function checkSessionToken()
12291223
}
12301224

12311225
// Verifica se il token è scaduto controllando le operazioni recenti
1232-
$session_timeout = 100;
1233-
$database = database();
1234-
1235-
$recent_operations = $database->fetchArray('SELECT COUNT(*) as count FROM zz_operations
1236-
WHERE id_utente = :user_id
1237-
AND DATE_ADD(created_at, INTERVAL :timeout MINUTE) >= NOW()', [
1238-
':user_id' => $this->user->id,
1239-
':timeout' => $session_timeout,
1240-
]);
1241-
1226+
$is_online = $this->user->isOnline();
1227+
12421228
// Se non ci sono operazioni recenti, il token è scaduto -> resetta il token
1243-
if (empty($recent_operations) || $recent_operations[0]['count'] == 0) {
1229+
if ($is_online == 0) {
1230+
$database = database();
12441231
$database->update('zz_users', [
12451232
'session_token' => null,
12461233
], [

src/Models/User.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,23 @@ public function getApiTokens()
218218
return $database->fetchArray($query);
219219
}
220220

221+
public function isOnline(): int
222+
{
223+
$session_timeout = (int) setting('Durata sessione', 60); // minuti
224+
$database = database();
225+
226+
$recent_operations = $database->fetchArray('SELECT COUNT(*) as count FROM zz_operations
227+
WHERE id_utente = :user_id
228+
AND DATE_ADD(created_at, INTERVAL :timeout MINUTE) >= NOW()', [
229+
':user_id' => $this->id,
230+
':timeout' => $session_timeout,
231+
]);
232+
233+
return !empty($recent_operations) && $recent_operations[0]['count'] != 0 ? 1 : 0;
234+
}
235+
236+
237+
221238
/* Relazioni Eloquent */
222239

223240
public function group()

token_login.php

Lines changed: 52 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232

3333
// Verifica che sia stata fornita un token
3434
if (empty($token)) {
35-
flash()->warning(tr('Token mancante'));
35+
$_SESSION['login_error'] = tr('Token mancante');
3636
redirect_url(base_path_osm().'/index.php');
3737
exit;
3838
}
@@ -90,7 +90,7 @@
9090
exit;
9191
} else {
9292
// Login fallito, mostra errore e torna al form OTP
93-
flash()->warning($result['message']);
93+
$_SESSION['login_error'] = $result['message'];
9494
redirect_url(base_path_osm().'/token_login.php?token='.urlencode($token_param).'&otp_requested=1');
9595
exit;
9696
}
@@ -131,12 +131,12 @@
131131
exit;
132132
} else {
133133
// Login fallito, mostra errore
134-
flash()->warning($result['message']);
134+
$_SESSION['login_error'] = $result['message'];
135135
redirect_url(base_path_osm().'/index.php');
136136
exit;
137137
}
138138
} else {
139-
flash()->error(tr('Token non valido'));
139+
$_SESSION['login_error'] = tr('Token non valido');
140140
redirect_url(base_path_osm().'/index.php');
141141
exit;
142142
}
@@ -152,7 +152,7 @@
152152
redirect_url(base_path_osm().'/token_login.php?token='.urlencode($token_param).'&otp_requested=1');
153153
exit;
154154
} else {
155-
flash()->error(tr('Token non valido'));
155+
$_SESSION['login_error'] = tr('Token non valido');
156156
redirect_url(base_path_osm().'/index.php');
157157
exit;
158158
}
@@ -183,7 +183,7 @@
183183
'user_agent' => Filter::getPurifier()->purify($_SERVER['HTTP_USER_AGENT']),
184184
]);
185185

186-
flash()->warning(tr('Token non valido o non abilitato'));
186+
$_SESSION['login_error'] = tr('Token non valido o non abilitato');
187187
redirect_url(base_path_osm().'/index.php');
188188
exit;
189189
}
@@ -209,7 +209,7 @@
209209
'user_agent' => Filter::getPurifier()->purify($_SERVER['HTTP_USER_AGENT']),
210210
]);
211211

212-
flash()->warning(tr('Token non attivo'));
212+
$_SESSION['login_error'] = tr('Token non attivo');
213213
redirect_url(base_path_osm().'/index.php');
214214
exit;
215215
}
@@ -227,7 +227,7 @@
227227
'user_agent' => Filter::getPurifier()->purify($_SERVER['HTTP_USER_AGENT']),
228228
]);
229229

230-
flash()->warning(tr('Utente non abilitato'));
230+
$_SESSION['login_error'] = tr('Utente non abilitato');
231231
redirect_url(base_path_osm().'/index.php');
232232
exit;
233233
}
@@ -274,13 +274,13 @@
274274
if (!empty($token_record['id_module_target']) && !empty($token_record['id_record_target'])) {
275275
redirect_url(base_path_osm().'/shared_editor.php?id_module='.$token_record['id_module_target'].'&id_record='.$token_record['id_record_target']);
276276
} else {
277-
flash()->warning(tr('Token non configurato correttamente per l\'accesso diretto'));
277+
$_SESSION['login_error'] = tr('Token non configurato correttamente per l\'accesso diretto');
278278
redirect_url(base_path_osm().'/index.php');
279279
}
280280
}
281281
exit;
282282
} else {
283-
flash()->warning($result['message']);
283+
$_SESSION['login_error'] = $result['message'];
284284
redirect_url(base_path_osm().'/index.php');
285285
exit;
286286
}
@@ -329,9 +329,9 @@
329329
}
330330
}
331331
} catch (Exception $e) {
332-
flash()->error(tr('Errore durante l\'invio dell\'email OTP: _MSG_', [
332+
$_SESSION['login_error'] = tr('Errore durante l\'invio dell\'email OTP: _MSG_', [
333333
'_MSG_' => $e->getMessage(),
334-
]));
334+
]);
335335
redirect_url(base_path_osm().'/token_login.php?token='.urlencode($token));
336336
exit;
337337
}
@@ -368,6 +368,46 @@
368368

369369
include_once App::filepath('include|custom|', 'top.php');
370370

371+
// Recupera il messaggio di errore dalla variabile di sessione
372+
$error_message = $_SESSION['login_error'] ?? null;
373+
if (!empty($error_message)) {
374+
// Rimuovi il messaggio dalla sessione dopo averlo recuperato
375+
unset($_SESSION['login_error']);
376+
377+
echo '
378+
<script>
379+
$(document).ready(function(){
380+
// Add shake animation to login box
381+
$(".login-box").addClass("animated shake");
382+
383+
// Add error styling to input field
384+
if ($("input[name=otp_code]").length > 0) {
385+
$("input[name=otp_code]").addClass("is-invalid");
386+
387+
// Add error message under OTP field
388+
$("input[name=otp_code]").parent().append(\'<div class="invalid-feedback d-block"><i class="fa fa-exclamation-circle mr-1"></i>'.addslashes($error_message).'</div>\');
389+
390+
// Focus on OTP field
391+
$("input[name=otp_code]").focus();
392+
} else if ($("input[name=password]").length > 0) {
393+
$("input[name=password]").addClass("is-invalid");
394+
395+
// Add error message under password field
396+
$(".password-field-container").append(\'<div class="invalid-feedback d-block"><i class="fa fa-exclamation-circle mr-1"></i>'.addslashes($error_message).'</div>\');
397+
398+
// Focus on password field
399+
$("input[name=password]").focus();
400+
}
401+
402+
// Remove error styling when user starts typing
403+
$("input[name=otp_code], input[name=password]").on("keydown", function() {
404+
$(this).removeClass("is-invalid");
405+
$(".invalid-feedback").fadeOut(300);
406+
});
407+
});
408+
</script>';
409+
}
410+
371411
// Controllo se è una beta e in caso mostro un warning
372412
if (Update::isBeta()) {
373413
echo '

update/2_10.sql

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -434,10 +434,18 @@ INSERT INTO `zz_settings_lang` (`id_lang`, `id_record`, `title`, `help`) VALUES
434434
(1, (SELECT MAX(`id`) FROM `zz_settings`), 'Abilita correttore ortografico', ''),
435435
(2, (SELECT MAX(`id`) FROM `zz_settings`), 'Enable spell checker', '');
436436

437-
-- Aggiunta impostazione Unità di misura predefinita
437+
-- Aggiunta impostazione Unità di misura predefinita
438438
INSERT INTO `zz_settings` (`nome`, `valore`, `tipo`, `editable`, `sezione`) VALUES
439439
('Unità di misura predefinita', '', 'query=SELECT id, valore as descrizione FROM mg_unitamisura', 1, 'Magazzino');
440440

441441
INSERT INTO `zz_settings_lang` (`id_lang`, `id_record`, `title`, `help`) VALUES
442442
(1, (SELECT MAX(`id`) FROM `zz_settings`), 'Unità di misura predefinita', ''),
443443
(2, (SELECT MAX(`id`) FROM `zz_settings`), 'Default unit of measurement', '');
444+
445+
-- Aggiunta impostazione Durata sessione
446+
INSERT INTO `zz_settings` (`nome`, `valore`, `tipo`, `editable`, `sezione`) VALUES
447+
('Durata sessione', '60', 'integer', 1, 'Generali');
448+
449+
INSERT INTO `zz_settings_lang` (`id_lang`, `id_record`, `title`, `help`) VALUES
450+
(1, (SELECT MAX(`id`) FROM `zz_settings`), 'Durata sessione (minuti)', ''),
451+
(2, (SELECT MAX(`id`) FROM `zz_settings`), 'Session duration (minutes)', '');

0 commit comments

Comments
 (0)