Compare commits

..

No commits in common. "b068f4f91e1569e184a5349d85c67c78213be381" and "10ba03993828d373b602436eb639632684db94b6" have entirely different histories.

18 changed files with 208 additions and 763 deletions

View file

@ -140,6 +140,25 @@ class Application(web.Application):
return '; '.join(data) + ';'
# data = {
# 'base-uri': '\'none\'',
# 'default-src': '\'none\'',
# 'frame-ancestors': '\'none\'',
# 'font-src': f'\'self\' https://{self.config.domain}',
# 'img-src': f'\'self\' https://{self.config.domain}',
# 'style-src': f'\'self\' https://{self.config.domain} \'nonce-randomstringhere\'',
# 'media-src': f'\'self\' https://{self.config.domain}',
# 'frame-src': f'\'self\' https:',
# 'manifest-src': f'\'self\' https://{self.config.domain}',
# 'form-action': f'\'self\'',
# 'child-src': f'\'self\' https://{self.config.domain}',
# 'worker-src': f'\'self\' https://{self.config.domain}',
# 'connect-src': f'\'self\' https://{self.config.domain} wss://{self.config.domain}',
# 'script-src': f'\'self\' https://{self.config.domain}'
# }
#
# return '; '.join(f'{key} {value}' for key, value in data.items()) + ';'
def push_message(self, inbox: str, message: Message, instance: Row) -> None:
self['push_queue'].put((inbox, message, instance))
@ -286,7 +305,6 @@ async def handle_response_headers(request: web.Request, handler: Callable) -> Re
resp = await handler(request)
resp.headers['Server'] = 'ActivityRelay'
# Still have to figure out how csp headers work
# if resp.content_type == 'text/html':
# resp.headers['Content-Security-Policy'] = Application.DEFAULT.get_csp(request)

View file

@ -13,10 +13,6 @@ schemes:
- https
securityDefinitions:
Cookie:
type: apiKey
in: cookie
name: user-token
Bearer:
type: apiKey
name: Authorization
@ -553,104 +549,6 @@ paths:
schema:
$ref: "#/definitions/Error"
/v1/user:
get:
tags:
- User
description: Get a list of all local users
produces:
- application/json
responses:
"200":
description: List of users
schema:
type: array
items:
$ref: "#/definitions/User"
post:
tags:
- User
description: Create a new user
parameters:
- in: formData
name: username
required: true
type: string
- in: formData
name: password
required: true
type: string
format: password
- in: formData
name: handle
required: false
type: string
format: email
produces:
- application/json
responses:
"200":
description: Newly created user
schema:
$ref: "#/definitions/User"
"404":
description: User already exists
schema:
$ref: "#/definitions/Error"
patch:
tags:
- User
description: Update a user's password or handle
parameters:
- in: formData
name: username
required: true
type: string
- in: formData
name: password
required: false
type: string
format: password
- in: formData
name: handle
required: false
type: string
format: email
produces:
- application/json
responses:
"200":
description: Updated user data
schema:
$ref: "#/definitions/User"
"404":
description: User does not exist
schema:
$ref: "#/definitions/Error"
delete:
tags:
- User
description: Delete a user
parameters:
- in: formData
name: username
required: true
type: string
produces:
- application/json
responses:
"202":
description: Successfully deleted user
schema:
$ref: "#/definitions/Message"
"404":
description: User not found
schema:
$ref: "#/definitions/Error"
/v1/whitelist:
get:
tags:
@ -850,21 +748,6 @@ definitions:
description: Character string used for authenticating with the api
type: string
User:
type: object
properties:
username:
description: Username of the account
type: string
handle:
description: Fediverse handle associated with the account
type: string
format: email
created:
description: Date the account was created
type: string
format: date-time
Whitelist:
type: object
properties:

View file

@ -190,28 +190,13 @@ class Connection(SqlConnection):
return cur.one() # type: ignore
def put_user(self, username: str, password: str | None, handle: str | None = None) -> Row:
if self.get_user(username):
data = {
'username': username
}
if password:
data['password'] = password
if handle:
data['handler'] = handle
else:
if password is None:
raise ValueError('Password cannot be empty')
data = {
'username': username,
'hash': self.hasher.hash(password),
'handle': handle,
'created': datetime.now(tz = timezone.utc)
}
def put_user(self, username: str, password: str, handle: str | None = None) -> Row:
data = {
'username': username,
'hash': self.hasher.hash(password),
'handle': handle,
'created': datetime.now(tz = timezone.utc)
}
with self.run('put-user', data) as cur:
return cur.one() # type: ignore

