Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[New] Now possible to add users from content server dashboard #54

Merged
merged 1 commit into from
Mar 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions Content Server/components/table/table.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { Component } from 'react';
import React from 'react';
import 'tailwindcss/tailwind.css';
import equal from 'fast-deep-equal';


export default class Table extends Component {
constructor(props) {
super(props);
this.title = props.title;

this.state = {
columns: this.props.columns ? this.props.columns : [],
data: this.props.data ? this.props.data : []
}
}

componentDidUpdate(prevProps, prevState) {
if (!equal(this.props.data, prevProps.data)) {
this.setState({
data: this.props.data
});
}
}

renderData(row, columnIndex) {
for (const column of row) {
if (column.key === this.state.columns[columnIndex].key) {
if (this.state.columns[columnIndex].dataRender) {
return this.state.columns[columnIndex].dataRender(column);
} else {
return (
<td className="px-6 py-4 whitespace-nowrap">
<div className="flex items-center">
<div className="ml-4">
<div className="text-sm font-medium text-white">{column.value}</div>
</div>
</div>
</td>
)
}
}
}
}

render() {
return (
<>
<h1>{this.title}</h1>
<br />
<div className="flex flex-col">
<div className="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
<div className="py-2 align-middle inline-block min-w-full sm:px-6 lg:px-8">
<div className="shadow overflow-hidden border-b border-gray-900 sm:rounded-lg">
<table className="min-w-full divide-y divide-gray-900">
<thead className="bg-gray-800">
<tr scope="col">
{this.state.columns.map(column => (
column.render ? column.render(column.title) : column.title
))}
</tr>
</thead>
<tbody className=" bg-gray-800 divide-y divide-gray-900">
{this.state.data.map((row, rowNum) => {

return (
<tr key={rowNum}>
{row.map((column, columnNum) => {
return this.renderData(row, columnNum);
})}
</tr>
)
})}
</tbody>
</table>
</div>
</div>
</div>
</div>
</>
)
}
}
6 changes: 6 additions & 0 deletions Content Server/files/dump.sql
Original file line number Diff line number Diff line change
Expand Up @@ -528,3 +528,9 @@ create table main_server_requests
create unique index main_server_requests_id_uindex
on main_server_requests (id);

create table general
(
server_name text not null,
main_server_ip text not null
);

1 change: 1 addition & 0 deletions Content Server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"eol": "^0.9.1",
"esm": "^3.2.25",
"express": "^4.17.1",
"fast-deep-equal": "^3.1.3",
"fluent-ffmpeg": "^2.1.2",
"fs-extra": "^10.0.0",
"glob": "^7.1.6",
Expand Down
38 changes: 25 additions & 13 deletions Content Server/pages/api/dashboard/setup/account.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,12 @@ const reportToMainServer = (mainServerUrl, contentServerIp, contentServerName) =
});
}
})
.catch(err => {
reject({
code: -1,
error: err
.catch(err => {
reject({
code: -1,
error: err
})
})
})
});
});
}
Expand All @@ -55,6 +55,14 @@ const addAdminAccount = (username, password) => {
});
}

const saveGeneralInfo = (serverName, mainServerIp) => {
return new Promise(resolve => {
db.none('INSERT INTO general (server_name, main_server_ip) VALUES ($1, $2)', [serverName, mainServerIp]).then(() => {
resolve();
});
});
}

