csrf token now default, groups improved

This commit is contained in:
Roman Hergenreder 2020-06-23 15:31:09 +02:00
parent 42e1ac95c8
commit a4504d8336
13 changed files with 140 additions and 83 deletions

@ -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()) {

@ -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;
}

@ -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() {

@ -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() {

@ -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; }

@ -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()) {

@ -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() {

@ -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");
}

@ -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")

@ -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,
);

4
js/admin.min.js vendored

File diff suppressed because one or more lines are too long

@ -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) {

@ -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>