View file

@ -1,29 +1,27 @@
-extends "base.haml"
-set page="Config"
-block head
%script(type="application/javascript" src="/static/config.js" nonce="{{view.request['hash']}}" defer)
-import "functions.haml" as func
-block content
%fieldset.section
%legend << Config
%form(action="/admin/config" method="POST")
.grid-2col
%label(for="name") << Name
%input(id = "name" name="name" placeholder="Relay Name" value="{{config.name or ''}}")
.grid-2col
%label(for="name") << Name
%input(id = "name" name="name" placeholder="Relay Name" value="{{config.name or ''}}")
%label(for="description") << Description
%textarea(id="description" name="note" value="{{config.note or ''}}") << {{config.note}}
%label(for="description") << Description
%textarea(id="description" name="note" value="{{config.note or ''}}") << {{config.note}}
%label(for="theme") << Color Theme
=func.new_select("theme", config.theme, themes)
%label(for="theme") << Color Theme
=func.new_select("theme", config.theme, themes)
%label(for="log-level") << Log Level
=func.new_select("log-level", config.log_level.name, levels)
%label(for="log-level") << Log Level
=func.new_select("log-level", config.log_level.name, levels)
%label(for="whitelist-enabled") << Whitelist
=func.new_checkbox("whitelist-enabled", config.whitelist_enabled)
%label(for="whitelist-enabled") << Whitelist
=func.new_checkbox("whitelist-enabled", config.whitelist_enabled)
%label(for="approval-required") << Approval Required
=func.new_checkbox("approval-required", config.approval_required)
%label(for="approval-required") << Approval Required
=func.new_checkbox("approval-required", config.approval_required)
%input(type="submit" value="Save")

View file

@ -2,20 +2,20 @@
-set page="Domain Bans"
-block head
%script(type="application/javascript" src="/static/domain_ban.js" nonce="{{view.request['hash']}}")
%script(type="application/javascript" src="/static/domain_ban.js" nonce="{{view.request['hash']}}", defer)
-block content
%details.section
%summary << Ban Domain
#add-item
%label(for="new-domain") << Domain
%input(type="domain" id="new-domain" placeholder="Domain")
%input(type="domain" id="new-domain" name="domain" placeholder="Domain")
%label(for="new-reason") << Ban Reason
%textarea(id="new-reason") << {{""}}
%textarea(id="new-reason" name="new") << {{""}}
%label(for="new-note") << Admin Note
%textarea(id="new-note") << {{""}}
%textarea(id="new-note" name="note") << {{""}}
%input(type="button" value="Ban Domain" onclick="ban();")
@ -23,7 +23,7 @@
%legend << Domain Bans
.data-table
%table
%table#table
%thead
%tr
%td.domain << Domain
@ -38,11 +38,11 @@
%summary -> =ban.domain
.grid-2col
%label.reason(for="{{ban.domain}}-reason") << Reason
%textarea.reason(id="{{ban.domain}}-reason") << {{ban.reason or ""}}
.reason << Reason
%textarea.reason(id="{{ban.domain}}-reason" name="reason") << {{ban.reason or ""}}
%label.note(for="{{ban.domain}}-note") << Note
%textarea.note(id="{{ban.domain}}-note") << {{ban.note or ""}}
.note << Note
%textarea.note(id="{{ban.domain}}-note" name="note") << {{ban.note or ""}}
%input(type="button" value="Update" onclick="update_ban('{{ban.domain}}')")
@ -50,4 +50,4 @@
=ban.created.strftime("%Y-%m-%d")
%td.remove
%a(href="#" onclick="unban('{{ban.domain}}')" title="Unban domain") << &#10006;
%a(href="#", onclick="unban('{{ban.domain}}')" title="Unban domain") << &#10006;

View file

