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