~busykoala/pwned_api

ref: c9acb81b352c531e4ab38a4ddfa941a95c11779e pwned_api/app/routes.py -rw-r--r-- 1.8 KiB
c9acb81b — Matthias Osswald Fix tests and index out of range error. 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from aiohttp import web
from dotenv import load_dotenv
from pathlib import Path
from typing import Any
from typing import Awaitable
from typing import Callable
from typing import Dict
import asyncio
import asyncpg
import hashlib
import os


router = web.RouteTableDef()
env_path = Path.cwd() / '.env'

if env_path.exists():
    load_dotenv(dotenv_path=env_path)

PG_PASSWORD = os.getenv('PG_PASSWORD')


async def fetch_pw(password: str) -> Dict[str, Any]:

    password_hash = hashlib.sha1(password.encode()).hexdigest().upper()

    conn = await asyncpg.connect(
        host='localhost', port=5432,
        user='postgres', password=PG_PASSWORD,
        database='pwned_api')
    stmt = await conn.prepare(
        '''SELECT * FROM passwords WHERE hash = $1''')
    results = await stmt.fetch(password_hash)
    await conn.close()

    if not results:
        return {}

    return dict(results[0])


def handle_json_error(
    func: Callable[[web.Request], Awaitable[web.Response]]
        ) -> Callable[[web.Request], Awaitable[web.Response]]:
    async def handler(request: web.Request) -> web.Response:
        try:
            return await func(request)
        except asyncio.CancelledError:
            raise
        except Exception as ex:
            return web.json_response(
                {"status": "failed", "reason": str(ex)}, status=400
            )

    return handler


@router.get("/")
@handle_json_error
async def index(request: web.Request) -> web.Response:
    return web.json_response({"status": 200})


@router.get("/api/{password}")
@handle_json_error
async def api_get_post(request: web.Request) -> web.Response:
    password = request.match_info["password"]
    db_ret = await fetch_pw(password)
    return web.json_response(
        {'status': 'ok', 'password': password, 'data': db_ret})