Database stuff

This commit is contained in:
Roman Hergenreder 2020-02-17 00:18:37 +01:00
parent 2c92020990
commit 64923b3e4f
9 changed files with 139 additions and 79 deletions

@ -17,7 +17,7 @@ class CreateApiKey extends Request {
} }
$apiKey = generateRandomString(64); $apiKey = generateRandomString(64);
$query = "INSERT INTO ApiKey (uidUser, api_key, valid_until) VALUES (?,?,(SELECT DATE_ADD(now(), INTERVAL 30 DAY)))"; $query = "INSERT INTO ApiKey (user_id, api_key, valid_until) VALUES (?,?,(SELECT DATE_ADD(now(), INTERVAL 30 DAY)))";
$request = new ExecuteStatement($this->user); $request = new ExecuteStatement($this->user);
$this->success = $request->execute(array("query" => $query, $this->user->getId(), $apiKey)); $this->success = $request->execute(array("query" => $query, $this->user->getId(), $apiKey));
$this->lastError = $request->getLastError(); $this->lastError = $request->getLastError();

@ -16,7 +16,7 @@ class GetApiKeys extends Request {
$query = "SELECT ApiKey.uid, ApiKey.api_key, ApiKey.valid_until $query = "SELECT ApiKey.uid, ApiKey.api_key, ApiKey.valid_until
FROM ApiKey FROM ApiKey
WHERE ApiKey.uidUser = ? WHERE ApiKey.user_id = ?
AND ApiKey.valid_until > now()"; AND ApiKey.valid_until > now()";
$request = new ExecuteSelect($this->user); $request = new ExecuteSelect($this->user);
$this->success = $request->execute(array("query" => $query, $this->user->getId())); $this->success = $request->execute(array("query" => $query, $this->user->getId()));

@ -13,6 +13,7 @@ class Login extends Request {
parent::__construct($user, $externCall, array( parent::__construct($user, $externCall, array(
'username' => new StringType('username', 32), 'username' => new StringType('username', 32),
'password' => new StringType('password'), 'password' => new StringType('password'),
'stayLoggedIn' => new Parameter('stayLoggedIn', Parameter::TYPE_BOOLEAN, true, true)
)); ));
$this->forbidMethod("GET"); $this->forbidMethod("GET");
} }
@ -39,6 +40,7 @@ class Login extends Request {
$this->success = false; $this->success = false;
$username = $this->getParam('username'); $username = $this->getParam('username');
$password = $this->getParam('password'); $password = $this->getParam('password');
$stayLoggedIn = $this->getParam('stayLoggedIn');
$query = 'SELECT User.uid, User.password, User.salt FROM User WHERE User.name=?'; $query = 'SELECT User.uid, User.password, User.salt FROM User WHERE User.name=?';
$request = new ExecuteSelect($this->user); $request = new ExecuteSelect($this->user);
@ -56,7 +58,7 @@ class Login extends Request {
$uid = $row['uid']; $uid = $row['uid'];
$hash = hash('sha256', $password . $salt); $hash = hash('sha256', $password . $salt);
if($hash === $row['password']) { if($hash === $row['password']) {
if(!($this->success = $this->user->createSession($uid))) { if(!($this->success = $this->user->createSession($uid, $stayLoggedIn))) {
return $this->createError("Error creating Session"); return $this->createError("Error creating Session");
} else { } else {
$this->result['logoutIn'] = $this->user->getSession()->getExpiresSeconds(); $this->result['logoutIn'] = $this->user->getSession()->getExpiresSeconds();

@ -14,7 +14,7 @@ class RefreshApiKey extends Request {
private function apiKeyExists() { private function apiKeyExists() {
$id = $this->getParam("id"); $id = $this->getParam("id");
$query = "SELECT * FROM ApiKey WHERE uid = ? AND uidUser = ? AND valid_until > now()"; $query = "SELECT * FROM ApiKey WHERE uid = ? AND user_id = ? AND valid_until > now()";
$request = new ExecuteSelect($this->user); $request = new ExecuteSelect($this->user);
$this->success = $request->execute(array("query" => $query, $id, $this->user->getId())); $this->success = $request->execute(array("query" => $query, $id, $this->user->getId()));
$this->lastError = $request->getLastError(); $this->lastError = $request->getLastError();
@ -36,7 +36,7 @@ class RefreshApiKey extends Request {
if(!$this->apiKeyExists()) if(!$this->apiKeyExists())
return false; return false;
$query = "UPDATE ApiKey SET valid_until = (SELECT DATE_ADD(now(), INTERVAL 30 DAY)) WHERE uid = ? AND uidUser = ? AND valid_until > now()"; $query = "UPDATE ApiKey SET valid_until = (SELECT DATE_ADD(now(), INTERVAL 30 DAY)) WHERE uid = ? AND user_id = ? AND valid_until > now()";
$request = new ExecuteStatement($this->user); $request = new ExecuteStatement($this->user);
$this->success = $request->execute(array("query" => $query, $id, $this->user->getId())); $this->success = $request->execute(array("query" => $query, $id, $this->user->getId()));
$this->lastError = $request->getLastError(); $this->lastError = $request->getLastError();

@ -14,7 +14,7 @@ class RevokeApiKey extends Request {
private function apiKeyExists() { private function apiKeyExists() {
$id = $this->getParam("id"); $id = $this->getParam("id");
$query = "SELECT * FROM ApiKey WHERE uid = ? AND uidUser = ? AND valid_until > now()"; $query = "SELECT * FROM ApiKey WHERE uid = ? AND user_id = ? AND valid_until > now()";
$request = new ExecuteSelect($this->user); $request = new ExecuteSelect($this->user);
$this->success = $request->execute(array("query" => $query, $id, $this->user->getId())); $this->success = $request->execute(array("query" => $query, $id, $this->user->getId()));
$this->lastError = $request->getLastError(); $this->lastError = $request->getLastError();
@ -36,7 +36,7 @@ class RevokeApiKey extends Request {
if(!$this->apiKeyExists()) if(!$this->apiKeyExists())
return false; return false;
$query = "DELETE FROM ApiKey WHERE valid_until < now() OR (uid = ? AND uidUser = ?)"; $query = "DELETE FROM ApiKey WHERE valid_until < now() OR (uid = ? AND user_id = ?)";
$request = new ExecuteStatement($this->user); $request = new ExecuteStatement($this->user);
$this->success = $request->execute(array("query" => $query, $id, $this->user->getId())); $this->success = $request->execute(array("query" => $query, $id, $this->user->getId()));
$this->lastError = $request->getLastError(); $this->lastError = $request->getLastError();

@ -48,7 +48,7 @@ class SetLanguage extends Request {
$languageId = $this->language->getId(); $languageId = $this->language->getId();
$userId = $this->user->getId(); $userId = $this->user->getId();
$query = "UPDATE User SET uidLanguage = ? WHERE uid = ?"; $query = "UPDATE User SET language_id = ? WHERE uid = ?";
$request = new ExecuteStatement($this->user); $request = new ExecuteStatement($this->user);
$this->success = $request->execute(array("query" => $query, $languageId, $userId)); $this->success = $request->execute(array("query" => $query, $languageId, $userId));
$this->lastError = $request->getLastError(); $this->lastError = $request->getLastError();

@ -1,51 +1,6 @@
-- --
-- API -- API
-- --
CREATE TABLE IF NOT EXISTS User (
`uid` INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
`email` VARCHAR(256) UNIQUE DEFAULT NULL,
`name` VARCHAR(32) UNIQUE NOT NULL,
`salt` varchar(16) NOT NULL,
`password` varchar(64) NOT NULL,
`uidLanguage` int(11) DEFAULT 1
);
CREATE TABLE IF NOT EXISTS UserInvitation (
`email` VARCHAR(256) NOT NULL,
`token` VARCHAR(36) UNIQUE NOT NULL,
`valid_until` DATETIME NOT NULL
);
CREATE TABLE IF NOT EXISTS `Group` (
`gid` INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(32) NOT NULL
);
INSERT INTO `Group` (gid, name) VALUES (1, "Default"), (2, "Administrator")
ON DUPLICATE KEY UPDATE name=name;
CREATE TABLE IF NOT EXISTS UserGroup (
`uid` INTEGER NOT NULL,
`gid` INTEGER NOT NULL,
UNIQUE(`uid`, `gid`)
);
CREATE TABLE IF NOT EXISTS Session (
`uid` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`expires` timestamp NOT NULL,
`uidUser` int(11) NOT NULL,
`ipAddress` varchar(45) NOT NULL,
`os` varchar(64) NOT NULL,
`browser` varchar(64) NOT NULL
);
CREATE TABLE IF NOT EXISTS ApiKey (
`uid` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`uidUser` int(11) NOT NULL,
`api_key` VARCHAR(64) NOT NULL,
`valid_until` DATETIME NOT NULL
);
CREATE TABLE IF NOT EXISTS Language ( CREATE TABLE IF NOT EXISTS Language (
`uid` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `uid` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`code` VARCHAR(5) UNIQUE NOT NULL, `code` VARCHAR(5) UNIQUE NOT NULL,
@ -57,6 +12,71 @@ INSERT INTO Language (`uid`, `code`, `name`) VALUES
(2, 'de_DE', 'Deutsch Standard') (2, 'de_DE', 'Deutsch Standard')
ON DUPLICATE KEY UPDATE name=name; ON DUPLICATE KEY UPDATE name=name;
CREATE TABLE IF NOT EXISTS User (
`uid` INTEGER NOT NULL AUTO_INCREMENT,
`email` VARCHAR(256) UNIQUE DEFAULT NULL,
`name` VARCHAR(32) UNIQUE NOT NULL,
`salt` varchar(16) NOT NULL,
`password` varchar(64) NOT NULL,
`language_id` int(11) DEFAULT 1,
PRIMARY KEY (`uid`),
FOREIGN KEY (`language_id`) REFERENCES `Language` (`uid`) ON DELETE SET DEFAULT
);
CREATE TABLE IF NOT EXISTS UserInvitation (
`email` VARCHAR(256) NOT NULL,
`token` VARCHAR(36) UNIQUE NOT NULL,
`valid_until` DATETIME NOT NULL
);
CREATE TABLE IF NOT EXISTS UserToken (
`user_id` INTEGER NOT NULL,
`token` VARCHAR(36) NOT NULL,
`type` ENUM('password_reset', 'confirmation') NOT NULL,
`valid_until` DATETIME NOT NULL,
FOREIGN KEY (`user_id`) REFERENCES `User` (`uid`) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS `Group` (
`gid` INTEGER NOT NULL AUTO_INCREMENT,
`name` VARCHAR(32) NOT NULL,
PRIMARY KEY (`gid`),
UNIQUE (`name`)
);
INSERT INTO `Group` (gid, name) VALUES (1, "Default"), (2, "Administrator")
ON DUPLICATE KEY UPDATE name=name;
CREATE TABLE IF NOT EXISTS UserGroup (
`uid` INTEGER NOT NULL,
`gid` INTEGER NOT NULL,
UNIQUE (`uid`, `gid`),
FOREIGN KEY (`uid`) REFERENCES `User` (`uid`),
FOREIGN KEY (`gid`) REFERENCES `Group` (`gid`)
);
CREATE TABLE IF NOT EXISTS Session (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`expires` timestamp NOT NULL,
`user_id` int(11) NOT NULL,
`ipAddress` varchar(45) NOT NULL,
`os` varchar(64) NOT NULL,
`browser` varchar(64) NOT NULL,
`data` JSON NOT NULL DEFAULT '{}',
`stay_logged_in` BOOLEAN DEFAULT TRUE,
PRIMARY KEY (`uid`),
FOREIGN KEY (`user_id`) REFERENCES `User` (`uid`) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS ApiKey (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`api_key` VARCHAR(64) NOT NULL,
`valid_until` DATETIME NOT NULL,
PRIMARY KEY (`uid`),
FOREIGN KEY (`user_id`) REFERENCES `User` (`uid`)
);
CREATE TABLE IF NOT EXISTS ExternalSiteCache ( CREATE TABLE IF NOT EXISTS ExternalSiteCache (
`url` VARCHAR(256) PRIMARY KEY, `url` VARCHAR(256) PRIMARY KEY,
`data` TEXT NOT NULL, `data` TEXT NOT NULL,

@ -12,10 +12,21 @@ class Session extends ApiObject {
private $ipAddress; private $ipAddress;
private $os; private $os;
private $browser; private $browser;
private $stayLoggedIn;
public function __construct($user, $sessionId = NULL) { public function __construct($user, $sessionId) {
$this->user = $user; $this->user = $user;
$this->sessionId = $sessionId; $this->sessionId = $sessionId;
$this->stayLoggedIn = true;
}
public static function create($user, $stayLoggedIn) {
$session = new Session($user, null);
if($session->insert($stayLoggedIn)) {
return $session;
}
return null;
} }
private function updateMetaData() { private function updateMetaData() {
@ -31,6 +42,16 @@ class Session extends ApiObject {
} }
} }
public function setData($data) {
foreach($data as $key => $value) {
$_SESSION[$key] = $value;
}
}
public function stayLoggedIn($val) {
$this->stayLoggedIn = $val;
}
public function sendCookie() { public function sendCookie() {
$this->updateMetaData(); $this->updateMetaData();
$jwt = $this->user->getConfiguration()->getJwt(); $jwt = $this->user->getConfiguration()->getJwt();
@ -38,22 +59,22 @@ class Session extends ApiObject {
$token = array('userId' => $this->user->getId(), 'sessionId' => $this->sessionId); $token = array('userId' => $this->user->getId(), 'sessionId' => $this->sessionId);
$sessionCookie = \External\JWT::encode($token, $jwt->getKey()); $sessionCookie = \External\JWT::encode($token, $jwt->getKey());
$secure = strcmp(getProtocol(), "https") === 0; $secure = strcmp(getProtocol(), "https") === 0;
setcookie('session', $sessionCookie, $this->expires, "/", "", $secure); setcookie('session', $sessionCookie, $this->getExpiresTime(), "/", "", $secure);
} }
} }
public function getExpiresTime() { public function getExpiresTime() {
return $this->expires; return ($this->stayLoggedIn == 0 ? 0 : $this->expires);
} }
public function getExpiresSeconds() { public function getExpiresSeconds() {
return ($this->expires - time()); return ($this->stayLoggedIn == 0 ? -1 : $this->expires - time());
} }
public function jsonSerialize() { public function jsonSerialize() {
return array( return array(
'uid' => $this->sessionId, 'uid' => $this->sessionId,
'uidUser' => $this->user->getId(), 'user_id' => $this->user->getId(),
'expires' => $this->expires, 'expires' => $this->expires,
'ipAddress' => $this->ipAddress, 'ipAddress' => $this->ipAddress,
'os' => $this->os, 'os' => $this->os,
@ -61,10 +82,10 @@ class Session extends ApiObject {
); );
} }
public function insert() { public function insert($stayLoggedIn) {
$this->updateMetaData(); $this->updateMetaData();
$query = 'INSERT INTO Session (expires, uidUser, ipAddress, os, browser) $query = "INSERT INTO Session (expires, user_id, ipAddress, os, browser, data, stay_logged_in)
VALUES (DATE_ADD(NOW(), INTERVAL ? MINUTE),?,?,?,?)'; VALUES (DATE_ADD(NOW(), INTERVAL ? MINUTE),?,?,?,?,?,?)";
$request = new \Api\ExecuteStatement($this->user); $request = new \Api\ExecuteStatement($this->user);
$success = $request->execute(array( $success = $request->execute(array(
@ -74,6 +95,8 @@ class Session extends ApiObject {
$this->ipAddress, $this->ipAddress,
$this->os, $this->os,
$this->browser, $this->browser,
json_encode($_SESSION),
$stayLoggedIn
)); ));
if($success) { if($success) {
@ -85,7 +108,7 @@ class Session extends ApiObject {
} }
public function destroy() { public function destroy() {
$query = 'DELETE FROM Session WHERE Session.uid=? OR Session.expires<=NOW()'; $query = 'DELETE FROM Session WHERE Session.uid=? OR (Session.stay_logged_in = 0 AND Session.expires<=NOW())';
$request = new \Api\ExecuteStatement($this->user); $request = new \Api\ExecuteStatement($this->user);
$success = $request->execute(array('query' => $query, $this->sessionId)); $success = $request->execute(array('query' => $query, $this->sessionId));
return $success; return $success;
@ -93,10 +116,12 @@ class Session extends ApiObject {
public function update() { public function update() {
$this->updateMetaData(); $this->updateMetaData();
$query = 'UPDATE Session $query = 'UPDATE Session
SET Session.expires=DATE_ADD(NOW(), INTERVAL ? MINUTE), Session.ipAddress=?, SET Session.expires=DATE_ADD(NOW(), INTERVAL ? MINUTE),
Session.os=?, Session.browser=? Session.ipAddress=?, Session.os=?, Session.browser=?, Session.data=?
WHERE Session.uid=?'; WHERE Session.uid=?';
$request = new \Api\ExecuteStatement($this->user); $request = new \Api\ExecuteStatement($this->user);
$success = $request->execute(array( $success = $request->execute(array(
'query' => $query, 'query' => $query,
@ -104,9 +129,9 @@ class Session extends ApiObject {
$this->ipAddress, $this->ipAddress,
$this->os, $this->os,
$this->browser, $this->browser,
json_encode($_SESSION),
$this->sessionId, $this->sessionId,
)); ));
return $success; return $success;
} }
} }

@ -13,6 +13,7 @@ class User extends ApiObject {
private $language; private $language;
public function __construct($configuration) { public function __construct($configuration) {
session_start();
$this->configuration = $configuration; $this->configuration = $configuration;
$this->setLangauge(Language::DEFAULT_LANGUAGE()); $this->setLangauge(Language::DEFAULT_LANGUAGE());
$this->reset(); $this->reset();
@ -95,14 +96,20 @@ class User extends ApiObject {
} }
public function readData($userId, $sessionId, $sessionUpdate = true) { public function readData($userId, $sessionId, $sessionUpdate = true) {
$query = 'SELECT User.name as userName, Language.uid as langId, Language.code as langCode, Language.name as langName $query = 'SELECT User.name as userName, Language.uid as langId, Language.code as langCode,
Language.name as langName, Session.data as sessionData, Session.stay_logged_in as stayLoggedIn
FROM User FROM User
INNER JOIN Session ON User.uid=Session.uidUser INNER JOIN Session ON User.uid=Session.user_id
LEFT JOIN Language ON User.uidLanguage=Language.uid LEFT JOIN Language ON User.language_id=Language.uid
WHERE User.uid=? AND Session.uid=? AND Session.expires>now()'; WHERE User.uid=? AND Session.uid=?
AND (Session.stay_logged_in OR Session.expires>now())';
$request = new \Api\ExecuteSelect($this); $request = new \Api\ExecuteSelect($this);
$success = $request->execute(array('query' => $query, $userId, $sessionId)); $success = $request->execute(array('query' => $query, $userId, $sessionId));
// var_dump($userId);
// var_dump($sessionId);
// var_dump($request->getResult());
if($success) { if($success) {
if(count($request->getResult()['rows']) === 0) { if(count($request->getResult()['rows']) === 0) {
$success = false; $success = false;
@ -111,6 +118,8 @@ class User extends ApiObject {
$this->username = $row['userName']; $this->username = $row['userName'];
$this->uid = $userId; $this->uid = $userId;
$this->session = new Session($this, $sessionId); $this->session = new Session($this, $sessionId);
$this->session->setData(json_decode($row["sessionData"]));
$this->session->stayLoggedIn($row["stayLoggedIn"]);
if($sessionUpdate) $this->session->update(); if($sessionUpdate) $this->session->update();
$this->loggedIn = true; $this->loggedIn = true;
@ -145,26 +154,30 @@ class User extends ApiObject {
if(isset($_GET['lang']) && is_string($_GET["lang"]) && !empty($_GET["lang"])) { if(isset($_GET['lang']) && is_string($_GET["lang"]) && !empty($_GET["lang"])) {
$this->updateLanguage($_GET['lang']); $this->updateLanguage($_GET['lang']);
}/* else if(isset($_COOKIE['lang']) && is_string($_COOKIE["lang"]) && !empty($_COOKIE["lang"])) { } else if(isset($_COOKIE['lang']) && is_string($_COOKIE["lang"]) && !empty($_COOKIE["lang"])) {
$this->updateLanguage($_COOKIE['lang']); $this->updateLanguage($_COOKIE['lang']);
}*/ }
} }
public function createSession($userId) { public function createSession($userId, $stayLoggedIn) {
$this->uid = $userId; $this->uid = $userId;
$this->session = new Session($this); $this->session = Session::create($this, $stayLoggedIn);
$this->loggedIn = $this->session->insert(); if($this->session) {
return $this->loggedIn; $this->loggedIn = true;
return true;
}
return false;
} }
public function authorize($apiKey) { public function authorize($apiKey) {
if($this->loggedIn) if($this->loggedIn)
return true; return true;
$query = 'SELECT ApiKey.uidUser as uid, User.name as username, Language.uid as langId, Language.code as langCode $query = 'SELECT ApiKey.user_id as uid, User.name as username, Language.uid as langId, Language.code as langCode
FROM ApiKey, User FROM ApiKey, User
LEFT JOIN Language ON User.uidLanguage=Language.uid LEFT JOIN Language ON User.language_id=Language.uid
WHERE api_key=? AND valid_until > now() AND User.uid = ApiKey.uidUser'; WHERE api_key=? AND valid_until > now() AND User.uid = ApiKey.user_id';
$request = new \Api\ExecuteSelect($this); $request = new \Api\ExecuteSelect($this);
$success = $request->execute(array('query' => $query, $apiKey)); $success = $request->execute(array('query' => $query, $apiKey));