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);
$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);
$this->success = $request->execute(array("query" => $query, $this->user->getId(), $apiKey));
$this->lastError = $request->getLastError();

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

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

@ -14,7 +14,7 @@ class RefreshApiKey extends Request {
private function apiKeyExists() {
$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);
$this->success = $request->execute(array("query" => $query, $id, $this->user->getId()));
$this->lastError = $request->getLastError();
@ -36,7 +36,7 @@ class RefreshApiKey extends Request {
if(!$this->apiKeyExists())
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);
$this->success = $request->execute(array("query" => $query, $id, $this->user->getId()));
$this->lastError = $request->getLastError();

@ -14,7 +14,7 @@ class RevokeApiKey extends Request {
private function apiKeyExists() {
$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);
$this->success = $request->execute(array("query" => $query, $id, $this->user->getId()));
$this->lastError = $request->getLastError();
@ -36,7 +36,7 @@ class RevokeApiKey extends Request {
if(!$this->apiKeyExists())
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);
$this->success = $request->execute(array("query" => $query, $id, $this->user->getId()));
$this->lastError = $request->getLastError();

@ -48,7 +48,7 @@ class SetLanguage extends Request {
$languageId = $this->language->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);
$this->success = $request->execute(array("query" => $query, $languageId, $userId));
$this->lastError = $request->getLastError();

@ -1,51 +1,6 @@
--
-- 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 (
`uid` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`code` VARCHAR(5) UNIQUE NOT NULL,
@ -57,6 +12,71 @@ INSERT INTO Language (`uid`, `code`, `name`) VALUES
(2, 'de_DE', 'Deutsch Standard')
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 (
`url` VARCHAR(256) PRIMARY KEY,
`data` TEXT NOT NULL,

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

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