redirecting login

This commit is contained in:
marko
2022-06-06 12:55:17 +02:00
parent 706b722b12
commit 3e3fb6d953
12 changed files with 304 additions and 144 deletions

View File

@@ -2,11 +2,89 @@
class participo{
private static $db = null;
static public function initDbConnection(){}
private static $message = ['error' => 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
"<div style=\"border: 1px solid black\">".
"Datum: ".date("Y-m-d")."<br />".
"Angemeldet als <strong>".htmlspecialchars($_SESSION['user']['username'])."</strong>.<br />".
"<a href=\"logout.php\">Sitzung beenden</a>".
"</div>";
}
/**
* 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', "<div>No DbConnection available</div>");
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', "<div>Falsches Passwort oder LoginName</div>");
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', "<div>Anmeldung erfolgreich</div>");
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() . "<br/>";
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;
}
}
}
?>

View File

@@ -0,0 +1,169 @@
<?php
class shiai{
private $id = null; //< unique id
private $date = null; //< date of the shiai
private $name = null; //< name of the shiai as string
private $ageclasses = null; //< age classes as space separated Uxy in a string
private $place = null; //< place of the shiai as string
private $announcementUrl = null; //< url to the announcement
private $routeUrl = null; //< url to a routing planner
private $galleryUrl = null; //< url of the gallery to a gallery of the shiai
private $promoImgUrl = null; //< promotional image for the shiai (as url)
function __construct($id, $date, $name, $ageclasses, $place, $announcementUrl, $routeUrl, $galleryUrl, $promoImgUrl){
//! @todo input validation and sanitation
$this->id = (int) $id;
$this->date = DateTime::createFromFormat("Y-m-d", $date);
$this->name = $name;
$this->ageclasses = $ageclasses;
$this->place = $place;
$this->announcementUrl = $announcementUrl;
$this->routeUrl = $routeUrl;
$this->galleryUrl = $galleryUrl;
$this->promoImgUrl = $promoImgUrl;
}
public function getName(){
return $this->name;
}
public function getAgeClasses(){
return $this->ageclasses ? $this->ageclasses : "-";
}
public function getId(){
return $this->id;
}
static public function fromArray($member){
return new shiai(
$member['lfdeNr'] ?? null,
$member['Datum'] ?? null,
$member['Veranstaltung'] ?? "<fehlender Name>",
$member['Altersklassen'] ?? null,
$member['Ort'] ?? "<fehlender Ort>",
$member['Ausschreibung'] ?? null,
$member['Routenplaner'] ?? null,
$member['galleryLink'] ?? null,
$member['promoPic'] ?? null
);
}
} // end class shiai
class event{
private $id = null; //< unique id of the event in the db
private $date = null; //< date for the event (@todo ranges?)
private $shiaiId = null; //< unique id of the shiai in the db (if appropriate)
private $deadline = null; //< until when one can register for the event
private $remarks = null; //< remarks to the event (special rules) or a json object for missing data (e.g. non-shiai events)
private $shiai = null;
function __construct($id, $date, $shiaiId, $deadline, $remarks, $shiai){
//! @todo InputValidation
$this->id = (int) $id;
$this->date = DateTime::createFromFormat("Y-m-d", $date);
$this->shiaiId = (($shiaiId!=null)?((int)$shiaiId):(null));
$this->deadline = DateTime::createFromFormat("Y-m-d", $deadline);
$this->remarks = $remarks;
$this->shiai = $shiai;
}
function asHtmlCard(){
return
"<div class=\"card blue-grey darken-1\">".
"<div class=\"card-content white-text\">".
"<span class=\"card-title\">".$this->shiai->getName()."</span>".
"<dl>".
"<dt>Datum</dt>".
"<dd>".$this->date->format("Y-m-d")."</dd>".
"<dt>Meldefrist</dt>".
"<dd>".$this->deadline->format("Y-m-d")."</dd>".
"<dt>Altersklassen</dt>".
"<dd>".$this->shiai->getAgeClasses()."</dd>".
"</div>".
"</div>";
}
public function htmlTableRow(){
return
"<tr>".
"<td>".$this->date->format("Y-m-d")."</td>".
"<td><a href=\"/pages/desktop/wkParticipo/showWkEvent.php?eventId=".$this->id."\" >".$this->shiai->getName()."</a></td>".
"</tr>";
}
static public function fromArray($member){
$shiai = json_decode($member['bemerkungen'], true);
return new event(
$member['id'] ?? null,
$member['date'] ?? null,
$member['wkId'] ?? null,
$member['meldefrist'] ?? null,
$member['bemerkungen'] ?? null,
shiai::fromArray( ($shiai != null) ? $shiai : $member )
);
}
} // end class event
class eventPlaner{
static private $db = null;
// set the dbConnection (just setting, no establishing)
public static function setDbConnection($dbConnection){
if($dbConnection instanceof PDO)
self::$db = $dbConnection;
else
self::$db = null;
return;
}
static public function getCommingWkEvents($someOptions=array() ){
// wir befinden uns in der Übergangsphase:
// - als Standard wird das derzeitige Verhalten definiert (ISO-8859-1
// und die Konvertierung erfolgt ausserhalb)
// - wenn einmal alle mbConvertEncoding weg sind, kann der Standard auf
// das gewünschte Verhalten umgestellt werden
$dbCharset = $someOptions['dbCharset'] ?? "ISO-8859-1";
// dbCharset = $someOptions['outCharset'] ?? "UTF-8";// das spätere, gewünschte Verhalten
$outCharset = $someOptions['outCharset'] ?? "ISO-8859-1";
$query =
"SELECT ".
"wkParticipo_Events.id, ".
"wkParticipo_Events.date, ".
"wkParticipo_Events.wkId, ".
"wkParticipo_Events.meldefrist, ".
"wkParticipo_Events.bemerkungen, ".
"wkParticipo_Events.kvOptions, ".
"wettkampfkalender.Datum, ".
"wettkampfkalender.Veranstaltung, ".
"wettkampfkalender.Altersklassen, ".
"wettkampfkalender.Ort, ".
"wettkampfkalender.Ausschreibung, ".
"wettkampfkalender.Routenplaner ".
"FROM wkParticipo_Events ".
"LEFT JOIN wettkampfkalender ".
"ON wettkampfkalender.lfdeNr = wkParticipo_Events.wkId ".
"WHERE wkParticipo_Events.date >= CURDATE() ".
"ORDER BY wkParticipo_Events.date;";
$ret = dbQuery(self::$db, $query);
$events = array();
foreach($ret as $event){
array_push( $events, event::fromArray( $event ) );
}
return $events;
}
static public function getHtmlEventTable($eventList){
$ret = "<table>";
foreach($eventList as $event){
$ret .= $event->htmlTableRow();
}
$ret .= "</table>";
return $ret;
}
}
?>