3 require_once "SQL/sql.php";
4 require_once "SQL/settings.php";
8 public $name = "SQLAuth";
9 public $author = "Valware";
10 public $version = "1.0";
11 public $description = "Provides a User Auth and Management Panel with an SQL backend";
12 public $email = "v.a.pond@outlook.com";
14 function __construct()
16 Hook
::func(HOOKTYPE_PRE_HEADER
, 'sql_auth::session_start');
17 Hook
::func(HOOKTYPE_USER_LOOKUP
, 'sql_auth::get_user');
18 Hook
::func(HOOKTYPE_USERMETA_ADD
, 'sql_auth::add_usermeta');
19 Hook
::func(HOOKTYPE_USERMETA_DEL
, 'sql_auth::del_usermeta');
20 Hook
::func(HOOKTYPE_USERMETA_GET
, 'sql_auth::get_usermeta');
21 Hook
::func(HOOKTYPE_USER_CREATE
, 'sql_auth::user_create');
22 Hook
::func(HOOKTYPE_GET_USER_LIST
, 'sql_auth::get_user_list');
23 Hook
::func(HOOKTYPE_USER_DELETE
, 'sql_auth::user_delete');
24 Hook
::func(HOOKTYPE_EDIT_USER
, 'sql_auth::edit_core');
25 Hook
::func(HOOKTYPE_PRE_OVERVIEW_CARD
, 'sql_auth::add_pre_overview_card');
26 AuthModLoaded
::$status = 1;
30 public static function add_pre_overview_card($empty)
32 if (defined('SQL_DEFAULT_USER'))
33 Message
::Fail("Warning: SQL_DEFAULT_USER is set in config.php. You should remove that item now, as it is only used during installation.");
34 if (defined('DEFAULT_USER'))
35 Message
::Fail("Warning: DEFAULT_USER is set in config.php. You should remove that item now, as it is only used during installation.");
39 public static function session_start($n)
41 $current_page = $_SERVER['REQUEST_URI'];
42 if (!isset($_SESSION))
44 session_set_cookie_params(3600);
47 if (!isset($_SESSION['id']) || empty($_SESSION))
50 $tok = split($_SERVER['SCRIPT_FILENAME'], "/");
51 if ($check = security_check() && $tok[count($tok) - 1] !== "error.php") {
52 header("Location: " . get_config("base_url") . "plugins/sql_auth/error.php");
55 header("Location: ".get_config("base_url")."login/?redirect=".urlencode($current_page));
60 if (!unreal_get_current_user()) // user no longer exists
63 header("Location: ".get_config("base_url")."login");
66 // you'll be automatically logged out after one hour of inactivity
67 $_SESSION['last-activity'] = time();
73 * Create the tables we'll be using in the SQLdb
76 public static function create_tables()
79 $conn->query("CREATE TABLE IF NOT EXISTS " . get_config("mysql::table_prefix") . "users (
80 user_id int AUTO_INCREMENT NOT NULL,
81 user_name VARCHAR(255) NOT NULL,
82 user_pass VARCHAR(255) NOT NULL,
83 user_email VARCHAR(255),
84 user_fname VARCHAR(255),
85 user_lname VARCHAR(255),
86 user_bio VARCHAR(255),
92 * Patch for beta users
93 * This adds the email column to existing tables without it
95 $columns = $conn->query("SHOW COLUMNS FROM " . get_config("mysql::table_prefix") . "users");
96 $column_names = array();
97 $c = $columns->fetchAll();
99 foreach($c as $column) {
100 $column_names[] = $column['Field'];
102 $column_exists = in_array("user_email", $column_names);
103 if (!$column_exists) {
104 $conn->query("ALTER TABLE " . get_config("mysql::table_prefix") . "users ADD COLUMN user_email varchar(255)");
108 * Another patch for beta users
109 * This changes the size of the meta_value so we can store more
112 $conn->query("CREATE TABLE IF NOT EXISTS " . get_config("mysql::table_prefix") . "user_meta (
113 meta_id int AUTO_INCREMENT NOT NULL,
114 user_id int NOT NULL,
115 meta_key VARCHAR(255) NOT NULL,
116 meta_value VARCHAR(255),
117 PRIMARY KEY (meta_id)
119 $conn->query("CREATE TABLE IF NOT EXISTS " . get_config("mysql::table_prefix") . "settings (
120 id int AUTO_INCREMENT NOT NULL,
121 setting_key VARCHAR(255) NOT NULL,
122 setting_value VARCHAR(255),
125 $conn->query("CREATE TABLE IF NOT EXISTS " . get_config("mysql::table_prefix") . "fail2ban (
126 id int AUTO_INCREMENT NOT NULL,
127 ip VARCHAR(255) NOT NULL,
132 if (($columns = $conn->query("SHOW COLUMNS FROM ".get_config("mysql::table_prefix")."user_meta")));
133 $c = $columns->fetchAll();
135 $conn->query("ALTER TABLE `".get_config("mysql::table_prefix")."user_meta` CHANGE `meta_value` `meta_value` VARCHAR(5000) CHARACTER SET utf8mb3 COLLATE utf8mb3_bin NULL DEFAULT NULL");
137 /* make sure everything went well */
138 $tables = ["users", "user_meta", "fail2ban", "settings"];
139 $errors = 0; // counter
140 $error_messages = "";
141 foreach($tables as $table)
143 $prefix = get_config("sql::table_prefix");
144 $sql = "SHOW TABLES LIKE '$prefix%'"; // SQL query to check if table exists
146 $result = $conn->query($sql);
147 if ($result->rowCount())
152 strcat($error_messages,"Table '$prefix$table' was not created successfully.<br>");
157 if (defined('DEFAULT_USER')) // we've got a default account
159 $lkup = new PanelUser(DEFAULT_USER
['username']);
161 if (!$lkup->id
) // doesn't exist, add it with full privileges
164 $user['user_name'] = DEFAULT_USER
['username'];
165 $user['user_pass'] = DEFAULT_USER
['password'];
167 create_new_user($user);
169 $lkup = new PanelUser(DEFAULT_USER
['username']);
170 if (!user_can($lkup, PERMISSION_MANAGE_USERS
))
171 $lkup->add_permission(PERMISSION_MANAGE_USERS
);
180 /* We convert $u with a full user as an object ;D*/
181 public static function get_user(&$u)
189 $prep = $conn->prepare("SELECT * FROM " . get_config("mysql::table_prefix") . "users WHERE user_id = :id LIMIT 1");
190 $prep->execute(["id" => strtolower($id)]);
194 $prep = $conn->prepare("SELECT * FROM " . get_config("mysql::table_prefix") . "users WHERE LOWER(user_name) = :name LIMIT 1");
195 $prep->execute(["name" => strtolower($name)]);
200 $data = $prep->fetchAll();
201 if (isset($data[0]) && $data = $data[0])
203 $obj->id
= $data['user_id'];
204 $obj->username
= $data['user_name'];
205 $obj->passhash
= $data['user_pass'];
206 $obj->first_name
= $data['user_fname'] ?? NULL;
207 $obj->last_name
= $data['user_lname'] ?? NULL;
208 $obj->created
= $data['created'];
209 $obj->bio
= $data['user_bio'];
210 $obj->email
= $data['user_email'];
211 $obj->user_meta
= (new PanelUser_Meta($obj->id
))->list;
216 public static function get_usermeta(&$u)
223 $prep = $conn->prepare("SELECT * FROM " . get_config("mysql::table_prefix") . "user_meta WHERE user_id = :id");
224 $prep->execute(["id" => $id]);
226 foreach ($prep->fetchAll() as $row)
228 $list[$row['meta_key']] = $row['meta_value'];
232 public static function add_usermeta(&$meta)
234 $meta = $meta['meta'];
236 /* check if it exists first, update it if it does */
237 $query = "SELECT * FROM " . get_config("mysql::table_prefix") . "user_meta WHERE user_id = :id AND meta_key = :key";
238 $stmt = $conn->prepare($query);
239 $stmt->execute(["id" => $meta['id'], "key" => $meta['key']]);
240 if ($stmt->rowCount()) // it exists, update instead of insert
242 $query = "UPDATE " . get_config("mysql::table_prefix") . "user_meta SET meta_value = :value WHERE user_id = :id AND meta_key = :key";
243 $stmt = $conn->prepare($query);
244 $stmt->execute($meta);
245 if ($stmt->rowCount())
252 $query = "INSERT INTO " . get_config("mysql::table_prefix") . "user_meta (user_id, meta_key, meta_value) VALUES (:id, :key, :value)";
253 $stmt = $conn->prepare($query);
254 $stmt->execute($meta);
255 if ($stmt->rowCount())
260 public static function del_usermeta(&$u)
263 $query = "DELETE FROM " . get_config("mysql::table_prefix") . "user_meta WHERE user_id = :id AND meta_key = :key";
264 $stmt = $conn->prepare($query);
265 $stmt->execute($u['meta']);
266 if ($stmt->rowCount())
270 public static function user_create(&$u)
272 $username = $u['user_name'];
273 $first_name = $u['fname'] ?? NULL;
274 $last_name = $u['lname'] ?? NULL;
275 $password = $u['user_pass'] ?? NULL;
276 $user_bio = $u['user_bio'] ?? NULL;
277 $user_email = $u['user_email'] ?? NULL;
279 $prep = $conn->prepare("INSERT INTO " . get_config("mysql::table_prefix") . "users (user_name, user_pass, user_fname, user_lname, user_bio, user_email, created) VALUES (:name, :pass, :fname, :lname, :user_bio, :user_email, :created)");
280 $prep->execute(["name" => $username, "pass" => $password, "fname" => $first_name, "lname" => $last_name, "user_bio" => $user_bio, "user_email" => $user_email, "created" => date("Y-m-d H:i:s")]);
281 if ($prep->rowCount())
282 $u['success'] = true;
284 $u['errmsg'][] = "Could not add user";
287 public static function get_user_list(&$list)
290 $result = $conn->query("SELECT user_id FROM " . get_config("mysql::table_prefix") . "users");
291 if (!$result) // impossible
293 die("Something went wrong.");
296 while($row = $result->fetch())
298 $userlist[] = new PanelUser(NULL, $row['user_id']);
300 if (!empty($userlist))
304 public static function user_delete(&$u)
307 $query = "DELETE FROM " . get_config("mysql::table_prefix") . "users WHERE user_id = :id";
309 $stmt = $conn->prepare($query);
310 $stmt->execute(["id" => $user->id
]);
311 $deleted = $stmt->rowCount();
314 $u['info'][] = "Successfully deleted user \"$user->username\"";
317 $u['info'][] = "Unknown error";
322 public static function edit_core($arr)
325 $user = $arr['user'];
326 $info = $arr['info'];
327 foreach($info as $key => $val)
330 if (!$val || !strlen($val) || BadPtr($val))
332 if (!strcmp($key,"update_fname") && $val != $user->first_name
)
334 $value = "user_fname";
335 $valuestr = "first name";
337 elseif (!strcmp($key,"update_lname") && $val != $user->last_name
)
339 $value = "user_lname";
340 $valuestr = "last name";
342 elseif (!strcmp($key,"update_bio") && $val != $user->bio
)
347 elseif (!strcmp($key,"update_pass") || !strcmp($key,"update_pass_conf"))
349 $value = "user_pass";
350 $valuestr = "password";
352 elseif(!strcmp($key,"update_email") && $val != $user->email
)
354 $value = "user_email";
355 $valuestr = "email address";
360 $query = "UPDATE " . get_config("mysql::table_prefix") . "users SET $value=:value WHERE user_id = :id";
361 $stmt = $conn->prepare($query);
362 $stmt->execute(["value" => $val, "id" => $user->id
]);
364 if (!$stmt->rowCount() && $stmt->errorInfo()[0] != "00000")
365 Message
::Fail("Could not update $valuestr for $user->username: ".$stmt->errorInfo()[0]." (CODE: ".$stmt->errorCode().")");
368 Message
::Success("Successfully updated the $valuestr for $user->username");
374 function security_check()
376 $ip = $_SERVER['REMOTE_ADDR'];
377 if (dnsbl_check($ip))
380 else if (fail2ban_check($ip))
386 function dnsbl_check($ip)
388 $dnsbl_lookup = get_config("dnsbl");
392 // clear variable just in case
395 // if the IP was not given because you're an idiot, stop processing
396 if (!$ip) { return; }
398 // get the first two segments of the IPv4
399 $because = split($ip, "."); // why you
400 $you = $because[1]; // gotta play
401 $want = $because[2]; // that song
402 $to = $you.".".$want."."; // so loud?
404 // exempt local connections because sometimes they get a false positive
405 if ($to == "192.168." || $to == "127.0.") { return NULL; }
407 // you spin my IP right round, right round, to check the records baby, right round-round-round
408 $reverse_ip = glue(array_reverse(split($ip, ".")), ".");
411 foreach ($dnsbl_lookup as $host) {
414 if (checkdnsrr($reverse_ip . "." . $host . ".", "A")) {
421 // if it was safe, return NOTHING
426 // else, you guessed it, return where it was listed
432 function fail2ban_check($ip)