]> jfr.im git - irc/unrealircd/unrealircd-webpanel.git/blob - plugins/sql_auth/sql_auth.php
Add sql::table_prefix to first setup screen
[irc/unrealircd/unrealircd-webpanel.git] / plugins / sql_auth / sql_auth.php
1 <?php
2
3 require_once "SQL/sql.php";
4 require_once "SQL/settings.php";
5
6 class sql_auth
7 {
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";
13
14 function __construct()
15 {
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;
27
28 }
29
30 public static function add_pre_overview_card($empty)
31 {
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.");
36 }
37
38 /* pre-Header hook */
39 public static function session_start($n)
40 {
41 $current_page = $_SERVER['REQUEST_URI'];
42 if (!isset($_SESSION))
43 {
44 session_set_cookie_params(3600);
45 session_start();
46 }
47 if (!isset($_SESSION['id']) || empty($_SESSION))
48 {
49
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");
53 die();
54 }
55 header("Location: ".get_config("base_url")."login/?redirect=".urlencode($current_page));
56 die();
57 }
58 else
59 {
60 if (!unreal_get_current_user()) // user no longer exists
61 {
62 session_destroy();
63 header("Location: ".get_config("base_url")."login");
64 die();
65 }
66 // you'll be automatically logged out after one hour of inactivity
67 $_SESSION['last-activity'] = time();
68
69 }
70 }
71
72 /**
73 * Create the tables we'll be using in the SQLdb
74 * @return void
75 */
76 public static function create_tables()
77 {
78 $conn = sqlnew();
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),
87 created VARCHAR(255),
88 PRIMARY KEY (user_id)
89 )");
90
91 /**
92 * Patch for beta users
93 * This adds the email column to existing tables without it
94 */
95 $columns = $conn->query("SHOW COLUMNS FROM " . get_config("mysql::table_prefix") . "users");
96 $column_names = array();
97 $c = $columns->fetchAll();
98
99 foreach($c as $column) {
100 $column_names[] = $column['Field'];
101 }
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)");
105 }
106
107 /**
108 * Another patch for beta users
109 * This changes the size of the meta_value so we can store more
110 */
111
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)
118 )");
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),
123 PRIMARY KEY (id)
124 )");
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,
128 count VARCHAR(255),
129 PRIMARY KEY (id)
130 )");
131 $c = [];
132 if (($columns = $conn->query("SHOW COLUMNS FROM ".get_config("mysql::table_prefix")."user_meta")));
133 $c = $columns->fetchAll();
134 if (!empty($c))
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");
136
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)
142 {
143 $prefix = get_config("sql::table_prefix");
144 $sql = "SHOW TABLES LIKE '$prefix%'"; // SQL query to check if table exists
145
146 $result = $conn->query($sql);
147 if ($result->rowCount())
148 { /* great! */ }
149
150 else {
151 $errors++;
152 strcat($error_messages,"Table '$prefix$table' was not created successfully.<br>");
153 }
154 }
155 if (!$errors)
156 {
157 if (defined('DEFAULT_USER')) // we've got a default account
158 {
159 $lkup = new PanelUser(DEFAULT_USER['username']);
160
161 if (!$lkup->id) // doesn't exist, add it with full privileges
162 {
163 $user = [];
164 $user['user_name'] = DEFAULT_USER['username'];
165 $user['user_pass'] = DEFAULT_USER['password'];
166 $user['err'] = "";
167 create_new_user($user);
168 }
169 $lkup = new PanelUser(DEFAULT_USER['username']);
170 if (!user_can($lkup, PERMISSION_MANAGE_USERS))
171 $lkup->add_permission(PERMISSION_MANAGE_USERS);
172 }
173 return true;
174 }
175 else
176 return false;
177
178 }
179
180 /* We convert $u with a full user as an object ;D*/
181 public static function get_user(&$u)
182 {
183 $id = $u['id'];
184 $name = $u['name'];
185 $conn = sqlnew();
186
187 if ($id)
188 {
189 $prep = $conn->prepare("SELECT * FROM " . get_config("mysql::table_prefix") . "users WHERE user_id = :id LIMIT 1");
190 $prep->execute(["id" => strtolower($id)]);
191 }
192 elseif ($name)
193 {
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)]);
196 }
197 $data = NULL;
198 $obj = (object) [];
199 if ($prep)
200 $data = $prep->fetchAll();
201 if (isset($data[0]) && $data = $data[0])
202 {
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;
212 }
213 $u['object'] = $obj;
214 }
215
216 public static function get_usermeta(&$u)
217 {
218 $list = &$u['meta'];
219 $id = $u['id'];
220 $conn = sqlnew();
221 if (isset($id))
222 {
223 $prep = $conn->prepare("SELECT * FROM " . get_config("mysql::table_prefix") . "user_meta WHERE user_id = :id");
224 $prep->execute(["id" => $id]);
225 }
226 foreach ($prep->fetchAll() as $row)
227 {
228 $list[$row['meta_key']] = $row['meta_value'];
229 }
230 }
231
232 public static function add_usermeta(&$meta)
233 {
234 $meta = $meta['meta'];
235 $conn = sqlnew();
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
241 {
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())
246 return true;
247 return false;
248 }
249
250 else
251 {
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())
256 return true;
257 return false;
258 }
259 }
260 public static function del_usermeta(&$u)
261 {
262 $conn = sqlnew();
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())
267 return true;
268 return false;
269 }
270 public static function user_create(&$u)
271 {
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;
278 $conn = sqlnew();
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;
283 else
284 $u['errmsg'][] = "Could not add user";
285 }
286
287 public static function get_user_list(&$list)
288 {
289 $conn = sqlnew();
290 $result = $conn->query("SELECT user_id FROM " . get_config("mysql::table_prefix") . "users");
291 if (!$result) // impossible
292 {
293 die("Something went wrong.");
294 }
295 $userlist = [];
296 while($row = $result->fetch())
297 {
298 $userlist[] = new PanelUser(NULL, $row['user_id']);
299 }
300 if (!empty($userlist))
301 $list = $userlist;
302
303 }
304 public static function user_delete(&$u)
305 {
306 $user = $u['user'];
307 $query = "DELETE FROM " . get_config("mysql::table_prefix") . "users WHERE user_id = :id";
308 $conn = sqlnew();
309 $stmt = $conn->prepare($query);
310 $stmt->execute(["id" => $user->id]);
311 $deleted = $stmt->rowCount();
312 if ($deleted)
313 {
314 $u['info'][] = "Successfully deleted user \"$user->username\"";
315 $u['boolint'] = 1;
316 } else {
317 $u['info'][] = "Unknown error";
318 $u['boolint'] = 0;
319 }
320 }
321
322 public static function edit_core($arr)
323 {
324 $conn = sqlnew();
325 $user = $arr['user'];
326 $info = $arr['info'];
327 foreach($info as $key => $val)
328 {
329 $value = NULL;
330 if (!$val || !strlen($val) || BadPtr($val))
331 continue;
332 if (!strcmp($key,"update_fname") && $val != $user->first_name)
333 {
334 $value = "user_fname";
335 $valuestr = "first name";
336 }
337 elseif (!strcmp($key,"update_lname") && $val != $user->last_name)
338 {
339 $value = "user_lname";
340 $valuestr = "last name";
341 }
342 elseif (!strcmp($key,"update_bio") && $val != $user->bio)
343 {
344 $value = "user_bio";
345 $valuestr = "bio";
346 }
347 elseif (!strcmp($key,"update_pass") || !strcmp($key,"update_pass_conf"))
348 {
349 $value = "user_pass";
350 $valuestr = "password";
351 }
352 elseif(!strcmp($key,"update_email") && $val != $user->email)
353 {
354 $value = "user_email";
355 $valuestr = "email address";
356 }
357
358 if (!$value)
359 continue;
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]);
363
364 if (!$stmt->rowCount() && $stmt->errorInfo()[0] != "00000")
365 Message::Fail("Could not update $valuestr for $user->username: ".$stmt->errorInfo()[0]." (CODE: ".$stmt->errorCode().")");
366
367 else
368 Message::Success("Successfully updated the $valuestr for $user->username");
369 }
370 }
371 }
372
373
374 function security_check()
375 {
376 $ip = $_SERVER['REMOTE_ADDR'];
377 if (dnsbl_check($ip))
378 return true;
379
380 else if (fail2ban_check($ip))
381 {
382
383 }
384 }
385
386 function dnsbl_check($ip)
387 {
388 $dnsbl_lookup = get_config("dnsbl");
389 if (!$dnsbl_lookup)
390 return;
391
392 // clear variable just in case
393 $listed = NULL;
394
395 // if the IP was not given because you're an idiot, stop processing
396 if (!$ip) { return; }
397
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?
403
404 // exempt local connections because sometimes they get a false positive
405 if ($to == "192.168." || $to == "127.0.") { return NULL; }
406
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, ".")), ".");
409
410 // checkem
411 foreach ($dnsbl_lookup as $host) {
412
413 //if it was listed
414 if (checkdnsrr($reverse_ip . "." . $host . ".", "A")) {
415
416 //take note
417 $listed = $host;
418 }
419 }
420
421 // if it was safe, return NOTHING
422 if (!$listed) {
423 return NULL;
424 }
425
426 // else, you guessed it, return where it was listed
427 else {
428 return $listed;
429 }
430 }
431
432 function fail2ban_check($ip)
433 {
434
435 }