Commit 48617ff0 authored by Stuart John Watson's avatar Stuart John Watson

Added the php to index.php to make it work with no javascript

parent a376c002
<?php
/*
* SUCS GameAuth v2
* Follows the idea of a SPA, largely based around php sessions
* User loads the page, session is started (or resumed), if it's in the db then
* the state is restored. Otherwise the see the page with a login form. POST
* requests to self with user/pass, if successfully authd using my LDAP auth
* lib then database is poked with their details.
* Idea mainly follows the old system, some things like bans were a last minute
* afterthought that's why they are so barebones
*
* Split into a sperate API by ~ripp_
*
*/
// include my ldap auth lib
include('ldap-auth.php');
error_reporting(E_ERROR);
// star/resume a session
session_start();
// initialise some variables we'll use later
$authd; // if they get authd, how, otherwise "nope"
$authdUser; // once authd, this is their username
$sessionid = session_id();
$time = time();
$uniAllowFilePATH = '/home/game-server/uni.allow';
$gameauthDBPATH = 'gameauth.db'; #WIP CHANGE
$username = $_POST["username"];
$password = $_POST["password"];
$accessLevel; //Set to one of NO_LOGIN|NO_GAMES|GAMES_ACCESS|AS_BEFORE
$oldLevel; //set to level is accessLevel is AS_BEFORE to get allowed info
$failReason; // If they can't connect contains the reason why.
// create the db object, if the db aint there then make it
if (!file_exists($gameauthDBPATH)){
$db = new SQLite3($gameauthDBPATH) or di("Could not create DB");
$db->exec("CREATE TABLE gamers
(
username TEXT PRIMARY KEY NOT NULL,
sessionid TEXT NOT NULL,
IP TEXT NOT NULL,
level TEXT NOT NULL,
lastseen INT NOT NULL
)"
);
$db->exec("CREATE TABLE bans
(
username TEXT PRIMARY KEY NOT NULL,
reason TEXT
)"
);
} else {
$db = new SQLite3($gameauthDBPATH);
}
$cip=$_SERVER['REMOTE_ADDR'];
$cip2=$_SERVER['HTTP_CLIENT_IP'];
$cip3=$_SERVER['HTTP_X_FORWARDED_FOR'];
$cookie=$_COOKIE["sucs_gameauth"];
/*echo("REMOTE_ADDR: $cip <br>");
echo("HTTP_CLIENT_IP: $cip2 <br>");
echo("HTTP_X_FORWARDED_FOR: $cip3 <br>");*/
// get a list of sessions in the db and banned users
$sessionsResult = $db->query("SELECT sessionid FROM gamers");
$bannedUsers = $db->query("SELECT username FROM bans");
// store sessions in another data format (1d array), easier to search
$sessions = array();
$i = 0;
while($res = $sessionsResult->fetchArray(SQLITE3_ASSOC)){
if(!isset($res['sessionid'])) continue;
$sessions[$i] = $res['sessionid'];
$i++;
}
//If they are renewing
if ($renew){
//Check if they are still in the database
if (in_array($sessionid, $sessions)){
//If they are update the ip & time
$query = $db->query("SELECT level FROM gamers WHERE sessionid='$sessionid'");
$oldLevel = $query->fetchArray()[0];
$query = $db->query("SELECT username FROM gamers WHERE sessionid='$sessionid'");
$authdUser = $query->fetchArray()[0];
$db->exec("DELETE FROM gamers WHERE username='$authdUser'");
$time = time();
$db->exec("INSERT INTO gamers (username,sessionid,IP,level,lastseen) VALUES ('$authdUser','$sessionid','$cip','$oldLevel','$time')");
$accessLevel = "AS_BEFORE";
} else {
//Otherwise return a timeout error
$accessLevel = "NO_LOGIN";
$failReason = "TIMEOUT";
}
//Oterwise check their post data to try and auth them
} else {
//Insure they have passed a username and password
if ($username == "" && $password == "") {
$authd = "";
$accessLevel = "NO_LOGIN";
$failReason = "MISSING_USERNAME_OR_PASSWORD";
} else {
// the main auth bit
$authd = ldapAuth($username, $password);
// bingo! we have a valid account
if ($authd == "sucs" || $authd == "uni") {
// people like to use emails to login so lets detect and strip
if(filter_var($username, FILTER_VALIDATE_EMAIL)){
//valid email, lets strip
// split the email into a string array "@" as a delim
$s = explode("@",$username);
// remove the last element (domain)
array_pop($s);
// put the array back togther using "@" as a seperator
$username = implode("@",$s);
}
$authdUser = strtolower($username);
// check if they are banned
if (in_array($authdUser, $bannedUsers->fetchArray())) {
$accessLevel = "NO_GAMES";
$failReason = "BANNED";
} else {
if ($authd == "sucs") {
$accessLevel = "GAME_ACCESS";
$type = "sucs";
$db->exec("DELETE FROM gamers WHERE username='$authdUser'");
$db->exec("INSERT INTO gamers (username,sessionid,IP,level,lastseen) VALUES ('$authdUser','$sessionid','$cip','$accessLevel','$time')");
} elseif ($authd == "uni") {
if (file_exists($uniAllowFilePATH)) {
$type = "uni";
$accessLevel = "GAME_ACCESS";
} else {
$accessLevel = "NO_GAMES";
$failReason = "UNI_DISALLOWED";
}
$db->exec("DELETE FROM gamers WHERE username='$authdUser'");
$db->exec("INSERT INTO gamers (username,sessionid,IP,level,lastseen) VALUES ('$authdUser','$sessionid','$cip','$accessLevel','$time')");
} else {
$accessLevel = "NO_LOGIN";
$failReason = "ERR_UNKNOWN_AUTH_TYPE";
}
}
} else if ($authd == "nope"){
$authd = "";
$accessLevel = "NO_LOGIN";
$failReason = "BAD_LOGIN";
}
}
}
// logouts are done by posting the username logout to the page
if ($username == "logout"){
//$db->exec("DELETE FROM gamers WHERE sessionid='$sessionid'");
$db->exec("UPDATE gamers SET lastseen=0, sessionid='n0p3' WHERE sessionid='$sessionid'");
session_destroy();
$authd = "loggedOut";
$failReason = null;
$authdUser = null;
$accessLevel = "NO_LOGIN";
}
//If the user is logged in succesfully iterate get the online uses (into a 1d array)
$onlineUsers;
if ($accessLevel == "GAME_ACCESS" || ($accessLevel == "AS_BEFORE" && $oldLevel == "GAME_ACCESS")){
$onlineUsers = [];
$loggedInUsers = $db->query("SELECT username FROM gamers");
while($res =$loggedInUsers->fetchArray(SQLITE3_ASSOC)){
if(!isset($res['username'])) continue;
$onlineUsers[] = $res['username'];
}
}
//Get other payload data
chdir("games");
include "_manager.php";
$services = getGameStatus();
chdir("..");
header('Content-Type: application/json');
//Echo response
echo json_encode([
level => $accessLevel,
loginError => $failReason,
username => $authdUser,
extraPayload => [
onlineUsers => $onlineUsers,
services => $services
]
]);
?>
No preview for this file type
<!doctype html>
<?php
include "controll_2.php";
$username = $_POST["username"];
$password = $_POST["password"];
$renew = $_POST["renew"];
$logout = $_POST["logout"];
$response;
if($renew){
$response = renew();
} else if ($logout){
$response = logout();
} else {
$response = login($username,$password);
}
$level = $response["level"];
$loginError = $response["loginError"];
if ($username == null && $password == null){
$level = "NO_LOGIN";
$loginError = "FIRST";
}
$ERR_MAP = [
"BAD_LOGIN" => "You have entered invalid credentials.",
"MISSING_USERNAME_OR_PASSWORD" => "Please enter a username and password.",
"BANNED" => "Sorry you are banned. For more information contact games@sucs.org",
"ERR_UNKNOWN_AUTH_TYPE" => "An unexpected error occoured - Bad Auth Type.",
"UNI_DISALLOWED" => "Only SUCS members are currentlly allowed access."
];
$errMsg = $ERR_MAP[$loginError];
function iff($test,$t,$f){
if ($test){
print $t;
} else {
print $f;
}
}
?>
<html lang="en">
<head>
<?php if ($level != "NO_LOGIN") { ?>
<noscript><meta http-equiv="refresh" content="30"></noscript>
<?php } ?>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/ripples.min.css" rel="stylesheet">
......@@ -8,6 +56,25 @@
<title>SUCS Games Server</title>
<style>
#loginErrorWrap{
display:<?php iff($errMsg,"block","none"); ?>
}
#login{
display:<?php iff($level == "NO_LOGIN","block","none"); ?>
}
#loginMessage{
display:<?php iff($level == "GAME_ACCESS" || $loginError == "UNI_DISALLOWED","block","none"); ?>
}
#logout{
display:<?php iff($level != "NO_LOGIN","inline-block","none"); ?>
}
#signup{
display:<?php iff($level == "NO_LOGIN" || $loginError == "UNI_DISALLOWED","inline-block","none"); ?>
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-warning">
......@@ -46,10 +113,13 @@
<div class="panel panel-default">
<div class="panel-body">
<!-- LOGIN SECTION -->
<div id="loginErrorWrap" class="alert alert-danger" role="alert">
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span class="sr-only">Error:</span>
<span id="loginError"></span>
<span id="loginError">
<?php print $ERR_MAP[$loginError]; ?>
</span>
</div>
<form method="post" class="form-login" id="login">
......@@ -63,8 +133,22 @@
Login with your SUCS username or Student Number
</form>
<p id="username">Hello $authdUser!</p>
<p id="loginMessage"></p>
<p id="username"></p>
<p id="loginMessage">
<?php if ($level == "GAME_ACCESS") { ?>
You are now logged into the SUCS Game Server system,
and can connect to any of the servers we have running by simply specifying the hostname/IP address 'games.sucs.org'.
This page must be left open while you are playing.
When you close this window, you will no longer have access to the games server,
and will have to login again if you wish to play some more.
<?php } else if ($loginError == "UNI_DISALLOWED") { ?>
Thank you for taking an interest in playing on the SUCS game server.
Unfortunately the game server is currently only available to SUCS members,
you can <a href=\"https://sucs.org/join\">sign up</a>
to SUCS and get 24/7 access to the server
plus all the other benefits that come with SUCS membership.
<?php } ?>
</p>
<a class="btn btn-warning" href="http://sucs.org/join" id="signup">Signup</a>
......
......@@ -10,7 +10,6 @@ SIGNUP_INFO = "Thank you for taking an interest in playing on the SUCS game serv
function loginRefresh(){
console.log()
$.post("endpoint.php",{renew:1},onPostResponse);
}
var REFRESH_ID;
......@@ -23,21 +22,21 @@ function cancelRefresh(){
function populateExtraData(data,domain){
if(domain === undefined){
domain = $("body")
domain = $("body");
}
$.each(data,function(key,value){
var target = domain.find("[data-target='"+key+"']");
if (target.length == 0){
if (target.length === 0){
console.warn("failed to find target",key,"under",domain);
return;
}
if (key == "_online"){
if (value){
target.css("color","green").text("Online")
target.css("color","green").text("Online");
} else {
target.css("color","red").text("Offline")
target.css("color","red").text("Offline");
}
} else if (value == null){
} else if (value === null){
target.empty();
} else if (value instanceof Array){
target.empty();
......@@ -45,26 +44,26 @@ function populateExtraData(data,domain){
$("<li>").text(value[i]).appendTo(target);
}
} else if (typeof value == "object") {
populateExtraData(value,target)
populateExtraData(value,target);
} else {
target.text(value);
}
})
});
}
function onPostResponse(response){
console.log(response)
console.log(response);
//When this response comes back it will be 1 of 5 diffrent state we care about
//DEFAULT|BANNED|UNI-NO|GAME-ACCESS|BAD-CREDENTIALS
//Populate extra payload data
populateExtraData(response.extraPayload)
populateExtraData(response.extraPayload);
//if the response is AS_BEFORE nothing changes, just schedle a refresh
if (response.level == "AS_BEFORE") {
scheduleRefresh();
return
return;
}
//Show an error if there is one
......@@ -92,7 +91,7 @@ function onPostResponse(response){
}
//Now lets take care of the other messages we end up having to display
var welcomeMessage
var welcomeMessage;
if (response.level == "GAME_ACCESS"){
welcomeMessage = SUCCESS;
} else if (response.loginError == "UNI_DISALLOWED"){
......@@ -116,12 +115,12 @@ function onPostResponse(response){
onPostResponse({level:"NO_LOGIN",extraPayload:{}});
$("form").submit(function(event){
var data={}
var data={};
$(this).find("input").each(function(){
var t = $(this);
data[t.attr("name")] = t.val();
if(t.attr("type") == "password"){
t.val("")
t.val("");
}
});
$.post("endpoint.php",data,onPostResponse);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment