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