Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions print_service/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def __init__(self):

class InvalidPageRequest(Exception):
def __init__(self):
super().__init__(f'Invalid format')
super().__init__(f'The number of requested pages exceeds the number of pages')


class UnionStudentDuplicate(Exception):
Expand All @@ -62,13 +62,13 @@ def __init__(self):

class FileIsNotReceived(Exception):
def __init__(self):
super().__init__(f'No file was recieved')
super().__init__(f'No file was received')


class InvalidType(Exception):
def __init__(self, content_type: str):
super().__init__(
f'Only {", ".join(settings.CONTENT_TYPES)} files allowed, but {content_type} was recieved'
f'Only {", ".join(settings.CONTENT_TYPES)} files allowed, but {content_type} was received'
)


Expand All @@ -90,3 +90,18 @@ def __init__(self):
class UnprocessableFileInstance(Exception):
def __init__(self):
super().__init__(f'Unprocessable file instance')


class TokenAlreadyUsed(Exception):
def __init__(self):
super().__init__(f'Token already used')


class Unauthorized(Exception):
def __init__(self):
super().__init__(f'Unauthorized')


class NotAuthenticated(Exception):
def __init__(self):
super().__init__(f'Not authenticated')
12 changes: 11 additions & 1 deletion print_service/routes/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import logging

from auth_lib.fastapi import UnionAuth
from fastapi import APIRouter, Depends, HTTPException
from fastapi import APIRouter, Depends
from redis import Redis

from print_service.exceptions import TerminalTokenNotFound
Expand Down Expand Up @@ -67,3 +67,13 @@ async def reboot_terminal(
return {'status': 'ok'}
sender.redis.close()
raise TerminalTokenNotFound()


@router.get("/settings")
async def setting_to_bot(user=Depends(UnionAuth(scopes=["print.print_bot.settings"]))):
logger.info(f"Bot {user} clone settings")
return {
"MAX_SIZE": settings.MAX_SIZE,
"MAX_PAGE_COUNT": settings.MAX_PAGE_COUNT,
"CONTENT_TYPES": settings.CONTENT_TYPES,
}
11 changes: 5 additions & 6 deletions print_service/routes/exc_handlers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import requests.models
import starlette.requests
from starlette.responses import JSONResponse

Expand Down Expand Up @@ -54,7 +53,7 @@ async def too_many_pages(req: starlette.requests.Request, exc: TooManyPages):


@app.exception_handler(InvalidPageRequest)
async def invalid_format(req: starlette.requests.Request, exc: TooManyPages):
async def invalid_format(req: starlette.requests.Request, exc: InvalidPageRequest):
return JSONResponse(
content=StatusResponseModel(
status="Error",
Expand All @@ -81,7 +80,7 @@ async def terminal_not_found_by_token(req: starlette.requests.Request, exc: Term
content=StatusResponseModel(
status="Error", message="Terminal not found by token", ru="Токен не найден"
).model_dump(),
status_code=400,
status_code=404,
)


Expand Down Expand Up @@ -167,15 +166,15 @@ async def already_upload(req: starlette.requests.Request, exc: AlreadyUploaded):
content=StatusResponseModel(
status="Error", message=f"{exc}", ru="Файл уже загружен"
).model_dump(),
status_code=415,
status_code=409,
)


@app.exception_handler(IsCorrupted)
async def is_corrupted(req: starlette.requests.Request, exc: IsCorrupted):
return JSONResponse(
content=StatusResponseModel(status="Error", message=f"{exc}", ru="Файл повреждён").model_dump(),
status_code=415,
status_code=422,
)


Expand Down Expand Up @@ -205,5 +204,5 @@ async def not_uploaded(req: starlette.requests.Request, exc: IsNotUploaded):
content=StatusResponseModel(
status="Error", message=f"{exc}", ru="Файл не загружен"
).model_dump(),
status_code=415,
status_code=404,
)
7 changes: 2 additions & 5 deletions print_service/routes/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import aiofiles.os
from auth_lib.fastapi import UnionAuth
from fastapi import APIRouter, File, UploadFile
from fastapi.exceptions import HTTPException
from fastapi.params import Depends
from fastapi_sqlalchemy import db
from pydantic import Field, field_validator
Expand All @@ -24,8 +23,6 @@
PINNotFound,
TooLargeSize,
TooManyPages,
UnprocessableFileInstance,
UserNotFound,
)
from print_service.models import File as FileModel
from print_service.models import UnionMember
Expand Down Expand Up @@ -258,7 +255,7 @@ async def update_file_options(
.order_by(FileModel.created_at.desc())
.one_or_none()
)
print(options)