@ -1,32 +1,29 @@
-extends "base.haml"
-set page="Instances"
-block head
%script(type="application/javascript" src="/static/instance.js" nonce="{{view.request['hash']}}")
-block content
%details.section
%summary << Add Instance
#add-item
%label(for="new-actor") << Actor
%input(type="url" id="new-actor" placeholder="Actor URL")
%form(action="/admin/instances" method="POST")
#add-item
%label(for="domain") << Domain
%input(type="domain" id="domain" name="domain" placeholder="Domain")
%label(for="new-inbox") << Inbox
%input(type="url" id="new-inbox" placeholder="Inbox URL")
%label(for="actor") << Actor URL
%input(type="url" id="actor" name="actor" placeholder="Actor URL")
%label(for="new-followid") << Follow ID
%input(type="url" id="new-followid" placeholder="Follow ID URL")
%label(for="inbox") << Inbox URL
%input(type="url" id="inbox" name="inbox" placeholder="Inbox URL")
%label(for="new-software") << Software
%input(id="new-software" placeholder="software")
%label(for="software") << Software
%input(name="software" id="software" placeholder="software")
%input(type="button" value="Add Instance", onclick="add_instance()")
%input(type="submit" value="Add Instance")
-if requests
%fieldset.section.requests
%fieldset.section
%legend << Follow Requests
.data-table
%table#requests
%table
%thead
%tr
%td.instance << Instance
@ -37,7 +34,7 @@
%tbody
-for request in requests
%tr(id="{{request.domain}}")
%tr
%td.instance
%a(href="https://{{request.domain}}" target="_new") -> =request.domain
@ -48,16 +45,16 @@
=request.created.strftime("%Y-%m-%d")
%td.approve
%a(href="#" onclick="req_response('{{request.domain}}', true)" title="Approve Request") << &check;
%a(href="/admin/instances/approve/{{request.domain}}" title="Approve Request") << &check;
%td.deny
%a(href="#" onclick="req_response('{{request.domain}}', false)" title="Deny Request") << &#10006;
%a(href="/admin/instances/deny/{{request.domain}}" title="Deny Request") << &#10006;
%fieldset.section.instances
%fieldset.section
%legend << Instances
.data-table
%table#instances
%table
%thead
%tr
%td.instance << Instance
@ -67,7 +64,7 @@
%tbody
-for instance in instances
%tr(id="{{instance.domain}}")
%tr
%td.instance
%a(href="https://{{instance.domain}}/" target="_new") -> =instance.domain
@ -78,4 +75,4 @@
=instance.created.strftime("%Y-%m-%d")
%td.remove
%a(href="#" onclick="del_instance('{{instance.domain}}')" title="Remove Instance") << &#10006;
%a(href="/admin/instances/delete/{{instance.domain}}" title="Remove Instance") << &#10006;

View file

@ -1,23 +1,20 @@
-extends "base.haml"
-set page="Software Bans"
-block head
%script(type="application/javascript" src="/static/software_ban.js" nonce="{{view.request['hash']}}")
-block content
%details.section
%summary << Ban Software
#add-item
%label(for="new-name") << Domain
%input(type="name" id="new-name" placeholder="Domain")
%form(action="/admin/software_bans" method="POST")
#add-item
%label(for="name") << Name
%input(id="name" name="name" placeholder="Name")
%label(for="new-reason") << Ban Reason
%textarea(id="new-reason") << {{""}}
%label(for="reason") << Ban Reason
%textarea(id="reason" name="reason") << {{""}}
%label(for="new-note") << Admin Note
%textarea(id="new-note") << {{""}}
%label(for="note") << Admin Note
%textarea(id="note" name="note") << {{""}}
%input(type="submit" value="Ban Software" onclick="ban()")
%input(type="submit" value="Ban Software")
%fieldset.section
%legend << Software Bans
@ -32,22 +29,23 @@
%tbody
-for ban in bans
%tr(id="{{ban.name}}")
%tr
%td.name
%details
%summary -> =ban.name
%form(action="/admin/software_bans" method="POST")
.grid-2col
.reason << Reason
%textarea.reason(id="reason" name="reason") << {{ban.reason or ""}}
.grid-2col
%label.reason(for="{{ban.name}}-reason") << Reason
%textarea.reason(id="{{ban.name}}-reason") << {{ban.reason or ""}}
.note << Note
%textarea.note(id="note" name="note") << {{ban.note or ""}}
%label.note(for="{{ban.name}}-note") << Note
%textarea.note(id="{{ban.name}}-note") << {{ban.note or ""}}
%input(type="button" value="Update" onclick="update_ban('{{ban.name}}')")
%input(type="hidden" name="name" value="{{ban.name}}")
%input(type="submit" value="Update")
%td.date
=ban.created.strftime("%Y-%m-%d")
%td.remove
%a(href="#" onclick="unban('{{ban.name}}')" title="Unban name") << &#10006;
%a(href="/admin/software_bans/delete/{{ban.name}}" title="Unban software") << &#10006;

