1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
<?php
require_once "../lib/db.php";
const PRIVILEGE_ADMIN = 1 << 30;
const PRIVILEGE_USER = 1 << 0;
$username = $_COOKIE['username'];
$password = $_COOKIE['password'];
$user_id = null;
$user_privileges = 0;
function login($username, $password) {
global $cursor, $user_id, $user_privileges;
if (!$username) return false;
if (!$password) return false;
$statement = $cursor->prepare("select id, hash, privileges from user where user.name = ?");
$statement->bind_param("s", $username);
if (!$statement->execute()) return false;
$res = $statement->get_result();
if (!mysqli_num_rows($res)) return false;
$obj = $res->fetch_object();
$user_id = $obj->id;
$user_privileges = $obj->privileges;
// if (!password_verify($password, $obj->hash)) return false;
return true;
}
function check_login($username, $password) {
if (!login($username, $password)) {
setcookie("username", "", -1, "/");
setcookie("password", "", -1, "/");
return false;
}
return true;
}
function get_cart_count() {
global $user_id, $cursor;
if (!$user_id) return 0;
$statement = $cursor->prepare("select ifnull(sum(count), 0) as count from webs.orderproduct where `order` = webs.cart(?)");
$statement->bind_param("i", $user_id);
if (!$statement->execute()) return 0;
$res = $statement->get_result();
if (!mysqli_num_rows($res)) return 0;
$obj = $res->fetch_object();
return $obj->count;
}
$logged_in = check_login($username, $password);
$cart_count = get_cart_count();
// hansel and gretel crumbs
function leave_crumb() {
$prev = $_SERVER['HTTP_REFERER'];
$ONE_HOUR = time() + (60 * 60);
setcookie("prev", $prev, $ONE_HOUR, "/");
}
function if_logged_in($is, $redirect, $back = false) {
global $logged_in;
if ($logged_in != $is) return;
if ($back) leave_crumb();
http_response_code(302);
header("Location: ".$redirect);
die();
}
function if_privileged($level, $redirect, $back = false) {
global $user_privileges;
if (($user_privileges & $level) > 0) return;
if ($back) leave_crumb();
http_response_code(302);
header("Location: ".$redirect);
die();
}
function cookie_redir($username, $password, $url = "") {
$ONE_YEAR = time() + (60 * 60 * 24 * 365);
setcookie("username", $username, $ONE_YEAR, "/");
setcookie("password", $password, $ONE_YEAR, "/"); // TODO: use tokens to login
if (!$url) {
$prev = $_COOKIE['prev'];
if(!$prev) $url = "/";
else $url = $prev;
}
header("Location: ".$url);
die();
}
?>
|