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