const saveToConfigFile = (config, mainServerUrl) => {
return new Promise((resolve, reject) => {
config.getConfig().then(info => {
Expand Down Expand Up @@ -108,11 +116,13 @@ export default async (req, res) => {
reportToMainServer(mainServerUrl, contentServerIp, contentServerName).then(() => {
addAdminAccount(username, password).then(() => {
saveToConfigFile(config, mainServerUrl).then(() => {
CommonEvent.emit('setup.done');
res.status(200).json({
success: true
saveGeneralInfo(contentServerName, mainServerUrl).then(() => {
CommonEvent.emit('setup.done');
res.status(200).json({
success: true
});
resolve();
});
resolve();
}).catch(err => {
// Error writing to config file
res.status(500).send({ success: false, error: "Couldn't write to config file" });
Expand All @@ -132,11 +142,13 @@ export default async (req, res) => {
logger.WARNING(`Server ${contentServerIp} is already added on the main server, continuing anyway`);
addAdminAccount(username, password).then(() => {
saveToConfigFile(config, mainServerUrl).then(() => {
CommonEvent.emit('setup.done');
res.status(200).json({
success: true
saveGeneralInfo(contentServerName, mainServerUrl).then(() => {
CommonEvent.emit('setup.done');
res.status(200).json({
success: true
});
resolve();
});
resolve();
}).catch(err => {
// Error writing to config file
res.status(500).send({ success: false, error: "Couldn't write to config file" });
Expand Down
27 changes: 27 additions & 0 deletions Content Server/pages/api/dashboard/users/access.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const db = require('../../../../lib/db');
const cors = require('../../../../lib/cors');
const validateUser = require('../../../../lib/validateUser');

export default (req, res) => {
return new Promise(resolve => {
if (req.method !== 'POST') {
res.status(405).send({ message: 'Only POST requests allowed' })
return
}
const { token, id, access } = req.body;
const setValue = access ? true : false; // Convert to boolean if weird data was sent in
res = cors(res);

if (!validateUser(token, process.env.DASHBOARD_SECRET)) {
console.log("nope" + token)
res.status(403).end();
return;
}

db.none(`UPDATE users SET has_access = $1 WHERE id = $2`, [setValue, id])
.then(data => {
res.status(200).json(data);
resolve();
});
});
}
104 changes: 104 additions & 0 deletions Content Server/pages/api/dashboard/users/create.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import MainServerRequestHandler from '../../../../lib/requests/MainServerRequestHandler';

const db = require('../../../../lib/db');
const hash = require('../../../../lib/hash');
const validateUser = require('../../../../lib/validateUser');
const Logger = require('../../../../lib/logger');
const logger = new Logger();

const addUserToMainServer = (mainServerUrl, serverName, username) => {
return new Promise((resolve, reject) => {
const requestHandler = new MainServerRequestHandler();
requestHandler.addExpectedRequest().then(id => {
fetch(`${mainServerUrl}/api/servers/users/add`, {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({
id: id,
serverName: serverName,
username: username
})
}).then(res => res.json()).then(result => {
if (result.success) {
resolve();
} else {
reject({
error: result.error,
code: result.code
});
}
}).catch(err => {
reject({
code: -1,
error: err
});
});
});
});
}

const getGeneralInfo = () => {
return new Promise((resolve, reject) => {
db.one('SELECT * FROM general').then(result => {
resolve(result);
})
});
}


export default (req, res) => {
const { username, token } = req.body;
if (!validateUser(token, process.env.DASHBOARD_SECRET)) {
res.status(403).json({
success: false,
error: 'Invalid token'
});
return;
} else if (!username) {
res.status(400).json({
success: false,
error: 'Missing username'
});
return;
}

return new Promise(async (resolve) => {
const generalInfo = await getGeneralInfo();
const mainServerUrl = generalInfo.main_server_ip;
const serverName = generalInfo.server_name;

addUserToMainServer(mainServerUrl, serverName, username).then(() => {
db.any(`SELECT * FROM users WHERE username = $1`, [username]).then(data => {
if (data.length > 0) {
logger.DEBUG(`User ${username} already exists`);
res.status(406).json({
success: false,
error: 'User already exists'
}); // 406 Not Acceptable
return;
}
db.none('INSERT INTO users (username, has_access) VALUES ($1, $2)', [username, true]).then(() => {
res.status(200).json({
success: true
});
logger.INFO(`Added user with username ${username}`);
resolve();
}).catch(err => {
logger.ERROR(`Failed to add user with username ${username}. ${err}`);
res.status(500).json({
success: false,
error: err
});
resolve();
});
});
}).catch(err => {
res.status(406).json({
success: false,
error: err.error
});
});
});
}
71 changes: 71 additions & 0 deletions Content Server/pages/api/dashboard/users/delete.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import Logger from '../../../../lib/logger';
import MainServerRequestHandler from '../../../../lib/requests/MainServerRequestHandler';
const logger = new Logger();

const db = require('../../../../lib/db');
const cors = require('../../../../lib/cors');
const validateUser = require('../../../../lib/validateUser');

const getGeneralInfo = () => {
return new Promise((resolve, reject) => {
db.one('SELECT * FROM general').then(result => {
resolve(result);
})
});
}

const removeUserFromMainServer = (mainServerUrl, serverName, username) => {
return new Promise((resolve, reject) => {
const requestHandler = new MainServerRequestHandler();
requestHandler.addExpectedRequest().then(id => {
fetch(`${mainServerUrl}/api/servers/users/delete`, {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({
id: id,
serverName: serverName,
username: username
})
}).then(res => res.json()).then(result => {
if (result.success) {
resolve();
} else {
reject({
error: result.error,
code: result.code
});
}
}).catch(err => {
reject({
code: -1,
error: err
});
});
});
});
}
export default async (req, res) => {
res = cors(res);
const { token, id, username } = req.body;

if (!validateUser(token, process.env.DASHBOARD_SECRET)) {
res.status(403).end();
return;
}

const generalInfo = await getGeneralInfo();
const mainServerUrl = generalInfo.main_server_ip;
const serverName = generalInfo.server_name;
removeUserFromMainServer(mainServerUrl, serverName, username).then(() => {
db.none(`DELETE FROM users WHERE id = $1`, [id]);
logger.INFO(`Deleted user with id ${id}`);
res.status(200).json();
}).catch(err => {
res.status(406).json({
success: false,
error: err.error
});
});
}
Loading