csrf token now default, groups improved

This commit is contained in:
Roman committed 2020-06-23 15:31:09 +02:00
1 parent 42e1ac95c8
commit a4504d8336
13 files changed
+140 -83

No files matched your search

-4
View File
@@ -41,7 +41,6 @@ namespace Api\ApiKey {
public function __construct($user, $externalCall = false) {
parent::__construct($user, $externalCall, array());
$this->apiKeyAllowed = false;
$this->csrfTokenRequired = true;
$this->loginRequired = true;
}
@@ -80,7 +79,6 @@ namespace Api\ApiKey {
public function __construct($user, $externalCall = false) {
parent::__construct($user, $externalCall, array());
$this->loginRequired = true;
$this->csrfTokenRequired = true;
}
public function execute($values = array()) {
@@ -127,7 +125,6 @@ namespace Api\ApiKey {
"id" => new Parameter("id", Parameter::TYPE_INT),
));
$this->loginRequired = true;
$this->csrfTokenRequired = true;
}
public function execute($values = array()) {
@@ -163,7 +160,6 @@ namespace Api\ApiKey {
"id" => new Parameter("id", Parameter::TYPE_INT),
));
$this->loginRequired = true;
$this->csrfTokenRequired = true;
}
public function execute($aValues = array()) {
+16 -11
View File
@@ -15,18 +15,16 @@ namespace Api\Groups {
class Fetch extends GroupsAPI {
const SELECT_SIZE = 10;
private int $groupCount;
public function __construct($user, $externalCall = false) {
parent::__construct($user, $externalCall, array(
'page' => new Parameter('page', Parameter::TYPE_INT, true, 1)
'page' => new Parameter('page', Parameter::TYPE_INT, true, 1),
'count' => new Parameter('count', Parameter::TYPE_INT, true, 20)
));
$this->loginRequired = true;
$this->requiredGroup = USER_GROUP_ADMIN;
$this->csrfTokenRequired = true;
$this->requiredGroup = array(USER_GROUP_SUPPORT, USER_GROUP_ADMIN);
$this->groupCount = 0;
}
@@ -54,19 +52,24 @@ namespace Api\Groups {
return $this->createError("Invalid page count");
}
$count = $this->getParam("count");
if($count < 1 || $count > 50) {
return $this->createError("Invalid fetch count");
}
if (!$this->getGroupCount()) {
return false;
}
$sql = $this->user->getSQL();
$res = $sql->select("Group.uid as groupId", "Group.name as groupName", $sql->count("UserGroup.user_id"))
$res = $sql->select("Group.uid as groupId", "Group.name as groupName", "Group.color as groupColor", $sql->count("UserGroup.user_id"))
->from("Group")
->innerJoin("UserGroup", "UserGroup.group_id", "Group.uid")
->leftJoin("UserGroup", "UserGroup.group_id", "Group.uid")
->groupBy("Group.uid")
->orderBy("Group.uid")
->ascending()
->limit(Fetch::SELECT_SIZE)
->offset(($page - 1) * Fetch::SELECT_SIZE)
->limit($count)
->offset(($page - 1) * $count)
->execute();
$this->success = ($res !== FALSE);
@@ -77,13 +80,15 @@ namespace Api\Groups {
foreach($res as $row) {
$groupId = intval($row["groupId"]);
$groupName = $row["groupName"];
$groupColor = $row["groupColor"];
$memberCount = $row["usergroup_user_id_count"];
$this->result["groups"][$groupId] = array(
"name" => $groupName,
"memberCount" => $memberCount
"memberCount" => $memberCount,
"color" => $groupColor,
);
}
$this->result["pageCount"] = intval(ceil($this->groupCount / Fetch::SELECT_SIZE));
$this->result["pageCount"] = intval(ceil($this->groupCount / $count));
$this->result["totalCount"] = $this->groupCount;
}
+1 -1
View File
@@ -60,7 +60,7 @@ namespace Api\Language {
'langId' => new Parameter('langId', Parameter::TYPE_INT, true, NULL),
'langCode' => new StringType('langCode', 5, true, NULL),
));
$this->csrfTokenRequired = true;
}
private function checkLanguage() {
+2 -2
View File
@@ -25,7 +25,7 @@ namespace Api\Notifications {
'message' => new StringType('message', 256),
));
$this->isPublic = false;
$this->csrfTokenRequired = true;
}
private function checkUser($userId) {
@@ -148,7 +148,7 @@ namespace Api\Notifications {
public function __construct($user, $externalCall = false) {
parent::__construct($user, $externalCall, array());
$this->loginRequired = true;
$this->csrfTokenRequired = true;
}
private function fetchUserNotifications() {
+10 -7
View File
@@ -16,7 +16,7 @@ class Request {
protected bool $variableParamCount;
protected bool $isDisabled;
protected bool $apiKeyAllowed;
protected int $requiredGroup;
protected array $requiredGroup;
protected bool $csrfTokenRequired;
private array $aDefaultParams;
@@ -36,9 +36,9 @@ class Request {
$this->variableParamCount = false;
$this->apiKeyAllowed = true;
$this->allowedMethods = array("GET", "POST");
$this->requiredGroup = 0;
$this->requiredGroup = array();
$this->lastError = "";
$this->csrfTokenRequired = false;
$this->csrfTokenRequired = true;
}
protected function forbidMethod($method) {
@@ -118,7 +118,7 @@ class Request {
return false;
}
if($this->loginRequired || $this->requiredGroup > 0) {
if($this->loginRequired || !empty($this->requiredGroup)) {
$apiKeyAuthorized = false;
if(isset($values['api_key']) && $this->apiKeyAllowed) {
$apiKey = $values['api_key'];
@@ -129,8 +129,9 @@ class Request {
$this->lastError = 'You are not logged in.';
header('HTTP 1.1 401 Unauthorized');
return false;
} else if($this->requiredGroup > 0 && !$this->user->hasGroup($this->requiredGroup)) {
$this->lastError = "Insufficient permissions. Required group: ". GroupName($this->requiredGroup);
} else if(!empty($this->requiredGroup) && !empty(array_intersect($this->requiredGroup, $this->user->getGroups()))) {
$this->lastError = "Insufficient permissions. Required group: "
. implode(", ", array_map(function ($group) { return GroupName($group); }, $this->requiredGroup));
header('HTTP 1.1 401 Unauthorized');
return false;
} else if($this->csrfTokenRequired && !$apiKeyAuthorized && $this->externalCall) {
@@ -166,7 +167,9 @@ class Request {
return false;
}
protected function getParam($name) { return isset($this->params[$name]) ? $this->params[$name]->value : NULL; }
protected function getParam($name) {
return isset($this->params[$name]) ? $this->params[$name]->value : NULL;
}
public function isPublic() { return $this->isPublic; }
public function getLastError() { return $this->lastError; }
+2 -3
View File
@@ -33,7 +33,7 @@ namespace Api\Routes {
public function __construct($user, $externalCall = false) {
parent::__construct($user, $externalCall, array());
$this->loginRequired = true;
$this->csrfTokenRequired = true;
}
public function execute($values = array()) {
@@ -135,8 +135,7 @@ namespace Api\Routes {
));
$this->loginRequired = true;
$this->csrfTokenRequired = true;
$this->requiredGroup = USER_GROUP_ADMIN;
$this->requiredGroup = array(USER_GROUP_ADMIN);
}
public function execute($values = array()) {
+2 -2
View File
@@ -9,9 +9,9 @@ class Stats extends Request {
public function __construct($user, $externalCall = false) {
parent::__construct($user, $externalCall, array());
$this->csrfTokenRequired = true;
$this->loginRequired = true;
$this->requiredGroup = USER_GROUP_ADMIN;
$this->requiredGroup = array(USER_GROUP_SUPPORT, USER_GROUP_ADMIN);
}
private function getUserCount() {
+45 -32
View File
@@ -51,6 +51,25 @@ namespace Api {
protected function hashPassword($password, $salt) {
return hash('sha256', $password . $salt);
}
protected function checkToken($token) {
$sql = $this->user->getSQL();
$res = $sql->select("UserToken.token_type", "User.name", "User.email")
->from("UserToken")
->innerJoin("User", "UserToken.user_id", "User.uid")
->where(new Compare("UserToken.token", $token))
->where(new Compare("UserToken.valid_until", $sql->now(), ">"))
->where(new Compare("UserToken.used", 0))
->execute();
$this->lastError = $sql->getLastError();
$this->success = ($res !== FALSE);
if ($this->success && !empty($res)) {
return $res[0];
}
return array();
}
}
}
@@ -63,8 +82,6 @@ namespace Api\User {
use Api\UserAPI;
use DateTime;
use Driver\SQL\Condition\Compare;
use Driver\SQL\Condition\CondBool;
use Views\Account\ConfirmEmail;
class Create extends UserAPI {
@@ -75,9 +92,9 @@ namespace Api\User {
'password' => new StringType('password'),
'confirmPassword' => new StringType('confirmPassword'),
));
$this->csrfTokenRequired = true;
$this->loginRequired = true;
$this->requiredGroup = USER_GROUP_ADMIN;
$this->requiredGroup = array(USER_GROUP_ADMIN);
}
public function execute($values = array()) {
@@ -103,20 +120,18 @@ namespace Api\User {
class Fetch extends UserAPI {
const SELECT_SIZE = 10;
private int $userCount;
public function __construct($user, $externalCall = false) {
parent::__construct($user, $externalCall, array(
'page' => new Parameter('page', Parameter::TYPE_INT, true, 1)
'page' => new Parameter('page', Parameter::TYPE_INT, true, 1),
'count' => new Parameter('count', Parameter::TYPE_INT, true, 20),
));
$this->loginRequired = true;
$this->requiredGroup = USER_GROUP_ADMIN;
$this->requiredGroup = array(USER_GROUP_SUPPORT, USER_GROUP_ADMIN);
$this->userCount = 0;
$this->csrfTokenRequired = true;
}
private function getUserCount() {
@@ -143,20 +158,25 @@ namespace Api\User {
return $this->createError("Invalid page count");
}
$count = $this->getParam("count");
if ($count < 1 || $count > 50) {
return $this->createError("Invalid fetch count");
}
if (!$this->getUserCount()) {
return false;
}
$sql = $this->user->getSQL();
$res = $sql->select("User.uid as userId", "User.name", "User.email", "User.registered_at",
"Group.uid as groupId", "Group.name as groupName")
"Group.uid as groupId", "Group.name as groupName", "Group.color as groupColor")
->from("User")
->leftJoin("UserGroup", "User.uid", "UserGroup.user_id")
->leftJoin("Group", "Group.uid", "UserGroup.group_id")
->orderBy("User.uid")
->ascending()
->limit(Fetch::SELECT_SIZE)
->offset(($page - 1) * Fetch::SELECT_SIZE)
->limit($count)
->offset(($page - 1) * $count)
->execute();
$this->success = ($res !== FALSE);
@@ -168,6 +188,7 @@ namespace Api\User {
$userId = intval($row["userId"]);
$groupId = intval($row["groupId"]);
$groupName = $row["groupName"];
$groupColor = $row["groupColor"];
if (!isset($this->result["users"][$userId])) {
$this->result["users"][$userId] = array(
"uid" => $userId,
@@ -179,10 +200,13 @@ namespace Api\User {
}
if (!is_null($groupId)) {
$this->result["users"][$userId]["groups"][$groupId] = $groupName;
$this->result["users"][$userId]["groups"][$groupId] = array(
"name" => $groupName,
"color" => $groupColor
);
}
}
$this->result["pageCount"] = intval(ceil($this->userCount / Fetch::SELECT_SIZE));
$this->result["pageCount"] = intval(ceil($this->userCount / $count));
$this->result["totalCount"] = $this->userCount;
}
@@ -194,7 +218,7 @@ namespace Api\User {
public function __construct($user, $externalCall = false) {
parent::__construct($user, $externalCall, array());
$this->csrfTokenRequired = true;
$this->csrfTokenRequired = false;
}
public function execute($values = array()) {
@@ -220,9 +244,9 @@ namespace Api\User {
'username' => new StringType('username', 32),
'email' => new StringType('email', 64),
));
$this->csrfTokenRequired = true;
$this->loginRequired = true;
$this->requiredGroup = USER_GROUP_ADMIN;
$this->requiredGroup = array(USER_GROUP_ADMIN);
}
public function execute($values = array()) {
@@ -344,7 +368,6 @@ If the invitation was not intended, you can simply ignore this email.<br><br><a
parent::__construct($user, $externalCall);
$this->loginRequired = true;
$this->apiKeyAllowed = false;
$this->csrfTokenRequired = true;
}
public function execute($values = array()) {
@@ -453,22 +476,12 @@ If the registration was not intended, you can simply ignore this email.<br><br><
}
$token = $this->getParam('token');
$sql = $this->user->getSQL();
$res = $sql->select("UserToken.token_type", "User.name", "User.email")
->from("UserToken")
->innerJoin("User", "UserToken.user_id", "User.uid")
->where(new Compare("UserToken.token", $token))
->where(new Compare("UserToken.valid_until", $sql->now(), ">"))
->where(new Compare("UserToken.used", 0))
->execute();
$this->lastError = $sql->getLastError();
$this->success = ($res !== FALSE);
$tokenEntry = $this->checkToken($token);
if ($this->success) {
if (count($res) > 0) {
$row = $res[0];
$this->result["token"] = array("type" => $row["token_type"]);
$this->result["user"] = array("name" => $row["name"], "email" => $row["email"]);
if (!empty($tokenEntry)) {
$this->result["token"] = array("type" => $tokenEntry["token_type"]);
$this->result["user"] = array("name" => $tokenEntry["name"], "email" => $tokenEntry["email"]);
} else {
return $this->createError("This token does not exist or is no longer valid");
}
+6 -4
View File
@@ -68,12 +68,14 @@ class CreateDatabase {
$queries[] = $sql->createTable("Group")
->addSerial("uid")
->addString("name", 32)
->addString("color", 10)
->primaryKey("uid")
->unique("name");
$queries[] = $sql->insert("Group", array("uid", "name"))
->addRow(USER_GROUP_DEFAULT, USER_GROUP_DEFAULT_NAME)
->addRow(USER_GROUP_ADMIN, USER_GROUP_ADMIN_NAME);
$queries[] = $sql->insert("Group", array("uid", "name", "color"))
->addRow(USER_GROUP_MODERATOR, USER_GROUP_MODERATOR_NAME, "#007bff")
->addRow(USER_GROUP_SUPPORT, USER_GROUP_SUPPORT_NAME, "#28a745")
->addRow(USER_GROUP_ADMIN, USER_GROUP_ADMIN_NAME, "#dc3545");
$queries[] = $sql->createTable("UserGroup")
->addInt("user_id")
@@ -130,7 +132,7 @@ class CreateDatabase {
->primaryKey("uid");
$queries[] = $sql->insert("Route", array("request", "action", "target", "extra"))
->addRow("^/admin(/.*)?$", "dynamic", "\\Documents\\AdminDashboard", NULL)
->addRow("^/admin(/.*)?$", "dynamic", "\\Documents\\Admin", NULL)
->addRow("^/register(/)?$", "dynamic", "\\Documents\\Account", "\\Views\\Account\\Register")
->addRow("^/confirmEmail(/)?$", "dynamic", "\\Documents\\Account", "\\Views\\Account\\ConfirmEmail")
->addRow("^/acceptInvite(/)?$", "dynamic", "\\Documents\\Account", "\\Views\\Account\\AcceptInvite")
+7 -4
View File
@@ -1,13 +1,16 @@
<?php
const USER_GROUP_DEFAULT = 1;
const USER_GROUP_DEFAULT_NAME = "Default";
const USER_GROUP_ADMIN = 2;
const USER_GROUP_MODERATOR = 1;
const USER_GROUP_MODERATOR_NAME = "Moderator";
const USER_GROUP_SUPPORT = 2;
const USER_GROUP_SUPPORT_NAME = "Support";
const USER_GROUP_ADMIN = 3;
const USER_GROUP_ADMIN_NAME = "Administrator";
function GroupName($index) {
$groupNames = array(
USER_GROUP_DEFAULT => USER_GROUP_DEFAULT_NAME,
USER_GROUP_MODERATOR => USER_GROUP_MODERATOR_NAME,
USER_GROUP_SUPPORT => USER_GROUP_SUPPORT_NAME,
USER_GROUP_ADMIN => USER_GROUP_ADMIN_NAME,
);
+2 -2
View File
@@ -7559,7 +7559,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) *
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return API; });\n/* harmony import */ var babel_polyfill__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babel-polyfill */ \"./node_modules/babel-polyfill/lib/index.js\");\n/* harmony import */ var babel_polyfill__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babel_polyfill__WEBPACK_IMPORTED_MODULE_0__);\nfunction asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }\n\nfunction _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err); } _next(undefined); }); }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\n\n\nvar API = /*#__PURE__*/function () {\n function API() {\n _classCallCheck(this, API);\n\n this.loggedIn = false;\n this.user = {};\n }\n\n _createClass(API, [{\n key: \"csrfToken\",\n value: function csrfToken() {\n return this.loggedIn ? this.user.session.csrf_token : null;\n }\n }, {\n key: \"apiCall\",\n value: function () {\n var _apiCall = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(method, params) {\n var response, res;\n return regeneratorRuntime.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n params = params || {};\n params.csrf_token = this.csrfToken();\n _context.next = 4;\n return fetch(\"/api/\" + method, {\n method: 'post',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(params)\n });\n\n case 4:\n response = _context.sent;\n _context.next = 7;\n return response.json();\n\n case 7:\n res = _context.sent;\n\n if (!res.success && res.msg === \"You are not logged in.\") {\n document.location.reload();\n }\n\n return _context.abrupt(\"return\", res);\n\n case 10:\n case \"end\":\n return _context.stop();\n }\n }\n }, _callee, this);\n }));\n\n function apiCall(_x, _x2) {\n return _apiCall.apply(this, arguments);\n }\n\n return apiCall;\n }()\n }, {\n key: \"fetchUser\",\n value: function () {\n var _fetchUser = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {\n var response, data;\n return regeneratorRuntime.wrap(function _callee2$(_context2) {\n while (1) {\n switch (_context2.prev = _context2.next) {\n case 0:\n _context2.next = 2;\n return fetch(\"/api/user/info\");\n\n case 2:\n response = _context2.sent;\n _context2.next = 5;\n return response.json();\n\n case 5:\n data = _context2.sent;\n this.user = data[\"user\"];\n this.loggedIn = data[\"loggedIn\"];\n return _context2.abrupt(\"return\", data && data.success && data.loggedIn);\n\n case 9:\n case \"end\":\n return _context2.stop();\n }\n }\n }, _callee2, this);\n }));\n\n function fetchUser() {\n return _fetchUser.apply(this, arguments);\n }\n\n return fetchUser;\n }()\n }, {\n key: \"logout\",\n value: function () {\n var _logout = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {\n return regeneratorRuntime.wrap(function _calleeLine truncated
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return API; });\n/* harmony import */ var babel_polyfill__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babel-polyfill */ \"./node_modules/babel-polyfill/lib/index.js\");\n/* harmony import */ var babel_polyfill__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babel_polyfill__WEBPACK_IMPORTED_MODULE_0__);\nfunction asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }\n\nfunction _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err); } _next(undefined); }); }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\n\n\nvar API = /*#__PURE__*/function () {\n function API() {\n _classCallCheck(this, API);\n\n this.loggedIn = false;\n this.user = {};\n }\n\n _createClass(API, [{\n key: \"csrfToken\",\n value: function csrfToken() {\n return this.loggedIn ? this.user.session.csrf_token : null;\n }\n }, {\n key: \"apiCall\",\n value: function () {\n var _apiCall = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(method, params) {\n var response, res;\n return regeneratorRuntime.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n params = params || {};\n params.csrf_token = this.csrfToken();\n _context.next = 4;\n return fetch(\"/api/\" + method, {\n method: 'post',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(params)\n });\n\n case 4:\n response = _context.sent;\n _context.next = 7;\n return response.json();\n\n case 7:\n res = _context.sent;\n\n if (!res.success && res.msg === \"You are not logged in.\") {\n document.location.reload();\n }\n\n return _context.abrupt(\"return\", res);\n\n case 10:\n case \"end\":\n return _context.stop();\n }\n }\n }, _callee, this);\n }));\n\n function apiCall(_x, _x2) {\n return _apiCall.apply(this, arguments);\n }\n\n return apiCall;\n }()\n }, {\n key: \"fetchUser\",\n value: function () {\n var _fetchUser = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {\n var response, data;\n return regeneratorRuntime.wrap(function _callee2$(_context2) {\n while (1) {\n switch (_context2.prev = _context2.next) {\n case 0:\n _context2.next = 2;\n return fetch(\"/api/user/info\");\n\n case 2:\n response = _context2.sent;\n _context2.next = 5;\n return response.json();\n\n case 5:\n data = _context2.sent;\n this.user = data[\"user\"];\n this.loggedIn = data[\"loggedIn\"];\n return _context2.abrupt(\"return\", data && data.success && data.loggedIn);\n\n case 9:\n case \"end\":\n return _context2.stop();\n }\n }\n }, _callee2, this);\n }));\n\n function fetchUser() {\n return _fetchUser.apply(this, arguments);\n }\n\n return fetchUser;\n }()\n }, {\n key: \"logout\",\n value: function () {\n var _logout = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {\n return regeneratorRuntime.wrap(function _calleeLine truncated
/***/ }),
@@ -7749,7 +7749,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) *
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return UserOverview; });\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _elements_icon__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../elements/icon */ \"./src/elements/icon.js\");\n/* harmony import */ var react_router_dom__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-router-dom */ \"./node_modules/react-router-dom/esm/react-router-dom.js\");\n/* harmony import */ var _global__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../global */ \"./src/global.js\");\n/* harmony import */ var _elements_alert__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../elements/alert */ \"./src/elements/alert.js\");\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !ReflectLine truncated
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return UserOverview; });\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _elements_icon__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../elements/icon */ \"./src/elements/icon.js\");\n/* harmony import */ var react_router_dom__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-router-dom */ \"./node_modules/react-router-dom/esm/react-router-dom.js\");\n/* harmony import */ var _global__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../global */ \"./src/global.js\");\n/* harmony import */ var _elements_alert__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../elements/alert */ \"./src/elements/alert.js\");\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !ReflectLine truncated
/***/ })
+4 -4
View File
@@ -43,12 +43,12 @@ export default class API {
return this.apiCall("notifications/fetch");
}
async fetchUsers(pageNum = 1) {
return this.apiCall("user/fetch", { page: pageNum });
async fetchUsers(pageNum = 1, count = 20) {
return this.apiCall("user/fetch", { page: pageNum, count: count });
}
async fetchGroups(pageNum = 1) {
return this.apiCall("groups/fetch", { page: pageNum });
async fetchGroups(pageNum = 1, count = 20) {
return this.apiCall("groups/fetch", { page: pageNum, count: count });
}
async inviteUser(username, email) {
+43 -7
View File
@@ -4,6 +4,8 @@ import {Link} from "react-router-dom";
import {getPeriodString} from "../global";
import Alert from "../elements/alert";
const TABLE_SIZE = 10;
export default class UserOverview extends React.Component {
constructor(props) {
@@ -28,12 +30,13 @@ export default class UserOverview extends React.Component {
},
errors: []
};
this.rowCount = 0;
}
fetchGroups(page) {
page = page || this.state.groups.page;
this.setState({...this.state, groups: {...this.state.groups, data: {}, page: 1, totalCount: 0}});
this.parent.api.fetchGroups(page).then((res) => {
this.parent.api.fetchGroups(page, TABLE_SIZE).then((res) => {
if (res.success) {
this.setState({
...this.state,
@@ -44,6 +47,7 @@ export default class UserOverview extends React.Component {
totalCount: res.totalCount,
}
});
this.rowCount = Math.max(this.rowCount, Object.keys(res.groups).length);
} else {
let errors = this.state.errors.slice();
errors.push({title: "Error fetching groups", message: res.msg});
@@ -61,7 +65,7 @@ export default class UserOverview extends React.Component {
fetchUsers(page) {
page = page || this.state.users.page;
this.setState({...this.state, users: {...this.state.users, data: {}, pageCount: 1, totalCount: 0}});
this.parent.api.fetchUsers(page).then((res) => {
this.parent.api.fetchUsers(page, TABLE_SIZE).then((res) => {
if (res.success) {
this.setState({
...this.state,
@@ -73,6 +77,7 @@ export default class UserOverview extends React.Component {
totalCount: res.totalCount,
}
});
this.rowCount = Math.max(this.rowCount, Object.keys(res.groups).length);
} else {
let errors = this.state.errors.slice();
errors.push({title: "Error fetching users", message: res.msg});
@@ -156,9 +161,13 @@ export default class UserOverview extends React.Component {
for (let groupId in user.groups) {
if (user.groups.hasOwnProperty(groupId)) {
let groupName = user.groups[groupId];
let color = (groupId === "1" ? "danger" : "secondary");
groups.push(<span key={"group-" + groupId} className={"mr-1 badge badge-" + color}>{groupName}</span>);
let groupName = user.groups[groupId].name;
let groupColor = user.groups[groupId].color;
groups.push(
<span key={"group-" + groupId} className={"mr-1 badge text-white"} style={{backgroundColor: groupColor}}>
{groupName}
</span>
);
}
}
@@ -172,6 +181,17 @@ export default class UserOverview extends React.Component {
);
}
while(userRows.length < this.rowCount) {
userRows.push(
<tr key={"empty-row-" + userRows.length}>
<td>&nbsp;</td>
<td/>
<td/>
<td/>
</tr>
);
}
let pages = [];
let previousDisabled = (this.state.users.page === 1 ? " disabled" : "");
let nextDisabled = (this.state.users.page >= this.state.users.pageCount ? " disabled" : "");
@@ -251,7 +271,22 @@ export default class UserOverview extends React.Component {
groupRows.push(
<tr key={"group-" + uid}>
<td>{group.name}</td>
<td>{group.memberCount}</td>
<td className={"text-center"}>{group.memberCount}</td>
<td>
<span className={"badge text-white mr-1"} style={{backgroundColor: group.color}}>
{group.color}
</span>
</td>
</tr>
);
}
while(groupRows.length < this.rowCount) {
groupRows.push(
<tr key={"empty-row-" + groupRows.length}>
<td>&nbsp;</td>
<td/>
<td/>
</tr>
);
}
@@ -288,7 +323,8 @@ export default class UserOverview extends React.Component {
<thead>
<tr>
<th>Name</th>
<th>Members</th>
<th className={"text-center"}>Members</th>
<th>Color</th>
</tr>
</thead>
<tbody>