if not file_model:
raise PINNotFound(pin)
file_model.option_pages = options.get('pages') or file_model.option_pages
Expand All @@ -269,7 +266,7 @@ async def update_file_options(
db.session.commit()
if file_model.flatten_pages:
if file_model.number_of_pages < max(file_model.flatten_pages):
raise InvalidPageRequest
raise InvalidPageRequest()
if file_model.sheets_count > settings.MAX_PAGE_COUNT:
raise TooManyPages()
return {
Expand Down
8 changes: 4 additions & 4 deletions print_service/routes/qrprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from starlette.status import WS_1000_NORMAL_CLOSURE
from typing_extensions import Annotated

from print_service.exceptions import TerminalQRNotFound
from print_service.exceptions import NotAuthenticated, TerminalQRNotFound, TokenAlreadyUsed, Unauthorized
from print_service.schema import BaseModel
from print_service.settings import Settings, get_settings
from print_service.utils import get_file
Expand Down Expand Up @@ -89,22 +89,22 @@ async def check_token(self):
me = await auth.check_token(self.terminal_token)
if me is None:
logger.error("Not authenticated")
raise Exception("Not authenticated")
raise NotAuthenticated

for scope in me['session_scopes']:
if scope['name'] == "print.qr_task.get":
break
else:
logger.error("Unauthorized")
logger.debug(me)
raise Exception("Unauthorized")
raise Unauthorized

# Token shouldn't be used yet
for key in self.redis.keys():
value = self.redis.get(key)
if self.redis.get(key) == self.terminal_token.encode():
logger.error("Token already used")
raise Exception("Token already used")
raise TokenAlreadyUsed

def __aiter__(self):
return self
Expand Down
4 changes: 1 addition & 3 deletions print_service/routes/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@

from auth_lib.fastapi import UnionAuth
from fastapi import APIRouter, Depends
from fastapi.exceptions import HTTPException
from fastapi_sqlalchemy import db
from pydantic import constr, validate_call
from pydantic import constr
from sqlalchemy import and_, func, or_

from print_service import __version__
Expand Down Expand Up @@ -51,7 +50,6 @@ async def check_union_member(
):
"""Проверяет наличие пользователя в списке."""

surname = surname.upper()
user = db.session.query(UnionMember)
if not settings.ALLOW_STUDENT_NUMBER:
user = user.filter(UnionMember.union_number != None)
Expand Down
2 changes: 1 addition & 1 deletion print_service/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from typing import List

from auth_lib.fastapi import UnionAuthSettings
from pydantic import AnyUrl, ConfigDict, DirectoryPath, PostgresDsn, RedisDsn
from pydantic import ConfigDict, DirectoryPath, PostgresDsn, RedisDsn
from pydantic_settings import BaseSettings


Expand Down
3 changes: 0 additions & 3 deletions print_service/utils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import io
import math
import random
import re
from datetime import date, datetime, timedelta
from os.path import abspath, exists

from fastapi import File
from fastapi.exceptions import HTTPException
from PyPDF4 import PdfFileReader
from sqlalchemy import func
from sqlalchemy.orm.session import Session
Expand All @@ -20,7 +18,6 @@
from print_service.models import File
from print_service.models import File as FileModel
from print_service.models import PrintFact
from print_service.routes import exc_handlers
from print_service.settings import Settings, get_settings


Expand Down