View file

@ -1,32 +1,29 @@
-extends "base.haml"
-set page="Users"
-block head
%script(type="application/javascript" src="/static/user.js" nonce="{{view.request['hash']}}")
-block content
%details.section
%summary << Add User
#add-item
%label(for="new-username") << Username
%input(id="new-username" name="username" placeholder="Username")
%form(action="/admin/users", method="POST")
#add-item
%label(for="username") << Username
%input(id="username" name="username" placeholder="Username")
%label(for="new-password") << Password
%input(id="new-password" type="password" placeholder="Password")
%label(for="password") << Password
%input(type="password" id="password" name="password" placeholder="Password")
%label(for="new-password2") << Password Again
%input(id="new-password2" type="password" placeholder="Password Again")
%label(for="password2") << Password Again
%input(type="password" id="password2" name="password2" placeholder="Password Again")
%label(for="new-handle") << Handle
%input(id="new-handle" type="email" placeholder="handle")
%label(for="handle") << Handle
%input(type="email" name="handle" id="handle" placeholder="handle")
%input(type="button" value="Add User" onclick="add_user()")
%input(type="submit" value="Add User")
%fieldset.section
%legend << Users
.data-table
%table#users
%table
%thead
%tr
%td.username << Username
@ -36,7 +33,7 @@
%tbody
-for user in users
%tr(id="{{user.username}}")
%tr
%td.username
=user.username
@ -47,4 +44,4 @@
=user.created.strftime("%Y-%m-%d")
%td.remove
%a(href="#" onclick="del_user('{{user.username}}')" title="Remove User") << &#10006;
%a(href="/admin/users/delete/{{user.username}}" title="Remove User") << &#10006;

View file

@ -1,22 +1,19 @@
-extends "base.haml"
-set page="Whitelist"
-block head
%script(type="application/javascript" src="/static/whitelist.js" nonce="{{view.request['hash']}}")
-block content
%details.section
%summary << Add Domain
#add-item
%label(for="new-domain") << Domain
%input(type="domain" id="new-domain" placeholder="Domain")
%form(action="/admin/whitelist" method="POST")
#add-item
%label(for="domain") << Domain
%input(type="domain" id="domain" name="domain" placeholder="Domain")
%input(type="button" value="Add Domain", onclick="add_whitelist()")
%input(type="submit" value="Add Domain")
%fieldset.data-table.section
%legend << Whitelist
%table#whitelist
%table
%thead
%tr
%td.domain << Domain
@ -25,7 +22,7 @@
%tbody
-for item in whitelist
%tr(id="{{item.domain}}")
%tr
%td.domain
=item.domain
@ -33,4 +30,4 @@
=item.created.strftime("%Y-%m-%d")
%td.remove
%a(href="#" onclick="del_whitelist('{{item.domain}}')" title="Remove whitlisted domain") << &#10006;
%a(href="/admin/whitelist/delete/{{item.domain}}" title="Remove whitlisted domain") << &#10006;

View file

