Skip to content

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

Feat/django session replace cookies (#260)

ali9c1948be3542
diff --git a/backend/account/authentication_controller.py b/backend/account/authentication_controller.py
index cb1bd2ed1..1dc76985b 100644
--- a/backend/account/authentication_controller.py
+++ b/backend/account/authentication_controller.py
@@ -1,6 +1,5 @@
import logging
from typing import Any, Optional, Union
-from urllib.parse import urlencode
from account.authentication_helper import AuthenticationHelper
from account.authentication_plugin_registry import AuthenticationPluginRegistry
@@ -14,7 +13,6 @@ from account.constants import (
)
from account.custom_exceptions import DuplicateData, Forbidden, UserNotExistError
from account.dto import (
- CallbackData,
MemberInvitation,
OrganizationData,
UserInfo,
@@ -31,13 +29,11 @@ from account.serializer import (
)
from account.user import UserService
from django.conf import settings
-from django.contrib.auth import login as django_login
from django.contrib.auth import logout as django_logout
from django.db.utils import IntegrityError
from django.middleware import csrf
from django.shortcuts import redirect
from django_tenants.utils import tenant_context
-from psycopg2.errors import UndefinedTable
from rest_framework import status
from rest_framework.request import Request
from rest_framework.response import Response
@@ -45,6 +41,7 @@ from tenant_account.models import OrganizationMember as OrganizationMember
from tenant_account.organization_member_service import OrganizationMemberService
from utils.cache_service import CacheService
from utils.local_context import StateStore
+from utils.user_session import UserSessionUtils
Logger = logging.getLogger(__name__)
@@ -90,47 +87,14 @@ class AuthenticationController:
Returns:
Any: Redirect response
"""
-
- callback_data: CallbackData = self.auth_service.get_callback_data(
- request=request
- )
- user: User = self.get_or_create_user_by_email(request, callback_data)
try:
- member = self.auth_service.handle_invited_user_while_callback(
- request=request, user=user
+ return self.auth_service.handle_authorization_callback(
+ request=request, backend=backend
)
-
except Exception as ex:
- """Error code reference
- frontend/src/components/error/GenericError/GenericError.jsx."""
- if ex.code == AuthorizationErrorCode.IDM: # type: ignore
- query_params = {"code": AuthorizationErrorCode.IDM}
- return redirect(f"{settings.ERROR_URL}?{urlencode(query_params)}")
- elif ex.code == AuthorizationErrorCode.UMM: # type: ignore
- query_params = {"code": AuthorizationErrorCode.UMM}
- return redirect(f"{settings.ERROR_URL}?{urlencode(query_params)}")
-
+ Logger.error(f"Error while handling authorization callback: {ex}")
return redirect(f"{settings.ERROR_URL}")
- if member.organization_id and member.role and len(member.role) > 0:
- organization: Optional[Organization] = (
- OrganizationService.get_organization_by_org_id(member.organization_id)
- )
- if organization:
- try:
- self.create_tenant_user(organization=organization, user=user)
- except UndefinedTable:
- pass
-
- response = self.auth_service.handle_authorization_callback(
- user=user,
- data=callback_data,
- redirect_url=request.GET.get("redirect_url"),
- )
- django_login(request, user, backend)
-
- return response
-
def user_organizations(self, request: Request) -> Any:
"""List a user's organizations.
@@ -224,13 +188,7 @@ class AuthenticationController:
f"{Common.LOG_EVENTS_ID}": StateStore.get(Common.LOG_EVENTS_ID),
},
)
- # Update user session data in redis
- user_session_info: dict[str, Any] = CacheService.get_user_session_info(
- user.email
- )
- user_session_info["current_org"] = organization_id
- CacheService.set_user_session_info(user_session_info)
- response.set_cookie(Cookie.ORG_ID, organization_id)
+ UserSessionUtils.set_organization_id(request, organization_id)
return response
return Response(status=status.HTTP_403_FORBIDDEN)
@@ -250,9 +208,7 @@ class AuthenticationController:
return self.auth_service.is_admin_by_role(role=role)
def get_organization_info(self, org_id: str) -> Optional[Organization]:
- organization = self.auth_service.get_organization_info(org_id)
- if not organization:
- organization = OrganizationService.get_organization_by_org_id(org_id=org_id)
+ organization = OrganizationService.get_organization_by_org_id(org_id=org_id)
return organization
def make_organization_and_add_member(
@@ -426,9 +382,7 @@ class AuthenticationController:
def create_tenant_user(self, organization: Organization, user: User) -> None:
with tenant_context(organization):
- existing_tenant_user = self.organization_member_service.get_user_by_id(
- id=user.id
- )
+ existing_tenant_user = OrganizationMemberService.get_user_by_id(id=user.id)
if existing_tenant_user:
Logger.info(f"{existing_tenant_user.user.email} Already exist")
else:
@@ -446,17 +400,6 @@ class AuthenticationController:
else:
raise UserNotExistError()
- def get_or_create_user_by_email(
- self, request: Request, callback_data: CallbackData
- ) -> Union[User, OrganizationMember]:
- email = callback_data.email
- user_service = UserService()
- user = user_service.get_user_by_email(email)
- if not user:
- user_id = callback_data.user_id
- user = user_service.create_user(email, user_id)
- return user
-
def get_or_create_user(
self, user: User
) -> Optional[Union[User, OrganizationMember]]:
diff --git a/backend/account/authentication_helper.py b/backend/account/authentication_helper.py
index 5336b672b..5833c875b 100644
--- a/backend/account/authentication_helper.py
+++ b/backend/account/authentication_helper.py
@@ -3,6 +3,7 @@ from typing import Any
from account.dto import MemberData
from account.models import Organization, User
+from account.user import UserService
from platform_settings.platform_auth_service import PlatformAuthenticationService
logger = logging.getLogger(__name__)
@@ -25,6 +26,26 @@ class AuthenticationHelper:
return members
+ @staticmethod
+ def get_or_create_user_by_email(user_id: str, email: str) -> User:
+ """Get or create a user with the given email.
+
+ If a user with the given email already exists, return that user.
+ Otherwise, create a new user with the given email and return it.
+
+ Parameters:
+ user_id (str): The ID of the user.
+ email (str): The email of the user.
+
+ Returns:
+ User: The user with the given email.
+ """
+ user_service = UserService()
+ user = user_service.get_user_by_email(email)
+ if not user:
+ user = user_service.create_user(email, user_id)
+ return user
+
def create_initial_platform_key(
self, user: User, organization: Organization
) -> None:
diff --git a/backend/account/authentication_service.py b/backend/account/authentication_service.py
index fe3c92aca..fe4ed2bac 100644
--- a/backend/account/authentication_service.py
+++ b/backend/account/authentication_service.py
@@ -64,6 +64,17 @@ class AuthenticationService:
return self.render_login_page_with_error(request, ErrorMessage.USER_LOGIN_ERROR)
+ def is_authenticated(self, request: HttpRequest) -> bool:
+ """Check if the user is authenticated.
+
+ Args:
+ request (Request): The HTTP request object.
+
+ Returns:
+ bool: True if the user is authenticated, False otherwise.
+ """
+ return request.user.is_authenticated
+
def authenticate_and_login(
self, request: Request, username: str, password: str
) -> bool:
@@ -167,10 +178,8 @@ class AuthenticationService:
return member_data
- def handle_authorization_callback(
- self, user: User, data: CallbackData, redirect_url: str = ""
- ) -> Response:
- return Response()
+ def handle_authorization_callback(self, request: Request, backend: str) -> Response:
+ raise MethodNotImplemented()
def add_to_organization(
self,
diff --git a/backend/account/constants.py b/backend/account/constants.py
index fe784a89f..5e9151b31 100644
--- a/backend/account/constants.py
+++ b/backend/account/constants.py
@@ -67,8 +67,15 @@ class PluginConfig:
class AuthorizationErrorCode:
- """Error code reference
- frontend/src/components/error/GenericError/GenericError.jsx."""
+ """Error codes
+ IDM: INVITATION DENIED MESSAGE (Unauthorized invitation)
+ INF: INVITATION NOT FOUND (Invitation is either invalid or has expired)
+ UMM: USER MEMBERSHIP MISCONDUCT
+ USF: USER FOUND (User Account Already Exists for Organization)
+
+ Error code reference :
+ frontend/src/components/error/GenericError/GenericError.jsx.
+ """
IDM = "IDM"
UMM = "UMM"
diff --git a/backend/account/custom_auth_middleware.py b/backend/account/custom_auth_middleware.py
index 4812df842..966583ef5 100644
--- a/backend/account/custom_auth_middleware.py
+++ b/backend/account/custom_auth_middleware.py
@@ -1,13 +1,8 @@
from account.authentication_plugin_registry import AuthenticationPluginRegistry
-from account.constants import Common, Cookie, DefaultOrg
-from account.dto import UserSessionInfo
-from account.user import UserService
+from account.authentication_service import AuthenticationService
+from account.constants import Common
from django.conf import settings
-from django.core.cache import cache
-from django.db import connection
from django.http import HttpRequest, HttpResponse, JsonResponse
-from tenant_account.organization_member_service import OrganizationMemberService
-from utils.cache_service import CacheService
from utils.local_context import StateStore
from backend.constants import RequestHeader
@@ -23,13 +18,6 @@ class CustomAuthMiddleware:
if any(request.path.startswith(path) for path in settings.WHITELISTED_PATHS):
return self.get_response(request)
- tenantAccessiblePublicPath = False
- if any(
- request.path.startswith(path)
- for path in settings.TENANT_ACCESSIBLE_PUBLIC_PATHS
- ):
- tenantAccessiblePublicPath = True
-
# Authenticating With API_KEY
x_api_key = request.headers.get(RequestHeader.X_API_KEY)
if (
@@ -38,73 +26,19 @@ class CustomAuthMiddleware:
): # Should API Key be in settings or just env alone?
return self.get_response(request)
- if not AuthenticationPluginRegistry.is_plugin_available():
- self.local_authentication(request)
- elif request.COOKIES:
- self.authenticate_with_cookies(request, tenantAccessiblePublicPath)
- if request.user and request.session and "user" in request.session:
+ if AuthenticationPluginRegistry.is_plugin_available():
+ auth_service: AuthenticationService = (
+ AuthenticationPluginRegistry.get_plugin()
+ )
+ else:
+ auth_service = AuthenticationService()
+
+ is_authenticated = auth_service.is_authenticated(request)
+
+ if is_authenticated:
StateStore.set(Common.LOG_EVENTS_ID, request.session.session_key)
response = self.get_response(request)
StateStore.clear(Common.LOG_EVENTS_ID)
return response
return JsonResponse({"message": "Unauthorized"}, status=401)
-
- def local_authentication(self, request: HttpRequest) -> None:
- org_id = DefaultOrg.MOCK_ORG
- if not request.user.is_authenticated:
- return
- user_session_info = CacheService.get_user_session_info(request.user.email)
- if not user_session_info:
- user_info: UserSessionInfo = UserSessionInfo(
- id=request.user.id,
- user_id=request.user.user_id,
- email=request.user.email,
- current_org=org_id,
- )
- CacheService.set_user_session_info(user_info)
- user_session_info = CacheService.get_user_session_info(request.user.email)
- request.org_id = org_id
- request.session["user"] = user_session_info
- request.session.save()
-
- def authenticate_with_cookies(
- self,
- request: HttpRequest,
- tenantAccessiblePublicPath: bool,
- ) -> None:
- z_code: str = request.COOKIES.get(Cookie.Z_CODE)
- token = cache.get(z_code) if z_code else None
- if not token:
- return
-
- user_email = token["userinfo"]["email"]
- user_session_info = CacheService.get_user_session_info(user_email)
- if not user_session_info:
- return
-
- current_org = user_session_info["current_org"]
- if not current_org:
- return
-
- if current_org != connection.get_schema() and not tenantAccessiblePublicPath:
- return
-
- if current_org == Common.PUBLIC_SCHEMA_NAME or tenantAccessiblePublicPath:
- user_service = UserService()
- else:
- organization_member_service = OrganizationMemberService()
- member = organization_member_service.get_user_by_email(user_email)
- if not member:
- return
- user_service = UserService()
-
- user = user_service.get_user_by_email(user_email)
-
- if not user:
- return
-
- request.user = user
- request.org_id = current_org
- request.session["user"] = token
- request.session.save()
diff --git a/backend/account/dto.py b/backend/account/dto.py
index dc60c3df4..1554901fb 100644
--- a/backend/account/dto.py
+++ b/backend/account/dto.py
@@ -57,7 +57,8 @@ class UserSessionInfo:
id: str
user_id: str
email: str
- current_org: str
+ organization_id: str
+ user: UserInfo
@staticmethod
def from_dict(data: dict[str, Any]) -> "UserSessionInfo":
@@ -65,7 +66,7 @@ class UserSessionInfo:
id=data["id"],
user_id=data["user_id"],
email=data["email"],
- current_org=data["current_org"],
+ organization_id=data["organization_id"],
)
def to_dict(self) -> Any:
@@ -73,7 +74,7 @@ class UserSessionInfo:
"id": self.id,
"user_id": self.user_id,
"email": self.email,
- "current_org": self.current_org,
+ "organization_id": self.organization_id,
}
diff --git a/backend/account/serializer.py b/backend/account/serializer.py
index 15d165d3a..57d166fe7 100644
--- a/backend/account/serializer.py
+++ b/backend/account/serializer.py
@@ -109,3 +109,10 @@ class LoginRequestSerializer(serializers.Serializer):
"Password must be at least 3 characters long."
)
return value
+
+
+class UserSessionResponseSerializer(serializers.Serializer):
+ id = serializers.IntegerField()
+ user_id = serializers.CharField()
+ email = serializers.CharField()
+ organization_id = serializers.CharField()
diff --git a/backend/account/urls.py b/backend/account/urls.py
index 8cc60e65c..aeb10707f 100644
--- a/backend/account/urls.py
+++ b/backend/account/urls.py
@@ -2,6 +2,7 @@ from account.views import (
callback,
create_organization,
get_organizations,
+ get_session_data,
login,
logout,
set_organization,
@@ -14,6 +15,7 @@ urlpatterns = [
path("signup", signup, name="signup"),
path("logout", logout, name="logout"),
path("callback", callback, name="callback"),
+ path("session", get_session_data, name="session"),
path("organization", get_organizations, name="get_organizations"),
path("organization/<str:id>/set", set_organization, name="set_organization"),
path("organization/create", create_organization, name="create_organization"),
diff --git a/backend/account/views.py b/backend/account/views.py
index 22a9b927a..a9b0bf80c 100644
--- a/backend/account/views.py
+++ b/backend/account/views.py
@@ -2,17 +2,23 @@ import logging
from typing import Any
from account.authentication_controller import AuthenticationController
-from account.dto import OrganizationSignupRequestBody, OrganizationSignupResponse
+from account.dto import (
+ OrganizationSignupRequestBody,
+ OrganizationSignupResponse,
+ UserSessionInfo,
+)
from account.models import Organization
from account.organization import OrganizationService
from account.serializer import (
OrganizationSignupResponseSerializer,
OrganizationSignupSerializer,
+ UserSessionResponseSerializer,
)
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.request import Request
from rest_framework.response import Response
+from utils.user_session import UserSessionUtils
Logger = logging.getLogger(__name__)
@@ -97,6 +103,48 @@ def set_organization(request: Request, id: str) -> Response:
return auth_controller.set_user_organization(request, id)
+@api_view(["GET"])
+def get_session_data(request: Request) -> Response:
+ """get_session_data.
+
+ Retrieve the current session data.
+ Args:
+ request (HttpRequest): _description_
+
+ Returns:
+ Response: Contains the User and Current organization details.
+ """
+ response = make_session_response(request)
+ return Response(
+ status=status.HTTP_201_CREATED,
+ data=response,
+ )
+
+
+def make_session_response(
+ request: Request,
+) -> Any:
+ """make_session_response.
+
+ Make the current session data.
+ Args:
+ request (HttpRequest): _description_
+
+ Returns:
+ User and Current organization details.
+ """
+ auth_controller = AuthenticationController()
+ return UserSessionResponseSerializer(
+ UserSessionInfo(
+ id=request.user.id,
+ user_id=request.user.user_id,
+ email=request.user.email,
+ user=auth_controller.get_user_info(request),
+ organization_id=UserSessionUtils.get_organization_id(request),
+ )
+ ).data
+
+
def makeSignupRequestParams(
serializer: OrganizationSignupSerializer,
) -> OrganizationSignupRequestBody:
diff --git a/backend/backend/settings/base.py b/backend/backend/settings/base.py
index 0f14e0b25..993ebedce 100644
--- a/backend/backend/settings/base.py
+++ b/backend/backend/settings/base.py
@@ -311,6 +311,8 @@ CACHES = {
}
}
+SESSION_ENGINE = "django.contrib.sessions.backends.cached_db"
+
RQ_QUEUES = {
"default": {"USE_REDIS_CACHE": "default"},
}
@@ -404,11 +406,6 @@ WHITELISTED_PATHS = [f"/{PATH_PREFIX}{PATH}" for PATH in WHITELISTED_PATHS_LIST]
# White lists workflow-api-deployment path
WHITELISTED_PATHS.append(f"/{API_DEPLOYMENT_PATH_PREFIX}")
-# White list paths under tenant paths
-TENANT_ACCESSIBLE_PUBLIC_PATHS_LIST = ["/oauth", "/organization", "/doc"]
-TENANT_ACCESSIBLE_PUBLIC_PATHS = [
- f"/{PATH_PREFIX}{PATH}" for PATH in TENANT_ACCESSIBLE_PUBLIC_PATHS_LIST
-]
# API Doc Generator Settings
# https://drf-yasg.readthedocs.io/en/stable/settings.html
diff --git a/backend/connector_auth/views.py b/backend/connector_auth/views.py
index c944d3565..5e097e75e 100644
--- a/backend/connector_auth/views.py
+++ b/backend/connector_auth/views.py
@@ -8,6 +8,7 @@ from rest_framework import status, viewsets
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.versioning import URLPathVersioning
+from utils.user_session import UserSessionUtils
logger = logging.getLogger(__name__)
@@ -36,7 +37,7 @@ class ConnectorAuthViewSet(viewsets.ViewSet):
random = str(uuid.uuid4())
user_id = request.user.user_id
- org_id = request.org_id
+ org_id = UserSessionUtils.get_organization_id(request)
cache_key = f"oauth:{org_id}|{user_id}|{backend}|{random}"
logger.info(f"Generated cache key: {cache_key}")
return Response(
diff --git a/backend/file_management/views.py b/backend/file_management/views.py
index 6cf34e456..7ff72a777 100644
--- a/backend/file_management/views.py
+++ b/backend/file_management/views.py
@@ -22,6 +22,7 @@ from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.versioning import URLPathVersioning
+from utils.user_session import UserSessionUtils
from unstract.connectors.exceptions import ConnectorError
from unstract.connectors.filesystems.local_storage.local_storage import LocalStorageFS
@@ -113,7 +114,7 @@ class FileManagementViewSet(viewsets.ModelViewSet):
file_name: str = document.document_name
tool_id: str = serializer.validated_data.get("tool_id")
file_path = FileManagerHelper.handle_sub_directory_for_tenants(
- request.org_id,
+ UserSessionUtils.get_organization_id(request),
is_create=False,
user_id=request.user.user_id,
tool_id=tool_id,
diff --git a/backend/prompt_studio/prompt_studio_core/views.py b/backend/prompt_studio/prompt_studio_core/views.py
index 412fdb3fa..d3664a692 100644
--- a/backend/prompt_studio/prompt_studio_core/views.py
+++ b/backend/prompt_studio/prompt_studio_core/views.py
@@ -43,6 +43,7 @@ from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.versioning import URLPathVersioning
from tool_instance.models import ToolInstance
+from utils.user_session import UserSessionUtils
from unstract.connectors.filesystems.local_storage.local_storage import LocalStorageFS
@@ -205,7 +206,7 @@ class PromptStudioCoreView(viewsets.ModelViewSet):
unique_id = PromptStudioHelper.index_document(
tool_id=str(tool.tool_id),
file_name=file_name,
- org_id=request.org_id,
+ org_id=UserSessionUtils.get_organization_id(request),
user_id=tool.created_by.user_id,
document_id=document_id,
)
@@ -217,7 +218,7 @@ class PromptStudioCoreView(viewsets.ModelViewSet):
cls.process(
tool_id=str(tool.tool_id),
file_name=file_name,
- org_id=request.org_id,
+ org_id=UserSessionUtils.get_organization_id(request),
user_id=tool.created_by.user_id,
document_id=document_id,
)
@@ -258,7 +259,7 @@ class PromptStudioCoreView(viewsets.ModelViewSet):
id=id,
tool_id=tool_id,
file_name=file_name,
- org_id=request.org_id,
+ org_id=UserSessionUtils.get_organization_id(request),
user_id=custom_tool.created_by.user_id,
document_id=document_id,
)
@@ -292,7 +293,7 @@ class PromptStudioCoreView(viewsets.ModelViewSet):
response: dict[str, Any] = PromptStudioHelper.prompt_responder(
tool_id=tool_id,
file_name=file_name,
- org_id=request.org_id,
+ org_id=UserSessionUtils.get_organization_id(request),
user_id=custom_tool.created_by.user_id,
document_id=document_id,
)
diff --git a/backend/tenant_account/invitation_views.py b/backend/tenant_account/invitation_views.py
index 8d727eb74..e6b0aeb5c 100644
--- a/backend/tenant_account/invitation_views.py
+++ b/backend/tenant_account/invitation_views.py
@@ -7,6 +7,7 @@ from rest_framework.decorators import action
from rest_framework.request import Request
from rest_framework.response import Response
from tenant_account.serializer import ListInvitationsResponseSerializer
+from utils.user_session import UserSessionUtils
Logger = logging.getLogger(__name__)
@@ -16,7 +17,7 @@ class InvitationViewSet(viewsets.ViewSet):
def list_invitations(self, request: Request) -> Response:
auth_controller = AuthenticationController()
invitations: list[MemberInvitation] = auth_controller.get_user_invitations(
- organization_id=request.org_id,
+ organization_id=UserSessionUtils.get_organization_id(request),
)
serialized_members = ListInvitationsResponseSerializer(
invitations, many=True
@@ -30,7 +31,8 @@ class InvitationViewSet(viewsets.ViewSet):
def delete_invitation(self, request: Request, id: str) -> Response:
auth_controller = AuthenticationController()
is_deleted: bool = auth_controller.delete_user_invitation(
- organization_id=request.org_id, invitation_id=id
+ organization_id=UserSessionUtils.get_organization_id(request),
+ invitation_id=id,
)
if is_deleted:
return Response(
diff --git a/backend/tenant_account/organization_member_service.py b/backend/tenant_account/organization_member_service.py
index 673952d15..2d58f9c2e 100644
--- a/backend/tenant_account/organization_member_service.py
+++ b/backend/tenant_account/organization_member_service.py
@@ -19,7 +19,8 @@ class OrganizationMemberService:
except OrganizationMember.DoesNotExist:
return None
- def get_user_by_id(self, id: str) -> Optional[OrganizationMember]:
+ @staticmethod
+ def get_user_by_id(id: str) -> Optional[OrganizationMember]:
try:
return OrganizationMember.objects.get(user=id) # type: ignore
except OrganizationMember.DoesNotExist:
diff --git a/backend/tenant_account/users_view.py b/backend/tenant_account/users_view.py
index 3e244332b..3d025929c 100644
--- a/backend/tenant_account/users_view.py
+++ b/backend/tenant_account/users_view.py
@@ -15,6 +15,7 @@ from tenant_account.serializer import (
UserInfoSerializer,
UserInviteResponseSerializer,
)
+from utils.user_session import UserSessionUtils
Logger = logging.getLogger(__name__)
@@ -28,7 +29,7 @@ class OrganizationUserViewSet(viewsets.ViewSet):
role = serializer.get_user_role(serializer.validated_data)
if not (user_email and role):
raise BadRequestException
- org_id: str = request.org_id
+ org_id: str = UserSessionUtils.get_organization_id(request)
auth_controller = AuthenticationController()
auth_controller = AuthenticationController()
@@ -54,7 +55,7 @@ class OrganizationUserViewSet(viewsets.ViewSet):
role = serializer.get_user_role(serializer.validated_data)
if not (user_email and role):
raise BadRequestException
- org_id: str = request.org_id
+ org_id: str = UserSessionUtils.get_organization_id(request)
auth_controller = AuthenticationController()
auth_controller = AuthenticationController()
@@ -107,7 +108,9 @@ class OrganizationUserViewSet(viewsets.ViewSet):
user_list = serializer.get_users(serializer.validated_data)
auth_controller = AuthenticationController()
invite_response = auth_controller.invite_user(
- admin=request.user, org_id=request.org_id, user_list=user_list
+ admin=request.user,
+ org_id=UserSessionUtils.get_organization_id(request),
+ user_list=user_list,
)
response_serializer = UserInviteResponseSerializer(invite_response, many=True)
@@ -130,7 +133,7 @@ class OrganizationUserViewSet(viewsets.ViewSet):
serializer.is_valid(raise_exception=True)
user_emails = serializer.get_user_emails(serializer.validated_data)
- organization_id: str = request.org_id
+ organization_id: str = UserSessionUtils.get_organization_id(request)
auth_controller = AuthenticationController()
is_updated = auth_controller.remove_users_from_organization(
@@ -152,7 +155,7 @@ class OrganizationUserViewSet(viewsets.ViewSet):
@action(detail=False, methods=["GET"])
def get_organization_members(self, request: Request) -> Response:
auth_controller = AuthenticationController()
- if request.org_id:
+ if UserSessionUtils.get_organization_id(request):
members: list[OrganizationMember] = (
auth_controller.get_organization_members_by_org_id()
)
diff --git a/backend/tenant_account/views.py b/backend/tenant_account/views.py
index 1f95d07ae..5f37fd3b2 100644
--- a/backend/tenant_account/views.py
+++ b/backend/tenant_account/views.py
@@ -13,6 +13,7 @@ from tenant_account.serializer import (
GetRolesResponseSerializer,
OrganizationLoginResponseSerializer,
)
+from utils.user_session import UserSessionUtils
logger = logging.getLogger(__name__)
@@ -54,7 +55,8 @@ def reset_password(request: Request) -> Response:
def get_organization(request: Request) -> Response:
auth_controller = AuthenticationController()
try:
- org_data = auth_controller.get_organization_info(request.org_id)
+ organization_id = UserSessionUtils.get_organization_id(request)
+ org_data = auth_controller.get_organization_info(organization_id)
if not org_data:
return Response(
status=status.HTTP_404_NOT_FOUND,
diff --git a/backend/tool_instance/views.py b/backend/tool_instance/views.py
index e6b537003..b5a1bc237 100644
--- a/backend/tool_instance/views.py
+++ b/backend/tool_instance/views.py
@@ -22,6 +22,7 @@ from tool_instance.serializers import ToolInstanceSerializer
from tool_instance.tool_instance_helper import ToolInstanceHelper
from tool_instance.tool_processor import ToolProcessor
from utils.filtering import FilterHelper
+from utils.user_session import UserSessionUtils
from workflow_manager.workflow.constants import WorkflowKey
from backend.constants import RequestKey
@@ -141,7 +142,9 @@ class ToolInstanceViewSet(viewsets.ModelViewSet):
# TODO: Move update logic into serializer
ToolInstanceHelper.update_instance_metadata(
- request.org_id, instance, metadata
+ UserSessionUtils.get_organization_id(request),
+ instance,
+ metadata,
)
return Response(serializer.data)
return super().partial_update(request, *args, **kwargs)
diff --git a/backend/utils/cache_service.py b/backend/utils/cache_service.py
index 6feedf970..83084e505 100644
--- a/backend/utils/cache_service.py
+++ b/backend/utils/cache_service.py
@@ -1,7 +1,6 @@
-from typing import Any, Optional, Union
+from typing import Any, Optional
from account.custom_cache import CustomCache
-from account.dto import UserSessionInfo
from django.conf import settings
from django.core.cache import cache
@@ -11,15 +10,20 @@ class CacheService:
def get_key(key: str) -> Optional[Any]:
data = cache.get(str(key))
if data is not None:
- return data.decode("utf-8")
+ if isinstance(data, bytes):
+ return data.decode("utf-8")
+ else:
+ return data
return data
@staticmethod
- def set_key(key: str, value: Any) -> None:
+ def set_key(
+ key: str, value: Any, expire: int = int(settings.CACHE_TTL_SEC)
+ ) -> None:
cache.set(
str(key),
value,
- int(settings.CACHE_TTL_SEC),
+ expire,
)
@staticmethod
@@ -27,43 +31,6 @@ class CacheService:
"""Delete keys in bulk based on the key pattern."""
cache.delete_pattern(key_pattern)
- @staticmethod
- def set_cookie(cookie: str, token: dict[str, Any]) -> None:
- cache.set(cookie, token)
-
- @staticmethod
- def get_cookie(cookie: str) -> dict[str, Any]:
- data: dict[str, Any] = cache.get(cookie)
- return data
-
- @staticmethod
- def set_user_session_info(
- user_session_info: Union[UserSessionInfo, dict[str, Any]]
- ) -> None:
- if isinstance(user_session_info, UserSessionInfo):
- email = user_session_info.email
- user_session = user_session_info.to_dict()
- else:
- email = user_session_info["email"]
- user_session = user_session_info
- session_info_key: str = CacheService.get_user_session_info_key(email)
- cache.set(
- session_info_key,
- user_session,
- int(settings.SESSION_EXPIRATION_TIME_IN_SECOND),
- )
-
- @staticmethod
- def get_user_session_info(email: str) -> dict[str, Any]:
- session_info_key: str = CacheService.get_user_session_info_key(email)
- data: dict[str, Any] = cache.get(session_info_key)
- return data
-
- @staticmethod
- def get_user_session_info_key(email: str) -> str:
- session_info_key: str = f"session:{email}"
- return session_info_key
-
@staticmethod
def check_a_key_exist(key: str, version: Any = None) -> bool:
data: bool = cache.has_key(key, version)
diff --git a/backend/utils/user_session.py b/backend/utils/user_session.py
new file mode 100644
index 000000000..542a06100
--- /dev/null
+++ b/backend/utils/user_session.py
@@ -0,0 +1,13 @@
+from typing import Optional
+
+from django.http import HttpRequest
+
+
+class UserSessionUtils:
+ @staticmethod
+ def get_organization_id(request: HttpRequest) -> Optional[str]:
+ return request.session.get("organization")
+
+ @staticmethod
+ def set_organization_id(request: HttpRequest, organization_id: str) -> None:
+ request.session["organization"] = organization_id
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 2af05353f..81f09c643 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -28,6 +28,7 @@
"escape-html": "^1.0.3",
"handlebars": "^4.7.8",
"http-proxy-middleware": "^2.0.6",
+ "js-cookie": "^3.0.5",
"js-yaml": "^4.1.0",
"markdown-to-jsx": "^7.2.1",
"moment": "^2.29.4",
@@ -12628,6 +12629,14 @@
"jiti": "bin/jiti.js"
}
},
+ "node_modules/js-cookie": {
+ "version": "3.0.5",
+ "resolved": "https://registry.npmjs.org/js-cookie/-/js-cookie-3.0.5.tgz",
+ "integrity": "sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw==",
+ "engines": {
+ "node": ">=14"
+ }
+ },
"node_modules/js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
@@ -29648,6 +29657,11 @@
"resolved": "https://registry.npmjs.org/jiti/-/jiti-1.18.2.tgz",
"integrity": "sha512-QAdOptna2NYiSSpv0O/BwoHBSmz4YhpzJHyi+fnMRTXFjp7B8i/YG5Z8IfusxB1ufjcD2Sre1F3R+nX3fvy7gg=="
},
+ "js-cookie": {
+ "version": "3.0.5",
+ "resolved": "https://registry.npmjs.org/js-cookie/-/js-cookie-3.0.5.tgz",
+ "integrity": "sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw=="
+ },
"js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
diff --git a/frontend/package.json b/frontend/package.json
index 3387d4e9d..d575f9887 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -23,6 +23,7 @@
"escape-html": "^1.0.3",
"handlebars": "^4.7.8",
"http-proxy-middleware": "^2.0.6",
+ "js-cookie": "^3.0.5",
"js-yaml": "^4.1.0",
"markdown-to-jsx": "^7.2.1",
"moment": "^2.29.4",
diff --git a/frontend/src/components/set-org/SetOrg.jsx b/frontend/src/components/set-org/SetOrg.jsx
index 334d84669..fb2f396ac 100644
--- a/frontend/src/components/set-org/SetOrg.jsx
+++ b/frontend/src/components/set-org/SetOrg.jsx
@@ -1,3 +1,5 @@
+import Cookies from "js-cookie";
+import { userSession } from "../../helpers/GetUserSession.js";
import { useEffect, useState } from "react";
import { Button, Card } from "antd";
import { useLocation, useNavigate } from "react-router-dom";
@@ -23,24 +25,26 @@ function SetOrg() {
const handleException = useExceptionHandler();
useEffect(() => {
- if (state === null || signedInOrgId) {
- navigate("/");
- }
- }, []);
+ const fetchData = async () => {
+ try {
+ const userSessionData = await userSession();
+ const signedInOrgId = userSessionData?.organization_id;
+ if (state === null || signedInOrgId) {
+ navigate("/");
+ }
+ } catch (error) {
+ navigate("/");
+ } finally {
+ setLoading(false);
+ }
+ };
+ fetchData();
+ }, [state, navigate]);
- const signedInOrgId =
- document?.cookie
- ?.split("; ")
- ?.find((row) => row.startsWith("org_id="))
- ?.split("=")[1] || null;
const handleContinue = (id) => {
setLoading(true);
setLoadingOrgId(id);
- const csrfToken = ("; " + document.cookie)
- ?.split(`; csrftoken=`)
- ?.pop()
- ?.split(";")[0];
-
+ const csrfToken = Cookies.get("csrftoken");
const requestOptions = {
method: "POST",
url: `/api/v1/organization/${id}/set`,
diff --git a/frontend/src/helpers/GetUserSession.js b/frontend/src/helpers/GetUserSession.js
new file mode 100644
index 000000000..79b0564ac
--- /dev/null
+++ b/frontend/src/helpers/GetUserSession.js
@@ -0,0 +1,19 @@
+import axios from "axios";
+import { useExceptionHandler } from "../hooks/useExceptionHandler.jsx";
+import { useAlertStore } from "../store/alert-store";
+const userSession = async () => {
+ try {
+ const requestOptions = {
+ method: "GET",
+ url: "/api/v1/session",
+ };
+ const res = await axios(requestOptions);
+ return res.data;
+ } catch (error) {
+ const handleException = useExceptionHandler();
+ const { setAlertDetails } = useAlertStore();
+ setAlertDetails(handleException(error, "Error while getting session"));
+ }
+};
+
+export { userSession };
diff --git a/frontend/src/hooks/useSessionValid.js b/frontend/src/hooks/useSessionValid.js
index d25cdde76..42246f2ce 100644
--- a/frontend/src/hooks/useSessionValid.js
+++ b/frontend/src/hooks/useSessionValid.js
@@ -1,6 +1,8 @@
import axios from "axios";
import { getSessionData } from "../helpers/GetSessionData";
+import Cookies from "js-cookie";
+import { userSession } from "../helpers/GetUserSession.js";
import { useSessionStore } from "../store/session-store";
import { useExceptionHandler } from "../hooks/useExceptionHandler.jsx";
import { useNavigate } from "react-router-dom";
@@ -16,15 +18,11 @@ function useSessionValid() {
const setSessionDetails = useSessionStore((state) => state.setSessionDetails);
const handleException = useExceptionHandler();
const navigate = useNavigate();
- const signedInOrgId =
- (document.cookie &&
- document.cookie
- .split("; ")
- .find((row) => row.startsWith("org_id="))
- ?.split("=")[1]) ||
- null;
return async () => {
try {
+ const userSessionData = await userSession();
+ const signedInOrgId = userSessionData?.organization_id;
+
// API to get the list of organizations
const requestOptions = {
method: "GET",
@@ -41,10 +39,7 @@ function useSessionValid() {
}
let userAndOrgDetails = null;
const orgId = signedInOrgId || orgs[0].id;
- const csrfToken = ("; " + document.cookie)
- .split(`; csrftoken=`)
- .pop()
- .split(";")[0];
+ const csrfToken = Cookies.get("csrftoken");
// API to set the organization and get the user details
requestOptions["method"] = "POST";
@@ -54,8 +49,6 @@ function useSessionValid() {
};
const setOrgRes = await axios(requestOptions).catch((error) => {
if (error?.response && error?.response?.status === 403) {
- // Remove cookie from the browser
- document.cookie = "org_id=;";
navigate("/", { state: null });
}
});