forked from ProfessionalUwU/stickerpicker
Add server with basic auth stuff
This commit is contained in:
6
sticker/server/database/__init__.py
Normal file
6
sticker/server/database/__init__.py
Normal file
@ -0,0 +1,6 @@
|
||||
from .base import Base
|
||||
from .upgrade import upgrade_table
|
||||
from .sticker import Sticker
|
||||
from .pack import Pack
|
||||
from .access_token import AccessToken
|
||||
from .user import User
|
71
sticker/server/database/access_token.py
Normal file
71
sticker/server/database/access_token.py
Normal file
@ -0,0 +1,71 @@
|
||||
# maunium-stickerpicker - A fast and simple Matrix sticker picker widget.
|
||||
# Copyright (C) 2020 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from typing import Optional, ClassVar
|
||||
from datetime import datetime, timedelta
|
||||
import hashlib
|
||||
|
||||
from attr import dataclass
|
||||
import asyncpg
|
||||
|
||||
from mautrix.types import UserID
|
||||
|
||||
from .base import Base
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class AccessToken(Base):
|
||||
token_expiry: ClassVar[timedelta] = timedelta(days=1)
|
||||
|
||||
user_id: UserID
|
||||
token_id: int
|
||||
token_hash: bytes
|
||||
last_seen_ip: str
|
||||
last_seen_date: datetime
|
||||
|
||||
@classmethod
|
||||
async def get(cls, token_id: int) -> Optional['AccessToken']:
|
||||
q = "SELECT user_id, token_hash, last_seen_ip, last_seen_date FROM pack WHERE token_id=$1"
|
||||
row: asyncpg.Record = await cls.db.fetchrow(q, token_id)
|
||||
if row is None:
|
||||
return None
|
||||
return cls(**row, token_id=token_id)
|
||||
|
||||
async def update_ip(self, ip: str) -> None:
|
||||
if self.last_seen_ip == ip and (self.last_seen_date.replace(second=0, microsecond=0)
|
||||
== datetime.now().replace(second=0, microsecond=0)):
|
||||
# Same IP and last seen on this minute, skip update
|
||||
return
|
||||
q = ("UPDATE access_token SET last_seen_ip=$3, last_seen_date=current_timestamp "
|
||||
"WHERE token_id=$1 RETURNING last_seen_date")
|
||||
self.last_seen_date = await self.db.fetchval(q, self.token_id, ip)
|
||||
self.last_seen_ip = ip
|
||||
|
||||
def check(self, token: str) -> bool:
|
||||
return self.token_hash == hashlib.sha256(token.encode("utf-8")).digest()
|
||||
|
||||
@property
|
||||
def expired(self) -> bool:
|
||||
return self.last_seen_date + self.token_expiry < datetime.now()
|
||||
|
||||
async def delete(self) -> None:
|
||||
await self.db.execute("DELETE FROM access_token WHERE token_id=$1", self.token_id)
|
||||
|
||||
@classmethod
|
||||
async def insert(cls, user_id: UserID, token: str, ip: str) -> int:
|
||||
q = ("INSERT INTO access_token (user_id, token_hash, last_seen_ip, last_seen_date) "
|
||||
"VALUES ($1, $2, $3, current_timestamp) RETURNING token_id")
|
||||
hashed = hashlib.sha256(token.encode("utf-8")).digest()
|
||||
return await cls.db.fetchval(q, user_id, hashed, ip)
|
9
sticker/server/database/base.py
Normal file
9
sticker/server/database/base.py
Normal file
@ -0,0 +1,9 @@
|
||||
from typing import ClassVar, TYPE_CHECKING
|
||||
|
||||
from mautrix.util.async_db import Database
|
||||
|
||||
fake_db = Database("") if TYPE_CHECKING else None
|
||||
|
||||
|
||||
class Base:
|
||||
db: ClassVar[Database] = fake_db
|
58
sticker/server/database/pack.py
Normal file
58
sticker/server/database/pack.py
Normal file
@ -0,0 +1,58 @@
|
||||
# maunium-stickerpicker - A fast and simple Matrix sticker picker widget.
|
||||
# Copyright (C) 2020 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from typing import List, Dict, Any
|
||||
|
||||
from attr import dataclass
|
||||
|
||||
from mautrix.types import UserID
|
||||
|
||||
from .base import Base
|
||||
from .sticker import Sticker
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class Pack(Base):
|
||||
id: str
|
||||
owner: UserID
|
||||
title: str
|
||||
meta: Dict[str, Any]
|
||||
|
||||
async def delete(self) -> None:
|
||||
await self.db.execute("DELETE FROM pack WHERE id=$1", self.id)
|
||||
|
||||
async def insert(self) -> None:
|
||||
await self.db.execute("INSERT INTO pack (id, owner, title, meta) VALUES ($1, $2, $3, $4)",
|
||||
self.id, self.owner, self.title, self.meta)
|
||||
|
||||
async def get_stickers(self) -> List[Sticker]:
|
||||
res = await self.db.fetch('SELECT id, url, body, meta, "order" '
|
||||
'FROM sticker WHERE pack_id=$1 ORDER BY "order"', self.id)
|
||||
return [Sticker(**row, pack_id=self.id) for row in res]
|
||||
|
||||
async def set_stickers(self, stickers: List[Sticker]) -> None:
|
||||
data = ((sticker.id, self.id, sticker.url, sticker.body, sticker.meta, order)
|
||||
for order, sticker in enumerate(stickers))
|
||||
columns = ["id", "pack_id", "url", "body", "meta", "order"]
|
||||
async with self.db.acquire() as conn, conn.transaction():
|
||||
await conn.execute("DELETE FROM sticker WHERE pack_id=$1", self.id)
|
||||
await conn.copy_records_to_table("sticker", records=data, columns=columns)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
**self.meta,
|
||||
"title": self.title,
|
||||
"id": self.id,
|
||||
}
|
49
sticker/server/database/sticker.py
Normal file
49
sticker/server/database/sticker.py
Normal file
@ -0,0 +1,49 @@
|
||||
# maunium-stickerpicker - A fast and simple Matrix sticker picker widget.
|
||||
# Copyright (C) 2020 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from typing import Dict, Any
|
||||
|
||||
from attr import dataclass
|
||||
import attr
|
||||
|
||||
from mautrix.types import ContentURI
|
||||
|
||||
from .base import Base
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class Sticker(Base):
|
||||
pack_id: str
|
||||
order: int
|
||||
id: str
|
||||
url: ContentURI = attr.ib(order=False)
|
||||
body: str = attr.ib(order=False)
|
||||
meta: Dict[str, Any] = attr.ib(order=False)
|
||||
|
||||
async def delete(self) -> None:
|
||||
await self.db.execute("DELETE FROM sticker WHERE id=$1", self.id)
|
||||
|
||||
async def insert(self) -> None:
|
||||
await self.db.execute('INSERT INTO sticker (id, pack_id, url, body, meta, "order") '
|
||||
"VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
self.id, self.pack_id, self.url, self.body, self.meta, self.order)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
**self.meta,
|
||||
"body": self.body,
|
||||
"url": self.url,
|
||||
"id": self.id,
|
||||
}
|
56
sticker/server/database/upgrade.py
Normal file
56
sticker/server/database/upgrade.py
Normal file
@ -0,0 +1,56 @@
|
||||
# maunium-stickerpicker - A fast and simple Matrix sticker picker widget.
|
||||
# Copyright (C) 2020 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from asyncpg import Connection
|
||||
|
||||
from mautrix.util.async_db.upgrade import UpgradeTable
|
||||
|
||||
upgrade_table = UpgradeTable()
|
||||
|
||||
|
||||
@upgrade_table.register(description="Initial revision")
|
||||
async def upgrade_v1(conn: Connection) -> None:
|
||||
await conn.execute("""CREATE TABLE "user" (
|
||||
id TEXT PRIMARY KEY,
|
||||
widget_secret TEXT NOT NULL,
|
||||
homeserver_url TEXT NOT NULL
|
||||
)""")
|
||||
await conn.execute("""CREATE TABLE access_token (
|
||||
token_id SERIAL PRIMARY KEY,
|
||||
user_id TEXT NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,
|
||||
token_hash BYTEA NOT NULL,
|
||||
last_seen_ip TEXT,
|
||||
last_seen_date TIMESTAMP
|
||||
)""")
|
||||
await conn.execute("""CREATE TABLE pack (
|
||||
id TEXT PRIMARY KEY,
|
||||
owner TEXT REFERENCES "user"(id) ON DELETE SET NULL,
|
||||
title TEXT NOT NULL,
|
||||
meta JSONB NOT NULL
|
||||
)""")
|
||||
await conn.execute("""CREATE TABLE user_pack (
|
||||
user_id TEXT REFERENCES "user"(id) ON DELETE CASCADE,
|
||||
pack_id TEXT REFERENCES pack(id) ON DELETE CASCADE,
|
||||
"order" INT NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (user_id, pack_id)
|
||||
)""")
|
||||
await conn.execute("""CREATE TABLE sticker (
|
||||
id TEXT PRIMARY KEY,
|
||||
pack_id TEXT NOT NULL REFERENCES pack(id) ON DELETE CASCADE,
|
||||
url TEXT NOT NULL,
|
||||
body TEXT NOT NULL,
|
||||
meta JSONB NOT NULL,
|
||||
"order" INT NOT NULL DEFAULT 0
|
||||
)""")
|
95
sticker/server/database/user.py
Normal file
95
sticker/server/database/user.py
Normal file
@ -0,0 +1,95 @@
|
||||
# maunium-stickerpicker - A fast and simple Matrix sticker picker widget.
|
||||
# Copyright (C) 2020 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from typing import Optional, List, ClassVar
|
||||
import random
|
||||
import string
|
||||
|
||||
from attr import dataclass
|
||||
import asyncpg
|
||||
|
||||
from mautrix.types import UserID
|
||||
|
||||
from .base import Base
|
||||
from .pack import Pack
|
||||
from .access_token import AccessToken
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class User(Base):
|
||||
token_charset: ClassVar[str] = string.ascii_letters + string.digits
|
||||
|
||||
id: UserID
|
||||
widget_secret: str
|
||||
homeserver_url: str
|
||||
|
||||
@classmethod
|
||||
def _random_token(cls) -> str:
|
||||
return "".join(random.choices(cls.token_charset, k=64))
|
||||
|
||||
@classmethod
|
||||
def new(cls, id: UserID, homeserver_url: str) -> 'User':
|
||||
return User(id=id, widget_secret=cls._random_token(), homeserver_url=homeserver_url)
|
||||
|
||||
@classmethod
|
||||
async def get(cls, id: UserID) -> Optional['User']:
|
||||
q = 'SELECT id, widget_secret, homeserver_url FROM "user" WHERE id=$1'
|
||||
row: asyncpg.Record = await cls.db.fetchrow(q, id)
|
||||
if row is None:
|
||||
return None
|
||||
return cls(**row)
|
||||
|
||||
async def regenerate_widget_secret(self) -> None:
|
||||
self.widget_secret = self._random_token()
|
||||
await self.db.execute('UPDATE "user" SET widget_secret=$1 WHERE id=$2',
|
||||
self.widget_secret, self.id)
|
||||
|
||||
async def set_homeserver_url(self, url: str) -> None:
|
||||
self.homeserver_url = url
|
||||
await self.db.execute('UPDATE "user" SET homeserver_url=$1 WHERE id=$2', url, self.id)
|
||||
|
||||
async def new_access_token(self, ip: str) -> str:
|
||||
token = self._random_token()
|
||||
token_id = await AccessToken.insert(self.id, token, ip)
|
||||
return f"{token_id}:{token}"
|
||||
|
||||
async def delete(self) -> None:
|
||||
await self.db.execute('DELETE FROM "user" WHERE id=$1', self.id)
|
||||
|
||||
async def insert(self) -> None:
|
||||
q = 'INSERT INTO "user" (id, widget_secret, homeserver_url) VALUES ($1, $2, $3)'
|
||||
await self.db.execute(q, self.id, self.widget_secret, self.homeserver_url)
|
||||
|
||||
async def get_packs(self) -> List[Pack]:
|
||||
res = await self.db.fetch("SELECT id, owner, title, meta FROM user_pack "
|
||||
"LEFT JOIN pack ON pack.id=user_pack.pack_id "
|
||||
'WHERE user_id=$1 ORDER BY "order"', self.id)
|
||||
return [Pack(**row) for row in res]
|
||||
|
||||
async def get_pack(self, pack_id: str) -> Optional[Pack]:
|
||||
row = await self.db.fetchrow("SELECT id, owner, title, meta FROM user_pack "
|
||||
"LEFT JOIN pack ON pack.id=user_pack.pack_id "
|
||||
"WHERE user_id=$1 AND pack_id=$2", self.id, pack_id)
|
||||
if row is None:
|
||||
return None
|
||||
return Pack(**row)
|
||||
|
||||
async def set_packs(self, packs: List[Pack]) -> None:
|
||||
data = ((self.id, pack.id, order)
|
||||
for order, pack in enumerate(packs))
|
||||
columns = ["user_id", "pack_id", "order"]
|
||||
async with self.db.acquire() as conn, conn.transaction():
|
||||
await conn.execute("DELETE FROM user_pack WHERE user_id=$1", self.id)
|
||||
await conn.copy_records_to_table("user_pack", records=data, columns=columns)
|
Reference in New Issue
Block a user