Verified Commit bc2e3453 authored by Mfon Eti-mfon's avatar Mfon Eti-mfon
Browse files

Initialize project

parents
# -----------------------------------------------------------------------------
# create password protected postgres user with permissions to create databases
# can do this is in psql using the command below
# CREATE USER username WITH PASSWORD pwd CREATEDB;
# -----------------------------------------------------------------------------
DATABASE_URL=postgresql://username:pwd!@localhost:5432/starlauth
# -----------------------------------------------------------------------------
# generate secret key in python using the code below
# import secrets; secrets.token_urlsafe()
# -----------------------------------------------------------------------------
SECRET_KEY=generated-secret
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# temporary files
*.tmp
*.temp
# Contributions to Starlauth
## Creator & Maintainer
* Mfon Eti-mfon <mfonetimfon@gmail.com>
## Contributors
In chronological order:
* [Your name or handle] <[email or website]>
* [Brief summary of your changes]
MIT License
Copyright (c) 2021 Mfon Eti-mfon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# Starlauth
Learning backend building with Starlette by building an app that does authentication and only authentication, LOL.
This diff is collapsed.
[tool.poetry]
name = "starlauth"
version = "0.1.0"
description = "A Starlette app that does authentication and only authentication"
authors = ["Mfon Eti-mfon <mfonetimfon@gmail.com>"]
license = "MIT"
[tool.poetry.dependencies]
python = "^3.8"
databases = {extras = ["postgresql"], version = "^0.4.3"}
httpx = "^0.18.2"
psycopg2 = "^2.9.1"
SQLAlchemy-Utils = "^0.37.8"
starlette = "^0.16.0"
uvicorn = "^0.14.0"
[tool.poetry.dev-dependencies]
black = {version = "^21.7b0", allow-prereleases = true}
pytest = "^5.2"
pytest-asyncio = "^0.15.1"
pytest-mock = "^3.6.1"
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
__version__ = "0.1.0"
from starlette.applications import Starlette
from . import settings
from .resources import db
from .routes import routes
app = Starlette(
debug=settings.DEBUG,
routes=routes,
on_startup=[db.connect],
on_shutdown=[db.disconnect],
)
from starlette.requests import Request
from starlette.responses import JSONResponse
from . import utils
from .resources import db
from .tables import users
async def create_user(request: Request):
data = await request.json()
pk = utils.get_uuid_str()
timestamp = utils.get_utcnow()
user_insertion_stmt = users.insert().values(
uuid=pk, username=data["username"], email=data["email"], created_at=timestamp
)
await db.execute(user_insertion_stmt)
return JSONResponse(
{
"uuid": pk,
"username": data["username"],
"email": data["email"],
},
status_code=201,
)
import databases
from .settings import DATABASE_URL, TESTING
if TESTING:
db = databases.Database(DATABASE_URL, force_rollback=True)
else:
db = databases.Database(DATABASE_URL)
from starlette.routing import Route
from . import endpoints
routes = [
Route(
"/users", endpoint=endpoints.create_user, methods=["POST"], name="user_creation"
),
]
import pathlib
import databases
from starlette.config import Config
from starlette.datastructures import Secret
BASE_DIR = pathlib.Path(__file__).parent.parent.absolute()
config = Config(BASE_DIR / ".env")
# Mode flags
DEBUG = config("DEBUG", cast=bool, default=False)
TESTING = config("TESTING", cast=bool, default=False)
# Secret key
SECRET_KEY = config("SECRET_KEY", cast=Secret)
# Other configs
DATABASE_URL = config("DATABASE_URL", cast=databases.DatabaseURL)
if TESTING:
DATABASE_URL = DATABASE_URL.replace(database="test_" + DATABASE_URL.database)
if DATABASE_URL.dialect == "postgres":
DATABASE_URL = DATABASE_URL.replace(dialect="postgresql") # pragma: nocover
from sqlalchemy import Column, DateTime, MetaData, String, Table
from . import utils
metadata = MetaData()
users = Table(
"users",
metadata,
Column("uuid", String(255), primary_key=True, default=utils.get_uuid_str),
Column("username", String(32), nullable=False, unique=True, index=True),
Column("email", String(255), nullable=False, unique=True, index=True),
Column(
"created_at", DateTime(timezone=True), nullable=False, default=utils.get_utcnow
),
)
import uuid
from datetime import datetime, timezone
def get_uuid_str() -> str:
return str(uuid.uuid4())
def get_utcnow() -> datetime:
return datetime.now(timezone.utc)
from datetime import datetime
import httpx
import pytest
from sqlalchemy import create_engine
from sqlalchemy.exc import ProgrammingError
from sqlalchemy_utils import create_database, drop_database
from starlette.config import environ
# configure environment variables for testing before importing
# application settings (or any other module that somehow reads from it)
# so it gets reflected there
environ["TESTING"] = "True"
environ["SECRET"] = "TESTING"
from starlauth import settings # noqa: E402
from starlauth.app import app # noqa: E402
from starlauth.resources import db # noqa: E402
from starlauth.tables import metadata # noqa: E402
@pytest.fixture(scope="session", autouse=True)
def create_test_database():
"""
Create a clean test database every time the tests are run.
"""
url = str(settings.DATABASE_URL)
engine = create_engine(url)
try:
drop_database(url)
except ProgrammingError:
pass
create_database(url)
metadata.create_all(engine)
@pytest.fixture()
async def client():
"""
Ensure full database rollbacks between test cases when used as fixture in test cases.
"""
try:
await db.connect()
async with httpx.AsyncClient(
app=app, base_url="https://testserver"
) as test_client:
yield test_client
finally:
await db.disconnect()
@pytest.fixture()
def uuid():
return "this-is-a-uuid"
@pytest.fixture()
def inception():
return datetime.fromisoformat("0001-01-01 00:00:00+00:00")
from datetime import timezone
import pytest
from sqlalchemy import func, select
from sqlalchemy.sql.expression import desc
from starlauth.app import app
from starlauth.resources import db
from starlauth.tables import users
@pytest.mark.asyncio
async def test_create_user(client, mocker, uuid, inception):
uuid_mock = mocker.patch(
"starlauth.utils.get_uuid_str", return_value=uuid, autospec=True
)
utcnow_mock = mocker.patch(
"starlauth.utils.get_utcnow", return_value=inception, autospec=True
)
payload = {"username": "HelloWorld", "email": "hello@world.me"}
path = app.url_path_for("user_creation")
user_count_stmt = select([func.count()]).select_from(users)
old_user_count = await db.execute(user_count_stmt)
response = await client.post(path, json=payload)
assert response.status_code == 201
uuid_mock.assert_called_once()
utcnow_mock.assert_called_once()
# user count
new_user_count = await db.execute(user_count_stmt)
assert new_user_count == old_user_count + 1
# created user
user_select_stmt = select([users]).order_by(desc(users.c.created_at))
created_user = await db.fetch_one(user_select_stmt)
assert created_user["uuid"] == uuid_mock.return_value
assert created_user["username"] == payload["username"]
assert created_user["email"] == payload["email"]
assert (
created_user["created_at"].replace(tzinfo=timezone.utc)
== utcnow_mock.return_value
)
# response data
data = response.json()
assert data["uuid"] == uuid_mock.return_value
assert data["username"] == payload["username"]
assert data["email"] == payload["email"]
from starlauth import __version__
def test_version():
assert __version__ == "0.1.0"
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment