init
This commit is contained in:
commit
97a64296cd
28 changed files with 2288 additions and 0 deletions
3
.gitignore
vendored
Normal file
3
.gitignore
vendored
Normal file
|
@ -0,0 +1,3 @@
|
|||
__pycache__/
|
||||
.pytest_cache/
|
||||
.env
|
201
LICENSE
Normal file
201
LICENSE
Normal file
|
@ -0,0 +1,201 @@
|
|||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
1
README.md
Normal file
1
README.md
Normal file
|
@ -0,0 +1 @@
|
|||
# pronouns.cc
|
114
alembic.ini
Normal file
114
alembic.ini
Normal file
|
@ -0,0 +1,114 @@
|
|||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# path to migration scripts
|
||||
script_location = alembic
|
||||
|
||||
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
||||
# Uncomment the line below if you want the files to be prepended with date and time
|
||||
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
|
||||
# for all available tokens
|
||||
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
||||
|
||||
# sys.path path, will be prepended to sys.path if present.
|
||||
# defaults to the current working directory.
|
||||
prepend_sys_path = .
|
||||
|
||||
# timezone to use when rendering the date within the migration file
|
||||
# as well as the filename.
|
||||
# If specified, requires the python>=3.9 or backports.zoneinfo library.
|
||||
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
|
||||
# string value is passed to ZoneInfo()
|
||||
# leave blank for localtime
|
||||
# timezone =
|
||||
|
||||
# max length of characters to apply to the
|
||||
# "slug" field
|
||||
# truncate_slug_length = 40
|
||||
|
||||
# set to 'true' to run the environment during
|
||||
# the 'revision' command, regardless of autogenerate
|
||||
# revision_environment = false
|
||||
|
||||
# set to 'true' to allow .pyc and .pyo files without
|
||||
# a source .py file to be detected as revisions in the
|
||||
# versions/ directory
|
||||
# sourceless = false
|
||||
|
||||
# version location specification; This defaults
|
||||
# to alembic/versions. When using multiple version
|
||||
# directories, initial revisions must be specified with --version-path.
|
||||
# The path separator used here should be the separator specified by "version_path_separator" below.
|
||||
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
|
||||
|
||||
# version path separator; As mentioned above, this is the character used to split
|
||||
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
|
||||
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
|
||||
# Valid values for version_path_separator are:
|
||||
#
|
||||
# version_path_separator = :
|
||||
# version_path_separator = ;
|
||||
# version_path_separator = space
|
||||
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
|
||||
|
||||
# set to 'true' to search source files recursively
|
||||
# in each "version_locations" directory
|
||||
# new in Alembic version 1.10
|
||||
# recursive_version_locations = false
|
||||
|
||||
# the output encoding used when revision files
|
||||
# are written from script.py.mako
|
||||
# output_encoding = utf-8
|
||||
|
||||
|
||||
[post_write_hooks]
|
||||
# post_write_hooks defines scripts or Python functions that are run
|
||||
# on newly generated revision scripts. See the documentation for further
|
||||
# detail and examples
|
||||
|
||||
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||
# hooks = black
|
||||
# black.type = console_scripts
|
||||
# black.entrypoint = black
|
||||
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
||||
|
||||
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
|
||||
# hooks = ruff
|
||||
# ruff.type = exec
|
||||
# ruff.executable = %(here)s/.venv/bin/ruff
|
||||
# ruff.options = --fix REVISION_SCRIPT_FILENAME
|
||||
|
||||
# Logging configuration
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
1
alembic/README
Normal file
1
alembic/README
Normal file
|
@ -0,0 +1 @@
|
|||
Generic single-database configuration.
|
84
alembic/env.py
Normal file
84
alembic/env.py
Normal file
|
@ -0,0 +1,84 @@
|
|||
from logging.config import fileConfig
|
||||
|
||||
from sqlalchemy import engine_from_config
|
||||
from sqlalchemy import pool
|
||||
|
||||
from alembic import context
|
||||
|
||||
from foxnouns.db import Base
|
||||
from foxnouns.settings import SYNC_DATABASE_URL
|
||||
|
||||
# this is the Alembic Config object, which provides
|
||||
# access to the values within the .ini file in use.
|
||||
config = context.config
|
||||
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
# from myapp import mymodel
|
||||
# target_metadata = mymodel.Base.metadata
|
||||
target_metadata = Base.metadata
|
||||
|
||||
# other values from the config, defined by the needs of env.py,
|
||||
# can be acquired:
|
||||
# my_important_option = config.get_main_option("my_important_option")
|
||||
# ... etc.
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
"""Run migrations in 'offline' mode.
|
||||
|
||||
This configures the context with just a URL
|
||||
and not an Engine, though an Engine is acceptable
|
||||
here as well. By skipping the Engine creation
|
||||
we don't even need a DBAPI to be available.
|
||||
|
||||
Calls to context.execute() here emit the given string to the
|
||||
script output.
|
||||
|
||||
"""
|
||||
url = SYNC_DATABASE_URL
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
"""Run migrations in 'online' mode.
|
||||
|
||||
In this scenario we need to create an Engine
|
||||
and associate a connection with the context.
|
||||
|
||||
"""
|
||||
engine_config = config.get_section(config.config_ini_section, {})
|
||||
engine_config["sqlalchemy.url"] = SYNC_DATABASE_URL
|
||||
|
||||
connectable = engine_from_config(
|
||||
engine_config,
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
with connectable.connect() as connection:
|
||||
context.configure(
|
||||
connection=connection, target_metadata=target_metadata
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
26
alembic/script.py.mako
Normal file
26
alembic/script.py.mako
Normal file
|
@ -0,0 +1,26 @@
|
|||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = ${repr(up_revision)}
|
||||
down_revision: Union[str, None] = ${repr(down_revision)}
|
||||
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
37
alembic/versions/0b63f7c8ab96_add_tokens.py
Normal file
37
alembic/versions/0b63f7c8ab96_add_tokens.py
Normal file
|
@ -0,0 +1,37 @@
|
|||
"""Add tokens
|
||||
|
||||
Revision ID: 0b63f7c8ab96
|
||||
Revises: b39613fd7327
|
||||
Create Date: 2024-03-13 17:01:50.434602
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "0b63f7c8ab96"
|
||||
down_revision: Union[str, None] = "b39613fd7327"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"tokens",
|
||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
||||
sa.Column("expires_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("scopes", postgresql.ARRAY(sa.Text()), nullable=False),
|
||||
sa.Column("user_id", sa.BigInteger(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["user_id"],
|
||||
["users.id"],
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table("tokens")
|
64
alembic/versions/b39613fd7327_init.py
Normal file
64
alembic/versions/b39613fd7327_init.py
Normal file
|
@ -0,0 +1,64 @@
|
|||
"""Init
|
||||
|
||||
Revision ID: b39613fd7327
|
||||
Revises:
|
||||
Create Date: 2024-03-09 16:32:28.590145
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "b39613fd7327"
|
||||
down_revision: Union[str, None] = None
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"fediverse_apps",
|
||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
||||
sa.Column("instance", sa.Text(), nullable=False),
|
||||
sa.Column("client_id", sa.Text(), nullable=False),
|
||||
sa.Column("client_secret", sa.Text(), nullable=False),
|
||||
sa.Column("instance_type", sa.Integer(), nullable=False),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("instance"),
|
||||
)
|
||||
op.create_table(
|
||||
"users",
|
||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
||||
sa.Column("username", sa.Text(), nullable=False),
|
||||
sa.Column("display_name", sa.Text(), nullable=True),
|
||||
sa.Column("bio", sa.Text(), nullable=True),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("username"),
|
||||
)
|
||||
op.create_table(
|
||||
"auth_methods",
|
||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
||||
sa.Column("auth_type", sa.Integer(), nullable=False),
|
||||
sa.Column("remote_id", sa.Text(), nullable=False),
|
||||
sa.Column("remote_username", sa.Text(), nullable=True),
|
||||
sa.Column("user_id", sa.BigInteger(), nullable=False),
|
||||
sa.Column("fediverse_app_id", sa.BigInteger(), nullable=True),
|
||||
sa.ForeignKeyConstraint(
|
||||
["fediverse_app_id"],
|
||||
["fediverse_apps.id"],
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["user_id"],
|
||||
["users.id"],
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table("auth_methods")
|
||||
op.drop_table("users")
|
||||
op.drop_table("fediverse_apps")
|
0
foxnouns/__init__.py
Normal file
0
foxnouns/__init__.py
Normal file
24
foxnouns/app.py
Normal file
24
foxnouns/app.py
Normal file
|
@ -0,0 +1,24 @@
|
|||
from quart import Quart, make_response, jsonify
|
||||
from quart_schema import QuartSchema, RequestSchemaValidationError
|
||||
|
||||
from .blueprints import users_blueprint
|
||||
from .exceptions import ExpectedError
|
||||
|
||||
app = Quart(__name__)
|
||||
QuartSchema(app)
|
||||
|
||||
app.register_blueprint(users_blueprint)
|
||||
|
||||
for route in app.url_map.iter_rules():
|
||||
print(route, route.host)
|
||||
|
||||
|
||||
@app.errorhandler(RequestSchemaValidationError)
|
||||
async def handle_request_validation_error(error: RequestSchemaValidationError):
|
||||
print(error.validation_error)
|
||||
return {"error": "VALIDATION"}, 400
|
||||
|
||||
|
||||
@app.errorhandler(ExpectedError)
|
||||
async def handle_expected_error(error: ExpectedError):
|
||||
return {"code": error.type, "message": error.msg}, error.status_code
|
1
foxnouns/blueprints/__init__.py
Normal file
1
foxnouns/blueprints/__init__.py
Normal file
|
@ -0,0 +1 @@
|
|||
from .v2.users import bp as users_blueprint
|
45
foxnouns/blueprints/v2/users.py
Normal file
45
foxnouns/blueprints/v2/users.py
Normal file
|
@ -0,0 +1,45 @@
|
|||
from pydantic import BaseModel, Field, field_validator
|
||||
from quart import Blueprint, request
|
||||
from quart_schema import validate_response, validate_request
|
||||
|
||||
from foxnouns.db.aio import async_session
|
||||
from foxnouns.db.util import user_from_ref
|
||||
from foxnouns.exceptions import NotFoundError, ErrorCode
|
||||
from foxnouns.models.user import UserModel, check_username
|
||||
from foxnouns.settings import BASE_DOMAIN, SHORT_DOMAIN
|
||||
|
||||
bp = Blueprint("users_v2", __name__)
|
||||
|
||||
|
||||
@bp.get("/api/v2/users/<user_ref>", host=BASE_DOMAIN)
|
||||
@validate_response(UserModel, 200)
|
||||
async def get_user(user_ref: str):
|
||||
print(request.host)
|
||||
|
||||
async with async_session() as session:
|
||||
user = await user_from_ref(session, user_ref)
|
||||
if not user:
|
||||
raise NotFoundError("User not found", type=ErrorCode.UserNotFound)
|
||||
return UserModel.model_validate(user)
|
||||
|
||||
@bp.get("/api/v2/users/<user_ref>", host=SHORT_DOMAIN)
|
||||
async def hello(user_ref):
|
||||
return {"hello": f"from {SHORT_DOMAIN}"}
|
||||
|
||||
|
||||
class EditUserRequest(BaseModel):
|
||||
username: str | None = Field(
|
||||
min_length=2, max_length=40, pattern=r"^[\w\-\.]{2,40}$", default=None
|
||||
)
|
||||
display_name: str | None = Field(min_length=2, max_length=100, default=None)
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
def check_username(cls, value):
|
||||
return check_username(value)
|
||||
|
||||
|
||||
@bp.patch("/api/v2/users/@me", host=BASE_DOMAIN)
|
||||
@validate_request(EditUserRequest)
|
||||
async def edit_user(data: EditUserRequest):
|
||||
return data
|
2
foxnouns/db/__init__.py
Normal file
2
foxnouns/db/__init__.py
Normal file
|
@ -0,0 +1,2 @@
|
|||
from .base import Base
|
||||
from .user import User, Token, AuthMethod, FediverseApp
|
6
foxnouns/db/aio.py
Normal file
6
foxnouns/db/aio.py
Normal file
|
@ -0,0 +1,6 @@
|
|||
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
|
||||
|
||||
from foxnouns.settings import ASYNC_DATABASE_URL
|
||||
|
||||
engine = create_async_engine(ASYNC_DATABASE_URL)
|
||||
async_session = async_sessionmaker(engine, expire_on_commit=False)
|
4
foxnouns/db/base.py
Normal file
4
foxnouns/db/base.py
Normal file
|
@ -0,0 +1,4 @@
|
|||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
110
foxnouns/db/snowflake.py
Normal file
110
foxnouns/db/snowflake.py
Normal file
|
@ -0,0 +1,110 @@
|
|||
import os
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
from random import randrange
|
||||
|
||||
_local = threading.local()
|
||||
|
||||
|
||||
def _get_increment() -> int:
|
||||
if not hasattr(_local, "increment"):
|
||||
_local.increment = randrange(0, 4095)
|
||||
|
||||
increment = _local.increment
|
||||
_local.increment += 1
|
||||
return increment
|
||||
|
||||
|
||||
class Snowflake:
|
||||
"""A Snowflake ID (https://en.wikipedia.org/wiki/Snowflake_ID).
|
||||
This class wraps an integer and adds convenience functions."""
|
||||
|
||||
EPOCH = 1_640_995_200_000 # 2022-01-01 at 00:00:00 UTC
|
||||
|
||||
_raw: int
|
||||
|
||||
def __init__(self, src: int):
|
||||
self._raw = src
|
||||
|
||||
def __str__(self) -> str:
|
||||
return str(self.id)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Snowflake<{self.id}, {self.process}, {self.thread}, {self.increment}, {self.timestamp}>"
|
||||
|
||||
def __int__(self) -> int:
|
||||
return self._raw
|
||||
|
||||
def __float__(self) -> float:
|
||||
return float(self._raw)
|
||||
|
||||
def __lt__(self, y: "Snowflake"):
|
||||
return self.id < y.id
|
||||
|
||||
def __le__(self, y: "Snowflake"):
|
||||
return self.id <= y.id
|
||||
|
||||
def __eq__(self, y: "Snowflake"):
|
||||
return self.id == y.id
|
||||
|
||||
def __ne__(self, y: "Snowflake"):
|
||||
return self.id != y.id
|
||||
|
||||
def __gt__(self, y: "Snowflake"):
|
||||
return self.id > y.id
|
||||
|
||||
def __ge__(self, y: "Snowflake"):
|
||||
return self.id >= y.id
|
||||
|
||||
@property
|
||||
def id(self) -> int:
|
||||
"""The raw integer value of the snowflake."""
|
||||
return self._raw
|
||||
|
||||
@property
|
||||
def time(self) -> datetime:
|
||||
"""The time embedded into the snowflake."""
|
||||
return datetime.fromtimestamp(self.timestamp, tz=timezone.utc)
|
||||
|
||||
@property
|
||||
def timestamp(self) -> float:
|
||||
"""The unix timestamp embedded into the snowflake."""
|
||||
return ((self._raw >> 22) + self.EPOCH) / 1000
|
||||
|
||||
@property
|
||||
def process(self) -> int:
|
||||
"""The process ID embedded into the snowflake."""
|
||||
return (self._raw & 0x3E0000) >> 17
|
||||
|
||||
@property
|
||||
def thread(self) -> int:
|
||||
"""The thread ID embedded into the snowflake."""
|
||||
return (self._raw & 0x1F000) >> 12
|
||||
|
||||
@property
|
||||
def increment(self) -> int:
|
||||
"""The increment embedded into the snowflake."""
|
||||
return self._raw & 0xFFF
|
||||
|
||||
@classmethod
|
||||
def generate(cls, time: datetime | None = None):
|
||||
"""Generates a new snowflake.
|
||||
If `time` is set, use that time for the snowflake, otherwise, use the current time.
|
||||
"""
|
||||
|
||||
process_id = os.getpid()
|
||||
thread_id = threading.get_native_id()
|
||||
increment = _get_increment()
|
||||
now = time if time else datetime.now(tz=timezone.utc)
|
||||
timestamp = round(now.timestamp() * 1000) - cls.EPOCH
|
||||
|
||||
return cls(
|
||||
timestamp << 22
|
||||
| (process_id % 32) << 17
|
||||
| (thread_id % 32) << 12
|
||||
| (increment % 4096)
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def generate_int(cls, time: datetime | None = None):
|
||||
return cls.generate(time).id
|
5
foxnouns/db/sync.py
Normal file
5
foxnouns/db/sync.py
Normal file
|
@ -0,0 +1,5 @@
|
|||
from sqlalchemy import create_engine
|
||||
|
||||
from foxnouns.settings import SYNC_DATABASE_URL
|
||||
|
||||
engine = create_engine(SYNC_DATABASE_URL)
|
109
foxnouns/db/user.py
Normal file
109
foxnouns/db/user.py
Normal file
|
@ -0,0 +1,109 @@
|
|||
from datetime import datetime
|
||||
import enum
|
||||
|
||||
from itsdangerous.url_safe import URLSafeTimedSerializer
|
||||
from sqlalchemy import Text, Integer, BigInteger, ForeignKey, DateTime
|
||||
from sqlalchemy.dialects.postgresql import ARRAY
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from .base import Base
|
||||
from .snowflake import Snowflake
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id: Mapped[int] = mapped_column(
|
||||
BigInteger(), primary_key=True, default=Snowflake.generate_int
|
||||
)
|
||||
username: Mapped[str] = mapped_column(Text(), unique=True, nullable=False)
|
||||
display_name: Mapped[str | None] = mapped_column(Text(), nullable=True)
|
||||
bio: Mapped[str | None] = mapped_column(Text(), nullable=True)
|
||||
|
||||
tokens: Mapped[list["Token"]] = relationship(
|
||||
back_populates="user", cascade="all, delete-orphan"
|
||||
)
|
||||
auth_methods: Mapped[list["AuthMethod"]] = relationship(
|
||||
back_populates="user", cascade="all, delete-orphan"
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
return f"User(id={self.id!r}, username={self.username!r})"
|
||||
|
||||
|
||||
class Token(Base):
|
||||
__tablename__ = "tokens"
|
||||
|
||||
id: Mapped[int] = mapped_column(
|
||||
BigInteger(), primary_key=True, default=Snowflake.generate_int
|
||||
)
|
||||
expires_at: Mapped[datetime] = mapped_column(DateTime(), nullable=False)
|
||||
scopes: Mapped[list[str]] = mapped_column(ARRAY(Text), nullable=False)
|
||||
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
|
||||
user: Mapped[User] = relationship(back_populates="tokens")
|
||||
|
||||
def __repr__(self):
|
||||
return f"Token(id={self.id!r}, user={self.user_id!r})"
|
||||
|
||||
def has_scope(self, scope: str):
|
||||
"""Returns whether this token can be used for the given scope."""
|
||||
|
||||
# `*` is a special scope for site tokens, which grants access to all endpoints.
|
||||
if "*" in self.scopes:
|
||||
return True
|
||||
|
||||
# Some scopes have sub-scopes, indicated by a `.` (i.e. `user.edit` is contained in `user`)
|
||||
# Tokens can have these narrower scopes given to them, or the wider, more privileged scopes
|
||||
# This way, both `user` and `user.edit` tokens will grant access to `user.edit` endpoints.
|
||||
return scope in self.scopes or scope.split(".")[0] in self.scopes
|
||||
|
||||
def token_str(self):
|
||||
...
|
||||
|
||||
|
||||
class AuthType(enum.IntEnum):
|
||||
DISCORD = 1
|
||||
GOOGLE = 2
|
||||
TUMBLR = 3
|
||||
FEDIVERSE = 4
|
||||
EMAIL = 5
|
||||
|
||||
|
||||
class AuthMethod(Base):
|
||||
__tablename__ = "auth_methods"
|
||||
|
||||
id: Mapped[int] = mapped_column(
|
||||
BigInteger(), primary_key=True, default=Snowflake.generate_int
|
||||
)
|
||||
auth_type: Mapped[AuthType] = mapped_column(Integer(), nullable=False)
|
||||
|
||||
remote_id: Mapped[str] = mapped_column(Text(), nullable=False)
|
||||
remote_username: Mapped[str | None] = mapped_column(Text(), nullable=True)
|
||||
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
|
||||
user: Mapped[User] = relationship(back_populates="auth_methods")
|
||||
|
||||
fediverse_app_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("fediverse_apps.id"), nullable=True
|
||||
)
|
||||
fediverse_app: Mapped["FediverseApp"] = relationship()
|
||||
|
||||
|
||||
class FediverseInstanceType(enum.IntEnum):
|
||||
MASTODON_API = 1
|
||||
MISSKEY_API = 2
|
||||
|
||||
|
||||
class FediverseApp(Base):
|
||||
__tablename__ = "fediverse_apps"
|
||||
|
||||
id: Mapped[int] = mapped_column(
|
||||
BigInteger(), primary_key=True, default=Snowflake.generate_int
|
||||
)
|
||||
instance: Mapped[str] = mapped_column(Text(), unique=True, nullable=False)
|
||||
client_id: Mapped[str] = mapped_column(Text(), nullable=False)
|
||||
client_secret: Mapped[str] = mapped_column(Text(), nullable=False)
|
||||
instance_type: Mapped[FediverseInstanceType] = mapped_column(
|
||||
Integer(), nullable=False
|
||||
)
|
27
foxnouns/db/util.py
Normal file
27
foxnouns/db/util.py
Normal file
|
@ -0,0 +1,27 @@
|
|||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
from quart import g
|
||||
|
||||
from .user import User
|
||||
from foxnouns.exceptions import ForbiddenError
|
||||
|
||||
|
||||
async def user_from_ref(session: AsyncSession, user_ref: str):
|
||||
"""Returns a user from a `user_ref` value. If `user_ref` is `@me`, returns the current user.
|
||||
Otherwise, tries to convert the user to a snowflake ID and queries that. Otherwise, returns a user with that username.
|
||||
"""
|
||||
query = select(User)
|
||||
|
||||
if user_ref == "@me":
|
||||
if "user" in g:
|
||||
query = query.where(User.id == g.user.id)
|
||||
else:
|
||||
raise ForbiddenError("Not authenticated")
|
||||
else:
|
||||
try:
|
||||
id = int(user_ref)
|
||||
query = query.where(User.id == id)
|
||||
except ValueError:
|
||||
query = query.where(User.username == user_ref)
|
||||
|
||||
return await session.scalar(query)
|
76
foxnouns/exceptions.py
Normal file
76
foxnouns/exceptions.py
Normal file
|
@ -0,0 +1,76 @@
|
|||
import enum
|
||||
|
||||
|
||||
class ErrorCode(enum.IntEnum):
|
||||
BadRequest = 400
|
||||
Forbidden = 403
|
||||
NotFound = 404
|
||||
MethodNotAllowed = 405
|
||||
TooManyRequests = 429
|
||||
InternalServerError = 500 # catch-all code for unknown errors
|
||||
# Login/authorize error codes
|
||||
InvalidState = 1001
|
||||
InvalidOAuthCode = 1002
|
||||
InvalidToken = 1003 # a token was supplied, but it is invalid
|
||||
InviteRequired = 1004
|
||||
InvalidTicket = 1005 # invalid signup ticket
|
||||
InvalidUsername = 1006 # invalid username (when signing up)
|
||||
UsernameTaken = 1007 # username taken (when signing up)
|
||||
InvitesDisabled = 1008 # invites are disabled (unneeded)
|
||||
InviteLimitReached = 1009 # invite limit reached (when creating invites)
|
||||
InviteAlreadyUsed = 1010 # invite already used (when signing up)
|
||||
DeletionPending = 1011 # own user deletion pending, returned with undo code
|
||||
RecentExport = 1012 # latest export is too recent
|
||||
UnsupportedInstance = 1013 # unsupported fediverse software
|
||||
AlreadyLinked = 1014 # user already has linked account of the same type
|
||||
NotLinked = 1015 # user already doesn't have a linked account
|
||||
LastProvider = (
|
||||
1016 # unlinking provider would leave account with no authentication method
|
||||
)
|
||||
InvalidCaptcha = 1017 # invalid or missing captcha response
|
||||
# User-related error codes
|
||||
UserNotFound = 2001
|
||||
MemberListPrivate = 2002
|
||||
FlagLimitReached = 2003
|
||||
RerollingTooQuickly = 2004
|
||||
# Member-related error codes
|
||||
MemberNotFound = 3001
|
||||
MemberLimitReached = 3002
|
||||
MemberNameInUse = 3003
|
||||
NotOwnMember = 3004
|
||||
# General request error codes
|
||||
RequestTooBig = 4001
|
||||
MissingPermissions = 4002
|
||||
# Moderation related error codes
|
||||
ReportAlreadyHandled = 5001
|
||||
NotSelfDelete = 5002
|
||||
|
||||
|
||||
class ExpectedError(Exception):
|
||||
msg: str
|
||||
type: ErrorCode
|
||||
status_code: int = 500
|
||||
|
||||
def __init__(self, msg: str, type: ErrorCode):
|
||||
self.msg = msg
|
||||
self.type = type
|
||||
super().__init__(msg)
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.__class__.__name__}({self.msg})"
|
||||
|
||||
|
||||
class NotFoundError(ExpectedError):
|
||||
status_code = 404
|
||||
|
||||
def __init__(self, msg: str, type=ErrorCode.NotFound):
|
||||
self.type = type
|
||||
super().__init__(msg, type)
|
||||
|
||||
|
||||
class ForbiddenError(ExpectedError):
|
||||
status_code = 403
|
||||
|
||||
def __init__(self, msg: str, type=ErrorCode.Forbidden):
|
||||
self.type = type
|
||||
super().__init__(msg, type)
|
14
foxnouns/models/__init__.py
Normal file
14
foxnouns/models/__init__.py
Normal file
|
@ -0,0 +1,14 @@
|
|||
from pydantic import BaseModel, field_validator
|
||||
|
||||
|
||||
class BaseSnowflakeModel(BaseModel):
|
||||
"""A base model with a Snowflake ID that is serialized as a string.
|
||||
Also sets `model_config.from_attributes` to `True`."""
|
||||
|
||||
id: str
|
||||
|
||||
@field_validator("id", mode="before")
|
||||
def transform_id_to_str(cls, value) -> str:
|
||||
return str(value)
|
||||
|
||||
model_config = {"from_attributes": True}
|
33
foxnouns/models/user.py
Normal file
33
foxnouns/models/user.py
Normal file
|
@ -0,0 +1,33 @@
|
|||
import re
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from . import BaseSnowflakeModel
|
||||
|
||||
|
||||
class UserModel(BaseSnowflakeModel):
|
||||
name: str = Field(alias="username")
|
||||
display_name: str | None
|
||||
bio: str | None
|
||||
|
||||
|
||||
def check_username(value):
|
||||
if not value:
|
||||
return value
|
||||
|
||||
if value.lower() in (
|
||||
"..",
|
||||
"admin",
|
||||
"administrator",
|
||||
"mod",
|
||||
"moderator",
|
||||
"api",
|
||||
"page",
|
||||
"pronouns",
|
||||
"settings",
|
||||
"pronouns.cc",
|
||||
"pronounscc",
|
||||
):
|
||||
raise ValueError("Username is not allowed")
|
||||
|
||||
return value
|
37
foxnouns/settings.py
Normal file
37
foxnouns/settings.py
Normal file
|
@ -0,0 +1,37 @@
|
|||
from environs import Env
|
||||
from sqlalchemy import URL
|
||||
|
||||
# read .env file
|
||||
env = Env()
|
||||
env.read_env()
|
||||
|
||||
DATABASE = {
|
||||
"USER": env("DATABASE_USER"),
|
||||
"PASSWORD": env("DATABASE_PASSWORD"),
|
||||
"HOST": env("DATABASE_HOST"),
|
||||
"NAME": env("DATABASE_NAME"),
|
||||
}
|
||||
|
||||
SYNC_DATABASE_URL = URL.create(
|
||||
"postgresql+psycopg",
|
||||
username=DATABASE["USER"],
|
||||
password=DATABASE["PASSWORD"],
|
||||
host=DATABASE["HOST"],
|
||||
database=DATABASE["NAME"],
|
||||
)
|
||||
|
||||
ASYNC_DATABASE_URL = URL.create(
|
||||
"postgresql+asyncpg",
|
||||
username=DATABASE["USER"],
|
||||
password=DATABASE["PASSWORD"],
|
||||
host=DATABASE["HOST"],
|
||||
database=DATABASE["NAME"],
|
||||
)
|
||||
|
||||
# The base domain the API is served on. This must be set.
|
||||
BASE_DOMAIN = env("BASE_DOMAIN")
|
||||
# The base domain for short URLs.
|
||||
SHORT_DOMAIN = env("SHORT_DOMAIN", "prns.localhost")
|
||||
|
||||
# Secret key for signing tokens, generate with (for example) `openssl rand -base64 32`
|
||||
SECRET_KEY = env("SECRET_KEY")
|
1213
poetry.lock
generated
Normal file
1213
poetry.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
35
pyproject.toml
Normal file
35
pyproject.toml
Normal file
|
@ -0,0 +1,35 @@
|
|||
[tool.poetry]
|
||||
name = "foxnouns"
|
||||
version = "0.1.0"
|
||||
description = ""
|
||||
authors = ["sam <sam@sleepycat.moe>"]
|
||||
license = "Apache-2.0"
|
||||
readme = "README.md"
|
||||
|
||||
[tool.poetry.dependencies]
|
||||
python = "^3.11"
|
||||
sqlalchemy = { extras = ["asyncio"], version = "^2.0.28" }
|
||||
psycopg = "^3.1.18"
|
||||
celery = { extras = ["redis"], version = "^5.3.6" }
|
||||
quart = "^0.19.4"
|
||||
quart-schema = { extras = ["pydantic"], version = "^0.19.1" }
|
||||
pydantic = "^2.6.3"
|
||||
itsdangerous = "^2.1.2"
|
||||
uvicorn = "^0.28.0"
|
||||
asyncpg = "^0.29.0"
|
||||
environs = "^11.0.0"
|
||||
alembic = "^1.13.1"
|
||||
|
||||
[tool.poetry.group.test]
|
||||
optional = true
|
||||
|
||||
[tool.poetry.group.test.dependencies]
|
||||
pytest = "^8.0.2"
|
||||
pytest-asyncio = "^0.23.5.post1"
|
||||
|
||||
[build-system]
|
||||
requires = ["poetry-core"]
|
||||
build-backend = "poetry.core.masonry.api"
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
addopts = ["--import-mode=importlib"]
|
8
tests/conftest.py
Normal file
8
tests/conftest.py
Normal file
|
@ -0,0 +1,8 @@
|
|||
import pytest_asyncio
|
||||
|
||||
|
||||
@pytest_asyncio.fixture(scope="session", autouse=True)
|
||||
async def setup():
|
||||
print("hello from setup!")
|
||||
yield
|
||||
print("bye from setup!")
|
8
tests/test_hello.py
Normal file
8
tests/test_hello.py
Normal file
|
@ -0,0 +1,8 @@
|
|||
import pytest
|
||||
|
||||
from foxnouns import hello
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_hello():
|
||||
assert (await hello()) == "Hello world!"
|
Loading…
Reference in a new issue