From 3e3fb6d953f6f06f9af3138068a7fde355385e15 Mon Sep 17 00:00:00 2001
From: marko
Date: Mon, 6 Jun 2022 12:55:17 +0200
Subject: [PATCH] redirecting login
---
homepage/participo/attendance.php | 14 +-
homepage/participo/auth.php | 4 +-
homepage/participo/events.inc.php | 18 +-
homepage/participo/events.php | 43 +++-
homepage/participo/index.php | 98 +--------
homepage/participo/lib/api.php | 2 +-
homepage/participo/lib/db.php | 17 +-
.../participo/lib/participoLib/participo.php | 191 +++++++++++++++++-
.../{planerLib => participoLib}/planer.php | 20 ++
homepage/participo/login.php | 30 ++-
homepage/participo/user.php | 9 +-
submodules/materialize | 2 +-
12 files changed, 304 insertions(+), 144 deletions(-)
rename homepage/participo/lib/{planerLib => participoLib}/planer.php (89%)
diff --git a/homepage/participo/attendance.php b/homepage/participo/attendance.php
index fa7f477..55e7edb 100644
--- a/homepage/participo/attendance.php
+++ b/homepage/participo/attendance.php
@@ -15,15 +15,15 @@ setlocale (LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge');
require_once($config['basePath']."/config/cwsvJudo.config.php");
require_once($config['basePath']."/config/phpcount.config.php");
- $dbConnection = getPdoDbConnection(
+ dbConnector::connect(
$cwsvJudoConfig["db"]["host"],
$cwsvJudoConfig["db"]["name"],
$cwsvJudoConfig["db"]["user"],
$cwsvJudoConfig["db"]["password"]
);
- $userData = getUserData($dbConnection, $_SESSION['user']['userId']);
- $usersKids = getUsersKids($dbConnection, $_SESSION['user']['userId']);
+ $userData = getUserData(dbConnector::getDbConnection(), $_SESSION['user']['userId']);
+ $usersKids = getUsersKids(dbConnector::getDbConnection(), $_SESSION['user']['userId']);
abstract class AttendanceType {
const __default = null;
@@ -273,13 +273,13 @@ foreach($usersKids as $k){
if($_SESSION['login']){
?>
- UserAttribute::InTraining]));?>
+ UserAttribute::InTraining]));?>
Eigene Anwesenheiten".
- Attendance::userAttendanceHtmlTable($dbConnection, $userData['id'])
+ Attendance::userAttendanceHtmlTable(dbConnector::getDbConnection(), $userData['id'])
); require_once("./lib/participoLib/participo.php");
}
@@ -290,7 +290,7 @@ if($_SESSION['login']){
if($userData['id']==$k['kidId']) continue;
echo(
"".$k['vorname']." ".$k['name']." ".
- Attendance::userAttendanceHtmlTable($dbConnection, $k['kidId'])
+ Attendance::userAttendanceHtmlTable(dbConnector::getDbConnection(), $k['kidId'])
);
}
}
diff --git a/homepage/participo/auth.php b/homepage/participo/auth.php
index c25f3a6..4cdd5bf 100644
--- a/homepage/participo/auth.php
+++ b/homepage/participo/auth.php
@@ -1,9 +1,9 @@
"Event Planer",
+ 'description' => "Planung von (Nicht-)Teilnahmen an Wettkämpfen und anderen Veranstaltungen"
+ );
?>
\ No newline at end of file
diff --git a/homepage/participo/events.php b/homepage/participo/events.php
index 2978706..f2da302 100644
--- a/homepage/participo/events.php
+++ b/homepage/participo/events.php
@@ -1,8 +1,5 @@
"Event Planer",
- 'description' => "Planung von (Nich-)Teilnahmen an Wettkämpfen und anderen Veranstaltungen"
-);
+set_include_path(get_include_path() . PATH_SEPARATOR . "./lib/");
include_once("events.inc.php");
@@ -28,7 +25,7 @@ include_once("events.inc.php");
- ])>
+
@@ -37,12 +34,46 @@ include_once("events.inc.php");
+ Übersicht anstehender Events
+
+ Detailansicht kommender Wettkämpfe
+ asHtmlCard());?>
diff --git a/homepage/participo/index.php b/homepage/participo/index.php
index f45462f..27490eb 100644
--- a/homepage/participo/index.php
+++ b/homepage/participo/index.php
@@ -1,110 +1,30 @@
= CURDATE() ".
- "ORDER BY wkParticipo_Events.date;";
- $ret = dbQuery($dbConn, $query);
- // $results = $anMysqlConn->query($query);
-
- // // Bei einem Fehler bei der Abfrage soll NULL zurückgeliefert werden
- // if( !$results ){
- // echo("No Results: ".$anMysqlConn->error);
- // return NULL;
- // }
- // // Bei einem leeren Ergebnis (NULL oder leeres Array) soll ein leeres Array zurückgeliefert werden
- // if( empty($results) ) return array();
-
- // while( $result = $results->fetch_assoc() ){
- // array_walk(
- // $result,
- // function (&$value, $key, $someOptions) {
- // $value = iconv($someOptions['dbCharset'], $someOptions['outCharset'], $value);
- // },
- // $someOptions
- // );
- // array_push( $ret, $result);
- // }
- return $ret;
-}
+ $userData = getUserData(dbConnector::getDbConnection(), $_SESSION['user']['userId']);
+ eventPlaner::setDbConnection( dbConnector::getDbConnection() );
-// array(12) {
-// ["id"]=> string(3) "139"
-// ["date"]=> string(10) "2021-12-29"
-// ["wkId"]=> string(0) ""
-// ["meldefrist"]=> string(10) "2021-12-28"
-// ["bemerkungen"]=> string(374) "{ "Datum": "2021-12-29", "Veranstaltung": "Jahresabschlusstraining", "Altersklassen": "alle", "bemerkungen": "
-
-// Zum Abschluss des Jahres noch einmal eine kleine Einheit hauptsächlich zum Spielen
-// Zeit: 16:00--19:00 Uhr
-
-// ", "Ort": "unser Dojo, Str. Usti nad Labem 42, 09120 Chemnitz", "Routenplaner": "https://osm.org/go/0MIYhLf3Q-" }"
-// ["kvOptions"]=> string(0) ""
-// ["Datum"]=> string(0) ""
-// ["Veranstaltung"]=> string(0) ""
-// ["Altersklassen"]=> string(0) ""
-// ["Ort"]=> string(0) ""
-// ["Ausschreibung"]=> string(0) ""
-// ["Routenplaner"]=> string(0) ""
-// }
-function getHtmlEventTable($eventList){
- $ret = "";
- foreach($eventList as $event){
- $e = json_decode($event['bemerkungen'], true);
- $e = (($e==null)?$event:$e);
- $e['id']=$event['id'];
- $ret .= "".$e['Datum']." ".$e['Veranstaltung']." ";
- }
- $ret .= "
";
- return $ret;
-}
?>
@@ -160,9 +80,9 @@ function getHtmlEventTable($eventList){
Einstellensettings
-
+
- adminStuff
+ adminStuff
@@ -189,7 +109,7 @@ echo(
AppCard::fromArray([
'link' => "/pages/desktop/wkParticipo",
'title' => "Event-Planer",
- 'description'=> "Organisieren der Teilnahmen (und nicht-Teilnahmen) an Wettkämpfen, Sondertrainingseinheiten, Feiern etc.
".getHtmlEventTable(getCommingWkEvents($dbConnection))."",
+ 'description'=> "Organisieren der Teilnahmen (und nicht-Teilnahmen) an Wettkämpfen, Sondertrainingseinheiten, Feiern etc.
".eventPlaner::getHtmlEventTable(eventPlaner::getCommingWkEvents())."",
'imgUrl' => "/ressourcen/graphiken/icons/terminKalender.svg",
'actions' => [
AppCardAction::fromArray(['caption'=>"Planer", 'link'=>"/pages/desktop/wkParticipo"]),
@@ -272,7 +192,7 @@ echo(
AdminStuff".
"
".
diff --git a/homepage/participo/lib/api.php b/homepage/participo/lib/api.php
index b455d83..b39ccb0 100644
--- a/homepage/participo/lib/api.php
+++ b/homepage/participo/lib/api.php
@@ -123,7 +123,7 @@ function updateUserPassword($db, $userId, $password){
':val' => array('value'=>$password, 'data_type'=>PDO::PARAM_STR),
':id' => array('value'=>$userId, 'data_type'=>PDO::PARAM_INT)
);
- dbQuery($db, $query, $params);
+ dbConnector::query($query, $params);
return;
}
diff --git a/homepage/participo/lib/db.php b/homepage/participo/lib/db.php
index d76a942..ae428cb 100644
--- a/homepage/participo/lib/db.php
+++ b/homepage/participo/lib/db.php
@@ -1,19 +1,4 @@
getMessage() );
- }
-return $dbConnection;
-}
-
function createDb($dbConnection){
<<
NULL, 'success' => NULL, 'notice' => NULL];
+
+ /**
+ * Returns the current login status
+ *
+ * The login status is stored in the session cookie. If it is not even set it means the login is invalid.
+ *
+ * @return The login status or false if none is set so far
+ */
+ static public function isLoginValid(){
+ return ($_SESSION['login'] ?? false);
+ }
+
+ /**
+ * A little Box with the login status as html entity
+ *
+ * @return string htmlEntity showing the login status
+ */
+ static public function htmlLoginStatus(){
+ return
+ "".
+ "Datum: ".date("Y-m-d")."
".
+ "Angemeldet als
".htmlspecialchars($_SESSION['user']['username'])." .
".
+ "
Sitzung beenden ".
+ "
";
+ }
+
+ /**
+ * Checks, if there already is a valid login, if not redirect to the login form
+ *
+ * @retval void
+ */
+ static public function authentificate(){
+ session_start();
+ if ( !self::isLoginValid() ) {
+ header("Location: login?returnToUrl=".urlencode($_SERVER['REQUEST_URI']), TRUE, 301);
+ exit(); // should'nt matter
+ }
+ }
+
+ static public function getMessages(){return self::$message;}
+ static public function addMessage($type, $message){self::$message[$type] = (self::$message[$type] ?? "").$message;}
+
+ static public function checkCredentials($loginName, $password){
+ sleep(1); // just to discurrage brute force attacks
+ // Check for dbConnection
+ if(!dbConnector::getDbConnection()){
+ self::addMessage('error', "No DbConnection available
");
+ return false;
+ }
+
+ // query all users with the entered name
+ $user = dbConnector::query(
+ "SELECT `id`, `loginName`, `pwHash`, `config` FROM `wkParticipo_Users` WHERE `loginName` = :loginName",
+ ['loginName' => ['value'=>$loginName, 'data_type'=>PDO::PARAM_STR]]
+ );
+
+ // If there is no such user OR the password isn't valid the login fails
+ if( empty($user || !password_verify( $password, $user['pwHash']) )){
+ sleep(5); // discourage brute force attacks
+ self::addMessage('error', "Falsches Passwort oder LoginName
");
+ return false;
+ }
+
+ session_start();
+ // case valid login: Set the session data
+ $_SESSION = array(
+ 'login' => true,
+ 'user' => array(
+ 'username' => $row['loginName'],
+ 'userId' => $row['id'],
+ 'userConfig' => json_decode($row['config'], true)
+ )
+ );
+
+ // Logging Logins
+ logLoginsToJsonFile($_SESSION['user']['username']);
+
+ self::addMessage('success', "Anmeldung erfolgreich
");
+ return true;
+ }
}
-
-
/**
* Action element of an MaterializeCss (App-)card
*/
@@ -273,4 +351,111 @@ function logLoginsToJsonFile($userName, $fileName="lastLogins.json"){
}
}
+
+class dbConnector{
+ static private $db = null;
+
+ // connect to the database
+ public static function connect($hostname, $dbName, $user, $password){
+ return self::setDbConnection( self::connectToPdo($hostname, $dbName, $user, $password) );
+ }
+
+ public static function getDbConnection(){return self::$db;}
+
+ /// perform a pdo-query
+ ///
+ /// @param $aQueryString
+ /// @param $aBindArray e.g. array(
+ /// ':userId' => array('value'=>$anUserId, 'data_type'=>PDO::PARAM_INT),
+ /// ':attributeId'=> array('value'=>$anAttributeId, 'data_type'=>PDO::PARAM_INT) )
+ /// @param $someOption
+ function query($aQueryString, $aBindArray = array(), $someOptions = array()){
+ // Standardbelegungen
+ if( empty($someOptions['dbCharset' ]) ) $someOptions['dbCharset' ] = "ISO-8859-1";
+ if( empty($someOptions['outCharset']) ) $someOptions['outCharset'] = "UTF-8";
+ if( empty($someOptions['dontFetch' ]) ) $someOptions['dontFetch' ] = false;
+
+ /// @toDo: Bisher wird nur die Rückgabe konvertiert. Eigentlich muss
+ /// doch auch die Eingabe konvertiert werden. Aber das jetzt
+ /// umzustellen wird schwer! Die User im Wettkampfplaner sind ja z.B.
+ /// als UTF8 in latin1(?) gespeichert.
+ /// @toDo: Die Standardwerte sollten vielleicht aus einer config
+ /// kommen, nicht hardcoded
+ try{
+ $pdoStatement = self::$db->prepare( $aQueryString );
+ foreach( $aBindArray as $bindName => $bind ){
+ if( $bind['data_type'] == PDO::PARAM_STR)
+ $bind['value'] = iconv(
+ $someOptions['outCharset'],
+ $someOptions['dbCharset'],
+ $bind['value']
+ );
+ $pdoStatement->bindValue(
+ $bindName,
+ $bind['value'],
+ (isset($bind['data_type'])?$bind['data_type']:PDO::PARAM_STR)
+ );
+ }
+ $pdoResult = $pdoStatement->execute();
+ if(!$pdoResult){
+ echo("Error during dbQuery!\n");
+ echo("DB-Error:\n"); var_dump(self::$db->errorInfo());
+ }
+ if($someOptions['dontFetch']){
+ $ret = NULL;
+ }
+ else{
+ $ret = $pdoStatement->fetchAll(PDO::FETCH_ASSOC);
+ }
+ }
+ catch(PDOException $db_error){
+ print "Error!: " . $db_error->getMessage() . " ";
+ return null;
+ }
+
+ // Zeichensatzkonvertierung
+ if( is_array($ret) ){
+ foreach($ret as &$entry){
+ array_walk(
+ $entry,
+ function (&$value, $key, $someOptions) {
+ $value = iconv($someOptions['dbCharset'], $someOptions['outCharset'], $value);
+ },
+ $someOptions
+ );
+ }
+ }
+ return $ret;
+ }
+
+ // get a Connection to the database
+ static private function connectToPdo($hostname, $dbName, $user, $password){
+ $dbConnection=null;
+ try{
+ $dbConnection = new PDO(
+ 'mysql:host='.$hostname.';dbname='.$dbName,
+ $user,
+ $password
+ );
+ }
+ catch(PDOException $dbError){
+ echo( "Error whilst getting a dbConnection!: " . $dbError->getMessage() );
+ }
+ return $dbConnection;
+ }
+
+ // set the dbConnection (just setting, no establishing)
+ private static function setDbConnection($dbConnection){
+ $success = false;
+ if($dbConnection instanceof PDO){
+ self::$db = $dbConnection;
+ $success = true;
+ }
+ else{
+ self::$db = null;
+ }
+ }
+
+
+}
?>
\ No newline at end of file
diff --git a/homepage/participo/lib/planerLib/planer.php b/homepage/participo/lib/participoLib/planer.php
similarity index 89%
rename from homepage/participo/lib/planerLib/planer.php
rename to homepage/participo/lib/participoLib/planer.php
index 7b6c91b..1e09d61 100644
--- a/homepage/participo/lib/planerLib/planer.php
+++ b/homepage/participo/lib/participoLib/planer.php
@@ -28,6 +28,9 @@ class shiai{
public function getName(){
return $this->name;
}
+ public function getAgeClasses(){
+ return $this->ageclasses ? $this->ageclasses : "-";
+ }
public function getId(){
return $this->id;
}
@@ -67,6 +70,21 @@ class event{
$this->shiai = $shiai;
}
+ function asHtmlCard(){
+ return
+ "".
+ "
".
+ "
".$this->shiai->getName()." ".
+ "
".
+ "Datum ".
+ "".$this->date->format("Y-m-d")." ".
+ "Meldefrist ".
+ "".$this->deadline->format("Y-m-d")." ".
+ "Altersklassen ".
+ "".$this->shiai->getAgeClasses()." ".
+ " ".
+ "
";
+ }
public function htmlTableRow(){
return
"".
@@ -146,4 +164,6 @@ class eventPlaner{
return $ret;
}
}
+
+
?>
\ No newline at end of file
diff --git a/homepage/participo/login.php b/homepage/participo/login.php
index fa9aadd..b4ebe6f 100644
--- a/homepage/participo/login.php
+++ b/homepage/participo/login.php
@@ -6,9 +6,17 @@ setlocale (LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge');
require_once("./local/dbConf.php");
-// Check, if the login is already set. If so move to the main page.
+ require_once($config['basePath']."/config/cwsvJudo.config.php");
+ dbConnector::connect(
+ $cwsvJudoConfig["db"]["host"],
+ $cwsvJudoConfig["db"]["name"],
+ $cwsvJudoConfig["db"]["user"],
+ $cwsvJudoConfig["db"]["password"]
+ );
+
+// Check, if the login is already set. If so move to the main page
if (isset($_SESSION['login'])) {
- header('Location: http://' . $_SERVER['HTTP_HOST'] . '/index.php');
+ header("Location: http://" . ($_POST['returnToUrl'] ?? "."), TRUE, 301);
}
// Otherwise check credentials if given.
else{
@@ -17,12 +25,14 @@ else{
empty($_POST['f']['username']) ||
empty($_POST['f']['password'])
) {
- $message['error'] = 'Es wurden nicht alle Felder ausgefüllt.';
+ $message = ['error' => "Es wurden nicht alle Felder ausgefüllt."];
} else {
-
- $message = checkCredentials($_POST['f']['username'], $_POST['f']['password'], $db_server, $db_user, $db_password, $db_name);
- if( !isset($message['error']) )
- $message['notice'] = "OnlineApps - cwsvJudo";
+ if( participo::checkCredentials( $_POST['f']['username'], $_POST['f']['password']) ){
+ $returnToUrl = $_POST['returnToUrl'] ?? ".";
+ participo::addMessage('success', "");
+ participo::addMessage('notice', "OnlineApps - cwsvJudo");
+ header("Location: " . $returnToUrl );
+ }
}
}
}
@@ -42,18 +52,20 @@ else{
Loginseite der Online-Apps der Judoka des CWSV
-
+