diff --git a/inc/database.php b/inc/database.php index 678d634..55244b7 100755 --- a/inc/database.php +++ b/inc/database.php @@ -53,6 +53,15 @@ class DataBase extends SQLite3 { FOREIGN KEY (personaid) REFERENCES personas(id) ON UPDATE CASCADE ON DELETE CASCADE ); + CREATE TABLE IF NOT EXISTS tokens ( + id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, + userid INTEGER NOT NULL, + token TEXT NOT NULL UNIQUE, + lastuse TEXT NOT NULL, + expires TEXT NOT NULL, + FOREIGN KEY (userid) REFERENCES users(id) ON UPDATE CASCADE ON DELETE CASCADE + ); + INSERT OR IGNORE INTO users (id, handle, name, about) VALUES ('0', 'SYSTEM', 'SYSTEM', 'SYSTEM'); "; @@ -70,6 +79,16 @@ class DataBase extends SQLite3 { } } + function getUserByHandle($handle) { + $handle = $this->escapeString($handle); + $sql = "SELECT * FROM users AS user WHERE handle='$handle';"; + $ret = $this->query($sql)->fetchArray(SQLITE3_ASSOC); + if(!$ret) { + return false; + } + return $ret; + } + function addPost($text, $userid=NULL, $personaid=NULL) { $id = hexdec(uniqid()); $time = time(); @@ -109,6 +128,56 @@ class DataBase extends SQLite3 { return password_verify($password, $dbhash); } + function tokenGen() { + return random_bytes(32); + } + function tokenAdd($userid) { + $token = $this->tokenGen(); + $hashed = hash('sha256', $token); + $time = time(); + $expires = $time + 2592000; // 30 days + $sql = "INSERT INTO tokens (userid, token, lastuse, expires) VALUES ('$userid', '$hashed', '$time', '$expires');"; + $ret = $this->exec($sql); + if(!$ret) { + die($this->lastErrorMsg()); + } + return $token; + } + function tokenRefresh($tokenid) { + $time = time(); + $expires = $time + 2592000; // 30 days + $sql = "UPDATE tokens SET lastuse='$time', expires='$expires' WHERE id='$tokenid';"; + $ret = $this->exec($sql); + if(!$ret) { + die($this->lastErrorMsg()); + } + } + function tokenRemove($token) { + $hashed = hash('sha256', $token); + $sql = "DELETE FROM tokens WHERE token='$hashed';"; + $ret = $this->exec($sql); + if(!$ret) { + die($this->lastErrorMsg()); + } + } + + function getAuthedUserId($token=NULL) { + if (empty($token)) { + if (empty($_COOKIE['token'])) { + return false; + } + $token = base64_decode($_COOKIE['token']); + } + $hashed = hash('sha256', $token); + $sql = "SELECT id AS id, userid AS userid FROM tokens WHERE token='$hashed';"; + $ret = $this->query($sql)->fetchArray(SQLITE3_ASSOC); + if(!$ret) { + return false; + } + $this->tokenRefresh($ret['id']); + return $ret['userid']; + } + function getPosts($userid=NULL, $personaid = NULL) { $sql = "SELECT * FROM posts AS post LEFT JOIN users AS user ON post.userid=user.id LEFT JOIN personas AS persona ON post.personaid=persona.id;"; diff --git a/index.php b/index.php index d4596d5..56a01fa 100755 --- a/index.php +++ b/index.php @@ -1,3 +1,10 @@ +lastErrorMsg()); +} +?>
@@ -9,6 +16,21 @@' . $post["post.text"] . '
'; - echo '