Skip to content

Commit

Permalink
v0.9.0 (#62)
Browse files Browse the repository at this point in the history
* backport changes from api-consistency branch
  • Loading branch information
zeratax authored Apr 9, 2021
1 parent b6853be commit 838fc13
Show file tree
Hide file tree
Showing 20 changed files with 593 additions and 247 deletions.
1 change: 0 additions & 1 deletion .coveragerc
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
[run]
source = matrix_registration
omit = matrix_registration/__main__.py
12 changes: 9 additions & 3 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
name: Tests

on: [push, pull_request]
on:
push:
branches:
- master
pull_request:
branches:
- master

jobs:
build:
Expand All @@ -9,7 +15,7 @@ jobs:

strategy:
matrix:
python-version: [ '3.6', '3.7', '3.8', '3.9' ]
python-version: [ '3.7', '3.8', '3.9' ]
name: Python ${{ matrix.python-version }}
steps:
- uses: actions/checkout@v2
Expand All @@ -26,7 +32,7 @@ jobs:
# stop the build if there are Python syntax errors or undefined names
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
flake8 matrix_registration --per-file-ignores="__init__.py:F401" --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
- name: Test with parameterized unit tests 🚨
run: |
python setup.py test
4 changes: 3 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
language: python
matrix:
include:
- python: 3.6
- python: 3.7
dist: focal
sudo: true
- python: 3.8
dist: focal
sudo: true
- python: 3.9
dist: focal
sudo: true
install:
- pip install tox-travis
- pip install coveralls
Expand Down
10 changes: 3 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,16 +100,12 @@ The html page looks for the query paramater `token` and sets the token input fie
If you already have a website and want to use your own register page, the [wiki](https://github.com/ZerataX/matrix-registration/wiki/reverse-proxy#advanced) describes a more advanced nginx setup.


### bot

### Troubleshooting
if you're looking for a bot to interface with matrix-registration and manage your tokens, take a look at:

#### SQLAlchemy complains that a value isn't in a DateTime value
[maubot-invite](https://github.com/williamkray/maubot-invite)

Before #17 introduced SQLAlchemy support the sqlite database incorrectly stored the expire dates, to fix this you have to manually run:
```sql
update tokens set ex_date=null where ex_date='None';
```
on your database once, or just delete your current database.

### Similar projects

Expand Down
71 changes: 71 additions & 0 deletions alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# A generic, single database configuration.

[alembic]
# path to migration scripts
script_location = alembic

# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s

# timezone to use when rendering the date
# within the migration file as well as the filename.
# string value is passed to dateutil.tz.gettz()
# 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
# version_locations = %(here)s/bar %(here)s/bat alembic/versions

# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8

# 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
Empty file added alembic/README
Empty file.
90 changes: 90 additions & 0 deletions alembic/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool

from alembic import context

import sys
from os import getcwd
from os.path import abspath, dirname

sys.path.insert(0, dirname(dirname(abspath(__file__))))

from matrix_registration import config as mr_config


# 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.
fileConfig(config.config_file_name)

# load matrix-registration config and set db path for alembic
config_path = context.get_x_argument(as_dictionary=True).get("config") or "config.yaml"
mr_config.config = mr_config.Config(config_path)
config.set_main_option("sqlalchemy.url", mr_config.config.db.replace("{cwd}", f"{getcwd()}/"))

# add your model's MetaData object here
# for 'autogenerate' support
# target_metadata = mymodel.Base.metadata
target_metadata = None

# 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():
"""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 = config.get_main_option("sqlalchemy.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():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section),
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()
24 changes: 24 additions & 0 deletions alembic/script.py.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""${message}

Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}

"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}

# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}


def upgrade():
${upgrades if upgrades else "pass"}


def downgrade():
${downgrades if downgrades else "pass"}
69 changes: 69 additions & 0 deletions alembic/versions/140a25d5f185_create_tokens_table.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
"""create tokens table
Revision ID: 140a25d5f185
Revises:
Create Date: 2020-12-12 01:44:28.195736
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy import Table, Column, Integer, String, Boolean, DateTime, ForeignKey
from sqlalchemy.engine.reflection import Inspector
from flask_sqlalchemy import SQLAlchemy


# revision identifiers, used by Alembic.
revision = '140a25d5f185'
down_revision = None
branch_labels = None
depends_on = None

db = SQLAlchemy()


def upgrade():
conn = op.get_bind()
inspector = Inspector.from_engine(conn)
tables = inspector.get_table_names()

if 'ips' not in tables:
op.create_table(
'ips',
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('address', sa.String(255), nullable=True)
)

if 'tokens' not in tables:
op.create_table(
'tokens',
sa.Column('name', String(255), primary_key=True),
sa.Column('expiration_date', DateTime, nullable=True),
sa.Column('max_usage', Integer, default=1),
sa.Column('used', Integer, default=0),
sa.Column('disabled', Boolean, default=False),
sa.Column('ips', Integer, ForeignKey('association.id'))
)
else:
with op.batch_alter_table('tokens') as batch_op:
batch_op.alter_column('ex_date', new_column_name='expiration_date', nullable=True)
batch_op.alter_column('one_time', new_column_name='max_usage')

batch_op.add_column(
Column('disabled', Boolean, default=False)
)


if 'association' not in tables:
op.create_table(
'association', db.Model.metadata,
Column('ips', String, ForeignKey('ips.address'), primary_key=True),
Column('tokens', Integer, ForeignKey('tokens.name'), primary_key=True)
)

op.execute("update tokens set expiration_date=null where expiration_date='None'")



def downgrade():
op.alter_column('tokens', 'expiration_date', new_column_name='ex_date')
op.alter_column('tokens', 'max_usage', new_column_name='one_time')
12 changes: 7 additions & 5 deletions config.sample.yaml
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
server_location: 'https://matrix.org'
server_name: 'matrix.org'
shared_secret: 'RegistrationSharedSecret'
admin_secret: 'APIAdminPassword'
base_url: ''
riot_instance: 'https://riot.im/app/'
registration_shared_secret: 'RegistrationSharedSecret' # see your synapse's homeserver.yaml
admin_api_shared_secret: 'APIAdminPassword' # to generate tokens via the web api
base_url: '' # e.g. '/element' for https://example.tld/element/register
client_redirect: 'https://app.element.io/#/login'
client_logo: 'static/images/element-logo.png' # use '{cwd}' for current working directory
db: 'sqlite:///{cwd}db.sqlite3'
host: 'localhost'
port: 5000
rate_limit: ["100 per day", "10 per minute"]
allow_cors: false
ip_logging: false
logging:
disable_existing_loggers: False
disable_existing_loggers: false
version: 1
root:
level: DEBUG
Expand Down
2 changes: 1 addition & 1 deletion matrix_registration/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
from . import tokens
from . import config

__version__ = '0.8.1.dev3'
__version__ = '0.9.0.dev1'
name = 'matrix_registration'
Loading

0 comments on commit 838fc13

Please sign in to comment.