Skip to content

Commit

Permalink
add verification request and test launch
Browse files Browse the repository at this point in the history
  • Loading branch information
Ferrariic committed May 25, 2022
1 parent f868137 commit 0315a09
Show file tree
Hide file tree
Showing 16 changed files with 244 additions and 86 deletions.
5 changes: 5 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.git
.github
.vscode
LICENSE
*.md
3 changes: 3 additions & 0 deletions .github/workflows/workflow.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ jobs:
runs-on: self-hosted
steps:
- uses: actions/checkout@v2
- name: Set Up ENV
run: |
echo "${{ secrets.SQL_URI }}" > .env
deploy:
runs-on: self-hosted
Expand Down
7 changes: 3 additions & 4 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
FROM python:3.10-slim

WORKDIR /code
COPY . /code
RUN pip install -r requirements.txt
CMD ["python","-u","/code/src/main.py"]
COPY . /code/
RUN pip install --no-cache-dir -r requirements.txt
CMD ["uvicorn", "api.app:app", "--proxy-headers", "--host", "0.0.0.0"]
40 changes: 38 additions & 2 deletions api/database/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,47 @@
from sqlalchemy.ext.asyncio import AsyncResult, AsyncSession
from sqlalchemy.sql.expression import insert, select

from api.database.models import UserToken, Users

logger = logging.getLogger(__name__)


async def verify_token(login: str, token: str) -> bool:
pass
async def verify_token(login: str, token: str, access_level=0) -> bool:
"""User verification request - this display's the user's access level and if they have permissions to access the content that they wish to view.
Args:
login (str): The username that is sending the auth request
token (str): The auth token being sent by the user
Returns:
bool: True|False depending upon if the request was successful, or not.
"""

sql = select(UserToken)
sql = sql.where(UserToken.token == token)
sql = sql.where(Users.login == login)
sql = sql.join(Users, UserToken.user_id == Users.user_id)

async with USERDATA_ENGINE.get_session() as session:
session: AsyncSession = session
async with session.begin():
request = await session.execute(sql)
data = sqlalchemy_result(request)
data = data.rows2dict()

if len(data) == 0:
raise HTTPException(
status_code=401,
detail=f"Insufficent permissions. You cannot access this content.",
)

auth_level = data[0]["auth_level"]
if access_level > auth_level:
raise HTTPException(
status_code=401,
detail=f"Insufficent permissions. You cannot access this content at your auth level.",
)
return True


