]> jfr.im git - irc/unrealircd/unrealircd-webpanel.git/blob - plugins/sql_auth/sql_auth.php
Fix password change error
[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 self::create_tables();
17 Hook::func(HOOKTYPE_PRE_HEADER, 'sql_auth::session_start');
18 Hook::func(HOOKTYPE_FOOTER, 'sql_auth::add_footer_info');
19 Hook::func(HOOKTYPE_USER_LOOKUP, 'sql_auth::get_user');
20 Hook::func(HOOKTYPE_USERMETA_ADD, 'sql_auth::add_usermeta');
21 Hook::func(HOOKTYPE_USERMETA_DEL, 'sql_auth::del_usermeta');
22 Hook::func(HOOKTYPE_USERMETA_GET, 'sql_auth::get_usermeta');
23 Hook::func(HOOKTYPE_USER_CREATE, 'sql_auth::user_create');
24 Hook::func(HOOKTYPE_GET_USER_LIST, 'sql_auth::get_user_list');
25 Hook::func(HOOKTYPE_USER_DELETE, 'sql_auth::user_delete');
26 Hook::func(HOOKTYPE_EDIT_USER, 'sql_auth::edit_core');
27
28 if (defined('SQL_DEFAULT_USER')) // we've got a default account
29 {
30 $lkup = new PanelUser(SQL_DEFAULT_USER['username']);
31
32 if (!$lkup->id) // doesn't exist, add it with full privileges
33 {
34 $user = [];
35 $user['user_name'] = SQL_DEFAULT_USER['username'];
36 $user['user_pass'] = SQL_DEFAULT_USER['password'];
37 $user['err'] = "";
38 create_new_user($user);
39 }
40 $lkup = new PanelUser(SQL_DEFAULT_USER['username']);
41 if (!user_can($lkup, PERMISSION_MANAGE_USERS))
42 $lkup->add_permission(PERMISSION_MANAGE_USERS);
43 }
44 }
45
46
47 public static function add_footer_info($empty)
48 {
49 if (!($user = unreal_get_current_user()))
50 return;
51
52 else {
53 echo "<code>Admin Panel v" . WEBPANEL_VERSION . "</code>";
54 }
55 }
56
57 /* pre-Header hook */
58 public static function session_start($n)
59 {
60 if (!isset($_SESSION))
61 {
62 session_set_cookie_params(3600);
63 session_start();
64 }
65 if (!isset($_SESSION['id']) || empty($_SESSION))
66 {
67 $secure = ($_SERVER['HTTPS'] == 'on') ? "https://" : "http://";
68 $current_url = "$secure$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
69 $tok = split($_SERVER['SCRIPT_FILENAME'], "/");
70 if ($check = security_check() && $tok[count($tok) - 1] !== "error.php") {
71 header("Location: " . BASE_URL . "plugins/sql_auth/error.php");
72 die();
73 }
74 header("Location: ".BASE_URL."login/?redirect=".urlencode($current_url));
75 die();
76 }
77 else
78 {
79 if (!unreal_get_current_user()) // user no longer exists
80 {
81 session_destroy();
82 header("Location: ".BASE_URL."login");
83 die();
84 }
85 // you'll be automatically logged out after one hour of inactivity
86 }
87 }
88
89 /**
90 * Create the tables we'll be using in the SQLdb
91 * @return void
92 */
93 public static function create_tables()
94 {
95 $conn = sqlnew();
96 $conn->query("CREATE TABLE IF NOT EXISTS " . SQL_PREFIX . "users (
97 user_id int AUTO_INCREMENT NOT NULL,
98 user_name VARCHAR(255) NOT NULL,
99 user_pass VARCHAR(255) NOT NULL,
100 user_email VARCHAR(255),
101 user_fname VARCHAR(255),
102 user_lname VARCHAR(255),
103 user_bio VARCHAR(255),
104 created VARCHAR(255),
105 PRIMARY KEY (user_id)
106 )");
107
108 /**
109 * Patch for beta users
110 * This adds the email column to existing tables without it
111 */
112 $columns = $conn->query("SHOW COLUMNS FROM " . SQL_PREFIX . "users");
113 $column_names = array();
114 $c = $columns->fetchAll();
115
116 foreach($c as $column) {
117 $column_names[] = $column['Field'];
118 }
119 $column_exists = in_array("user_email", $column_names);
120 if (!$column_exists) {
121 $conn->query("ALTER TABLE " . SQL_PREFIX . "users ADD COLUMN user_email varchar(255)");
122 }
123
124 /**
125 * Another patch for beta users
126 * This changes the size of the meta_value so we can store more
127 */
128 $columns = $conn->query("SHOW COLUMNS FROM ".SQL_PREFIX."user_meta");
129 $c = $columns->fetchAll();
130 if (!empty($c))
131 $conn->query("ALTER TABLE `".SQL_PREFIX."user_meta` CHANGE `meta_value` `meta_value` VARCHAR(5000) CHARACTER SET utf8mb3 COLLATE utf8mb3_bin NULL DEFAULT NULL");
132
133
134 $conn->query("CREATE TABLE IF NOT EXISTS " . SQL_PREFIX . "user_meta (
135 meta_id int AUTO_INCREMENT NOT NULL,
136 user_id int NOT NULL,
137 meta_key VARCHAR(255) NOT NULL,
138 meta_value VARCHAR(255),
139 PRIMARY KEY (meta_id)
140 )");
141 $conn->query("CREATE TABLE IF NOT EXISTS " . SQL_PREFIX . "auth_settings (
142 id int AUTO_INCREMENT NOT NULL,
143 setting_key VARCHAR(255) NOT NULL,
144 setting_value VARCHAR(255),
145 PRIMARY KEY (id)
146 )");
147 $conn->query("CREATE TABLE IF NOT EXISTS " . SQL_PREFIX . "fail2ban (
148 id int AUTO_INCREMENT NOT NULL,
149 ip VARCHAR(255) NOT NULL,
150 count VARCHAR(255),
151 PRIMARY KEY (id)
152 )");
153 new AuthSettings();
154 }
155
156 /* We convert $u with a full user as an object ;D*/
157 public static function get_user(&$u)
158 {
159 $id = $u['id'];
160 $name = $u['name'];
161 $conn = sqlnew();
162
163 if ($id)
164 {
165 $prep = $conn->prepare("SELECT * FROM " . SQL_PREFIX . "users WHERE user_id = :id LIMIT 1");
166 $prep->execute(["id" => strtolower($id)]);
167 }
168 elseif ($name)
169 {
170 $prep = $conn->prepare("SELECT * FROM " . SQL_PREFIX . "users WHERE LOWER(user_name) = :name LIMIT 1");
171 $prep->execute(["name" => strtolower($name)]);
172 }
173 $data = NULL;
174 $obj = (object) [];
175 if ($prep)
176 $data = $prep->fetchAll();
177 if (isset($data[0]) && $data = $data[0])
178 {
179 $obj->id = $data['user_id'];
180 $obj->username = $data['user_name'];
181 $obj->passhash = $data['user_pass'];
182 $obj->first_name = $data['user_fname'] ?? NULL;
183 $obj->last_name = $data['user_lname'] ?? NULL;
184 $obj->created = $data['created'];
185 $obj->bio = $data['user_bio'];
186 $obj->email = $data['user_email'];
187 $obj->user_meta = (new PanelUser_Meta($obj->id))->list;
188 }
189 $u['object'] = $obj;
190 }
191
192 public static function get_usermeta(&$u)
193 {
194 $list = &$u['meta'];
195 $id = $u['id'];
196 $conn = sqlnew();
197 if (isset($id))
198 {
199 $prep = $conn->prepare("SELECT * FROM " . SQL_PREFIX . "user_meta WHERE user_id = :id");
200 $prep->execute(["id" => $id]);
201 }
202 foreach ($prep->fetchAll() as $row)
203 {
204 $list[$row['meta_key']] = $row['meta_value'];
205 }
206 }
207
208 public static function add_usermeta(&$meta)
209 {
210 $meta = $meta['meta'];
211 $conn = sqlnew();
212 /* check if it exists first, update it if it does */
213 $query = "SELECT * FROM " . SQL_PREFIX . "user_meta WHERE user_id = :id AND meta_key = :key";
214 $stmt = $conn->prepare($query);
215 $stmt->execute(["id" => $meta['id'], "key" => $meta['key']]);
216 if ($stmt->rowCount()) // it exists, update instead of insert
217 {
218 $query = "UPDATE " . SQL_PREFIX . "user_meta SET meta_value = :value WHERE user_id = :id AND meta_key = :key";
219 $stmt = $conn->prepare($query);
220 $stmt->execute($meta);
221 if ($stmt->rowCount())
222 return true;
223 return false;
224 }
225
226 else
227 {
228 $query = "INSERT INTO " . SQL_PREFIX . "user_meta (user_id, meta_key, meta_value) VALUES (:id, :key, :value)";
229 $stmt = $conn->prepare($query);
230 $stmt->execute($meta);
231 if ($stmt->rowCount())
232 return true;
233 return false;
234 }
235 }
236 public static function del_usermeta(&$u)
237 {
238 $conn = sqlnew();
239 $query = "DELETE FROM " . SQL_PREFIX . "user_meta WHERE user_id = :id AND meta_key = :key";
240 $stmt = $conn->prepare($query);
241 $stmt->execute($u['meta']);
242 if ($stmt->rowCount())
243 return true;
244 return false;
245 }
246 public static function user_create(&$u)
247 {
248 $username = $u['user_name'];
249 $first_name = $u['fname'] ?? NULL;
250 $last_name = $u['lname'] ?? NULL;
251 $password = $u['user_pass'] ?? NULL;
252 $user_bio = $u['user_bio'] ?? NULL;
253 $user_email = $u['user_email'] ?? NULL;
254 $conn = sqlnew();
255 $prep = $conn->prepare("INSERT INTO " . SQL_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)");
256 $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")]);
257 if ($prep->rowCount())
258 $u['success'] = true;
259 else
260 $u['errmsg'][] = "Could not add user";
261 }
262
263 public static function get_user_list(&$list)
264 {
265 $conn = sqlnew();
266 $result = $conn->query("SELECT user_id FROM " . SQL_PREFIX . "users");
267 if (!$result) // impossible
268 {
269 die("Something went wrong.");
270 }
271 $userlist = [];
272 while($row = $result->fetch())
273 {
274 $userlist[] = new PanelUser(NULL, $row['user_id']);
275 }
276 if (!empty($userlist))
277 $list = $userlist;
278
279 }
280 public static function user_delete(&$u)
281 {
282 $user = $u['user'];
283 $query = "DELETE FROM " . SQL_PREFIX . "users WHERE user_id = :id";
284 $conn = sqlnew();
285 $stmt = $conn->prepare($query);
286 $stmt->execute(["id" => $user->id]);
287 $deleted = $stmt->rowCount();
288 if ($deleted)
289 {
290 $u['info'][] = "Successfully deleted user \"$user->username\"";
291 $u['boolint'] = 1;
292 } else {
293 $u['info'][] = "Unknown error";
294 $u['boolint'] = 0;
295 }
296 }
297
298 public static function edit_core($arr)
299 {
300 $conn = sqlnew();
301 $user = $arr['user'];
302 $info = $arr['info'];
303 foreach($info as $key => $val)
304 {
305 if (!$val)
306 continue;
307 if (!strcmp($key,"update_fname"))
308 $value = "user_fname";
309
310 elseif (!strcmp($key,"update_lname"))
311 $value = "user_lname";
312
313 elseif (!strcmp($key,"update_bio"))
314 $value = "user_bio";
315
316 elseif (!strcmp($key,"update_pass") || !strcmp($key,"update_pass_conf"))
317 $value = "user_pass";
318
319 elseif(!strcmp($key,"update_email"))
320 $value = "user_email";
321 else
322 die("Malfunction");
323 $query = "UPDATE " . SQL_PREFIX . "users SET $value=:value WHERE user_id = :id";
324 $stmt = $conn->prepare($query);
325 $stmt->execute(["value" => $val, "id" => $user->id]);
326 }
327 }
328 }
329
330
331 function security_check()
332 {
333 $ip = $_SERVER['REMOTE_ADDR'];
334 if (dnsbl_check($ip))
335 return true;
336
337 else if (fail2ban_check($ip))
338 {
339
340 }
341 }
342
343 function dnsbl_check($ip)
344 {
345
346 if (!defined('DNSBL'))
347 return;
348 $dnsbl_lookup = DNSBL;
349
350 // clear variable just in case
351 $listed = NULL;
352
353 // if the IP was not given because you're an idiot, stop processing
354 if (!$ip) { return; }
355
356 // get the first two segments of the IPv4
357 $because = split($ip, "."); // why you
358 $you = $because[1]; // gotta play
359 $want = $because[2]; // that song
360 $to = $you.".".$want."."; // so loud?
361
362 // exempt local connections because sometimes they get a false positive
363 if ($to == "192.168." || $to == "127.0.") { return NULL; }
364
365 // you spin my IP right round, right round, to check the records baby, right round-round-round
366 $reverse_ip = glue(array_reverse(split($ip, ".")), ".");
367
368 // checkem
369 foreach ($dnsbl_lookup as $host) {
370
371 //if it was listed
372 if (checkdnsrr($reverse_ip . "." . $host . ".", "A")) {
373
374 //take note
375 $listed = $host;
376 }
377 }
378
379 // if it was safe, return NOTHING
380 if (!$listed) {
381 return NULL;
382 }
383
384 // else, you guessed it, return where it was listed
385 else {
386 return $listed;
387 }
388 }
389
390 function fail2ban_check($ip)
391 {
392
393 }