register starts is now possible in the new materialize version

This commit is contained in:
marko
2023-01-15 18:45:33 +01:00
parent 6d5d7e7142
commit 90d84283e8
13 changed files with 1201 additions and 461 deletions

View File

@@ -1,28 +1,40 @@
<?php
require_once 'participoLib/dbConnector.php';
// require_once("spyc/Spyc.php");
require_once 'participoLib/user.php';
/**
* FrameWork for the participoApp
*/
class participo
{
private static $db = null;
private static $message = ['error' => null, 'success' => null, 'notice' => null];
private static $userId = null;
/**
* Returns the current login status
/** 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
* @return bool true if the login status is true, false otherwise
*/
public static function isLoginValid()
{
return ($_SESSION['login'] ?? false);
return (isset($_SESSION) && array_key_exists('login', $_SESSION) && $_SESSION['login'] == true);
}
/**
* A little Box with the login status as html entity
/** Remove all login data from the session data
*
* @return void
*/
public static function logout()
{
foreach (['login', 'user'] as $key) {
unset($_SESSION[$key]);
}
}
/** A little Box with the login status as html entity
*
* @return string htmlEntity showing the login status
*/
@@ -36,48 +48,54 @@ class participo
'</div>';
}
/**
* Checks, if there already is a valid login, if not redirect to the login form
* @todo rename to authenticate
/** Checking if an action is allowed. A present apiKey overrides (and deletes) a present login.
*
* 1. If apiKey is present:
* - chancel current login
* - If apiKey is valid for requested action:
* - set some session data
* - return
* 2. If there is a valid Login session:
* - return
* 3. redirect to Login Page
*
* @todo rename to authenticate (authorize?)
*
* @param $action the action we want to get authorized for (default=['login'])
*
* @retval void
*/
public static function authentificate()
public static function authentificate($action = ['login'])
{
// Ensure a session is started
session_start();
// check if an api key was received
// check if an apiKey was received
if (array_key_exists('apiKey', $_GET)) {
self::logout();
$key = ApiKey::loadFromDb($_GET['apiKey']);
if ($key) {
if ($key->isValidFor('login')) {
// query *all* users with the entered name
// @todo check for e.g., len(user)=1
// @todo getUser?
$user = dbConnector::query(
'SELECT `id`, `loginName`, `config` FROM `wkParticipo_Users` WHERE `id` = :id',
['id' => ['value' => $key->getUserId(), 'data_type' => PDO::PARAM_INT]]
);
$user = $user[0];
// case valid login: Set the session data
$_SESSION = [
'login' => true,
'user' => [
'username' => $user['loginName'],
'userId' => $user['id'],
'userConfig' => json_decode($user['config'], true)
]
];
};
}
if (isset($key) && $key->isValidFor($action)) {
$user = User::loadFromDb($key->getUserId());
// case valid login: Set the session data
$_SESSION = [
'login' => true, //false,
'apiKey' => $key->getKey(),
'user' => [
'username' => $user->getLoginName(),
'userId' => $user->getId(),
'userConfig' => $user->getConfig(),
]
];
// we're not logged in, but authorized for the stuff we want to do. So don't redirect
return;
};
}
// if not returned yet: no login, no valid apiKey -> redirect to login page
if (!self::isLoginValid()) {
header('Location: login?returnToUrl=' . urlencode($_SERVER['REQUEST_URI'] . ($_POST['fragment'] ?? '')), true, 301);
exit(); // should'nt matter
exit(); // shouldn't matter
}
participo::$userId = $_SESSION['user']['userId'];
}
public static function getMessages()
@@ -90,8 +108,7 @@ class participo
self::$message[$type] = (self::$message[$type] ?? '') . $message;
}
/**
* check password for user
/** check password for user
*
* @param string $loginName user who wants to get in
* @param string $password password for the user
@@ -102,23 +119,17 @@ class participo
public static function checkCredentials($loginName, $password)
{
sleep(1); // just to discourage 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
// @todo check for e.g., len(user)=1
// @todo getUser?
$user = dbConnector::query(
'SELECT `id`, `loginName`, `pwHash`, `config` FROM `wkParticipo_Users` WHERE `loginName` = :loginName',
['loginName' => ['value' => $loginName, 'data_type' => PDO::PARAM_STR]]
);
$user = $user[0];
$user = User::loadFromDbByLoginName($loginName);
// If there is no such user OR the password isn't valid the login fails
if (empty($user) || !password_verify($password, $user['pwHash'])) {
if ($user == null || !$user->verifyPassword($password)) {
sleep(5); // discourage brute force attacks
self::addMessage('error', '<div>Falsches Passwort oder LoginName</div>');
return false;
@@ -129,9 +140,9 @@ class participo
$_SESSION = [
'login' => true,
'user' => [
'username' => $user['loginName'],
'userId' => $user['id'],
'userConfig' => json_decode($user['config'], true)
'username' => $user->getLoginName(),
'userId' => $user->getId(),
'userConfig' => json_decode($user->getConfig(), true)
]
];
@@ -142,8 +153,7 @@ class participo
return true;
}
/**
* Checks, if a user is an admin
/** Checks, if a user is an admin
*
* @param [type] $userId id of the user to check
* @retval true user with id $userId has attribute "isAdmin"
@@ -154,8 +164,48 @@ class participo
return self::hasUserAttribute($userId, 'isAdmin');
}
/**
* Checks, if a user as a certain attribute
public static function getKids($userId = null)
{
$userId = $userId ?? $_SESSION['user']['userId'] ?? null;
$query =
'SELECT * FROM `wkParticipo_Users` '
. 'INNER JOIN `vormundschaft` ON `wkParticipo_Users`.`id` = `vormundschaft`.`kidId` '
. 'WHERE `vormundschaft`.`userId` = :userId;';
$params = [':userId' => ['value' => $userId, 'data_type' => PDO::PARAM_INT]];
$response = dbConnector::query($query, $params);
$kids = [];
foreach ($response as $r) {
$kids[] = User::fromDbArray($r, ['id' => 'kidId']);
}
return $kids;
}
/** Check if one user is ward of another
*
* @param integer $kidId ID of the ward
* @param integer|null $userId ID of the guardian, if null it is tried to read it from the session data
* @return boolean true if kid is ward of user, false otherwise
*/
public static function isWardOf(int $kidId, int $userId = null)
{
// Try to get the Guard from the session data.
$userId = $userId ?? $_SESSION['user']['userId'] ?? null;
$query = 'SELECT `kidId` FROM `vormundschaft` WHERE `userId` = :userId AND `kidId` = :kidId;';
$params = [
':userId' => ['value' => $userId, 'data_type' => PDO::PARAM_INT],
':kidId' => ['value' => $kidId, 'data_type' => PDO::PARAM_INT]
];
$response = dbConnector::query($query, $params);
return (count($response) >= 1);
}
/** Checks, if a user as a certain attribute
*
* @param [type] $userId id of the user to check
* @param [type] $attributeName string name of the attribute to check
@@ -207,22 +257,20 @@ FROM `wkParticipo_Starter`
WHERE `wkParticipo_Events`.`date` >= $sinceDate AND `vormundschaft`.`userId` = $userId
ORDER BY `wkParticipo_Events`.`date` DESC;
SQL;
$commingStarts = dbConnector::query($query);
$comingStarts = dbConnector::query($query);
return $commingStarts;
return $comingStarts;
}
}
/**
* Action element of an MaterializeCss (App-)card
/** Action element of an MaterializeCss (App-)card
*/
class AppCardAction
{
private $caption = null; //< Caption for the action
private $link = '.'; //< link for the action
/**
* Constructor for the AppAction
/** Constructor for the AppAction
*
* @param string $caption caption for the action
* @param string $link link to the action
@@ -234,8 +282,7 @@ class AppCardAction
$this->caption = $caption;
}
/**
* Create htmlCode for the action
/** Create htmlCode for the action
*
* @return string with htmlCode of the action
*/
@@ -244,8 +291,7 @@ class AppCardAction
return '<a href="' . $this->link . '">' . $this->caption . '</a>';
}
/**
* Create AppCardAction from assoziative array
/** Create AppCardAction from assoziative array
*
* @param array $member array with the member values
* @return AppCardAction
@@ -258,8 +304,7 @@ class AppCardAction
}
}
/**
* MaterializeCss card for an App
/** MaterializeCss card for an App
*/
class AppCard
{
@@ -331,8 +376,7 @@ class AppCard
}
}
/**
* Generate a html table of the last logins of the users
/** Generate a html table of the last logins of the users
*
* @param string $jsonFileName path to the json file with the logged logins
* @return string Html table of users last logins
@@ -387,11 +431,10 @@ function htmlRetMessage($anRetMessage)
return $retHtmlString;
}
/**
* load a MarkdownFile with yaml header
/** load a MarkdownFile with yaml header
*
* @param string $fileName filename of the markdown file
* @return array assocative array('yaml'=>array(..), 'mdText'=>string) containing the yamlHeader as associative array and the markdown text as string
* @return array associative array('yaml'=>array(..), 'mdText'=>string) containing the yamlHeader as associative array and the markdown text as string
*/
function loadMarkdownFile($fileName)
{
@@ -399,7 +442,7 @@ function loadMarkdownFile($fileName)
$fileText = file_get_contents($fileName);
// split at '---' to get ((),yamls,array)
$fileParts = preg_split('/[\n]*[-]{3}[\n]/', $fileText, 3);
// not all mdfiles have a yamlHeader, so the mdText can be at different indices
// not all mdFiles have a yamlHeader, so the mdText can be at different indices
$yaml = [];
$mdText = '';
switch(count($fileParts)) {
@@ -433,8 +476,7 @@ function loadMarkdownFile($fileName)
];
}
/**
* Log the Login of an user into a logFile
/** Log the Login of an user into a logFile
*
* @param string $userName name of the user
* @param string $fileName filename to log to
@@ -460,64 +502,18 @@ function logLoginsToJsonFile($userName, $fileName = 'lastLogins.json')
}
}
/**
* User for the Participo system
*/
class User
/// @brief Gibt die URL der gerade aufgerufenen Seite zurück
function getCurPagesUrl()
{
private $id;
private $loginName;
private $name;
private $firstName;
private $dateOfBirth;
private $eMail;
public function __construct($id, $loginName, $name, $firstName, $dateOfBirth, $eMail)
{
$this->id = (int) id;
$this->loginName = $loginName;
$this->name = $name;
$this->firstName = $firstName;
$this->dateOfBirth = $dateOfBirth != null ? DateTime::createFromFormat('Y-m-d', $dateOfBirth) : null;
$this->eMail = $eMail;
$pageURL = 'http';
if ($_SERVER['HTTPS'] == 'on') {
$pageURL .= 's';
}
/**
* Create a User from an assoziative array like it is returned from db requests
*
* @param array $member associative array with the UserData from the dbRequest
* @return User initialized user
*/
public static function fromDbArray($member)
{
return new User(
$member['id'] ?? null,
$member['loginName'] ?? null,
$member['name'] ?? null,
$member['vorname'] ?? null,
$member['gebDatum'] ?? null,
array_key_exist('eMail', $member) ? explode(',', $member['eMail']) : null
);
}
/**
* Export the User data into an associative array
*/
public function toAssoc()
{
return [
'id' => $this->id,
'loginName' => $this->loginName,
'name' => $this->name,
'vorname' => $this->firstName,
'gebDatum' => $this->dateOfBirth,
'eMail' => $this->eMail];
}
public function loadFromDb($dbConn, $id)
{
$this->set(
loadUserDataFromDb($dbConn, $id)
);
$pageURL .= '://';
if ($_SERVER['SERVER_PORT'] != '80') {
$pageURL .= $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI'];
} else {
$pageURL .= $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
}
return $pageURL;
}