async def parse_sql(
Expand Down
4 changes: 2 additions & 2 deletions api/database/models.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from datetime import datetime
from numpy import integer

from numpy import integer
from sqlalchemy import (
BLOB,
DATETIME,
INTEGER,
SMALLINT,
TIME,
TIMESTAMP,
Expand All @@ -17,7 +18,6 @@
Index,
String,
Text,
INTEGER,
column,
text,
)
Expand Down
17 changes: 15 additions & 2 deletions api/routers/request_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
from typing import Optional
from urllib.request import Request

from api.database.functions import USERDATA_ENGINE, EngineType, sqlalchemy_result
from api.database.functions import (
USERDATA_ENGINE,
EngineType,
sqlalchemy_result,
verify_token,
)
from api.database.models import RequestHistory
from fastapi import APIRouter, HTTPException, Query, status
from pydantic import BaseModel
Expand Down Expand Up @@ -37,6 +42,7 @@ class request_history(BaseModel):
@router.get("/V1/request-history/", tags=["request history"])
async def get_request_history(
token: str,
login: str,
s_user_id: int,
r_user_id: int,
timestamp_START: Optional[datetime] = None,
Expand Down Expand Up @@ -68,6 +74,9 @@ async def get_request_history(
json : A json containing the relevant information from the request.\n
"""

if not await verify_token(login=login, token=token, access_level=9):
return

table = RequestHistory
sql: Select = select(table)

Expand Down Expand Up @@ -111,14 +120,18 @@ async def get_request_history(


@router.post("/V1/request-history", tags=["request history"])
async def post_request_history(request_history: request_history) -> json:
async def post_request_history(
login: str, token: str, request_history: request_history
) -> json:
"""
Args:\n
request_history (request_history): Json containing the relevant elements of a request-history entry.\n
Returns:\n
json: {"ok": "ok"}\n
"""
if not await verify_token(login=login, token=token, access_level=9):
return
values = request_history.dict()
table = RequestHistory
sql = insert(table).values(values)
Expand Down
15 changes: 14 additions & 1 deletion api/routers/trainer_acception_status.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
from typing import Optional
from urllib.request import Request

from api.database.functions import USERDATA_ENGINE, EngineType, sqlalchemy_result
from api.database.functions import (
USERDATA_ENGINE,
EngineType,
sqlalchemy_result,
verify_token,
)
from api.database.models import TrainerAcceptionStatus
from fastapi import APIRouter, HTTPException, Query, status
from pydantic import BaseModel
Expand Down Expand Up @@ -35,6 +40,7 @@ class trainer_acception_status(BaseModel):
)
async def get_trainer_acception_status(
token: str,
login: str,
user_id: int,
ID: Optional[int] = None,
is_trainer: Optional[bool] = None,
Expand All @@ -58,6 +64,9 @@ async def get_trainer_acception_status(
json: Json response containing the relevant information.\n
"""

if not await verify_token(login=login, token=token, access_level=9):
return

table = TrainerAcceptionStatus
sql: Select = select(table)

Expand Down Expand Up @@ -91,6 +100,8 @@ async def get_trainer_acception_status(
"/V1/trainer-acception-status", tags=["trainer", "trainer acception status"]
)
async def post_trainer_acception_status(
login: str,
token: str,
trainer_acception_status: trainer_acception_status,
) -> json:
"""
Expand All @@ -100,6 +111,8 @@ async def post_trainer_acception_status(
Returns:\n
json: {"ok": "ok"}\n
"""
if not await verify_token(login=login, token=token, access_level=9):
return
values = trainer_acception_status.dict()
table = TrainerAcceptionStatus
sql = insert(table).values(values)
Expand Down
118 changes: 59 additions & 59 deletions api/routers/trainer_identification_information.py
Original file line number Diff line number Diff line change
@@ -1,74 +1,74 @@
from datetime import datetime
import json
from typing import Optional
from urllib.request import Request
# from datetime import datetime
# import json
# from typing import Optional
# from urllib.request import Request

from api.database.functions import USERDATA_ENGINE, EngineType, sqlalchemy_result
from api.database.models import TrainerIdentificationInformation
from fastapi import APIRouter, HTTPException, Query, status
from pydantic import BaseModel
from pydantic.fields import Field
from pymysql import Timestamp
from sqlalchemy import DATETIME, TIMESTAMP, func, select
from sqlalchemy.dialects.mysql import Insert
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import aliased
from sqlalchemy.sql.expression import Select, select, insert
# from api.database.functions import USERDATA_ENGINE, EngineType, sqlalchemy_result, verify_token
# from api.database.models import TrainerIdentificationInformation
# from fastapi import APIRouter, HTTPException, Query, status
# from pydantic import BaseModel
# from pydantic.fields import Field
# from pymysql import Timestamp
# from sqlalchemy import DATETIME, TIMESTAMP, func, select
# from sqlalchemy.dialects.mysql import Insert
# from sqlalchemy.ext.asyncio import AsyncSession
# from sqlalchemy.orm import aliased
# from sqlalchemy.sql.expression import Select, select, insert

router = APIRouter()
# router = APIRouter()


class trainer_identification_information(BaseModel):
"""
trainer_identification_information base model containing the types and content expected by the database
"""
# class trainer_identification_information(BaseModel):
# """
# trainer_identification_information base model containing the types and content expected by the database
# """


@router.get(
"/V1/trainer-identification-information/",
tags=["trainer", "trainer identification information"],
)
async def get_trainer_identification_information(
token: str,
ID: Optional[int],
user_id: int,
content_type: Optional[int],
timestamp=Optional[datetime],
# content = Column(BLOB),
row_count: Optional[int] = Query(100, ge=1, le=1000),
page: Optional[int] = Query(1, ge=1),
) -> json:
# @router.get(
# "/V1/trainer-identification-information/",
# tags=["trainer", "trainer identification information"],
# )
# async def get_trainer_identification_information(
# token: str,
# ID: Optional[int],
# user_id: int,
# content_type: Optional[int],
# timestamp=Optional[datetime],
# # content = Column(BLOB),
# row_count: Optional[int] = Query(100, ge=1, le=1000),
# page: Optional[int] = Query(1, ge=1),
# ) -> json:

table = TrainerIdentificationInformation
sql: Select = select(table)
# table = TrainerIdentificationInformation
# sql: Select = select(table)

sql = sql.limit(row_count).offset(row_count * (page - 1))
# sql = sql.limit(row_count).offset(row_count * (page - 1))

async with USERDATA_ENGINE.get_session() as session:
session: AsyncSession = session
async with session.begin():
data = await session.execute(sql)
# async with USERDATA_ENGINE.get_session() as session:
# session: AsyncSession = session
# async with session.begin():
# data = await session.execute(sql)

data = sqlalchemy_result(data)
return data.rows2dict()
# data = sqlalchemy_result(data)
# return data.rows2dict()


@router.post(
"/V1/trainer-identification-information",
tags=["trainer", "trainer identification information"],
)
async def post_trainer_identification_status(
trainer_identification_information: trainer_identification_information,
) -> json:
# @router.post(
# "/V1/trainer-identification-information",
# tags=["trainer", "trainer identification information"],
# )
# async def post_trainer_identification_status(
# trainer_identification_information: trainer_identification_information,
# ) -> json:

values = trainer_identification_information.dict()
table = TrainerIdentificationInformation
sql = insert(table).values(values)
sql = sql.prefix_with("ignore")
# values = trainer_identification_information.dict()
# table = TrainerIdentificationInformation
# sql = insert(table).values(values)
# sql = sql.prefix_with("ignore")

async with USERDATA_ENGINE.get_session() as session:
session: AsyncSession = session
async with session.begin():
data = await session.execute(sql)
# async with USERDATA_ENGINE.get_session() as session:
# session: AsyncSession = session
# async with session.begin():
# data = await session.execute(sql)

return {"ok": "ok"}
# return {"ok": "ok"}
16 changes: 14 additions & 2 deletions api/routers/user_chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@

from pyparsing import Opt

from api.database.functions import USERDATA_ENGINE, EngineType, sqlalchemy_result
from api.database.functions import (
USERDATA_ENGINE,
EngineType,
sqlalchemy_result,
verify_token,
)
from api.database.models import UserChat
from fastapi import APIRouter, HTTPException, Query, status
from pydantic import BaseModel
Expand Down Expand Up @@ -37,6 +42,7 @@ class user_chat(BaseModel):
@router.get("/V1/user-chat/", tags=["user", "chat"])
async def get_user_chat(
token: str,
login: str,
ID: Optional[int] = None,
timestamp: Optional[datetime] = None,
s_user_id: Optional[int] = None,
Expand Down Expand Up @@ -64,6 +70,9 @@ async def get_user_chat(
json: Json of above query\n
"""

if not await verify_token(login=login, token=token, access_level=9):
return

table = UserChat
sql: Select = select(table)

Expand Down Expand Up @@ -100,14 +109,17 @@ async def get_user_chat(


@router.post("/V1/user-chat", tags=["user", "chat"])
async def post_user_chat(user_chat: user_chat) -> json:
async def post_user_chat(login: str, token: str, user_chat: user_chat) -> json:
"""
Args:\n
user_chat (user_chat): user chat model\n
Returns:\n
json: {"ok": "ok"}\n
"""

if not await verify_token(login=login, token=token, access_level=9):
return

values = user_chat.dict()
table = UserChat
sql = insert(table).values(values)
Expand Down
Loading

0 comments on commit 0315a09

Please sign in to comment.