mirror of
https://git.ugnet.gay/CrossTalk/azul.git
synced 2026-11-25 08:30:04 +00:00
0.6 final
This commit is contained in:
1 parent
7c0581eb97
commit
b89e1932bb
160 files changed
+20534
-4664
No files matched your search
@@ -0,0 +1 @@
|
||||
from .entry import register
|
||||
@@ -0,0 +1,127 @@
|
||||
from collections import deque
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Deque, Dict, List, Optional, Tuple
|
||||
import asyncio, hashlib, hmac, secrets, time
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
import core.db as db
|
||||
from util import hash
|
||||
import settings
|
||||
|
||||
COOKIE_NAME = 'azul_admin'
|
||||
_DUMMY_HASH: Optional[str] = None
|
||||
MAX_FAILURES = 5
|
||||
FAIL_WINDOW = 900
|
||||
|
||||
@dataclass
|
||||
class AdminSession:
|
||||
token: str
|
||||
uuid: str
|
||||
username: str
|
||||
csrf: str
|
||||
expires: float
|
||||
address: str
|
||||
flashes: List[Tuple[str, str]] = field(default_factory = list)
|
||||
reveal: Optional[Dict[str, str]] = None
|
||||
|
||||
def flash(self, text: str, kind: str = 'success') -> None:
|
||||
self.flashes.append((kind, text))
|
||||
|
||||
def take_flashes(self) -> List[Tuple[str, str]]:
|
||||
flashes, self.flashes = self.flashes, []
|
||||
return flashes
|
||||
|
||||
def take_reveal(self) -> Optional[Dict[str, str]]:
|
||||
reveal, self.reveal = self.reveal, None
|
||||
return reveal
|
||||
|
||||
class AdminAuth:
|
||||
__slots__ = ('_sessions', '_failures')
|
||||
|
||||
_sessions: Dict[str, AdminSession]
|
||||
_failures: Dict[str, Deque[float]]
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._sessions = {}
|
||||
self._failures = {}
|
||||
|
||||
@staticmethod
|
||||
def configured() -> bool:
|
||||
return len(str(getattr(settings, 'ADMIN_KEY', '') or '')) == 64
|
||||
|
||||
@staticmethod
|
||||
def key_matches(key: str) -> bool:
|
||||
expected = str(getattr(settings, 'ADMIN_KEY', '') or '').lower()
|
||||
if len(expected) != 64:
|
||||
return False
|
||||
return hmac.compare_digest(hashlib.sha256(key.encode('utf-8')).hexdigest(), expected)
|
||||
|
||||
def throttled(self, address: str) -> bool:
|
||||
failures = self._failures.get(address)
|
||||
if not failures:
|
||||
return False
|
||||
now = time.monotonic()
|
||||
while failures and now - failures[0] > FAIL_WINDOW:
|
||||
failures.popleft()
|
||||
return len(failures) >= MAX_FAILURES
|
||||
|
||||
def _fail(self, address: str) -> None:
|
||||
self._failures.setdefault(address, deque()).append(time.monotonic())
|
||||
|
||||
async def sign_in(self, address: str, login: str, password: str, key: str) -> Optional[AdminSession]:
|
||||
login = login.strip()
|
||||
with db.Session() as sess:
|
||||
row = sess.query(db.User).filter(sa.or_(sa.func.lower(db.User.email) == login.lower(), sa.func.lower(db.User.username) == login.lower())).first()
|
||||
stored = row.password if row is not None else None
|
||||
found = (row.uuid, row.username, bool(row.is_admin), bool(row.suspended)) if row is not None else None
|
||||
loop = asyncio.get_running_loop()
|
||||
global _DUMMY_HASH
|
||||
if stored is None and _DUMMY_HASH is None:
|
||||
_DUMMY_HASH = await loop.run_in_executor(None, hash.hasher.encode, secrets.token_hex(8))
|
||||
password_ok = bool(await loop.run_in_executor(None, hash.hasher.verify, password, stored or _DUMMY_HASH))
|
||||
key_ok = self.key_matches(key)
|
||||
if found is None or not password_ok or not key_ok or not found[2] or found[3]:
|
||||
self._fail(address)
|
||||
return None
|
||||
self._failures.pop(address, None)
|
||||
session = AdminSession(
|
||||
secrets.token_urlsafe(32), found[0], found[1], secrets.token_urlsafe(24),
|
||||
time.time() + int(getattr(settings, 'ADMIN_SESSION_LIFETIME', 8 * 3600)), address,
|
||||
)
|
||||
self._prune()
|
||||
self._sessions[session.token] = session
|
||||
return session
|
||||
|
||||
def get(self, token: Optional[str]) -> Optional[AdminSession]:
|
||||
if not token:
|
||||
return None
|
||||
session = self._sessions.get(token)
|
||||
if session is None:
|
||||
return None
|
||||
if session.expires <= time.time():
|
||||
self._sessions.pop(token, None)
|
||||
return None
|
||||
return session
|
||||
|
||||
def still_admin(self, session: AdminSession) -> bool:
|
||||
with db.Session() as sess:
|
||||
row = sess.query(db.User.is_admin, db.User.suspended).filter(db.User.uuid == session.uuid).one_or_none()
|
||||
return row is not None and bool(row[0]) and not bool(row[1])
|
||||
|
||||
def sign_out(self, token: Optional[str]) -> None:
|
||||
if token:
|
||||
self._sessions.pop(token, None)
|
||||
|
||||
def sign_out_user(self, uuid: str) -> None:
|
||||
for token in [token for token, session in self._sessions.items() if session.uuid == uuid]:
|
||||
self._sessions.pop(token, None)
|
||||
|
||||
def _prune(self) -> None:
|
||||
now = time.time()
|
||||
for token in [token for token, session in self._sessions.items() if session.expires <= now]:
|
||||
self._sessions.pop(token, None)
|
||||
|
||||
@staticmethod
|
||||
def csrf_ok(session: AdminSession, value: Any) -> bool:
|
||||
return isinstance(value, str) and hmac.compare_digest(session.csrf, value)
|
||||
@@ -0,0 +1,625 @@
|
||||
from datetime import datetime
|
||||
from math import ceil
|
||||
from typing import Any, Awaitable, Callable, Dict, List, Optional
|
||||
import asyncio, os, secrets
|
||||
|
||||
import jinja2
|
||||
from aiohttp import web
|
||||
|
||||
from core.alerts import AGENTS, MAX_BODY
|
||||
from core.backend import Backend
|
||||
from core.interservice.ctrl import ALERT_NETWORKS, INSCtrl
|
||||
from core.interservice.local import LocalLink, LocalINSError
|
||||
from core.interservice.registry import ClientRegistry
|
||||
from util.misc import AIOHTTPRunner
|
||||
import settings
|
||||
|
||||
from .auth import AdminAuth, COOKIE_NAME
|
||||
|
||||
TMPL_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmpl')
|
||||
PAGE_SIZE = 50
|
||||
SECTIONS = [
|
||||
('/', 'overview', 'bi-grid-1x2-fill'),
|
||||
('/users', 'users', 'bi-people-fill'),
|
||||
('/sessions', 'sessions', 'bi-plug-fill'),
|
||||
('/circles', 'circles', 'bi-chat-square-dots-fill'),
|
||||
('/broadcast', 'broadcast', 'bi-megaphone-fill'),
|
||||
('/interservice', 'interservice', 'bi-diagram-3-fill'),
|
||||
]
|
||||
USER_FILTERS = [
|
||||
('online', 'signed in', 'online'),
|
||||
('suspended', 'suspended', 'suspended'),
|
||||
('unverified', 'unverified e-mail', '!account_verified'),
|
||||
('blocked', 'can\'t sign in', '!verified_to_login'),
|
||||
('admins', 'administrators', 'is_admin'),
|
||||
('testers', 'testers', 'is_tester'),
|
||||
]
|
||||
NETWORK_NAMES = { 'msn': 'MSN Messenger', 'ymsg': 'Yahoo! Messenger', 'aim': 'AIM', 'icq': 'ICQ', 'irc': 'IRC' }
|
||||
PROGRAM_NAMES = { **NETWORK_NAMES, 'toc': 'AIM (TOC)', 'msim': 'MySpaceIM' }
|
||||
ALERT_LANGUAGES = [
|
||||
(1033, 'English (United States)'), (2057, 'English (United Kingdom)'), (1031, 'German'), (1036, 'French (France)'),
|
||||
(3082, 'Spanish (Spain)'), (2058, 'Spanish (Mexico)'), (1040, 'Italian'), (1043, 'Dutch'), (1046, 'Portuguese (Brazil)'),
|
||||
(2070, 'Portuguese (Portugal)'), (1053, 'Swedish'), (1030, 'Danish'), (1044, 'Norwegian (Bokmål)'), (1035, 'Finnish'),
|
||||
(1045, 'Polish'), (1049, 'Russian'), (1055, 'Turkish'), (1032, 'Greek'), (1041, 'Japanese'), (1042, 'Korean'),
|
||||
(2052, 'Chinese (Simplified)'), (1028, 'Chinese (Traditional)'),
|
||||
]
|
||||
USER_FLAGS = [
|
||||
#('verified_to_login', 'Can sign in', 'Off blocks every client and the website until it\'s turned back on.'),
|
||||
('suspended', 'Suspended', 'Signs them out everywhere and keeps them out.'),
|
||||
('account_verified', 'E-mail verified', 'Their e-mail address is confirmed as theirs.'),
|
||||
('show_in_dir', 'Listed in the member directory', 'Other members can find them and see their profile.'),
|
||||
('alias_active', 'Username alias active', 'They sign in with username@crosstalk.im instead of their e-mail address.'),
|
||||
('is_tester', 'Tester', 'Sees experimental and unfinished features.'),
|
||||
('is_mvp', 'MVP', 'Shows the MVP badge where clients support it.'),
|
||||
('is_admin', 'Administrator', 'Can sign into this panel (with the admin key).'),
|
||||
]
|
||||
LEGACY_CLIENTS = [('oldmsn', 'MSN Messenger 1.0 - 4.7'), ('yahoo', 'Yahoo! Messenger'), ('oldaim', 'AOL Instant Messenger'), ('msim', 'MySpaceIM')]
|
||||
ROLE_NAMES = { 1: 'owner', 2: 'administrator', 3: 'member', 4: 'invited' }
|
||||
|
||||
Handler = Callable[[web.Request], Awaitable[web.StreamResponse]]
|
||||
|
||||
def register(loop: asyncio.AbstractEventLoop, backend: Backend, registry: Optional[ClientRegistry]) -> web.Application:
|
||||
app = create_app(backend, registry)
|
||||
backend.add_runner(AIOHTTPRunner(settings.ADMIN_HOST, settings.ADMIN_PORT, app, service = 'Admin'))
|
||||
if not AdminAuth.configured():
|
||||
print('[Admin] <Info> ADMIN_KEY is not set, so nobody can sign into the admin panel yet (see settings.py)')
|
||||
print(f'[Admin] <Info> Admin panel on http://{settings.ADMIN_HOST}:{settings.ADMIN_PORT}/')
|
||||
return app
|
||||
|
||||
def create_app(backend: Backend, registry: Optional[ClientRegistry]) -> web.Application:
|
||||
app = web.Application(middlewares = [_security_headers, _require_admin])
|
||||
app['backend'] = backend
|
||||
app['registry'] = registry
|
||||
app['auth'] = AdminAuth()
|
||||
env = jinja2.Environment(loader = jinja2.FileSystemLoader(TMPL_DIR), autoescape = jinja2.select_autoescape(default = True))
|
||||
env.globals.update(
|
||||
settings = settings, role_names = ROLE_NAMES, sections = SECTIONS, network_names = NETWORK_NAMES, program_names = PROGRAM_NAMES,
|
||||
)
|
||||
env.filters['when'] = _when
|
||||
env.filters['ago'] = _ago
|
||||
env.filters['until'] = _until
|
||||
app['jinja'] = env
|
||||
r = app.router
|
||||
r.add_get('/login', page_login)
|
||||
r.add_post('/login', page_login)
|
||||
r.add_post('/logout', action_logout)
|
||||
r.add_get('/', page_overview)
|
||||
r.add_get('/users', page_users)
|
||||
r.add_get('/users/{uuid}', page_user)
|
||||
r.add_post('/users/{uuid}', action_user)
|
||||
r.add_get('/sessions', page_sessions)
|
||||
r.add_post('/sessions', action_sessions)
|
||||
r.add_get('/circles', page_circles)
|
||||
r.add_get('/circles/{chat_id}', page_circle)
|
||||
r.add_post('/circles/{chat_id}', action_circle)
|
||||
r.add_get('/broadcast', page_broadcast)
|
||||
r.add_post('/broadcast', action_broadcast)
|
||||
r.add_get('/interservice', page_interservice)
|
||||
r.add_post('/interservice', action_interservice)
|
||||
return app
|
||||
|
||||
def _when(value: Any) -> str:
|
||||
if not value:
|
||||
return 'never'
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
value = datetime.fromisoformat(value.rstrip('Z'))
|
||||
except ValueError:
|
||||
return value
|
||||
return '{} {}, {} {}'.format(value.strftime('%B'), value.day, value.year, value.strftime('%H:%M UTC'))
|
||||
|
||||
def _ago(value: Any) -> str:
|
||||
if not value:
|
||||
return 'never'
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
value = datetime.fromisoformat(value.rstrip('Z'))
|
||||
except ValueError:
|
||||
return value
|
||||
seconds = int((datetime.utcnow() - value).total_seconds())
|
||||
if seconds < 60:
|
||||
return 'just now'
|
||||
for size, name in ((86400 * 365, 'year'), (86400 * 30, 'month'), (86400, 'day'), (3600, 'hour'), (60, 'minute')):
|
||||
if seconds >= size:
|
||||
n = seconds // size
|
||||
return '{} {}{} ago'.format(n, name, '' if n == 1 else 's')
|
||||
return 'just now'
|
||||
|
||||
def _until(value: Any) -> str:
|
||||
if not value:
|
||||
return 'never'
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
value = datetime.fromisoformat(value.rstrip('Z'))
|
||||
except ValueError:
|
||||
return value
|
||||
seconds = int((value - datetime.utcnow()).total_seconds())
|
||||
if seconds <= 0:
|
||||
return 'at the next check'
|
||||
for size, name in ((86400, 'day'), (3600, 'hour'), (60, 'minute')):
|
||||
if seconds >= size:
|
||||
n = seconds // size
|
||||
return 'in {} {}{}'.format(n, name, '' if n == 1 else 's')
|
||||
return 'in under a minute'
|
||||
|
||||
def _peer(req: web.Request) -> str:
|
||||
return req.remote or ''
|
||||
|
||||
def _harden(headers: Any) -> None:
|
||||
headers['X-Frame-Options'] = 'DENY'
|
||||
headers['X-Content-Type-Options'] = 'nosniff'
|
||||
headers['Referrer-Policy'] = 'no-referrer'
|
||||
headers['Cache-Control'] = 'no-store'
|
||||
headers['Content-Security-Policy'] = (
|
||||
"default-src 'none'; img-src 'self' data: http: https:; style-src 'unsafe-inline' https://{0} https://cdn.jsdelivr.net https://fonts.googleapis.com; "
|
||||
"font-src https://{0} https://cdn.jsdelivr.net https://fonts.gstatic.com; script-src https://{0} https://code.jquery.com; "
|
||||
"connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"
|
||||
).format(settings.STATIC_HOST)
|
||||
|
||||
@web.middleware
|
||||
async def _security_headers(req: web.Request, handler: Handler) -> web.StreamResponse:
|
||||
try:
|
||||
resp = await handler(req)
|
||||
except web.HTTPException as ex:
|
||||
_harden(ex.headers)
|
||||
raise
|
||||
_harden(resp.headers)
|
||||
return resp
|
||||
|
||||
@web.middleware
|
||||
async def _require_admin(req: web.Request, handler: Handler) -> web.StreamResponse:
|
||||
if req.path == '/login':
|
||||
return await handler(req)
|
||||
auth: AdminAuth = req.app['auth']
|
||||
session = auth.get(req.cookies.get(COOKIE_NAME))
|
||||
if session is None or not auth.still_admin(session):
|
||||
if session is not None:
|
||||
auth.sign_out(session.token)
|
||||
if req.method != 'GET':
|
||||
raise web.HTTPForbidden(text = 'Sign in again.')
|
||||
raise web.HTTPFound('/login?next={}'.format(req.path_qs if req.path != '/' else '/'))
|
||||
if req.method == 'POST':
|
||||
data = await req.post()
|
||||
if not AdminAuth.csrf_ok(session, data.get('csrf')):
|
||||
raise web.HTTPForbidden(text = 'That form expired. Go back, reload the page and try again.')
|
||||
req['form'] = data
|
||||
req['admin'] = session
|
||||
req['ins'] = LocalLink(req.app['backend'], session.username)
|
||||
return await handler(req)
|
||||
|
||||
def render(req: web.Request, tmpl: str, ctxt: Optional[Dict[str, Any]] = None, *, status: int = 200) -> web.Response:
|
||||
session: AdminSession | None = req.get('admin')
|
||||
backend = req.app['backend'] # type: Backend
|
||||
context = dict(ctxt or {})
|
||||
context.update(
|
||||
admin = session, csrf = session.csrf if session else '', flashes = session.take_flashes() if session else [],
|
||||
reveal = session.take_reveal() if session else None, path = req.path,
|
||||
nav = {
|
||||
'sessions': sum(1 for _ in backend._sc.iter_sessions()),
|
||||
'maintenance': bool(backend.maintenance_mode or backend.notify_maintenance),
|
||||
},
|
||||
)
|
||||
html = req.app['jinja'].get_template(tmpl).render(**context)
|
||||
return web.Response(text = html, content_type = 'text/html', status = status)
|
||||
|
||||
def back(req: web.Request, location: str, text: Optional[str] = None, kind: str = 'success') -> web.Response:
|
||||
if text:
|
||||
req['admin'].flash(text, kind)
|
||||
raise web.HTTPSeeOther(location)
|
||||
|
||||
async def ins(req: web.Request, cmd: str, data: Optional[Dict[str, Any]] = None) -> Any:
|
||||
link: LocalLink = req['ins']
|
||||
return await link.call(cmd, data)
|
||||
|
||||
def _error_text(ex: LocalINSError) -> str:
|
||||
return ex.message or 'InterService error {:03}'.format(ex.code)
|
||||
|
||||
async def page_login(req: web.Request) -> web.Response:
|
||||
auth: AdminAuth = req.app['auth']
|
||||
next_page = req.query.get('next', '/')
|
||||
if not next_page.startswith('/') or next_page.startswith('//'):
|
||||
next_page = '/'
|
||||
error = None
|
||||
login = ''
|
||||
if req.method == 'POST':
|
||||
data = await req.post()
|
||||
login = str(data.get('login', ''))[:254]
|
||||
if not auth.configured():
|
||||
error = 'The admin key isn\'t set up on this server yet. Put its SHA-256 hash in ADMIN_KEY and restart azul.'
|
||||
elif auth.throttled(_peer(req)):
|
||||
error = 'Too many attempts. Wait a few minutes and try again.'
|
||||
else:
|
||||
session = await auth.sign_in(_peer(req), login, str(data.get('password', '')), str(data.get('key', '')))
|
||||
if session is None:
|
||||
error = 'Those details aren\'t right, or that account can\'t use the admin panel.'
|
||||
else:
|
||||
resp = web.HTTPSeeOther(next_page)
|
||||
resp.set_cookie(
|
||||
COOKIE_NAME, session.token, httponly = True, samesite = 'Strict', path = '/',
|
||||
secure = bool(getattr(settings, 'ADMIN_COOKIE_SECURE', False)),
|
||||
)
|
||||
raise resp
|
||||
env = req.app['jinja']
|
||||
html = env.get_template('login.html').render(settings = settings, error = error, login = login, next = next_page, configured = auth.configured())
|
||||
return web.Response(text = html, content_type = 'text/html', status = 401 if error else 200)
|
||||
|
||||
async def action_logout(req: web.Request) -> web.Response:
|
||||
req.app['auth'].sign_out(req['admin'].token)
|
||||
resp = web.HTTPSeeOther('/login')
|
||||
resp.del_cookie(COOKIE_NAME, path = '/')
|
||||
raise resp
|
||||
|
||||
async def page_overview(req: web.Request) -> web.Response:
|
||||
info = await ins(req, 'INF')
|
||||
stats = await ins(req, 'STA')
|
||||
alerts = (await ins(req, 'ALR', { 'action': 'LIST' })).get('alerts') or []
|
||||
suspended = await ins(req, 'LSU', { 'trait': 'suspended', 'limit': 1 })
|
||||
registry: ClientRegistry | None = req.app['registry']
|
||||
clients = registry.clients() if registry is not None else []
|
||||
online = stats.get('online') or {}
|
||||
sessions = int(online.get('sessions') or 0)
|
||||
return render(req, 'overview.html', {
|
||||
'title': 'Overview', 'info': info, 'stats': stats,
|
||||
'clients_active': len([c for c in clients if not c.revoked]),
|
||||
'links': [link for link in info.get('links') or [] if link.get('link') != 'local'],
|
||||
'uptime': _duration(info.get('uptime')),
|
||||
'hourly': _hourly(stats.get('hourly') or []),
|
||||
'programs': [
|
||||
{ 'name': PROGRAM_NAMES.get(p.get('program'), p.get('program')), 'sessions': p.get('sessions', 0), 'pct': round(100 * p.get('sessions', 0) / sessions, 1) if sessions else 0 }
|
||||
for p in online.get('by_program') or []
|
||||
],
|
||||
'alerts': _alert_rows(alerts[:4]), 'alerts_count': len(alerts),
|
||||
'suspended': int(suspended.get('matched') or 0), 'suspended_days': getattr(settings, 'SUSPENDED_ACCOUNT_DAYS', None),
|
||||
})
|
||||
|
||||
def _hourly(hours: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
||||
top = max([int(h.get('users_active') or 0) for h in hours] + [1])
|
||||
out = [] # type: List[Dict[str, Any]]
|
||||
for i, h in enumerate(hours):
|
||||
value = int(h.get('users_active') or 0)
|
||||
try:
|
||||
label = datetime.fromisoformat(str(h.get('hour') or '').rstrip('Z')).strftime('%H:00')
|
||||
except ValueError:
|
||||
label = ''
|
||||
out.append({ 'label': label, 'value': value, 'peak': int(h.get('peak') or 0), 'messages': int(h.get('messages_sent') or 0), 'pct': round(100 * value / top, 1), 'is_now': i == len(hours) - 1 })
|
||||
return out
|
||||
|
||||
def _duration(seconds: Any) -> str:
|
||||
try:
|
||||
seconds = int(seconds or 0)
|
||||
except (TypeError, ValueError):
|
||||
return '-'
|
||||
days, rest = divmod(seconds, 86400)
|
||||
hours, rest = divmod(rest, 3600)
|
||||
minutes = rest // 60
|
||||
parts = [] # type: List[str]
|
||||
if days:
|
||||
parts.append('{} day{}'.format(days, '' if days == 1 else 's'))
|
||||
if hours:
|
||||
parts.append('{} hour{}'.format(hours, '' if hours == 1 else 's'))
|
||||
if not days and minutes:
|
||||
parts.append('{} minute{}'.format(minutes, '' if minutes == 1 else 's'))
|
||||
return ', '.join(parts) or 'less than a minute'
|
||||
|
||||
async def page_users(req: web.Request) -> web.Response:
|
||||
query = req.query.get('q', '').strip()[:100]
|
||||
shown = req.query.get('show', '')
|
||||
trait = next((t for name, _, t in USER_FILTERS if name == shown), None)
|
||||
if trait is None:
|
||||
shown = ''
|
||||
try:
|
||||
page = max(1, int(req.query.get('page', 1)))
|
||||
except ValueError:
|
||||
page = 1
|
||||
result = await ins(req, 'LSU', { 'query': query, 'trait': trait, 'limit': PAGE_SIZE, 'offset': (page - 1) * PAGE_SIZE })
|
||||
matched = int(result.get('matched') or 0)
|
||||
return render(req, 'users.html', {
|
||||
'title': 'Users', 'q': query, 'show': shown, 'filters': USER_FILTERS, 'page': page, 'pages': max(1, ceil(matched / PAGE_SIZE)),
|
||||
'matched': matched, 'users': result.get('users') or [], 'total': result.get('total'), 'online': result.get('online'),
|
||||
})
|
||||
|
||||
async def _user_or_404(req: web.Request, uuid: str) -> Dict[str, Any]:
|
||||
try:
|
||||
return await ins(req, 'GTU', { 'uuid': uuid })
|
||||
except LocalINSError as ex:
|
||||
if ex.code == 428:
|
||||
raise web.HTTPNotFound(text = 'No such user.')
|
||||
raise
|
||||
|
||||
async def page_user(req: web.Request) -> web.Response:
|
||||
uuid = req.match_info['uuid']
|
||||
user = await _user_or_404(req, uuid)
|
||||
sessions = (await ins(req, 'LSS', { 'filter': { 'uuid': uuid } })).get('sessions') or []
|
||||
return render(req, 'user.html', {
|
||||
'title': user['username'], 'user': user, 'sessions': sessions, 'flags': USER_FLAGS, 'legacy_clients': LEGACY_CLIENTS,
|
||||
'reset_available': bool(INSCtrl.listeners('password.reset')),
|
||||
'email_available': bool(INSCtrl.listeners('alert.email')),
|
||||
'is_self': user['uuid'] == req['admin'].uuid,
|
||||
'suspended_days': getattr(settings, 'SUSPENDED_ACCOUNT_DAYS', None),
|
||||
'programs': sorted({ PROGRAM_NAMES.get((s.get('client') or {}).get('program'), '?') for s in sessions }),
|
||||
})
|
||||
|
||||
async def action_user(req: web.Request) -> web.Response:
|
||||
uuid = req.match_info['uuid']
|
||||
form = req['form']
|
||||
action = form.get('action')
|
||||
here = '/users/{}'.format(uuid)
|
||||
user = await _user_or_404(req, uuid)
|
||||
try:
|
||||
if action == 'flags':
|
||||
changes = {} # type: Dict[str, bool]
|
||||
for key, _, _ in USER_FLAGS:
|
||||
value = form.get(key) == 'on'
|
||||
if key == 'is_admin' and user['uuid'] == req['admin'].uuid and not value:
|
||||
return back(req, here, 'You can\'t take away your own admin rights. Ask another administrator.', 'danger')
|
||||
if bool(user.get(key)) != value:
|
||||
changes[key] = value
|
||||
if not changes:
|
||||
return back(req, here, 'Nothing changed.', 'info')
|
||||
await ins(req, 'EDU', { 'uuid': uuid, 'fields': changes })
|
||||
if changes.get('is_admin') is False or changes.get('suspended'):
|
||||
req.app['auth'].sign_out_user(uuid)
|
||||
return back(req, here, 'Saved {}.'.format(', '.join(label.lower() for key, label, _ in USER_FLAGS if key in changes)))
|
||||
if action == 'password':
|
||||
password = str(form.get('password', ''))
|
||||
if len(password) < 6:
|
||||
return back(req, here, 'Passwords need at least 6 characters.', 'danger')
|
||||
clients = [flag for flag, _ in LEGACY_CLIENTS if form.get('client_' + flag) == 'on']
|
||||
await ins(req, 'EDU', { 'uuid': uuid, 'fields': { 'password': password }, 'clients': clients })
|
||||
return back(req, here, 'Password changed. Their open sessions were signed out.')
|
||||
if action == 'temp-password':
|
||||
password = '-'.join(secrets.token_hex(3) for _ in range(3))
|
||||
await ins(req, 'EDU', { 'uuid': uuid, 'fields': { 'password': password }, 'clients': user.get('clients') or [] })
|
||||
req['admin'].reveal = { 'kind': 'password', 'value': password, 'for': user['username'] }
|
||||
return back(req, here)
|
||||
if action == 'reset-email':
|
||||
listeners = INSCtrl.listeners('password.reset')
|
||||
if not listeners:
|
||||
return back(req, here, 'No website is linked to send the e-mail right now.', 'danger')
|
||||
INSCtrl.broadcast('password.reset', { 'uuid': uuid, 'email': user['email'] })
|
||||
return back(req, here, 'Asked the website to e-mail a reset link to {}.'.format(user['email']))
|
||||
if action == 'kill':
|
||||
killed = (await ins(req, 'KLS', { 'id': str(form.get('session', '')) }))['killed']
|
||||
return back(req, here, 'Signed out {} session{}.'.format(killed, '' if killed == 1 else 's'))
|
||||
if action == 'kill-all':
|
||||
killed = (await ins(req, 'KLS', { 'uuid': uuid }))['killed']
|
||||
return back(req, here, 'Signed out {} session{}.'.format(killed, '' if killed == 1 else 's'))
|
||||
if action == 'alert':
|
||||
fields = _alert_fields(form)
|
||||
if not fields['rich'] and not fields['text']:
|
||||
return back(req, here, 'Write the alert first.', 'danger')
|
||||
result = await ins(req, 'ALR', { **fields, 'targets': [uuid] })
|
||||
return back(req, here, _alert_report(result))
|
||||
if action == 'delete':
|
||||
if str(form.get('confirm', '')).strip() != user['username']:
|
||||
return back(req, here, 'Type their username exactly to delete the account.', 'danger')
|
||||
if user['uuid'] == req['admin'].uuid:
|
||||
return back(req, here, 'You can\'t delete your own account from here.', 'danger')
|
||||
await ins(req, 'RMU', { 'uuid': uuid })
|
||||
req.app['auth'].sign_out_user(uuid)
|
||||
return back(req, '/users', 'Deleted {}.'.format(user['username']))
|
||||
except LocalINSError as ex:
|
||||
return back(req, here, _error_text(ex), 'danger')
|
||||
raise web.HTTPBadRequest(text = 'Unknown action.')
|
||||
|
||||
async def page_sessions(req: web.Request) -> web.Response:
|
||||
program = req.query.get('program', '')
|
||||
flt = { 'program': program } if program else {}
|
||||
result = await ins(req, 'LSS', { 'filter': flt })
|
||||
sessions = result.get('sessions') or []
|
||||
everything = (await ins(req, 'LSS', {})).get('sessions') or [] if program else sessions
|
||||
programs = sorted({ (s.get('client') or {}).get('program') or '?' for s in everything })
|
||||
return render(req, 'sessions.html', {
|
||||
'title': 'Sessions', 'sessions': sessions, 'program': program, 'programs': [(p, PROGRAM_NAMES.get(p, p)) for p in programs],
|
||||
'count': result.get('count', 0), 'total': len(everything),
|
||||
})
|
||||
|
||||
async def action_sessions(req: web.Request) -> web.Response:
|
||||
form = req['form']
|
||||
try:
|
||||
killed = (await ins(req, 'KLS', { 'id': str(form.get('session', '')) }))['killed']
|
||||
except LocalINSError as ex:
|
||||
return back(req, '/sessions', _error_text(ex), 'danger')
|
||||
return back(req, '/sessions' + ('?program=' + str(form.get('program')) if form.get('program') else ''), 'Signed out {} session{}.'.format(killed, '' if killed == 1 else 's'))
|
||||
|
||||
async def page_circles(req: web.Request) -> web.Response:
|
||||
circles = (await ins(req, 'CIR', { 'action': 'LIST' })).get('circles') or []
|
||||
circles.sort(key = lambda c: str(c.get('name') or '').lower())
|
||||
return render(req, 'circles.html', { 'title': 'Circles', 'circles': circles })
|
||||
|
||||
async def _circle_or_404(req: web.Request, chat_id: str) -> Dict[str, Any]:
|
||||
try:
|
||||
return await ins(req, 'CIR', { 'action': 'INFO', 'chat_id': chat_id })
|
||||
except LocalINSError as ex:
|
||||
if ex.code == 200:
|
||||
raise web.HTTPNotFound(text = 'No such circle.')
|
||||
raise
|
||||
|
||||
async def page_circle(req: web.Request) -> web.Response:
|
||||
circle = await _circle_or_404(req, req.match_info['chat_id'])
|
||||
members = [m for m in circle.get('members') or [] if m.get('state') not in (0, 4)]
|
||||
members.sort(key = lambda m: (m.get('role') or 9, str(m.get('username') or '').lower()))
|
||||
return render(req, 'circle.html', { 'title': circle['name'], 'circle': circle, 'members': members })
|
||||
|
||||
async def action_circle(req: web.Request) -> web.Response:
|
||||
chat_id = req.match_info['chat_id']
|
||||
circle = await _circle_or_404(req, chat_id)
|
||||
form = req['form']
|
||||
action = form.get('action')
|
||||
here = '/circles/{}'.format(chat_id)
|
||||
member = str(form.get('uuid', ''))
|
||||
try:
|
||||
if action == 'role':
|
||||
role = int(str(form.get('role', '0')))
|
||||
if role == 1:
|
||||
owner = next((m for m in circle.get('members') or [] if m.get('role') == 1 and m.get('state') == 3), None)
|
||||
await ins(req, 'CIR', { 'action': 'ROLE', 'chat_id': chat_id, 'uuid': member, 'role': 1, 'uuid_self': owner['uuid'] if owner else None })
|
||||
return back(req, here, 'Ownership moved.')
|
||||
await ins(req, 'CIR', { 'action': 'ROLE', 'chat_id': chat_id, 'uuid': member, 'role': role })
|
||||
return back(req, here, 'Role changed.')
|
||||
if action == 'remove':
|
||||
await ins(req, 'CIR', { 'action': 'REMOVE', 'chat_id': chat_id, 'uuid': member })
|
||||
return back(req, here, 'Removed from the circle.')
|
||||
if action == 'revoke':
|
||||
await ins(req, 'CIR', { 'action': 'REVOKE', 'chat_id': chat_id, 'uuid': member })
|
||||
return back(req, here, 'Invite withdrawn.')
|
||||
if action == 'delete':
|
||||
if str(form.get('confirm', '')).strip() != circle['name']:
|
||||
return back(req, here, 'Type the circle\'s name exactly to delete it.', 'danger')
|
||||
await ins(req, 'CIR', { 'action': 'DELETE', 'chat_id': chat_id })
|
||||
return back(req, '/circles', 'Deleted {}.'.format(circle['name']))
|
||||
except (ValueError, TypeError):
|
||||
return back(req, here, 'That isn\'t a role.', 'danger')
|
||||
except LocalINSError as ex:
|
||||
return back(req, here, _error_text(ex), 'danger')
|
||||
raise web.HTTPBadRequest(text = 'Unknown action.')
|
||||
|
||||
async def page_broadcast(req: web.Request) -> web.Response:
|
||||
info = await ins(req, 'INF')
|
||||
alerts = (await ins(req, 'ALR', { 'action': 'LIST' })).get('alerts') or []
|
||||
return render(req, 'broadcast.html', {
|
||||
'title': 'Broadcast', 'info': info, 'alerts': _alert_rows(alerts), 'languages': ALERT_LANGUAGES, 'agents': AGENTS,
|
||||
'networks': ALERT_NETWORKS, 'max_body': MAX_BODY, 'site_url': settings.ALERT_SITE_URL,
|
||||
'email_available': bool(INSCtrl.listeners('alert.email')),
|
||||
})
|
||||
|
||||
def _alert_fields(form: Any) -> Dict[str, Any]:
|
||||
message = str(form.get('message', '')).replace('\r\n', '\n').strip()
|
||||
align = str(form.get('align', 'left') or 'left')
|
||||
rich = message if message and (align != 'left' or '*' in message or '\\' in message) else ''
|
||||
plain = str(form.get('plain', '')).strip()
|
||||
kind = str(form.get('kind', 'bell') or 'bell')
|
||||
icon = str(form.get('icon', '')).strip() if kind == 'custom' else ''
|
||||
fields = {
|
||||
'text': plain if rich else message, 'rich': rich, 'align': align,
|
||||
'url': str(form.get('url', '')).strip(), 'subscr_url': str(form.get('subscr_url', '')).strip(),
|
||||
'kind': 'bell' if kind == 'custom' else kind, 'icon': icon,
|
||||
'lang': str(form.get('lang', '') or '1033'), 'priority': str(form.get('priority', '') or '1'),
|
||||
'message_id': str(form.get('message_id', '') or '0'), 'via': str(form.get('via', '')).strip() or None,
|
||||
} # type: Dict[str, Any]
|
||||
if form.get('networks_shown'):
|
||||
fields['networks'] = [n for n in ALERT_NETWORKS if form.get('network_' + n) == 'on']
|
||||
if form.get('email') == 'on':
|
||||
fields['email'] = True
|
||||
fields['email_text'] = str(form.get('email_text', '')).strip()
|
||||
return fields
|
||||
|
||||
def _alert_report(result: Dict[str, Any]) -> str:
|
||||
delivered = int(result.get('delivered') or 0)
|
||||
per_network = [(NETWORK_NAMES.get(n, n), c) for n, c in (result.get('networks') or {}).items() if c]
|
||||
text = 'Alert shown in {}'.format(_count(delivered, 'session'))
|
||||
if len(per_network) > 1:
|
||||
text += ' ({})'.format(', '.join('{} {}'.format(c, name) for name, c in per_network))
|
||||
elif per_network:
|
||||
text += ' of {}'.format(per_network[0][0])
|
||||
text += '.'
|
||||
skipped = int(result.get('skipped') or 0)
|
||||
if skipped:
|
||||
text += ' {} couldn\'t show it.'.format(_count(skipped, 'session').capitalize())
|
||||
emailed = int(result.get('emailed') or 0)
|
||||
if emailed:
|
||||
text += ' A copy was e-mailed to {}.'.format(_count(emailed, 'person', 'people'))
|
||||
return text
|
||||
|
||||
def _count(n: int, noun: str, plural: Optional[str] = None) -> str:
|
||||
return '{} {}'.format(n, noun if n == 1 else (plural or noun + 's'))
|
||||
|
||||
def _alert_rows(alerts: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
||||
rows = []
|
||||
for alert in alerts:
|
||||
targets = alert.get('targets')
|
||||
shown = ['{} {}'.format(c, NETWORK_NAMES.get(n, n)) for n, c in (alert.get('networks') or {}).items() if c]
|
||||
reach = '{} · shown in {}{}'.format(
|
||||
'everyone' if targets == 'all' else ', '.join(str(t) for t in targets or []), _count(int(alert.get('delivered') or 0), 'session'),
|
||||
' ({})'.format(', '.join(shown)) if len(shown) > 1 else (' of ' + shown[0].split(' ', 1)[1] if shown else ''),
|
||||
)
|
||||
if alert.get('emailed'):
|
||||
reach += ' · e-mailed to {}'.format(_count(int(alert['emailed']), 'person', 'people'))
|
||||
rows.append({ **alert, 'reach': reach })
|
||||
return rows
|
||||
|
||||
async def action_broadcast(req: web.Request) -> web.Response:
|
||||
form = req['form']
|
||||
action = form.get('action')
|
||||
try:
|
||||
if action == 'alert':
|
||||
fields = _alert_fields(form)
|
||||
if not fields['rich'] and not fields['text']:
|
||||
return back(req, '/broadcast#alert', 'Write the alert first.', 'danger')
|
||||
everyone = form.get('who', 'everyone') != 'people'
|
||||
targets = ['all'] if everyone else [t.strip() for t in str(form.get('targets', '')).replace('\n', ',').split(',') if t.strip()]
|
||||
if not targets:
|
||||
return back(req, '/broadcast#alert', 'Name who the alert is for, or send it to everyone.', 'danger')
|
||||
if fields.get('email') and everyone:
|
||||
return back(req, '/broadcast#alert', 'Alerts are only e-mailed to the people you name.', 'danger')
|
||||
if 'networks' in fields and not fields['networks']:
|
||||
return back(req, '/broadcast#alert', 'Pick at least one network.', 'danger')
|
||||
result = await ins(req, 'ALR', { **fields, 'targets': targets })
|
||||
return back(req, '/broadcast#history', _alert_report(result))
|
||||
if action == 'announce':
|
||||
await ins(req, 'ANC', { 'title': str(form.get('title', '')).strip(), 'text': str(form.get('text', '')).strip(), 'url': str(form.get('url', '')).strip() })
|
||||
return back(req, '/broadcast#announcement', 'Posted to CrossTalk Beacon and What\'s New.')
|
||||
if action == 'maintenance':
|
||||
await ins(req, 'MNT', { 'minutes': int(str(form.get('minutes', '')) or '-1') })
|
||||
return back(req, '/broadcast#maintenance', 'Maintenance announced to everyone signed in.')
|
||||
except (ValueError, TypeError):
|
||||
return back(req, '/broadcast#maintenance', 'Give the minutes as a number.', 'danger')
|
||||
except LocalINSError as ex:
|
||||
return back(req, '/broadcast#{}'.format('alert' if action == 'alert' else action), _error_text(ex), 'danger')
|
||||
raise web.HTTPBadRequest(text = 'Unknown action.')
|
||||
|
||||
async def page_interservice(req: web.Request) -> web.Response:
|
||||
registry: ClientRegistry | None = req.app['registry']
|
||||
linked = { link.client_record.id: link for link in INSCtrl._links.values() if link.client_record is not None }
|
||||
return render(req, 'interservice.html', {
|
||||
'title': 'InterService', 'enabled': registry is not None,
|
||||
'clients': registry.clients() if registry is not None else [], 'codes': registry.codes() if registry is not None else [],
|
||||
'linked': linked, 'identifiers': settings.INS_IDENTIFIERS, 'host_key': registry.host_public if registry is not None else b'',
|
||||
'fingerprint': _fingerprint(registry.host_public) if registry is not None else '',
|
||||
})
|
||||
|
||||
def _fingerprint(raw: bytes) -> str:
|
||||
from core.interservice.crypto import fingerprint
|
||||
return fingerprint(raw)
|
||||
|
||||
async def action_interservice(req: web.Request) -> web.Response:
|
||||
registry: ClientRegistry | None = req.app['registry']
|
||||
if registry is None:
|
||||
raise web.HTTPNotFound(text = 'InterService is turned off.')
|
||||
form = req['form']
|
||||
action = form.get('action')
|
||||
here = '/interservice'
|
||||
try:
|
||||
client_id = int(str(form.get('client', '0') or '0'))
|
||||
except ValueError:
|
||||
client_id = 0
|
||||
if action == 'code':
|
||||
identifier = str(form.get('identifier', ''))
|
||||
try:
|
||||
hours = int(str(form.get('hours', '24') or '24'))
|
||||
code, record = registry.create_code(
|
||||
identifier, label = str(form.get('label', '')).strip(), address = str(form.get('address', '')).strip() or None,
|
||||
hours = hours, created_by = req['admin'].username,
|
||||
)
|
||||
except ValueError as ex:
|
||||
return back(req, here, 'Couldn\'t make the code: {}.'.format(ex), 'danger')
|
||||
req['admin'].reveal = { 'kind': 'code', 'value': code, 'for': identifier, 'expires': _when(record.expires) }
|
||||
return back(req, here)
|
||||
if action == 'cancel-code':
|
||||
try:
|
||||
ok = registry.cancel_code(int(str(form.get('code', '0'))))
|
||||
except ValueError:
|
||||
ok = False
|
||||
return back(req, here, 'Code cancelled.' if ok else 'That code was already used.', 'success' if ok else 'danger')
|
||||
if action == 'revoke':
|
||||
record = registry.revoke(client_id)
|
||||
return back(req, here, 'Revoked {} "{}". Its links were closed.'.format(record.identifier, record.label) if record else 'No such client.')
|
||||
if action == 'delete':
|
||||
return back(req, here, 'Deleted.' if registry.delete(client_id) else 'Only revoked keys can be deleted.')
|
||||
if action == 'addresses':
|
||||
try:
|
||||
record = registry.set_addresses(client_id, str(form.get('addresses', '')).replace(',', '\n').splitlines())
|
||||
except (KeyError, ValueError) as ex:
|
||||
return back(req, here, 'Couldn\'t save the addresses ({}).'.format(ex), 'danger')
|
||||
return back(req, here, 'Addresses for {} "{}" saved.'.format(record.identifier, record.label))
|
||||
raise web.HTTPBadRequest(text = 'Unknown action.')
|
||||
@@ -0,0 +1,71 @@
|
||||
{% macro hub(title, sub=None) -%}
|
||||
<header class="ct-hub adm-hub">
|
||||
<h1 class="ct-hub-title">{{ title }}</h1>
|
||||
{% if sub %}<p class="ct-hub-sub">{{ sub }}</p>{% endif %}
|
||||
{% if caller %}{{ caller() }}{% endif %}
|
||||
</header>
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro flash_list(flashes) -%}
|
||||
{% for kind, text in flashes %}
|
||||
<div class="alert alert-{{ kind }}" role="{{ 'alert' if kind == 'danger' else 'status' }}">
|
||||
<i class="bi bi-{{ 'exclamation-triangle-fill' if kind == 'danger' else ('info-circle-fill' if kind == 'info' else 'check-circle-fill') }}" aria-hidden="true"></i>
|
||||
<div>{{ text }}</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro csrf_field(csrf) -%}
|
||||
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro copy_field(id, value, label) -%}
|
||||
<div class="adm-copy">
|
||||
<label class="visually-hidden" for="{{ id }}">{{ label }}</label>
|
||||
<input class="form-control" id="{{ id }}" value="{{ value }}" readonly spellcheck="false">
|
||||
<button type="button" class="btn btn-primary" data-ct-copy="{{ value }}" aria-label="Copy the {{ label | lower }}">Copy</button>
|
||||
</div>
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro flags(user) -%}
|
||||
{%- if user.is_admin %}<span class="ct-chip ct-chip-accent">admin</span>{% endif -%}
|
||||
{%- if user.suspended %}<span class="ct-chip ct-chip-danger">suspended</span>{% endif -%}
|
||||
{#{%- if not user.verified_to_login %}<span class="ct-chip ct-chip-warning">can't sign in</span>{% endif -%}#}
|
||||
{%- if not user.account_verified %}<span class="ct-chip">unverified e-mail</span>{% endif -%}
|
||||
{%- if user.show_in_dir %}<span class="ct-chip">listed in directory</span>{% endif -%}
|
||||
{%- if user.is_tester %}<span class="ct-chip">tester</span>{% endif -%}
|
||||
{%- if user.is_mvp %}<span class="ct-chip">MVP</span>{% endif -%}
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro pager(page, pages, base) -%}
|
||||
{% if pages > 1 %}
|
||||
<nav class="mt-4" aria-label="Pages">
|
||||
<ul class="pagination flex-wrap">
|
||||
<li class="page-item {% if page <= 1 %}disabled{% endif %}"><a class="page-link" href="{{ base }}page={{ page - 1 }}" aria-label="Previous page"{% if page <= 1 %} aria-disabled="true" tabindex="-1"{% endif %} data-ct-swap-link>«</a></li>
|
||||
{% for p in range([1, page - 2] | max, [pages, page + 2] | min + 1) %}
|
||||
<li class="page-item {% if p == page %}active{% endif %}"><a class="page-link" href="{{ base }}page={{ p }}"{% if p == page %} aria-current="page"{% endif %} data-ct-swap-link>{{ p }}</a></li>
|
||||
{% endfor %}
|
||||
<li class="page-item {% if page >= pages %}disabled{% endif %}"><a class="page-link" href="{{ base }}page={{ page + 1 }}" aria-label="Next page"{% if page >= pages %} aria-disabled="true" tabindex="-1"{% endif %} data-ct-swap-link>»</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
{% endif %}
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro tile(href, icon, big, name, note=None, tone=1, wide=False) -%}
|
||||
<a class="ct-tile adm-tile {{ 'adm-tile-hero' if tone == 'hero' else 'ct-tile-' ~ tone }}{% if wide %} ct-tile-wide{% endif %}" href="{{ href }}" data-ct-swap-link>
|
||||
<i class="bi {{ icon }} ct-tile-icon" aria-hidden="true"></i>
|
||||
<span class="adm-tile-big">{{ big }}</span>
|
||||
<span class="adm-tile-name">{{ name }}</span>
|
||||
{% if note %}<span class="adm-tile-note">{{ note }}</span>{% endif %}
|
||||
</a>
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro alert_row(alert) -%}
|
||||
<li class="adm-alert">
|
||||
<span class="adm-alert-icon" aria-hidden="true">{% if alert.icon %}<img src="{{ alert.icon }}" alt="" width="32" height="32" loading="lazy">{% else %}<i class="bi {{ {'stocks': 'bi-graph-up-arrow', 'calendar': 'bi-calendar-event-fill'}.get(alert.kind, 'bi-bell-fill') }}"></i>{% endif %}</span>
|
||||
<div class="adm-alert-body">
|
||||
<p class="adm-alert-text">{{ alert.text }}</p>
|
||||
<p class="adm-alert-meta">{{ alert.date | ago }} by {{ alert.by }} · {{ alert.reach }}{% if alert.url %} · <a href="{{ alert.url }}" rel="noreferrer" target="_blank">link<span class="visually-hidden"> (opens in a new tab)</span></a>{% endif %}</p>
|
||||
</div>
|
||||
</li>
|
||||
{%- endmacro %}
|
||||
@@ -0,0 +1,81 @@
|
||||
{% from '_ui.html' import flash_list -%}
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<meta name="robots" content="noindex, nofollow">
|
||||
<link rel="icon" href="https://{{ settings.STATIC_HOST }}/svc/ct/logo/favicon.ico"/>
|
||||
<link rel="stylesheet" href="https://{{ settings.STATIC_HOST }}/sites/ct/style/style.css">
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.css">
|
||||
<script src="https://{{ settings.STATIC_HOST }}/sites/ct/style/style.js"></script>
|
||||
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
|
||||
<script src="https://{{ settings.STATIC_HOST }}/sites/ct/bootstrap/bootstrap.bundle.min.js"></script>
|
||||
<title>{% if title %}{{ title }} | {% endif %}azul admin</title>
|
||||
</head>
|
||||
<body class="light-mode adm-body">
|
||||
<a class="visually-hidden-focusable ct-skip" href="#main">Skip to main content</a>
|
||||
<header>
|
||||
<nav class="navbar navbar-dark bg-primary fixed-top adm-bar" aria-label="Admin">
|
||||
<div class="container-fluid">
|
||||
<a class="navbar-brand" href="/" style="color:white;">
|
||||
<img src="https://{{ settings.STATIC_HOST }}/svc/ct/logo/shadow.svg" height="28" alt="">
|
||||
CrossTalk <span class="adm-brand-tag">admin</span>
|
||||
</a>
|
||||
<form method="get" action="/users" class="adm-find" role="search" aria-label="Find an account" data-ct-swap-form>
|
||||
<i class="bi bi-search" aria-hidden="true"></i>
|
||||
<label for="admFind" class="visually-hidden">Find an account by username, e-mail or UUID</label>
|
||||
<input type="search" class="form-control form-control-sm" id="admFind" name="q" placeholder="find an account" autocomplete="off" spellcheck="false">
|
||||
</form>
|
||||
<div class="adm-bar-end">
|
||||
<button type="button" class="ct-icon-btn adm-bar-btn" id="mode-toggle-anchor" role="switch" aria-checked="false" aria-label="Dark theme"><i id="mode-toggle-icon" class="bi" aria-hidden="true"></i><span id="mode-toggle-label" class="visually-hidden">Dark theme</span></button>
|
||||
<div class="dropdown">
|
||||
<button type="button" class="adm-who dropdown-toggle" id="admWho" data-bs-toggle="dropdown" aria-expanded="false" aria-label="Account menu for {{ admin.username }}">
|
||||
<img src="http://{{ settings.USERSTORAGE_HOST }}/avatar/{{ admin.uuid }}/im" alt="" width="28" height="28">
|
||||
<span class="adm-who-name">{{ admin.username }}</span>
|
||||
</button>
|
||||
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="admWho">
|
||||
<li class="ct-menu-head">
|
||||
<img src="http://{{ settings.USERSTORAGE_HOST }}/avatar/{{ admin.uuid }}/im" alt="" width="36" height="36">
|
||||
<span><strong>{{ admin.username }}</strong>administrator</span>
|
||||
</li>
|
||||
<li><a class="dropdown-item" href="/users/{{ admin.uuid }}" data-ct-swap-link><i class="bi bi-person-fill" aria-hidden="true"></i>Your account</a></li>
|
||||
<li><hr class="dropdown-divider"></li>
|
||||
<li>
|
||||
<form method="post" action="/logout" class="m-0">
|
||||
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||
<button type="submit" class="dropdown-item text-danger"><i class="bi bi-box-arrow-right" aria-hidden="true"></i>Sign out</button>
|
||||
</form>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<div class="adm-shell">
|
||||
<nav class="adm-nav" aria-label="Sections" data-ct-pivot-nav>
|
||||
<ul>
|
||||
{% for href, label, icon in sections %}
|
||||
{% set current = (path == href) or (href != '/' and path.startswith(href)) %}
|
||||
<li>
|
||||
<a href="{{ href }}"{% if current %} aria-current="page" class="is-current"{% endif %}>
|
||||
<i class="bi {{ icon }}" aria-hidden="true"></i><span class="adm-nav-label">{{ label }}</span>
|
||||
{% if href == '/sessions' %}<span class="adm-nav-count" id="admNavSessions" data-ct-swap-sync>{{ nav.sessions }}<span class="visually-hidden"> open</span></span>{% endif %}
|
||||
{% if href == '/broadcast' %}<span class="adm-nav-mark" id="admNavMaintenance" data-ct-swap-sync>{% if nav.maintenance %}<span class="ct-dot" aria-hidden="true"></span><span class="visually-hidden">, maintenance announced</span>{% endif %}</span>{% endif %}
|
||||
</a>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
<p class="adm-nav-foot">azul {{ settings.VERSION }}</p>
|
||||
</nav>
|
||||
|
||||
<main class="adm-main" id="main" tabindex="-1" data-ct-swap>
|
||||
{{ flash_list(flashes) }}
|
||||
{% block content %}{% endblock %}
|
||||
</main>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,190 @@
|
||||
{% extends 'base.html' %}
|
||||
{% from '_ui.html' import hub, csrf_field, alert_row %}
|
||||
{% block content %}
|
||||
{% set maintenance = info.maintenance or {} %}
|
||||
{{ hub('broadcast', 'Alerts in people\'s clients, news on CrossTalk Beacon, and warnings before maintenance.') }}
|
||||
|
||||
<div class="ct-pivot adm-broadcast-pivot" role="tablist" aria-label="Broadcast" data-ct-tabs data-ct-tabs-hash>
|
||||
<button type="button" role="tab" id="bcTabAlert" aria-controls="bcAlert" aria-selected="true" data-hash="alert">alert</button>
|
||||
<button type="button" role="tab" id="bcTabAnnounce" aria-controls="bcAnnounce" aria-selected="false" tabindex="-1" data-hash="announcement">announcement</button>
|
||||
<button type="button" role="tab" id="bcTabMaintenance" aria-controls="bcMaintenance" aria-selected="false" tabindex="-1" data-hash="maintenance">maintenance{% if maintenance.active or maintenance.pending %} <span class="ct-dot" style="--ct-tone: var(--ct-info)" aria-hidden="true"></span><span class="visually-hidden">, announced</span>{% endif %}</button>
|
||||
<button type="button" role="tab" id="bcTabHistory" aria-controls="bcHistory" aria-selected="false" tabindex="-1" data-hash="history">history <span class="ct-count">{{ alerts | length }}</span></button>
|
||||
</div>
|
||||
|
||||
<section class="ct-pane" role="tabpanel" id="bcAlert" aria-labelledby="bcTabAlert">
|
||||
<form method="post" class="adm-composer" data-ct-alert-composer data-max-body="{{ max_body }}" data-site-url="{{ site_url }}">
|
||||
{{ csrf_field(csrf) }}
|
||||
<input type="hidden" name="action" value="alert">
|
||||
<input type="hidden" name="networks_shown" value="1">
|
||||
<div class="adm-composer-form ct-card">
|
||||
<div class="ct-field">
|
||||
<div class="adm-label-row">
|
||||
<label for="alertMessage" class="form-label">Message</label>
|
||||
<div class="adm-tools" role="toolbar" aria-label="Formatting" aria-controls="alertMessage">
|
||||
<button type="button" class="ct-icon-btn ct-icon-btn-sm" data-alert-wrap="**" aria-label="Bold" title="Bold (**text**)"><i class="bi bi-type-bold" aria-hidden="true"></i></button>
|
||||
<button type="button" class="ct-icon-btn ct-icon-btn-sm" data-alert-wrap="*" aria-label="Italic" title="Italic (*text*)"><i class="bi bi-type-italic" aria-hidden="true"></i></button>
|
||||
<span class="adm-tools-gap" aria-hidden="true"></span>
|
||||
{% for align, icon in [('left', 'bi-text-left'), ('center', 'bi-text-center'), ('right', 'bi-text-right')] %}
|
||||
<input type="radio" class="btn-check" name="align" id="alertAlign-{{ align }}" value="{{ align }}" autocomplete="off"{% if loop.first %} checked{% endif %}>
|
||||
<label class="ct-icon-btn ct-icon-btn-sm adm-tool-toggle" for="alertAlign-{{ align }}" title="Align {{ align }}"><i class="bi {{ icon }}" aria-hidden="true"></i><span class="visually-hidden">Align {{ align }}</span></label>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
<textarea class="form-control" id="alertMessage" name="message" rows="5" maxlength="1000" required aria-describedby="alertMarkup"></textarea>
|
||||
<small class="form-text" id="alertMarkup">**bold**, *italic*, a backslash before a * to keep it, and a blank line for a new paragraph. Messenger 6 and later show the formatting; everything else gets the words.</small>
|
||||
</div>
|
||||
|
||||
<div class="row g-3 mt-1">
|
||||
<div class="col-sm-6 ct-field mb-0">
|
||||
<label for="alertUrl" class="form-label">Link</label>
|
||||
<input type="url" class="form-control" id="alertUrl" name="url" inputmode="url" placeholder="{{ site_url }}" aria-describedby="alertUrlHelp">
|
||||
<small class="form-text" id="alertUrlHelp">Where clicking the alert goes. Empty goes to {{ site_url }}.</small>
|
||||
</div>
|
||||
<fieldset class="col-sm-6 ct-field mb-0">
|
||||
<legend class="form-label">Icon</legend>
|
||||
<div class="adm-choices">
|
||||
{% for kind, label, icon in [('bell', 'bell', 'bi-bell-fill'), ('stocks', 'stocks', 'bi-graph-up-arrow'), ('calendar', 'calendar', 'bi-calendar-event-fill'), ('custom', 'your own', 'bi-image-fill')] %}
|
||||
<input type="radio" class="btn-check" name="kind" id="alertKind-{{ kind }}" value="{{ kind }}" autocomplete="off"{% if loop.first %} checked{% endif %}>
|
||||
<label class="adm-choice" for="alertKind-{{ kind }}"><i class="bi {{ icon }}" aria-hidden="true"></i>{{ label }}</label>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</fieldset>
|
||||
</div>
|
||||
<div class="ct-field mt-3" data-alert-when="kind=custom">
|
||||
<label for="alertIcon" class="form-label">Icon address</label>
|
||||
<input type="url" class="form-control" id="alertIcon" name="icon" inputmode="url" placeholder="https://example.com/alert_32x32.png" aria-describedby="alertIconHelp">
|
||||
<small class="form-text" id="alertIconHelp">A 32×32 PNG. Messenger 6 and later swap <code>_32x32</code> in its name for <code>_48x32</code> and use that one if it's there.</small>
|
||||
</div>
|
||||
|
||||
<fieldset class="ct-field mt-3">
|
||||
<legend class="form-label">Who</legend>
|
||||
<div class="adm-choices">
|
||||
<input type="radio" class="btn-check" name="who" id="alertWho-everyone" value="everyone" autocomplete="off" checked>
|
||||
<label class="adm-choice" for="alertWho-everyone"><i class="bi bi-globe2" aria-hidden="true"></i>everyone signed in</label>
|
||||
<input type="radio" class="btn-check" name="who" id="alertWho-people" value="people" autocomplete="off">
|
||||
<label class="adm-choice" for="alertWho-people"><i class="bi bi-person-lines-fill" aria-hidden="true"></i>certain people</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
<div data-alert-when="who=people">
|
||||
<div class="ct-field">
|
||||
<label for="alertTargets" class="form-label">Their usernames or e-mail addresses</label>
|
||||
<textarea class="form-control" id="alertTargets" name="targets" rows="2" spellcheck="false" aria-describedby="alertTargetsHelp"></textarea>
|
||||
<small class="form-text" id="alertTargetsHelp">Separated with commas or on lines of their own.</small>
|
||||
</div>
|
||||
<div class="form-check form-switch mb-2">
|
||||
<input class="form-check-input" type="checkbox" role="switch" id="alertEmail" name="email"{% if not email_available %} disabled aria-describedby="alertEmailHelp"{% endif %}>
|
||||
<label class="form-check-label" for="alertEmail">Also e-mail it to them</label>
|
||||
</div>
|
||||
{% if not email_available %}<p class="form-text mt-0" id="alertEmailHelp">The website isn't linked right now, so it can't send e-mail.</p>{% endif %}
|
||||
<div class="ct-field" data-alert-when="email">
|
||||
<label for="alertEmailText" class="form-label">The e-mail's text <span class="ct-muted">(optional)</span></label>
|
||||
<textarea class="form-control" id="alertEmailText" name="email_text" rows="3" aria-describedby="alertEmailTextHelp"></textarea>
|
||||
<small class="form-text" id="alertEmailTextHelp">Empty sends the alert's words and its link. Messenger also gets it as the alert's <code>EMAILTEXT</code>.</small>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<fieldset class="ct-field mt-3">
|
||||
<legend class="form-label">Clients</legend>
|
||||
<div class="adm-choices">
|
||||
{% for network in networks %}
|
||||
<input type="checkbox" class="btn-check" name="network_{{ network }}" id="alertNetwork-{{ network }}" autocomplete="off" checked>
|
||||
<label class="adm-choice adm-choice-name" for="alertNetwork-{{ network }}"><i class="bi bi-check-lg adm-choice-tick" aria-hidden="true"></i>{{ network_names.get(network, network) }}</label>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<details class="ct-details adm-more">
|
||||
<summary>more .NET Alerts options</summary>
|
||||
<div class="ct-details-body">
|
||||
<div class="row g-3">
|
||||
<div class="col-sm-6 ct-field mb-0">
|
||||
<label for="alertSubscr" class="form-label">"Change alert" link</label>
|
||||
<input type="url" class="form-control" id="alertSubscr" name="subscr_url" inputmode="url" aria-describedby="alertSubscrHelp">
|
||||
<small class="form-text" id="alertSubscrHelp">Messenger's option to change the alert (<code>SUBSCR</code>). Empty uses the link.</small>
|
||||
</div>
|
||||
<div class="col-sm-6 ct-field mb-0">
|
||||
<label for="alertLang" class="form-label">Language</label>
|
||||
<select class="form-select" id="alertLang" name="lang">
|
||||
{% for lcid, name in languages %}<option value="{{ lcid }}"{% if lcid == 1033 %} selected{% endif %}>{{ name }} ({{ lcid }})</option>{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-sm-4 ct-field mb-0">
|
||||
<label for="alertPriority" class="form-label">Priority</label>
|
||||
<input type="number" class="form-control" id="alertPriority" name="priority" min="0" max="4294967295" value="1">
|
||||
</div>
|
||||
<div class="col-sm-4 ct-field mb-0">
|
||||
<label for="alertMessageId" class="form-label">Message ID</label>
|
||||
<input type="number" class="form-control" id="alertMessageId" name="message_id" min="0" max="4294967295" value="0">
|
||||
</div>
|
||||
<div class="col-sm-4 ct-field mb-0">
|
||||
<label for="alertVia" class="form-label">Sent via</label>
|
||||
<select class="form-select" id="alertVia" name="via">
|
||||
<option value="">nothing said</option>
|
||||
{% for agent in agents %}<option value="{{ agent }}">{{ agent }}</option>{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ct-field mt-3 mb-0">
|
||||
<label for="alertPlain" class="form-label">Plain-text version <span class="ct-muted">(optional)</span></label>
|
||||
<textarea class="form-control" id="alertPlain" name="plain" rows="2" aria-describedby="alertPlainHelp"></textarea>
|
||||
<small class="form-text" id="alertPlainHelp">What Messenger 5 and older, Yahoo!, AIM and IRC show when the message has formatting. Empty takes the message's words.</small>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<div class="ct-form-actions"><button type="submit" class="btn btn-primary">Send alert</button></div>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="ct-pane ct-card" role="tabpanel" id="bcAnnounce" aria-labelledby="bcTabAnnounce" data-ct-later>
|
||||
<p class="ct-muted">A news item on CrossTalk Beacon and in Windows Live Messenger's What's New.</p>
|
||||
<form method="post" class="adm-narrow-form">
|
||||
{{ csrf_field(csrf) }}
|
||||
<input type="hidden" name="action" value="announce">
|
||||
<div class="ct-field">
|
||||
<label for="ancTitle" class="form-label">Title</label>
|
||||
<input type="text" class="form-control" id="ancTitle" name="title" maxlength="100" required>
|
||||
</div>
|
||||
<div class="ct-field">
|
||||
<label for="ancText" class="form-label">Text</label>
|
||||
<textarea class="form-control" id="ancText" name="text" rows="3" maxlength="255" required></textarea>
|
||||
</div>
|
||||
<div class="ct-field">
|
||||
<label for="ancUrl" class="form-label">Link <span class="ct-muted">(optional)</span></label>
|
||||
<input type="url" class="form-control" id="ancUrl" name="url" inputmode="url">
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">Post announcement</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="ct-pane ct-card" role="tabpanel" id="bcMaintenance" aria-labelledby="bcTabMaintenance" data-ct-later>
|
||||
{% if maintenance.active %}
|
||||
<p class="mb-0">The server is in maintenance mode right now.</p>
|
||||
{% elif maintenance.pending %}
|
||||
<p class="mb-0">Maintenance is already announced, in about {{ maintenance.minutes }} minute{{ 's' if maintenance.minutes != 1 else '' }}.</p>
|
||||
{% else %}
|
||||
<p>Tells everyone signed in that the server is going down, with a countdown. The website's status page shows it too.</p>
|
||||
<form method="post" class="d-flex flex-wrap align-items-end gap-2">
|
||||
{{ csrf_field(csrf) }}
|
||||
<input type="hidden" name="action" value="maintenance">
|
||||
<div>
|
||||
<label for="mntMinutes" class="form-label">In how many minutes</label>
|
||||
<input type="number" class="form-control adm-narrow" id="mntMinutes" name="minutes" min="0" max="1440" value="10" required>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-outline-danger">Announce maintenance</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
<section class="ct-pane ct-card" role="tabpanel" id="bcHistory" aria-labelledby="bcTabHistory" data-ct-later>
|
||||
{% if alerts %}
|
||||
<p class="ct-muted">The last {{ alerts | length }} alert{{ 's' if alerts | length != 1 else '' }} since azul started, newest first.</p>
|
||||
<ul class="adm-alerts">
|
||||
{% for alert in alerts %}{{ alert_row(alert) }}{% endfor %}
|
||||
</ul>
|
||||
{% else %}
|
||||
<p class="ct-muted">No alerts since azul started.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,77 @@
|
||||
{% extends 'base.html' %}
|
||||
{% from '_ui.html' import csrf_field %}
|
||||
{% block content %}
|
||||
<p class="ct-back"><a href="/circles" data-ct-swap-link>Circles</a></p>
|
||||
|
||||
<section class="ct-card adm-identity" aria-labelledby="circleName">
|
||||
<span class="adm-glyph adm-glyph-lg" aria-hidden="true">{{ (circle.name or '?')[:1] }}</span>
|
||||
<div class="min-w-0 flex-grow-1">
|
||||
<h1 class="adm-identity-name" id="circleName">{{ circle.name }}</h1>
|
||||
<p class="ct-muted mb-0">{{ members | length }} member{{ 's' if members | length != 1 else '' }} · {{ members | selectattr('in_chat') | list | length }} in the conversation now · <code>{{ circle.chat_id }}</code></p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="ct-card" aria-labelledby="circleMembers">
|
||||
<h2 class="ct-card-title" id="circleMembers">members</h2>
|
||||
<ul class="adm-roster">
|
||||
{% for m in members %}
|
||||
{% set invited = m.role == 4 and m.state == 1 %}
|
||||
<li class="adm-roster-row">
|
||||
<a class="adm-roster-who" href="/users/{{ m.uuid }}" data-ct-swap-link>
|
||||
<span class="adm-avatar">
|
||||
<img src="http://{{ settings.USERSTORAGE_HOST }}/avatar/{{ m.uuid }}/im" alt="" width="36" height="36" loading="lazy">
|
||||
{% if m.online %}<span class="ct-presence" aria-hidden="true"></span>{% endif %}
|
||||
</span>
|
||||
<span class="adm-person-body">
|
||||
<span class="adm-person-name">{{ m.username }}</span>
|
||||
<span class="adm-person-meta">{% if invited %}invited{% if m.inviter_email %} by {{ m.inviter_email }}{% endif %}{% elif m.in_chat %}in the conversation{% elif m.online %}signed in{% else %}{{ m.email }}{% endif %}</span>
|
||||
</span>
|
||||
</a>
|
||||
<div class="adm-roster-actions">
|
||||
{% if invited %}
|
||||
<form method="post" class="m-0">
|
||||
{{ csrf_field(csrf) }}
|
||||
<input type="hidden" name="action" value="revoke">
|
||||
<input type="hidden" name="uuid" value="{{ m.uuid }}">
|
||||
<button type="submit" class="btn btn-sm btn-outline-secondary">Withdraw invite<span class="visually-hidden"> for {{ m.username }}</span></button>
|
||||
</form>
|
||||
{% else %}
|
||||
<form method="post" class="d-flex align-items-center gap-2 m-0">
|
||||
{{ csrf_field(csrf) }}
|
||||
<input type="hidden" name="action" value="role">
|
||||
<input type="hidden" name="uuid" value="{{ m.uuid }}">
|
||||
<label class="visually-hidden" for="role-{{ loop.index }}">Role for {{ m.username }}</label>
|
||||
<select class="form-select form-select-sm" id="role-{{ loop.index }}" name="role">
|
||||
{% for value, name in [(1, 'owner'), (2, 'administrator'), (3, 'member')] %}
|
||||
<option value="{{ value }}"{% if m.role == value %} selected{% endif %}>{{ name }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
<button type="submit" class="btn btn-sm btn-outline-secondary">Set<span class="visually-hidden"> the role for {{ m.username }}</span></button>
|
||||
</form>
|
||||
<form method="post" class="m-0">
|
||||
{{ csrf_field(csrf) }}
|
||||
<input type="hidden" name="action" value="remove">
|
||||
<input type="hidden" name="uuid" value="{{ m.uuid }}">
|
||||
<button type="submit" class="btn btn-sm btn-outline-danger">Remove<span class="visually-hidden"> {{ m.username }}</span></button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</div>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section class="ct-card adm-danger" aria-labelledby="circleDelete">
|
||||
<h2 class="ct-card-title" id="circleDelete">delete this circle</h2>
|
||||
<p>Ends the conversation for everyone and takes the circle off every member's contact list. It can't be undone.</p>
|
||||
<form method="post" class="adm-confirm">
|
||||
{{ csrf_field(csrf) }}
|
||||
<input type="hidden" name="action" value="delete">
|
||||
<label for="circleConfirm" class="form-label">Type <strong>{{ circle.name }}</strong> to confirm</label>
|
||||
<div class="d-flex flex-wrap gap-2">
|
||||
<input type="text" class="form-control" id="circleConfirm" name="confirm" autocomplete="off" spellcheck="false" required>
|
||||
<button type="submit" class="btn btn-danger">Delete circle</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,24 @@
|
||||
{% extends 'base.html' %}
|
||||
{% from '_ui.html' import hub %}
|
||||
{% block content %}
|
||||
{{ hub('circles', '{:,}'.format(circles | length) ~ ' group chats on the server.') }}
|
||||
|
||||
{% if circles %}
|
||||
<ul class="adm-people ct-card">
|
||||
{% for c in circles %}
|
||||
<li>
|
||||
<a class="adm-person" href="/circles/{{ c.chat_id }}" data-ct-swap-link>
|
||||
<span class="adm-glyph" aria-hidden="true">{{ (c.name or '?')[:1] }}</span>
|
||||
<span class="adm-person-body">
|
||||
<span class="adm-person-name">{{ c.name }}</span>
|
||||
<span class="adm-person-meta">started by {{ c.owner_friendly or c.owner_uuid }}</span>
|
||||
</span>
|
||||
<span class="adm-person-when ct-muted">{{ c.members_count }} member{{ 's' if c.members_count != 1 else '' }}<br><code>{{ c.chat_id }}</code></span>
|
||||
</a>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% else %}
|
||||
<p class="ct-muted">No circles yet.</p>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,133 @@
|
||||
{% extends 'base.html' %}
|
||||
{% from '_ui.html' import hub, csrf_field, copy_field %}
|
||||
{% block content %}
|
||||
{{ hub('interservice', 'The services linked to azul (the website, bots, tools). Each one has keys of its own that only work from the machine and address it enrolled from.') }}
|
||||
|
||||
{% if not enabled %}
|
||||
<p class="ct-muted">InterService is turned off on this server (<code>ENABLE_INS</code>).</p>
|
||||
{% else %}
|
||||
|
||||
{% if reveal and reveal.kind == 'code' %}
|
||||
<section class="ct-card adm-reveal" aria-labelledby="newCode">
|
||||
<h2 class="ct-card-title" id="newCode">enrollment code for {{ reveal['for'] }}</h2>
|
||||
<p>Put it in the service's settings (the website's is <code>INS_ENROLLMENT_CODE</code>) before {{ reveal.expires }}. It works once, and this is the only time it's shown.</p>
|
||||
{{ copy_field('enrollCodeValue', reveal.value, 'Enrollment code') }}
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
<section aria-labelledby="insClients">
|
||||
<h2 class="ct-section" id="insClients">enrolled services</h2>
|
||||
{% if clients %}
|
||||
<ul class="adm-keys">
|
||||
{% for c in clients %}
|
||||
{% set link = linked.get(c.id) %}
|
||||
<li class="ct-card adm-key{% if c.revoked %} is-revoked{% endif %}">
|
||||
<div class="adm-key-head">
|
||||
<span class="ct-dot adm-key-state" aria-hidden="true" style="--ct-tone: {{ 'var(--ct-danger)' if c.revoked else ('var(--ct-online)' if link else '#8a8494') }}"></span>
|
||||
<div class="min-w-0 flex-grow-1">
|
||||
<h3 class="adm-key-name">{{ c.label or c.identifier }}</h3>
|
||||
<p class="ct-muted mb-0">{{ c.identifier }} · {% if c.revoked %}revoked {{ c.revoked_at | ago }}{% elif link %}linked now{% else %}last seen {{ c.last_seen | ago }}{% endif %}</p>
|
||||
</div>
|
||||
{% if not c.revoked %}
|
||||
<form method="post" class="m-0">
|
||||
{{ csrf_field(csrf) }}
|
||||
<input type="hidden" name="action" value="revoke">
|
||||
<input type="hidden" name="client" value="{{ c.id }}">
|
||||
<button type="submit" class="btn btn-sm btn-outline-danger">Revoke<span class="visually-hidden"> {{ c.label }}</span></button>
|
||||
</form>
|
||||
{% else %}
|
||||
<form method="post" class="m-0">
|
||||
{{ csrf_field(csrf) }}
|
||||
<input type="hidden" name="action" value="delete">
|
||||
<input type="hidden" name="client" value="{{ c.id }}">
|
||||
<button type="submit" class="btn btn-sm btn-outline-secondary">Delete<span class="visually-hidden"> {{ c.label }}</span></button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</div>
|
||||
<dl class="adm-key-facts">
|
||||
<div><dt>key</dt><dd><code>{{ c.fingerprint }}</code></dd></div>
|
||||
<div><dt>enrolled</dt><dd>{{ c.created | when }}</dd></div>
|
||||
<div><dt>last address</dt><dd>{{ c.last_address or '-' }}</dd></div>
|
||||
</dl>
|
||||
{% if not c.revoked %}
|
||||
<form method="post" class="adm-key-addresses">
|
||||
{{ csrf_field(csrf) }}
|
||||
<input type="hidden" name="action" value="addresses">
|
||||
<input type="hidden" name="client" value="{{ c.id }}">
|
||||
<label for="addr-{{ c.id }}" class="form-label">Works from</label>
|
||||
<div class="d-flex flex-wrap gap-2">
|
||||
<input type="text" class="form-control" id="addr-{{ c.id }}" name="addresses" value="{{ c.addresses | join(', ') }}" spellcheck="false" aria-describedby="addrHelp-{{ c.id }}">
|
||||
<button type="submit" class="btn btn-outline-secondary">Save</button>
|
||||
</div>
|
||||
<small class="form-text" id="addrHelp-{{ c.id }}">Addresses or networks (CIDR), separated with commas. Anything else is turned away, even with the right keys.</small>
|
||||
</form>
|
||||
{% endif %}
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% else %}
|
||||
<p class="ct-muted">Nothing has enrolled yet. Make a code below for the website first.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
<div class="adm-columns">
|
||||
<section class="ct-card" id="enroll" aria-labelledby="insEnroll">
|
||||
<h2 class="ct-card-title" id="insEnroll">enroll a service</h2>
|
||||
<p class="ct-muted">A one-time code. The service makes its own keys the first time it connects with it, and they never leave that machine.</p>
|
||||
<form method="post">
|
||||
{{ csrf_field(csrf) }}
|
||||
<input type="hidden" name="action" value="code">
|
||||
<div class="row g-3">
|
||||
<div class="col-sm-6 ct-field mb-0">
|
||||
<label for="codeIdentifier" class="form-label">Identifier</label>
|
||||
<select class="form-select" id="codeIdentifier" name="identifier">
|
||||
{% for identifier in identifiers %}<option value="{{ identifier }}">{{ identifier }}</option>{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-sm-6 ct-field mb-0">
|
||||
<label for="codeLabel" class="form-label">Name it</label>
|
||||
<input type="text" class="form-control" id="codeLabel" name="label" maxlength="100" placeholder="CrossTalk website">
|
||||
</div>
|
||||
<div class="col-sm-6 ct-field mb-0">
|
||||
<label for="codeAddress" class="form-label">Only from <span class="ct-muted">(optional)</span></label>
|
||||
<input type="text" class="form-control" id="codeAddress" name="address" placeholder="Any address" spellcheck="false">
|
||||
</div>
|
||||
<div class="col-sm-6 ct-field mb-0">
|
||||
<label for="codeHours" class="form-label">Valid for (hours)</label>
|
||||
<input type="number" class="form-control" id="codeHours" name="hours" min="1" max="720" value="24" required>
|
||||
</div>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary mt-3">Make a code</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="ct-card" aria-labelledby="insCodes">
|
||||
<h2 class="ct-card-title" id="insCodes">codes</h2>
|
||||
{% set shown = codes[:12] %}
|
||||
{% if shown %}
|
||||
<ul class="ct-list">
|
||||
{% for code in shown %}
|
||||
<li class="ct-list-item">
|
||||
<span class="ct-list-body">
|
||||
<span class="ct-list-title">{{ code.label or code.identifier }}</span>
|
||||
<span class="ct-list-meta">{{ code.identifier }}{% if code.address %} from {{ code.address }}{% endif %} · {% if code.state == 'used' %}used {{ code.used | ago }}{% elif code.state == 'expired' %}expired{% else %}waiting until {{ code.expires | when }}{% endif %}</span>
|
||||
</span>
|
||||
{% if code.state == 'waiting' %}
|
||||
<form method="post" class="m-0">
|
||||
{{ csrf_field(csrf) }}
|
||||
<input type="hidden" name="action" value="cancel-code">
|
||||
<input type="hidden" name="code" value="{{ code.id }}">
|
||||
<button type="submit" class="btn btn-sm btn-outline-secondary">Cancel</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% else %}
|
||||
<p class="ct-muted">None made yet.</p>
|
||||
{% endif %}
|
||||
<p class="ct-muted small mt-3 mb-0">Server host key <code>{{ fingerprint }}</code></p>
|
||||
</section>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,68 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<meta name="robots" content="noindex, nofollow">
|
||||
<link rel="icon" href="https://{{ settings.STATIC_HOST }}/svc/ct/logo/favicon.ico"/>
|
||||
<link rel="stylesheet" href="https://{{ settings.STATIC_HOST }}/sites/ct/style/style.css">
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.css">
|
||||
<script src="https://{{ settings.STATIC_HOST }}/sites/ct/style/style.js"></script>
|
||||
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
|
||||
<title>Sign in | azul admin</title>
|
||||
</head>
|
||||
<body class="light-mode adm-body adm-login-body">
|
||||
<header>
|
||||
<nav class="navbar navbar-dark bg-primary fixed-top adm-bar" aria-label="Admin">
|
||||
<div class="container-fluid">
|
||||
<a class="navbar-brand" href="/login" style="color:white;">
|
||||
<img src="https://{{ settings.STATIC_HOST }}/svc/ct/logo/shadow.svg" height="28" alt="">
|
||||
CrossTalk <span class="adm-brand-tag">admin</span>
|
||||
</a>
|
||||
<div class="adm-bar-end">
|
||||
<button type="button" class="ct-icon-btn adm-bar-btn" id="mode-toggle-anchor" role="switch" aria-checked="false" aria-label="Dark theme"><i id="mode-toggle-icon" class="bi" aria-hidden="true"></i><span id="mode-toggle-label" class="visually-hidden">Dark theme</span></button>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
<main class="container my-4" id="main" tabindex="-1">
|
||||
<section class="au-card ct-card" aria-labelledby="adminSignIn">
|
||||
<header class="au-head">
|
||||
<h1 class="au-title" id="adminSignIn">sign in</h1>
|
||||
<p class="au-sub">sign in to manage azul {{ settings.VERSION }}</p>
|
||||
</header>
|
||||
{% if not configured %}
|
||||
<div class="alert alert-warning" role="status"><i class="bi bi-exclamation-triangle-fill" aria-hidden="true"></i><div>No admin key is set up yet. Put the SHA-256 hash of one in <code>ADMIN_KEY</code> and restart azul.</div></div>
|
||||
{% endif %}
|
||||
{% if error %}
|
||||
<div class="alert alert-danger" role="alert"><i class="bi bi-exclamation-triangle-fill" aria-hidden="true"></i><div>{{ error }}</div></div>
|
||||
{% elif next and next != '/' %}
|
||||
<div class="alert alert-info" role="status"><i class="bi bi-lock-fill" aria-hidden="true"></i><div>Sign in to carry on where you were.</div></div>
|
||||
{% endif %}
|
||||
<form method="post" action="/login?next={{ next | urlencode }}" aria-labelledby="adminSignIn">
|
||||
<div class="ct-field">
|
||||
<label for="login" class="form-label">E-mail or username</label>
|
||||
<input type="text" class="form-control" id="login" name="login" value="{{ login }}" placeholder="E-mail or username" autocomplete="username" autocapitalize="none" spellcheck="false" required autofocus>
|
||||
</div>
|
||||
<div class="ct-field">
|
||||
<label for="password" class="form-label">Password</label>
|
||||
<div class="ct-password">
|
||||
<input type="password" class="form-control" id="password" name="password" placeholder="Password" autocomplete="current-password" required>
|
||||
<button type="button" class="ct-icon-btn" data-ct-reveal="password" aria-pressed="false" aria-label="Show password"><i class="bi bi-eye-fill" aria-hidden="true"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ct-field">
|
||||
<label for="key" class="form-label">Admin key</label>
|
||||
<div class="ct-password">
|
||||
<input type="password" class="form-control" id="key" name="key" placeholder="The server's admin key" autocomplete="off" spellcheck="false" required aria-describedby="keyHelp">
|
||||
<button type="button" class="ct-icon-btn" data-ct-reveal="key" aria-pressed="false" aria-label="Show admin key"><i class="bi bi-eye-fill" aria-hidden="true"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary w-100 au-submit">Sign in</button>
|
||||
</form>
|
||||
<p class="au-alt">not an administrator? this panel is only for the people who run this server, so shoo, go away.</p>
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,139 @@
|
||||
{% extends 'base.html' %}
|
||||
{% from '_ui.html' import hub, tile, alert_row %}
|
||||
{% block content %}
|
||||
{% set online = stats.online or {} %}
|
||||
{% set accounts = stats.accounts or {} %}
|
||||
{% set maintenance = info.maintenance or {} %}
|
||||
{{ hub('overview', 'azul ' ~ info.version ~ ', up for ' ~ uptime ~ '.') }}
|
||||
|
||||
{% if maintenance.active or maintenance.pending %}
|
||||
<div class="alert alert-info" role="status"><i class="bi bi-cone-striped" aria-hidden="true"></i><div>{% if maintenance.active %}The server is in maintenance mode.{% else %}Maintenance is coming up in about {{ maintenance.minutes }} minute{{ 's' if maintenance.minutes != 1 else '' }}.{% endif %}</div></div>
|
||||
{% endif %}
|
||||
|
||||
<section aria-labelledby="admNow">
|
||||
<h2 class="visually-hidden" id="admNow">Right now</h2>
|
||||
<div class="ct-tiles adm-tiles">
|
||||
{{ tile('/sessions', 'bi-plug-fill', '{:,}'.format(info.sessions or 0), 'sessions open', '{:,}'.format(info.users_online or 0) ~ (' person' if info.users_online == 1 else ' people') ~ ' signed in', tone='hero', wide=True) }}
|
||||
{{ tile('/users', 'bi-people-fill', '{:,}'.format(accounts.total or 0), 'accounts', '{:,}'.format(accounts.new_week or 0) ~ ' new this week', tone=2) }}
|
||||
{{ tile('/users?show=suspended', 'bi-person-fill-x', '{:,}'.format(suspended), 'suspended', ('deleted after ' ~ suspended_days ~ ' days') if suspended_days is not none else 'kept for good', tone=3) }}
|
||||
{{ tile('/circles', 'bi-chat-square-dots-fill', '{:,}'.format(stats.circles or 0), 'circles', 'group chats', tone=4) }}
|
||||
{{ tile('/broadcast#history', 'bi-bell-fill', '{:,}'.format(alerts_count), 'alerts', 'sent since azul started', tone=5) }}
|
||||
{{ tile('/interservice', 'bi-diagram-3-fill', links | length, 'services linked', clients_active ~ ' enrolled', tone=6) }}
|
||||
{% if maintenance.active %}
|
||||
{{ tile('/broadcast#maintenance', 'bi-cone-striped', 'on', 'maintenance', 'the server is down for it', tone=3) }}
|
||||
{% elif maintenance.pending %}
|
||||
{{ tile('/broadcast#maintenance', 'bi-cone-striped', maintenance.minutes ~ ' min', 'maintenance', 'announced to everyone', tone=3) }}
|
||||
{% else %}
|
||||
{{ tile('/broadcast#maintenance', 'bi-cone-striped', 'none', 'maintenance', 'nothing planned', tone=1) }}
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="adm-columns">
|
||||
<section class="ct-card" aria-labelledby="admDay">
|
||||
<h2 class="ct-card-title" id="admDay">the last 24 hours</h2>
|
||||
{% if hourly %}
|
||||
{% set busiest = hourly | map(attribute='value') | max %}
|
||||
<div class="ct-chart-wrap">
|
||||
<div class="ct-chart" style="--n: {{ hourly | length }}" role="img" aria-label="People active per hour over the last 24 hours. The busiest hour had {{ busiest }}.">
|
||||
{% for h in hourly %}
|
||||
<div class="ct-chart-col{% if h.is_now %} is-now{% endif %}" data-tip="{{ h.label }}: {{ h.value }} active"><div class="ct-chart-bar" style="--h: {{ h.pct }}%; --i: {{ loop.index0 }}"></div></div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<div class="ct-chart-axis" aria-hidden="true"><span>{{ hourly[0].label }}</span><span>{{ hourly[(hourly | length) // 2].label }}</span><span>now</span></div>
|
||||
</div>
|
||||
<details class="ct-details adm-table-details">
|
||||
<summary>show as a table</summary>
|
||||
<div class="ct-details-body">
|
||||
<div class="table-responsive">
|
||||
<table class="ct-table">
|
||||
<caption>Every hour of the last 24, times in UTC</caption>
|
||||
<thead><tr><th scope="col">hour</th><th scope="col">active</th><th scope="col">most online</th><th scope="col">messages sent</th></tr></thead>
|
||||
<tbody>
|
||||
{% for h in hourly | reverse %}
|
||||
<tr><th scope="row" class="fw-normal">{{ h.label }}{% if h.is_now %} <span class="ct-chip ct-chip-success">now</span>{% endif %}</th><td>{{ h.value }}</td><td>{{ h.peak }}</td><td>{{ h.messages }}</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
{% else %}
|
||||
<p class="ct-muted mb-0">Nothing counted yet.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
<section class="ct-card" aria-labelledby="admClients">
|
||||
<h2 class="ct-card-title" id="admClients">clients</h2>
|
||||
{% if programs %}
|
||||
<ul class="ct-bars">
|
||||
{% for p in programs %}
|
||||
<li>
|
||||
<div class="ct-bar-head"><strong>{{ p.name }}</strong><span>{{ '{:,}'.format(p.sessions) }} session{{ 's' if p.sessions != 1 else '' }} · {{ p.pct }}%</span></div>
|
||||
<div class="ct-bar-track" aria-hidden="true"><div class="ct-bar-fill" style="--w: {{ p.pct }}%"></div></div>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% else %}
|
||||
<p class="ct-muted">Nobody is signed in right now.</p>
|
||||
{% endif %}
|
||||
<dl class="ct-facts mt-3">
|
||||
<div><dt>active today</dt><dd>{{ '{:,}'.format((stats.active or {}).today or 0) }}</dd></div>
|
||||
<div><dt>sign-ins today</dt><dd>{{ '{:,}'.format(stats.logins_today or 0) }}</dd></div>
|
||||
<div><dt>messages today</dt><dd>{{ '{:,}'.format(((stats.messages or {}).today or {}).sent or 0) }}</dd></div>
|
||||
<div><dt>most online today</dt><dd>{{ '{:,}'.format((stats.peak_today or {}).value or 0) }}</dd></div>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section class="ct-card" aria-labelledby="admAlerts">
|
||||
<h2 class="ct-card-title" id="admAlerts">latest alerts</h2>
|
||||
{% if alerts %}
|
||||
<ul class="adm-alerts">
|
||||
{% for alert in alerts %}{{ alert_row(alert) }}{% endfor %}
|
||||
</ul>
|
||||
<p class="mt-3 mb-0"><a href="/broadcast#history" data-ct-swap-link>Every alert since azul started</a></p>
|
||||
{% else %}
|
||||
<p class="ct-muted mb-0">None sent since azul started.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
<section class="ct-card" aria-labelledby="admLinks">
|
||||
<h2 class="ct-card-title" id="admLinks">linked services</h2>
|
||||
{% if links %}
|
||||
<ul class="ct-list">
|
||||
{% for link in links %}
|
||||
<li class="ct-list-item">
|
||||
<span class="ct-presence" aria-hidden="true"></span>
|
||||
<span class="ct-list-body">
|
||||
<span class="ct-list-title">{{ link.label or link.identifier }}</span>
|
||||
<span class="ct-list-meta">{{ link.identifier }} from {{ link.peer }}{% if link.client and link.client.program %} · {{ link.client.program }} {{ link.client.version }}{% endif %}</span>
|
||||
</span>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% else %}
|
||||
<p class="ct-muted">Nothing is linked over InterService right now. The website needs its own link for accounts, the directory and CrossTalk Beacon.</p>
|
||||
{% endif %}
|
||||
<h3 class="ct-aside-title mt-3" id="admServices">listening</h3>
|
||||
{% if info.services %}
|
||||
<dl class="ct-facts">
|
||||
{% for service in info.services %}
|
||||
<div><dt>{{ service.name }}</dt><dd>{{ service.ports | join(', ') }}</dd></div>
|
||||
{% endfor %}
|
||||
</dl>
|
||||
{% else %}
|
||||
<p class="ct-muted mb-0">No IM services are listening (none are turned on in the settings).</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section class="mt-4" aria-labelledby="admQuick">
|
||||
<h2 class="ct-section mt-0" id="admQuick">quick jobs</h2>
|
||||
<div class="ct-actions">
|
||||
<a class="btn btn-primary btn-sm" href="/broadcast#alert" data-ct-swap-link>Send an alert</a>
|
||||
<a class="btn btn-outline-secondary btn-sm" href="/broadcast#maintenance" data-ct-swap-link>Schedule maintenance</a>
|
||||
<a class="btn btn-outline-secondary btn-sm" href="/interservice#enroll" data-ct-swap-link>Enroll a service</a>
|
||||
<a class="btn btn-outline-secondary btn-sm" href="/users?show=online" data-ct-swap-link>Who's signed in</a>
|
||||
</div>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,41 @@
|
||||
{% extends 'base.html' %}
|
||||
{% from '_ui.html' import hub, csrf_field %}
|
||||
{% block content %}
|
||||
{{ hub('sessions', '{:,}'.format(count) ~ ' open' ~ (' in ' ~ program_names.get(program, program) if program else '') ~ '.') }}
|
||||
|
||||
{% if programs %}
|
||||
<nav class="ct-pivot ct-pivot-sm mb-3" aria-label="Filter by client" data-ct-swap-pivot>
|
||||
<a href="/sessions" data-ct-swap-link{% if not program %} aria-current="page"{% endif %}>everything <span class="ct-count">{{ total }}</span></a>
|
||||
{% for p, name in programs %}<a href="/sessions?program={{ p | urlencode }}" data-ct-swap-link{% if p == program %} aria-current="page"{% endif %}>{{ name | lower }}</a>{% endfor %}
|
||||
</nav>
|
||||
{% endif %}
|
||||
|
||||
{% if sessions %}
|
||||
<div class="ct-card adm-table-card">
|
||||
<div class="table-responsive">
|
||||
<table class="ct-table ct-table-stack">
|
||||
<thead><tr><th scope="col">who</th><th scope="col">client</th><th scope="col">status</th><th scope="col" class="text-end"><span class="visually-hidden">actions</span></th></tr></thead>
|
||||
<tbody>
|
||||
{% for s in sessions %}
|
||||
<tr>
|
||||
<td><a href="/users/{{ s.uuid }}" data-ct-swap-link><strong>{{ s.username }}</strong></a><br><small class="ct-muted">{{ s.email }}</small></td>
|
||||
<td data-label="client">{{ program_names.get(s.client.program, s.client.program) }} {{ s.client.version }}<br><small class="ct-muted">{{ s.client.via }}</small></td>
|
||||
<td data-label="status">{% if s.visible %}<span class="ct-presence me-1" aria-hidden="true"></span>{% endif %}{{ s.status | lower }}</td>
|
||||
<td class="text-end">
|
||||
<form method="post" class="m-0">
|
||||
{{ csrf_field(csrf) }}
|
||||
<input type="hidden" name="session" value="{{ s.id }}">
|
||||
<input type="hidden" name="program" value="{{ program }}">
|
||||
<button type="submit" class="btn btn-sm btn-outline-danger">Sign out<span class="visually-hidden"> {{ s.username }} from {{ s.client.program }}</span></button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="ct-muted">Nobody is signed in{% if program %} with {{ program_names.get(program, program) }}{% endif %}.</p>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,181 @@
|
||||
{% extends 'base.html' %}
|
||||
{% from '_ui.html' import flags as flag_chips, csrf_field, copy_field %}
|
||||
{% block content %}
|
||||
<p class="ct-back"><a href="/users" data-ct-swap-link>Users</a></p>
|
||||
|
||||
<section class="ct-card adm-identity" aria-labelledby="userName">
|
||||
<span class="adm-avatar adm-avatar-lg">
|
||||
<img src="http://{{ settings.USERSTORAGE_HOST }}/avatar/{{ user.uuid }}/static" alt="" width="72" height="72">
|
||||
{% if user.online %}<span class="ct-presence" aria-hidden="true"></span>{% endif %}
|
||||
</span>
|
||||
<div class="min-w-0 flex-grow-1">
|
||||
<h1 class="adm-identity-name" id="userName">{{ user.username }}</h1>
|
||||
<p class="ct-muted mb-1 text-truncate">{{ user.email }}{% if user.uin %} · UIN {{ user.uin }}{% endif %}</p>
|
||||
<p class="mb-0">{{ flag_chips(user) }}</p>
|
||||
</div>
|
||||
<dl class="adm-identity-facts">
|
||||
<div><dt>status</dt><dd>{% if user.online %}{{ user.status | lower }}, {{ user.sessions }} session{{ 's' if user.sessions != 1 else '' }}{% if programs %} ({{ programs | join(', ') }}){% endif %}{% else %}signed out{% endif %}</dd></div>
|
||||
<div><dt>joined</dt><dd>{{ user.date_created | when }}</dd></div>
|
||||
<div><dt>last signed in</dt><dd>{{ user.date_login | when }}</dd></div>
|
||||
<div><dt>UUID</dt><dd><code class="adm-uuid">{{ user.uuid }}</code><button type="button" class="ct-icon-btn ct-icon-btn-sm" data-ct-copy="{{ user.uuid }}" aria-label="Copy the UUID" title="Copy"><i class="bi bi-copy" aria-hidden="true"></i></button></dd></div>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
{% if user.suspended %}
|
||||
<section class="ct-card adm-suspended" aria-labelledby="userSuspended">
|
||||
<div>
|
||||
<h2 class="adm-suspended-title" id="userSuspended">suspended{% if user.suspended_at %} {{ user.suspended_at | ago }}{% endif %}</h2>
|
||||
{% if user.deleted_at is none or suspended_days is none %}
|
||||
<p class="mb-0">{% if user.suspended_at %}Since {{ user.suspended_at | when }}. {% endif %}Suspended accounts are kept on this server.</p>
|
||||
{% elif user.suspended_at %}
|
||||
<p class="mb-0">Since {{ user.suspended_at | when }}. The account is deleted <strong>{{ user.deleted_at | until }}</strong> ({{ user.deleted_at | when }}), {{ suspended_days }} days after it was suspended, unless it's unsuspended before then.</p>
|
||||
{% else %}
|
||||
<p class="mb-0">It was suspended before azul kept the date, so it's deleted <strong>at the next hourly check</strong>, unless it's unsuspended first.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
{% if reveal and reveal.kind == 'password' %}
|
||||
<section class="ct-card adm-reveal" aria-labelledby="tempPassword">
|
||||
<h2 class="ct-card-title" id="tempPassword">temporary password for {{ reveal['for'] }}</h2>
|
||||
<p>Give it to them however you can reach them. It won't be shown again, and they should change it once they're in.</p>
|
||||
{{ copy_field('tempPasswordValue', reveal.value, 'Temporary password') }}
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
<div class="adm-columns">
|
||||
<section class="ct-card" aria-labelledby="userFlags">
|
||||
<h2 class="ct-card-title" id="userFlags">account</h2>
|
||||
<form method="post">
|
||||
{{ csrf_field(csrf) }}
|
||||
<input type="hidden" name="action" value="flags">
|
||||
<div class="ct-switches">
|
||||
{% for key, label, desc in flags %}
|
||||
<label class="ct-switch-row form-switch" for="flag-{{ key }}">
|
||||
<span>
|
||||
<span class="ct-switch-title">{{ label }}</span>
|
||||
<span class="ct-switch-desc">{{ desc }}{% if key == 'is_admin' and is_self %} You can't turn this off for yourself.{% endif %}{% if key == 'suspended' and suspended_days is not none %} Suspended accounts are deleted after {{ suspended_days }} days.{% endif %}</span>
|
||||
</span>
|
||||
<input class="form-check-input" type="checkbox" role="switch" id="flag-{{ key }}" name="{{ key }}"{% if user[key] %} checked{% endif %}{% if key == 'is_admin' and is_self %} disabled{% endif %}>
|
||||
</label>
|
||||
{% if key == 'is_admin' and is_self and user[key] %}<input type="hidden" name="is_admin" value="on">{% endif %}
|
||||
{% endfor %}
|
||||
</div>
|
||||
<div class="ct-form-actions"><button type="submit" class="btn btn-primary">Save</button></div>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<div>
|
||||
<section class="ct-card" aria-labelledby="userAlert">
|
||||
<h2 class="ct-card-title" id="userAlert">alert</h2>
|
||||
<form method="post" class="adm-mini-alert">
|
||||
{{ csrf_field(csrf) }}
|
||||
<input type="hidden" name="action" value="alert">
|
||||
<div class="ct-field">
|
||||
<label for="alertMessage" class="form-label">Message</label>
|
||||
<textarea class="form-control" id="alertMessage" name="message" rows="3" maxlength="1000" required aria-describedby="alertMarkup"></textarea>
|
||||
<small class="form-text" id="alertMarkup">**bold**, *italic*, and a blank line for a new paragraph: Messenger 6 and later show them, the rest get the words.</small>
|
||||
</div>
|
||||
<div class="ct-field">
|
||||
<label for="alertUrl" class="form-label">Link <span class="ct-muted">(optional)</span></label>
|
||||
<input type="url" class="form-control" id="alertUrl" name="url" inputmode="url" placeholder="https://">
|
||||
</div>
|
||||
{% if email_available %}
|
||||
<div class="form-check form-switch my-3">
|
||||
<input class="form-check-input" type="checkbox" role="switch" id="alertEmail" name="email">
|
||||
<label class="form-check-label" for="alertEmail">Also e-mail it to {{ user.email }}</label>
|
||||
</div>
|
||||
{% endif %}
|
||||
<button type="submit" class="btn btn-outline-secondary"{% if not user.online and not email_available %} disabled aria-describedby="alertOffline"{% endif %}>Send alert</button>
|
||||
{% if not user.online %}<p class="form-text" id="alertOffline">{{ user.username }} isn't signed in{% if email_available %}, so only an e-mail copy would reach them{% else %}, and the website isn't linked to e-mail it{% endif %}.</p>{% endif %}
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="ct-card" aria-labelledby="userSessions">
|
||||
<h2 class="ct-card-title" id="userSessions">sessions</h2>
|
||||
{% if sessions %}
|
||||
<ul class="ct-list">
|
||||
{% for s in sessions %}
|
||||
<li class="ct-list-item">
|
||||
<span class="ct-list-body">
|
||||
<span class="ct-list-title">{{ program_names.get(s.client.program, s.client.program) }} {{ s.client.version }}</span>
|
||||
<span class="ct-list-meta">{{ s.status | lower }} via {{ s.client.via }}</span>
|
||||
</span>
|
||||
<form method="post" class="m-0">
|
||||
{{ csrf_field(csrf) }}
|
||||
<input type="hidden" name="action" value="kill">
|
||||
<input type="hidden" name="session" value="{{ s.id }}">
|
||||
<button type="submit" class="btn btn-sm btn-outline-danger">Sign out<span class="visually-hidden"> {{ s.client.program }}</span></button>
|
||||
</form>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
<form method="post" class="mt-2">
|
||||
{{ csrf_field(csrf) }}
|
||||
<input type="hidden" name="action" value="kill-all">
|
||||
<button type="submit" class="btn btn-outline-danger">Sign out everywhere</button>
|
||||
</form>
|
||||
{% else %}
|
||||
<p class="ct-muted">Not signed in anywhere.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
<section class="ct-card" aria-labelledby="userPassword">
|
||||
<h2 class="ct-card-title" id="userPassword">password</h2>
|
||||
<form method="post" class="mb-3">
|
||||
{{ csrf_field(csrf) }}
|
||||
<input type="hidden" name="action" value="password">
|
||||
<div class="ct-field">
|
||||
<label for="newPassword" class="form-label">New password</label>
|
||||
<div class="ct-password">
|
||||
<input type="password" class="form-control" id="newPassword" name="password" minlength="6" autocomplete="new-password" required>
|
||||
<button type="button" class="ct-icon-btn" data-ct-reveal="newPassword" aria-pressed="false" aria-label="Show password"><i class="bi bi-eye-fill" aria-hidden="true"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
<fieldset class="adm-inline-checks">
|
||||
<legend class="form-label">Keep working in</legend>
|
||||
{% for flag, name in legacy_clients %}
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" id="client-{{ flag }}" name="client_{{ flag }}"{% if flag in (user.clients or []) %} checked{% endif %}>
|
||||
<label class="form-check-label" for="client-{{ flag }}">{{ name }}</label>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</fieldset>
|
||||
<button type="submit" class="btn btn-primary">Set password</button>
|
||||
</form>
|
||||
<div class="ct-actions">
|
||||
<form method="post" class="m-0">
|
||||
{{ csrf_field(csrf) }}
|
||||
<input type="hidden" name="action" value="temp-password">
|
||||
<button type="submit" class="btn btn-outline-secondary">Make a temporary one</button>
|
||||
</form>
|
||||
<form method="post" class="m-0">
|
||||
{{ csrf_field(csrf) }}
|
||||
<input type="hidden" name="action" value="reset-email">
|
||||
<button type="submit" class="btn btn-outline-secondary"{% if not reset_available %} disabled aria-describedby="resetHelp"{% endif %}>E-mail them a reset link</button>
|
||||
</form>
|
||||
</div>
|
||||
{% if not reset_available %}<p class="form-text" id="resetHelp">The website isn't linked right now, so it can't send the e-mail.</p>{% endif %}
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section class="ct-card adm-danger" aria-labelledby="userDelete">
|
||||
<h2 class="ct-card-title" id="userDelete">delete this account</h2>
|
||||
{% if is_self %}
|
||||
<p class="ct-muted mb-0">You can't delete your own account from the admin panel.</p>
|
||||
{% else %}
|
||||
<p>Removes {{ user.username }} for good: their contacts, CrossTalk Beacon posts, reactions and comments go too, and circles they ran pass to the next administrator or member. It can't be undone.</p>
|
||||
<form method="post" class="adm-confirm">
|
||||
{{ csrf_field(csrf) }}
|
||||
<input type="hidden" name="action" value="delete">
|
||||
<label for="deleteConfirm" class="form-label">Type <strong>{{ user.username }}</strong> to confirm</label>
|
||||
<div class="d-flex flex-wrap gap-2">
|
||||
<input type="text" class="form-control" id="deleteConfirm" name="confirm" autocomplete="off" spellcheck="false" required>
|
||||
<button type="submit" class="btn btn-danger">Delete account</button>
|
||||
</div>
|
||||
</form>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,50 @@
|
||||
{% extends 'base.html' %}
|
||||
{% from '_ui.html' import hub, flags, pager %}
|
||||
{% block content %}
|
||||
{{ hub('users', '{:,}'.format(total or 0) ~ ' accounts, ' ~ '{:,}'.format(online or 0) ~ ' signed in right now.') }}
|
||||
|
||||
<form method="get" action="/users" class="adm-search" role="search" aria-label="Search users" data-ct-swap-form>
|
||||
{% if show %}<input type="hidden" name="show" value="{{ show }}">{% endif %}
|
||||
<div class="ct-search flex-grow-1">
|
||||
<i class="bi bi-search" aria-hidden="true"></i>
|
||||
<label for="userSearch" class="visually-hidden">Search by username, e-mail or UUID</label>
|
||||
<input type="search" class="form-control" id="userSearch" name="q" value="{{ q }}" placeholder="Username, e-mail or UUID" autocomplete="off" spellcheck="false">
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">Search</button>
|
||||
{% if q %}<a class="btn btn-outline-secondary" href="/users{% if show %}?show={{ show }}{% endif %}" data-ct-swap-link>Clear</a>{% endif %}
|
||||
</form>
|
||||
|
||||
{% set query = ('&q=' ~ (q | urlencode)) if q else '' %}
|
||||
<nav class="ct-pivot ct-pivot-sm adm-filters" aria-label="Show" data-ct-swap-pivot>
|
||||
<a href="/users{% if q %}?q={{ q | urlencode }}{% endif %}" data-ct-swap-link{% if not show %} aria-current="page"{% endif %}>everyone</a>
|
||||
{% for name, label, _ in filters %}
|
||||
<a href="/users?show={{ name }}{{ query }}" data-ct-swap-link{% if show == name %} aria-current="page"{% endif %}>{{ label }}</a>
|
||||
{% endfor %}
|
||||
</nav>
|
||||
|
||||
{% if q or show %}<p class="ct-muted mb-3">{{ '{:,}'.format(matched) }} {{ 'account' if matched == 1 else 'accounts' }}{% if q %} matching "{{ q }}"{% endif %}</p>{% endif %}
|
||||
|
||||
{% if users %}
|
||||
<ul class="adm-people ct-card">
|
||||
{% for u in users %}
|
||||
<li>
|
||||
<a class="adm-person" href="/users/{{ u.uuid }}" data-ct-swap-link>
|
||||
<span class="adm-avatar">
|
||||
<img src="http://{{ settings.USERSTORAGE_HOST }}/avatar/{{ u.uuid }}/im" alt="" width="36" height="36" loading="lazy">
|
||||
{% if u.online %}<span class="ct-presence" aria-hidden="true"></span>{% endif %}
|
||||
</span>
|
||||
<span class="adm-person-body">
|
||||
<span class="adm-person-name">{{ u.username }}{% if u.online %}<span class="visually-hidden">, signed in</span>{% endif %}</span>
|
||||
<span class="adm-person-meta">{{ u.email }}{% if u.suspended and u.deleted_at %} · <span class="adm-doomed">deleted {{ u.deleted_at | until }}</span>{% endif %}</span>
|
||||
</span>
|
||||
<span class="adm-person-flags">{{ flags(u) }}</span>
|
||||
<span class="adm-person-when ct-muted">joined {{ u.date_created | ago }}<br>last in {{ u.date_login | ago }}</span>
|
||||
</a>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{{ pager(page, pages, '/users?' ~ ('show=' ~ show ~ '&' if show else '') ~ ('q=' ~ (q | urlencode) ~ '&' if q else '')) }}
|
||||
{% else %}
|
||||
<p class="ct-muted">{% if q or show %}Nobody matches that.{% else %}There are no accounts yet.{% endif %}</p>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
Reference in new issue
Block a user