felicity-lims/felicity/api/gql/__init__.py

106 lines
2.3 KiB
Python
Raw Normal View History

2021-04-18 18:37:49 +08:00
import logging
2022-03-10 14:38:30 +08:00
from typing import Optional, Tuple, Union
import strawberry # noqa
2023-03-19 23:21:32 +08:00
from felicity.core.uid_gen import FelicityID
from ...apps.user.models import User, UserAuth
2021-09-06 02:05:20 +08:00
2021-04-18 18:37:49 +08:00
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
2021-09-06 02:05:20 +08:00
@strawberry.type
class PageInfo:
has_next_page: bool
has_previous_page: bool
start_cursor: Optional[str]
end_cursor: Optional[str]
@strawberry.type
class DeletedItem:
2023-03-19 23:21:32 +08:00
uid: FelicityID
@strawberry.type
class MessageType:
message: str
@strawberry.type
class OperationError:
error: str
suggestion: Optional[str] = ""
2022-11-06 20:09:44 +08:00
@strawberry.type
class OperationSuccess:
message: str
DeleteResponse = strawberry.union(
"DeleteResponse",
(DeletedItem, OperationError),
description="Union of possible outcomes when deleting some object",
)
MessageResponse = strawberry.union(
"MessageResponse",
(MessageType, OperationError),
description="Union of possible outcomes when deleting some object",
)
2023-02-24 08:44:14 +08:00
SuccessErrorResponse = strawberry.union(
"SuccessErrorResponse",
(OperationSuccess, OperationError),
description="Union of possible outcomes when deleting some object",
)
2021-04-18 18:37:49 +08:00
def is_authenticated(request):
return request.user.is_authenticated
def same_origin(request):
return request.headers.get("sec-fetch-site", "unknown") == "same-origin"
2021-04-19 03:20:22 +08:00
2022-11-06 20:09:44 +08:00
async def auth_from_info(info) -> Tuple[bool, Optional[User]]:
is_auth = is_authenticated(info.context["request"])
2021-09-06 02:05:20 +08:00
try:
username = info.context["request"].user.username
2021-09-06 02:05:20 +08:00
except AttributeError:
username = None
if not username:
return False, None
auth = await UserAuth.get_by_username(username)
2021-09-06 02:05:20 +08:00
if not auth:
return False, None
user = await User.get(auth_uid=auth.uid)
2021-09-06 02:05:20 +08:00
if not user:
return False, None
return is_auth, user
2023-03-19 23:21:32 +08:00
def verify_user_auth(
is_auth: bool = False, user=None, err_msg: str = None
) -> Tuple[bool, Optional[OperationError]]:
2021-09-06 02:05:20 +08:00
if not is_auth:
2023-03-19 23:21:32 +08:00
return False, OperationError(
error=f"{err_msg}", suggestion="Try to login again"
)
2021-09-06 02:05:20 +08:00
if not user:
2022-11-20 21:20:41 +08:00
return False, OperationError(
error="Failed to acquire authenticated user",
suggestion="refresh your page. If error persists, logout and login again",
)
2022-11-20 21:20:41 +08:00
return True, None