init auth-service

This commit is contained in:
2023-09-27 16:01:41 +01:00
parent 7192f11059
commit 0ae3ee3af4
40 changed files with 2616 additions and 2 deletions

View File

@@ -0,0 +1 @@
DROP TABLE IF EXISTS auth_methods CASCADE;

View File

@@ -0,0 +1,4 @@
CREATE TABLE auth_methods (
"user_id" varchar(64) PRIMARY KEY,
"password" varchar(128) NOT NULL
);

View File

@@ -0,0 +1,39 @@
from typing import Optional
from databases import Database
from auth_service.models.service import AuthDBRepository, AuthRecord
class ServiceDBRepository(AuthDBRepository):
"""Database repository responsible for CRUD actions
on the database.
This repository will be utilised by other upstream repositories
or the Kafka event consumers.
Attributes:
_db (Database): The postgres database connection handler.
"""
def __init__(self, db: Database) -> None:
self._db = db
async def get_auth_record(self, user_id: str) -> Optional[AuthRecord]:
query = "SELECT user_id, password FROM auth_methods WHERE user_id = :user_id"
result = await self._db.fetch_one(query=query, values={"user_id": user_id})
if result is None:
return None
return AuthRecord(user_id=result["user_id"], password=result["password"])
async def create_password_auth_method(self, user_id: str, password: str) -> None:
query = "INSERT INTO auth_methods (user_id, password) VALUES (:user_id, :password)"
await self._db.execute(query=query, values={"user_id": user_id, "password": password})
async def update_password_auth_method(self, user_id: str, password: str) -> None:
query = "UPDATE auth_methods SET password = :password WHERE user_id = :user_id"
await self._db.execute(query=query, values={"user_id": user_id, "password": password})
async def delete_password_auth_method(self, user_id: str) -> None:
query = "DELETE FROM auth_methods WHERE user_id = :user_id"
await self._db.execute(query=query, values={"user_id": user_id})

View File

@@ -0,0 +1,40 @@
import logging
from databases import Database
from auth_service.models.config import Config
from auth_service.postgres.repository import ServiceDBRepository
async def connect_database(config: Config) -> Database:
"""Opens a connection to the database.
Args:
config (Config): The app configuration.
Returns:
A connected databases.Database instance
"""
db = Database(config.postgres_dsn)
try:
await db.connect()
except Exception:
logging.error("failed to connect to postgresql database")
raise
return db
async def create_db_repository(config: Config) -> ServiceDBRepository:
"""Create the database repository.
Open a database connection and instantialise the
database repository.
Returns:
ServiceDBRepository
"""
db = await connect_database(config)
return ServiceDBRepository(db)