Skip to content

Commit

Permalink
- Refactors the following modules so they separetely load data and cr…
Browse files Browse the repository at this point in the history
…eate the template dictionary (called rendering) and use dependency injection: adminlog, assets, users, config, games and jams

- Splits authentication php file into authentication and users php files
- Splits entries php file into jams and games php files (Large refactor to the former monolith LoadEntries() method)
- Removes the two charts from the manage content page
- Removes concept of "authors" from code, instead authors are determined by mustache (users who are authors - see main.html)
- Removes concept of admin candidates from code, instead admin candidates are determined by mustache (users who are admin candidates who aren't admins - see editusers.html)
- The three major modules (jams, games and users + also config) are now organised in the template dictionary with an array called LIST and other single-value parameters on the same level as LIST. For example: what used to be in users is now in users.LIST and all_authors_count is now in users.all_authors_count
  • Loading branch information
liambaloh committed Jan 1, 2019
1 parent 4573962 commit 76281ad
Show file tree
Hide file tree
Showing 30 changed files with 1,307 additions and 1,318 deletions.
6 changes: 3 additions & 3 deletions php/actions/login.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
//Function called when the login form is sent. Either logs in or registers the
//user, depending on whether the username exists.
function LogInOrRegister($username, $password){
global $config, $users;
global $users;

$username = str_replace(" ", "_", strtolower(trim($username)));
$password = trim($password);
Expand Down Expand Up @@ -151,8 +151,8 @@ function LogInUser($username, $password){
if($correctPasswordHash == $passwordHash){
//User password correct!
$sessionID = "".GenerateSalt();
$pepper = isset($config["PEPPER"]) ? $config["PEPPER"] : "BetterThanNothing";
$sessionIDHash = HashPassword($sessionID, $pepper, $config["SESSION_PASSWORD_ITERATIONS"]);
$pepper = isset($config["PEPPER"]["VALUE"]) ? $config["PEPPER"]["VALUE"] : "BetterThanNothing";
$sessionIDHash = HashPassword($sessionID, $pepper, $config["SESSION_PASSWORD_ITERATIONS"]["VALUE"]);

setcookie("sessionID", $sessionID, time()+60*60*24*30);
$_COOKIE["sessionID"] = $sessionID;
Expand Down
4 changes: 2 additions & 2 deletions php/actions/logout.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ function LogOut(){

// Delete the session out of our DB
$sessionID = "".$_COOKIE["sessionID"];
$pepper = isset($config["PEPPER"]) ? $config["PEPPER"] : "BetterThanNothing";
$sessionIDHash = HashPassword($sessionID, $pepper, $config["SESSION_PASSWORD_ITERATIONS"]);
$pepper = isset($config["PEPPER"]["VALUE"]) ? $config["PEPPER"]["VALUE"] : "BetterThanNothing";
$sessionIDHash = HashPassword($sessionID, $pepper, $config["SESSION_PASSWORD_ITERATIONS"]["VALUE"]);

$sql = "
DELETE FROM session
Expand Down
17 changes: 9 additions & 8 deletions php/adminlog.php
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
<?php

function LoadAdminLog(){
global $dbConn, $adminLog, $dictionary;
global $dbConn;

$adminLog = Array();

$sql = "select log_id, log_datetime, log_ip, log_user_agent, log_admin_username, log_subject_username, log_type, log_content from admin_log order by log_id desc";
$data = mysqli_query($dbConn, $sql);
$sql = "";

$suggestedNextJamTime = GetNextJamDateAndTime();
$dictionary["next_jam_timer_code"] = gmdate("Y-m-d", $suggestedNextJamTime)."T".gmdate("H:i", $suggestedNextJamTime).":00Z";

$currentJamData = GetCurrentJamNumberAndID();

while($info = mysqli_fetch_array($data)){

//Read data about the jam
Expand All @@ -23,12 +20,12 @@ function LoadAdminLog(){
$log["admin_username"] = $info["log_admin_username"];
$log["subject_username"] = $info["log_subject_username"];
$log["log_type"] = $info["log_type"];
$log["log_content"] = $info["log_content"];
$log["log_content"] = $info["log_content"];

$adminLog[] = $log;
}

$dictionary["adminlog"] = $adminLog;
return $adminLog;
}

function AddToAdminLog($logType, $logContent, $logSubjectUsername){
Expand Down Expand Up @@ -60,6 +57,10 @@ function AddToAdminLog($logType, $logContent, $logSubjectUsername){
$sql = "";
}

function RenderAdminLog($adminLog){
return $adminLog;
}

function GetAdminLogForAdminFormatted($username){
global $dbConn;

Expand Down
19 changes: 10 additions & 9 deletions php/assets.php
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
<?php

function LoadAssets(){
global $dictionary, $assets, $dbConn;

//Clear public lists which get updated by this function
$dictionary["assets"] = Array();
global $dictionary, $dbConn;

$assets = Array();

//Fill list of themes - will return same row multiple times (once for each valid themevote_type)
$sql = "
SELECT a.asset_id, a.asset_author, a.asset_title, a.asset_description, a.asset_type, a.asset_content, u.user_display_name
FROM asset a, user u
Expand All @@ -17,7 +14,6 @@ function LoadAssets(){
$data = mysqli_query($dbConn, $sql);
$sql = "";

//Fill dictionary with non-banned themes
while($asset = mysqli_fetch_array($data)){
$id = $asset["asset_id"];
$author = $asset["asset_author"];
Expand Down Expand Up @@ -52,11 +48,16 @@ function LoadAssets(){

$assets[$id] = $a;
}

$dictionary["assets"] = Array();

return $assets;
}

function RenderAssets($assets){
$render = Array();
foreach($assets as $id => $asset){
$dictionary["assets"][] = $asset;
$render[] = $asset;
}
return $render;
}

function GetAssetsOfUserFormatted($author){
Expand Down
73 changes: 10 additions & 63 deletions php/authentication.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ function GenerateSalt(){
//TODO: Move min and max iterations to config
function HashPassword($password, $salt, $iterations){
global $config;
$pepper = isset($config["PEPPER"]) ? $config["PEPPER"] : "";
$pepper = isset($config["PEPPER"]["VALUE"]) ? $config["PEPPER"]["VALUE"] : "";
$pswrd = $pepper.$password.$salt;

//Check that we have sufficient iterations for password generation.
Expand All @@ -31,66 +31,13 @@ function HashPassword($password, $salt, $iterations){
return $pswrd;
}

//(Re)Loads the users into the globally accessible $users variable.
function LoadUsers(){
global $users, $loggedInUser, $dictionary, $dbConn, $userIDLookup;

$users = Array();

$sql = "SELECT user_id, user_username, user_display_name, user_twitter, user_email,
user_password_salt, user_password_hash, user_password_iterations, user_role,
DATEDIFF(Now(), user_last_login_datetime) AS days_since_last_login,
DATEDIFF(Now(), log_max_datetime) AS days_since_last_admin_action
FROM
user u LEFT JOIN
(
SELECT log_admin_username, max(log_datetime) AS log_max_datetime
FROM admin_log
GROUP BY log_admin_username
) al ON u.user_username = al.log_admin_username";
$data = mysqli_query($dbConn, $sql);
$sql = "";

while($info = mysqli_fetch_array($data)){
//Read data about the user
$currentUser = Array();
$currentUser["id"] = $info["user_id"];
$currentUser["username"] = $info["user_username"];
$currentUser["display_name"] = $info["user_display_name"];
$currentUser["twitter"] = $info["user_twitter"];
$currentUser["twitter_text_only"] = str_replace("@", "", $info["user_twitter"]);
$currentUser["email"] = $info["user_email"];
$currentUser["salt"] = $info["user_password_salt"];
$currentUser["password_hash"] = $info["user_password_hash"];
$currentUser["password_iterations"] = intval($info["user_password_iterations"]);
$currentUser["admin"] = intval($info["user_role"]);

//This fixes an issue where user_last_login_datetime was not set properly in the database, which results in days_since_last_login being null for users who have not logged in since the fix was applied
if($info["days_since_last_login"] == null){
$info["days_since_last_login"] = 1000000;
}

//For cases where users have never performed an admin action
if($info["days_since_last_admin_action"] == null){
$info["days_since_last_admin_action"] = 1000000;
}

$currentUser["days_since_last_login"] = intval($info["days_since_last_login"]);
$currentUser["days_since_last_admin_action"] = intval($info["days_since_last_admin_action"]);

$users[$currentUser["username"]] = $currentUser;
$userIDLookup[$currentUser["id"]] = $currentUser["username"];
}
//Returns the username of the user associated with the provided user id
function GetUsernameForUserId($userID){
global $users;

ksort($users);
$dictionary["users"] = $users;
$dictionary["admins"] = Array();
$dictionary["registered_users"] = Array();
foreach($users as $i => $user){
if($user["admin"] == 1){
$dictionary["admins"][] = $user;
}else{
$dictionary["registered_users"][] = $user;
if($user["id"] == $userID){
return $user["username"];
}
}
}
Expand All @@ -103,7 +50,7 @@ function LoadUsers(){
//Returns either the logged in user's username or FALSE if not logged in.
//Set $force to TRUE to force reloading (for example if a user setting was changed for the logged in user)
function IsLoggedIn($force = FALSE){
global $loginChecked, $loggedInUser, $config, $users, $dictionary, $dbConn, $userIDLookup, $ip, $userAgent;
global $loginChecked, $loggedInUser, $config, $users, $dictionary, $dbConn, $ip, $userAgent;

if($loginChecked && !$force){
return $loggedInUser;
Expand All @@ -119,8 +66,8 @@ function IsLoggedIn($force = FALSE){
}

$sessionID = "".$_COOKIE["sessionID"];
$pepper = isset($config["PEPPER"]) ? $config["PEPPER"] : "BetterThanNothing";
$sessionIDHash = HashPassword($sessionID, $pepper, $config["SESSION_PASSWORD_ITERATIONS"]);
$pepper = isset($config["PEPPER"]) ? $config["PEPPER"]["VALUE"] : "BetterThanNothing";
$sessionIDHash = HashPassword($sessionID, $pepper, $config["SESSION_PASSWORD_ITERATIONS"]["VALUE"]);

$cleanSessionIdHash = mysqli_real_escape_string($dbConn, $sessionIDHash);

Expand All @@ -135,7 +82,7 @@ function IsLoggedIn($force = FALSE){
if($session = mysqli_fetch_array($data)){
//Session ID does in fact exist
$userID = $session["session_user_id"];
$username = $userIDLookup[$userID];
$username = GetUsernameForUserId($userID);
$loggedInUser = $users[$username];
$loggedInUser["username"] = $username;
$dictionary["user"] = $loggedInUser;
Expand Down
96 changes: 52 additions & 44 deletions php/config.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,16 @@
//Initializes configuration, stores it in the global $config variable.

function LoadConfig(){
global $config, $dictionary, $configCategorySettings, $dbConn;
global $dbConn;

$config = Array(); //Clear any existing configuration.
$dictionary["CONFIG"] = Array(); //Clear any config entries in the dictionary
$config = Array();

//Fill list of themes - will return same row multiple times (once for each valid themevote_type)
$sql = " SELECT * FROM config ORDER BY config_id; ";
$data = mysqli_query($dbConn, $sql);
$data = mysqli_query($dbConn, $sql);
$sql = "";

//Fill dictionary with non-banned themes
while($configEntry = mysqli_fetch_array($data)) {
$baseKey = $configEntry["config_key"];
$key = $configEntry["config_key"];
$value = $configEntry["config_value"];
$category = $configEntry["config_category"];
$description = $configEntry["config_description"];
Expand All @@ -40,24 +37,17 @@ function LoadConfig(){
$required = $configEntry["config_required"];
$addedToDictionary = $configEntry["config_added_to_dictionary"];

$key = "CONFIG_" . $baseKey;

$config[$baseKey] = $value;

if ($addedToDictionary) {
$dictionary[$key] = $value;
}

$configCategoryHeader = $configCategorySettings[$category];

$configEntry = Array(
"KEY" => $key,
"VALUE" => htmlentities($value),
"NAME" => $description,
"VALUE" => $value,
"VALUE_HTML_ENCODED" => htmlentities($value),
"CATEGORY" => $category,
"DESCRIPTION" => $description,
"DISABLED" => !$editable,
"EDITABLE" => $editable,
"REQUIRED" => $required,
"TYPE" => $type,
"ADDED_TO_DICTIONARY" => $addedToDictionary,
);

switch($type) {
Expand Down Expand Up @@ -87,42 +77,60 @@ function LoadConfig(){
$configEntry["TYPE_TEXTAREA"] = 1;
break;
}

$config[$key] = $configEntry;
}

$config = VerifyConfig($config);

return $config;
}

$i = count($dictionary["CONFIG"]);
foreach($dictionary["CONFIG"] as $index => $configDictionaryEntry){
function RenderConfig($config){
global $configCategorySettings;

$render = Array("LIST" => Array(), "VALUES" => Array());

foreach($config as $i => $configEntry){
$configKey = $configEntry["KEY"];
$configValue = $configEntry["VALUE"];
$category = $configEntry["CATEGORY"];
$configCategoryHeader = $configCategorySettings[$category];

$render["VALUES"][$configKey] = $configValue;

$categoryIndex = count($render["LIST"]);
foreach($render["LIST"] as $index => $configDictionaryEntry){
if($configDictionaryEntry["CATEGORY_ID"] == $category){
$i = $index;
$categoryIndex = $index;
}
}

$dictionary["CONFIG"][$i]["CATEGORY_ID"] = $category;
$dictionary["CONFIG"][$i]["CATEGORY_HEADER"] = $configCategoryHeader;
$dictionary["CONFIG"][$i]["ENTRIES"][] = $configEntry;
$render["LIST"][$categoryIndex]["CATEGORY_ID"] = $category;
$render["LIST"][$categoryIndex]["CATEGORY_HEADER"] = $configCategoryHeader;
$render["LIST"][$categoryIndex]["ENTRIES"][] = $configEntry;
}

// print_r($config);
// print_r($dictionary);

VerifyConfig();
RedirectToHttpsIfRequired();
return $render;
}

function VerifyConfig() {
global $config;

if (!isset($config["PEPPER"]) || strlen($config["PEPPER"]) < 1) {
UpdateConfig("PEPPER", GenerateSalt(), -1);
function VerifyConfig($config) {
if (!isset($config["PEPPER"]["VALUE"]) || strlen($config["PEPPER"]["VALUE"]) < 1) {
$config = UpdateConfig($config, "PEPPER", GenerateSalt(), -1);
}

if (!isset($config["SESSION_PASSWORD_ITERATIONS"]) || strlen($config["SESSION_PASSWORD_ITERATIONS"]) < 1) {
UpdateConfig("SESSION_PASSWORD_ITERATIONS", rand(10000, 20000), -1);
if (!isset($config["SESSION_PASSWORD_ITERATIONS"]["VALUE"]) || strlen($config["SESSION_PASSWORD_ITERATIONS"]["VALUE"]) < 1) {
$config = UpdateConfig($config, "SESSION_PASSWORD_ITERATIONS", rand(10000, 20000), -1);
}

return $config;
}


// Actually updates the config. Doesn't check auth.
function UpdateConfig($key, $value, $userID) {
global $config, $dbConn;
function UpdateConfig($config, $key, $value, $userID) {
global $dbConn;

if(!IsAdmin()){
return; //Lacks permissions to make edits
Expand All @@ -131,7 +139,7 @@ function UpdateConfig($key, $value, $userID) {
$keyClean = mysqli_real_escape_string($dbConn, $key);
$valueClean = mysqli_real_escape_string($dbConn, $value);

$config[$key] = $value;
$config[$key]["VALUE"] = $value;
$sql = "
UPDATE config
SET config_value = '$valueClean',
Expand All @@ -142,14 +150,14 @@ function UpdateConfig($key, $value, $userID) {
mysqli_query($dbConn, $sql);
$sql = "";

AddToAdminLog("CONFIG_UPDATED", "Config value edited: $key = '$value'", "");
AddToAdminLog("CONFIG_UPDATED", "Config value edited: $key = '$value'", "");

return $config;
}


function RedirectToHttpsIfRequired(){
global $config;

if($config["REDIRECT_TO_HTTPS"]){
function RedirectToHttpsIfRequired($config){
if($config["REDIRECT_TO_HTTPS"]["VALUE"]){
if(!isset($_SERVER['HTTPS'])){
//Redirect to https
$url = "https://". $_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
Expand Down

0 comments on commit 76281ad

Please sign in to comment.