@ -1,3 +1,15 @@
function get_cookie(name) {
const regex = new RegExp(`(^| )` + name + `=([^;]+)`);
const match = document.cookie.match(regex);
if (match) {
return match[2]
}
return null;
}
function get_date_string(date) {
var year = date.getFullYear().toString();
var month = date.getMonth().toString();
@ -15,61 +27,64 @@ function get_date_string(date) {
}
function append_table_row(table, row_name, row) {
var table_row = table.insertRow(-1);
table_row.id = row_name;
class Client {
constructor() {
this.token = get_cookie("user-token");
}
index = 0;
for (var prop in row) {
if (Object.prototype.hasOwnProperty.call(row, prop)) {
var cell = table_row.insertCell(index);
cell.className = prop;
cell.innerHTML = row[prop];
index += 1;
async request(method, path, body = null) {
var headers = {
"Accept": "application/json"
}
}
}
if (body !== null) {
headers["Content-Type"] = "application/json"
body = JSON.stringify(body)
}
async function request(method, path, body = null) {
var headers = {
"Accept": "application/json"
}
if (this.token !== null) {
headers["Authorization"] = "Bearer " + this.token;
}
if (body !== null) {
headers["Content-Type"] = "application/json"
body = JSON.stringify(body)
}
const response = await fetch("/api/" + path, {
method: method,
mode: "cors",
cache: "no-store",
redirect: "follow",
body: body,
headers: headers
});
const message = await response.json();
if (Object.hasOwn(message, "error")) {
throw new Error(message.error);
}
if (Array.isArray(message)) {
message.forEach((msg) => {
if (Object.hasOwn(msg, "created")) {
msg.created = new Date(msg.created);
}
const response = await fetch("/api/" + path, {
method: method,
mode: "cors",
cache: "no-store",
redirect: "follow",
body: body,
headers: headers
});
} else {
const message = await response.json();
if (Object.hasOwn(message, "error")) {
throw new Error(message.error);
}
if (Object.hasOwn(message, "created")) {
message.created = new Date(message.created);
}
return message;
}
return message;
async ban(domain, reason, note) {
const params = {
"domain": domain,
"reason": reason,
"note": note
}
return await this.request("POST", "v1/domain_ban", params);
}
async unban(domain) {
const params = {"domain": domain}
return await this.request("DELETE", "v1/domain_ban", params);
}
}
client = new Client();

View file

@ -1,34 +0,0 @@
const elems = [
document.querySelector("#name"),
document.querySelector("#description"),
document.querySelector("#theme"),
document.querySelector("#log-level"),
document.querySelector("#whitelist-enabled"),
document.querySelector("#approval-required")
]
async function handle_config_change(event) {
params = {
key: event.target.id,
value: event.target.type === "checkbox" ? event.target.checked : event.target.value
}
try {
await request("POST", "v1/config", params);
} catch (error) {
alert(error);
return;
}
if (params.key === "name") {
document.querySelector("#header .title").innerHTML = params.value;
document.querySelector("title").innerHTML = params.value;
}
}
for (const elem of elems) {
elem.addEventListener("change", handle_config_change);
}

View file

@ -3,9 +3,9 @@ function create_ban_object(domain, reason, note) {
text += `<summary>${domain}</summary>\n`;
text += '<div class="grid-2col">\n';
text += `<label for="${domain}-reason" class="reason">Reason</label>\n`;
text += `<textarea id="${domain}-reason" class="reason">${reason}</textarea>\n`;
text += `<textarea id="${domain}-reason" class="reason" name="reason">${reason}</textarea>\n`;
text += `<label for="${domain}-note" class="note">Note</label>\n`;
text += `<textarea id="${domain}-note" class="note">${note}</textarea>\n`;
text += `<textarea id="${domain}-note" class="note" name="note">${note}</textarea>\n`;
text += `<input type="button" value="Update" onclick="update_ban(\"${domain}\"")">`;
text += '</details>';
@ -14,7 +14,9 @@ function create_ban_object(domain, reason, note) {
async function ban() {
var table = document.querySelector("table");
var table = document.getElementById("table");
var row = table.insertRow(-1);
var elems = {
domain: document.getElementById("new-domain"),
reason: document.getElementById("new-reason"),
@ -33,59 +35,49 @@ async function ban() {
}
try {
var ban = await request("POST", "v1/domain_ban", values);
var ban = await client.ban(values.domain, values.reason, values.note);
} catch (err) {
alert(err);
return
}
append_table_row(document.getElementById("instances"), ban.domain, {
domain: create_ban_object(ban.domain, ban.reason, ban.note),
date: get_date_string(ban.created),
remove: `<a href="#" onclick="unban('${ban.domain}')" title="Unban domain">&#10006;</a>`
});
row.id = ban.domain;
var new_domain = row.insertCell(0);
var new_date = row.insertCell(1);
var new_remove = row.insertCell(2);
new_domain.className = "domain";
new_date.className = "date";
new_remove.className = "remove";
new_domain.innerHTML = create_ban_object(ban.domain, ban.reason, ban.note);
new_date.innerHTML = get_date_string(ban.created);
new_remove.innerHTML = `<a href="#" onclick="unban('${ban.domain}')" title="Unban domain">&#10006;</a>`;
elems.domain.value = null;
elems.reason.value = null;
elems.note.value = null;
document.querySelector("details.section").open = false;
document.querySelectorAll("details.section").forEach((elem) => {
elem.open = false;
});
}
async function update_ban(domain) {
var row = document.getElementById(domain);
var elems = {
"reason": row.querySelector("textarea.reason"),
"note": row.querySelector("textarea.note")
}
var values = {
"domain": domain,
"reason": elems.reason.value,
"note": elems.note.value
}
try {
await request("PATCH", "v1/domain_ban", values)
} catch (error) {
alert(error);
return;
}
row.querySelector("details").open = false;
}
async function unban(domain) {
try {
await request("DELETE", "v1/domain_ban", {"domain": domain});
console.log(domain);
} catch (error) {
alert(error);
try {
await client.unban(domain);
} catch (err) {
alert(err);
return;
}

View file

@ -1,93 +0,0 @@
async function add_instance() {
var elems = {
actor: document.getElementById("new-actor"),
inbox: document.getElementById("new-inbox"),
followid: document.getElementById("new-followid"),
software: document.getElementById("new-software")
}
var values = {
actor: elems.actor.value.trim(),
inbox: elems.inbox.value.trim(),
followid: elems.followid.value.trim(),
software: elems.software.value.trim()
}
if (values.actor === "") {
alert("Actor is required");
return;
}
try {
var instance = await request("POST", "v1/instance", values);
} catch (err) {
alert(err);
return
}
append_table_row(document.getElementById("instances"), instance.domain, {
domain: `<a href="https://${instance.domain}/" target="_new">${instance.domain}</a>`,
software: instance.software,
date: get_date_string(instance.created),
remove: `<a href="#" onclick="del_instance('${instance.domain}')" title="Remove Instance">&#10006;</a>`
});
elems.actor.value = null;
elems.inbox.value = null;
elems.followid.value = null;
elems.software.value = null;
document.querySelector("details.section").open = false;
}
async function del_instance(domain) {
try {
await request("DELETE", "v1/instance", {"domain": domain});
} catch (error) {
alert(error);
return;
}
document.getElementById(domain).remove();
}
async function req_response(domain, accept) {
params = {
"domain": domain,
"accept": accept
}
try {
await request("POST", "v1/request", params);
} catch (error) {
alert(error);
return;
}
document.getElementById(domain).remove();
if (document.getElementById("requests").rows.length < 2) {
document.querySelector("fieldset.requests").remove()
}
if (!accept) {
return;
}
instances = await request("GET", `v1/instance`, null);
instances.forEach((instance) => {
if (instance.domain === domain) {
append_table_row(document.getElementById("instances"), instance.domain, {
domain: `<a href="https://${instance.domain}/" target="_new">${instance.domain}</a>`,
software: instance.software,
date: get_date_string(instance.created),
remove: `<a href="#" onclick="del_instance('${instance.domain}')" title="Remove Instance">&#10006;</a>`
});
}
});
}

View file

@ -1,95 +0,0 @@
function create_ban_object(name, reason, note) {
var text = '<details>\n';
text += `<summary>${name}</summary>\n`;
text += '<div class="grid-2col">\n';
text += `<label for="${name}-reason" class="reason">Reason</label>\n`;
text += `<textarea id="${name}-reason" class="reason">${reason}</textarea>\n`;
text += `<label for="${name}-note" class="note">Note</label>\n`;
text += `<textarea id="${name}-note" class="note">${note}</textarea>\n`;
text += `<input type="button" value="Update" onclick="update_ban(\"${name}\"")">`;
text += '</details>';
return text;
}
async function ban() {
var table = document.querySelector("table");
var row = table.insertRow(-1);
var elems = {
name: document.getElementById("new-name"),
reason: document.getElementById("new-reason"),
note: document.getElementById("new-note")
}
var values = {
name: elems.name.value.trim(),
reason: elems.reason.value,
note: elems.note.value
}
if (values.name === "") {
alert("Domain is required");
return;
}
try {
var ban = await request("POST", "v1/software_ban", values);
} catch (err) {
alert(err);
return
}
append_table_row(document.getElementById("instances"), ban.name, {
name: create_ban_object(ban.name, ban.reason, ban.note),
date: get_date_string(ban.created),
remove: `<a href="#" onclick="unban('${ban.domain}')" title="Unban software">&#10006;</a>`
});
elems.name.value = null;
elems.reason.value = null;
elems.note.value = null;
document.querySelector("details.section").open = false;
}
async function update_ban(name) {
var row = document.getElementById(name);
var elems = {
"reason": row.querySelector("textarea.reason"),
"note": row.querySelector("textarea.note")
}
var values = {
"name": name,
"reason": elems.reason.value,
"note": elems.note.value
}
try {
await request("PATCH", "v1/software_ban", values)
} catch (error) {
alert(error);
return;
}
row.querySelector("details").open = false;
}
async function unban(name) {
try {
await request("DELETE", "v1/software_ban", {"name": name});
} catch (error) {
alert(error);
return;
}
document.getElementById(name).remove();
}

View file

@ -1,60 +0,0 @@
async function add_user() {
var elems = {
username: document.getElementById("new-username"),
password: document.getElementById("new-password"),
password2: document.getElementById("new-password2"),
handle: document.getElementById("new-handle")
}
var values = {
username: elems.username.value.trim(),
password: elems.password.value.trim(),
password2: elems.password2.value.trim(),
handle: elems.handle.value.trim()
}
if (values.username === "" | values.password === "" | values.password2 === "") {
alert("Username, password, and password2 are required");
return;
}
if (values.password !== values.password2) {
alert("Passwords do not match");
return;
}
try {
var user = await request("POST", "v1/user", values);
} catch (err) {
alert(err);
return
}
append_table_row(document.getElementById("users"), user.username, {
domain: user.username,
handle: user.handle,
date: get_date_string(user.created),
remove: `<a href="#" onclick="del_user('${user.username}')" title="Delete User">&#10006;</a>`
});
elems.username.value = null;
elems.password.value = null;
elems.password2.value = null;
elems.handle.value = null;
document.querySelector("details.section").open = false;
}
async function del_user(username) {
try {
await request("DELETE", "v1/user", {"username": username});
} catch (error) {
alert(error);
return;
}
document.getElementById(username).remove();
}

View file

@ -1,39 +0,0 @@
async function add_whitelist() {
var domain_elem = document.getElementById("new-domain");
var domain = domain_elem.value.trim();
if (domain === "") {
alert("Domain is required");
return;
}
try {
var item = await request("POST", "v1/whitelist", {"domain": domain});
} catch (err) {
alert(err);
return
}
append_table_row(document.getElementById("whitelist"), item.domain, {
domain: item.domain,
date: get_date_string(item.created),
remove: `<a href="#" onclick="del_whitelist('${item.domain}')" title="Remove whitelisted domain">&#10006;</a>`
});
domain_elem.value = null;
document.querySelector("details.section").open = false;
}
async function del_whitelist(domain) {
try {
await request("DELETE", "v1/whitelist", {"domain": domain});
} catch (error) {
alert(error);
return;
}
document.getElementById(domain).remove();
}

View file

@ -10,7 +10,7 @@ from .base import View, register_route
from .. import __version__
from ..database import ConfigData
from ..misc import Message, Response, boolean, get_app
from ..misc import Message, Response, get_app
if typing.TYPE_CHECKING:
from aiohttp.web import Request
@ -34,11 +34,7 @@ def check_api_path(method: str, path: str) -> bool:
@web.middleware
async def handle_api_path(request: Request, handler: Callable) -> Response:
try:
if (token := request.cookies.get('user-token')):
request['token'] = token
else:
request['token'] = request.headers['Authorization'].replace('Bearer', '').strip()
request['token'] = request.headers['Authorization'].replace('Bearer', '').strip()
with get_app().database.session() as conn:
request['user'] = conn.get_user_by_token(request['token'])
@ -137,8 +133,6 @@ class Config(View):
if isinstance(data, Response):
return data
data['key'] = data['key'].replace('-', '_');
if data['key'] not in ConfigData.USER_KEYS():
return Response.new_error(400, 'Invalid key', 'json')
@ -167,7 +161,7 @@ class Config(View):
class Inbox(View):
async def get(self, request: Request) -> Response:
with self.database.session() as conn:
data = conn.get_inboxes()
data = tuple(conn.execute('SELECT * FROM inboxes').all())
return Response.new(data, ctype = 'json')
@ -192,12 +186,6 @@ class Inbox(View):
data['inbox'] = actor_data.shared_inbox
if not data.get('software'):
nodeinfo = await self.client.fetch_nodeinfo(data['domain'])
if nodeinfo is not None:
data['software'] = nodeinfo.sw_name
row = conn.put_inbox(**data)
return Response.new(row, ctype = 'json')
@ -218,7 +206,7 @@ class Inbox(View):
return Response.new(instance, ctype = 'json')
async def delete(self, request: Request) -> Response:
async def delete(self, request: Request, domain: str) -> Response:
with self.database.session() as conn:
data = await self.get_api_data(['domain'], [])
@ -244,7 +232,10 @@ class RequestView(View):
async def post(self, request: Request) -> Response:
data = await self.get_api_data(['domain', 'accept'], [])
data['accept'] = boolean(data['accept'])
if not isinstance(data['accept'], bool):
atype = type(data['accept']).__name__
return Response.new_error(400, f'Invalid type for "accept": {atype}', 'json')
try:
with self.database.session(True) as conn:
@ -283,54 +274,6 @@ class DomainBan(View):
return Response.new(bans, ctype = 'json')
async def post(self, request: Request) -> Response:
data = await self.get_api_data(['domain'], ['note', 'reason'])
if isinstance(data, Response):
return data
with self.database.session() as conn:
if conn.get_domain_ban(data['domain']):
return Response.new_error(400, 'Domain already banned', 'json')
ban = conn.put_domain_ban(**data)
return Response.new(ban, ctype = 'json')
async def patch(self, request: Request) -> Response:
with self.database.session() as conn:
data = await self.get_api_data(['domain'], ['note', 'reason'])
if isinstance(data, Response):
return data
if not conn.get_domain_ban(data['domain']):
return Response.new_error(404, 'Domain not banned', 'json')
if not any([data.get('note'), data.get('reason')]):
return Response.new_error(400, 'Must include note and/or reason parameters', 'json')
ban = conn.update_domain_ban(**data)
return Response.new(ban, ctype = 'json')
async def delete(self, request: Request) -> Response:
with self.database.session() as conn:
data = await self.get_api_data(['domain'], [])
if isinstance(data, Response):
return data
if not conn.get_domain_ban(data['domain']):
return Response.new_error(404, 'Domain not banned', 'json')
conn.del_domain_ban(data['domain'])
return Response.new({'message': 'Unbanned domain'}, ctype = 'json')
@register_route('/api/v1/software_ban')
class SoftwareBan(View):
async def get(self, request: Request) -> Response:
@ -368,7 +311,7 @@ class SoftwareBan(View):
if not any([data.get('note'), data.get('reason')]):
return Response.new_error(400, 'Must include note and/or reason parameters', 'json')
ban = conn.update_software_ban(**data)
ban = conn.update_software_ban(data['name'], **data)
return Response.new(ban, ctype = 'json')
@ -388,63 +331,6 @@ class SoftwareBan(View):
return Response.new({'message': 'Unbanned software'}, ctype = 'json')
@register_route('/api/v1/user')
class User(View):
async def get(self, request: Request) -> Response:
with self.database.session() as conn:
items = []
for row in conn.execute('SELECT * FROM users'):
del row['hash']
items.append(row)
return Response.new(items, ctype = 'json')
async def post(self, request: Request) -> Response:
data = await self.get_api_data(['username', 'password'], ['handle'])
if isinstance(data, Response):
return data
with self.database.session() as conn:
if conn.get_user(data['username']):
return Response.new_error(404, 'User already exists', 'json')
user = conn.put_user(**data)
del user['hash']
return Response.new(user, ctype = 'json')
async def patch(self, request: Request) -> Response:
data = await self.get_api_data(['username'], ['password', ['handle']])
if isinstance(data, Response):
return data
with self.database.session(True) as conn:
user = conn.put_user(**data)
del user['hash']
return Response.new(user, ctype = 'json')
async def delete(self, request: Request) -> Response:
data = await self.get_api_data(['username'], [])
if isinstance(data, Response):
return data
with self.database.session(True) as conn:
if not conn.get_user(data['username']):
return Response.new_error(404, 'User does not exist', 'json')
conn.del_user(data['username'])
return Response.new({'message': 'Deleted user'}, ctype = 'json')
@register_route('/api/v1/whitelist')
class Whitelist(View):
async def get(self, request: Request) -> Response:

View file

@ -126,7 +126,7 @@ class View(AbstractView):
return Response.new_error(400, 'Invalid JSON data', 'json')
else:
post_data = convert_data(self.request.query) # type: ignore
post_data = convert_data(await self.request.query) # type: ignore
data = {}