-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
75 lines (52 loc) · 2.06 KB
/
main.py
File metadata and controls
75 lines (52 loc) · 2.06 KB
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
71
72
73
74
75
import sys
from typing import Annotated
import uvicorn
from fastapi import FastAPI, Header, status
from fastapi.responses import JSONResponse, Response
from pydantic import create_model
from auth import Auth, Claims
import users_repository as users
from config import *
app = FastAPI()
auth = Auth(auth_key, auth_algorithm, run_url, token_lifespan_seconds=auth_token_lifespan_seconds)
@app.post('/')
def register() -> create_model('RegisteredUuid', uuid=(str, None)):
return {'uuid': users.new_user()}
@app.get('/login/{uuid}')
def login(uuid: str) -> create_model('LoginToken', token=(str, None)):
uuid = uuid.upper()
print(f'{uuid=}')
if not users.exists(uuid):
return JSONResponse(
content={'message': 'This user does not exists'},
status_code=404
)
return {'token': auth.jwe(uuid)}
@app.get('/renew')
def renew(authorisation: Annotated[str | None, Header()] = None) -> str:
if authorisation is None:
return Response(status_code=status.HTTP_401_UNAUTHORIZED)
if authorisation.startswith('Bearer '):
authorisation = authorisation.replace('Bearer ', '')
result = auth.validate(authorisation)
if isinstance(result, str):
return JSONResponse(status_code=status.HTTP_401_UNAUTHORIZED, content={'message': result})
claims: Claims = result
return login(claims.sub)['token']
@app.head('/{uuid}')
def validate_by_jwt(
uuid: str,
authorisation: Annotated[str | None, Header()] = None
):
uuid = uuid.upper()
if authorisation is None:
print('401 No authentication token provided', file=sys.stderr)
return Response(status_code=status.HTTP_401_UNAUTHORIZED)
validation_error_message = auth.validate(authorisation.replace('Bearer ', ''), uuid)
if isinstance(validation_error_message, str):
print(401, validation_error_message)
return Response(status_code=status.HTTP_401_UNAUTHORIZED)
return Response(status_code=200)
if __name__ == '__main__':
users.init()
uvicorn.run(app, host=host, port=port, log_level='trace')