diff --git a/ApiServices/AuthService/endpoints/auth/route.py b/ApiServices/AuthService/endpoints/auth/route.py index 6cd9e7e..4cdac00 100644 --- a/ApiServices/AuthService/endpoints/auth/route.py +++ b/ApiServices/AuthService/endpoints/auth/route.py @@ -296,6 +296,7 @@ def authentication_token_check_post( "domain": domain or "", "eys-ext": f"{str(uuid.uuid4())}", "token": token, + "tz": tz or "GMT+3", } if not domain or not language: return JSONResponse( @@ -303,10 +304,15 @@ def authentication_token_check_post( status_code=status.HTTP_406_NOT_ACCEPTABLE, headers=headers, ) - + if AuthHandlers.LoginHandler.authentication_check_token_valid(access_token=token): + return JSONResponse( + content={"message": "MSG_0001"}, + status_code=status.HTTP_202_ACCEPTED, + headers=headers, + ) return JSONResponse( - content={}, - status_code=status.HTTP_202_ACCEPTED, + content={"error": "EYS_0033"}, + status_code=status.HTTP_406_NOT_ACCEPTABLE, headers=headers, ) diff --git a/ApiServices/AuthService/events/auth/auth.py b/ApiServices/AuthService/events/auth/auth.py index 7b50e45..bb312de 100644 --- a/ApiServices/AuthService/events/auth/auth.py +++ b/ApiServices/AuthService/events/auth/auth.py @@ -601,6 +601,13 @@ class LoginHandler: token_dict=token_object, ) + @classmethod + def authentication_check_token_valid(cls, access_token: str) -> bool: + redis_handler = RedisHandlers() + if redis_handler.get_object_from_redis(access_token=access_token): + return True + return False + class PasswordHandler: diff --git a/ApiServices/TemplateService/providers/token_provider.py b/ApiServices/TemplateService/providers/token_provider.py index 8b5a8e0..89f9329 100644 --- a/ApiServices/TemplateService/providers/token_provider.py +++ b/ApiServices/TemplateService/providers/token_provider.py @@ -130,14 +130,12 @@ class TokenProvider: AUTH_TOKEN: str = "AUTH_TOKEN" @classmethod - def process_redis_object(cls, redis_object: Dict[str, Any]) -> TokenDictType: + def convert_redis_object_to_token( + cls, redis_object: Dict[str, Any] + ) -> TokenDictType: """ Process Redis object and return appropriate token object. """ - if not redis_object.get("selected_company"): - redis_object["selected_company"] = None - if not redis_object.get("selected_occupant"): - redis_object["selected_occupant"] = None if redis_object.get("user_type") == UserType.employee.value: return EmployeeTokenObject(**redis_object) elif redis_object.get("user_type") == UserType.occupant.value: @@ -160,12 +158,14 @@ class TokenProvider: if token: result = RedisActions.get_json(list_keys=auth_key_list, limit=1) if first_record := result.first: - return cls.process_redis_object(first_record) + return cls.convert_redis_object_to_token(first_record) elif user_uu_id: result = RedisActions.get_json(list_keys=auth_key_list) if all_records := result.all: for all_record in all_records: - list_of_token_dict.append(cls.process_redis_object(all_record)) + list_of_token_dict.append( + cls.convert_redis_object_to_token(all_record) + ) return list_of_token_dict raise ValueError( "Token not found in Redis. Please check the token or user_uu_id." @@ -181,6 +181,8 @@ class TokenProvider: elif isinstance(tokens, list): retrieved_event_apps = [] for token in tokens: + if not isinstance(token, TokenDictType): + continue if application_codes := token.reachable_app_codes.get(page_url, None): retrieved_event_apps.append(application_codes) return retrieved_event_apps @@ -196,10 +198,9 @@ class TokenProvider: elif isinstance(tokens, List): retrieved_event_codes = [] for token in tokens: - if isinstance(token, TokenDictType): - if event_codes := token.reachable_event_codes.get( - endpoint_code, None - ): - retrieved_event_codes.append(event_codes) + if not isinstance(token, TokenDictType): + continue + if event_codes := token.reachable_event_codes.get(endpoint_code, None): + retrieved_event_codes.append(event_codes) return retrieved_event_codes raise ValueError("Invalid token type or no event codes found.") diff --git a/WebServices/client-frontend/src/apicalls/api-fetcher.tsx b/WebServices/client-frontend/src/apicalls/api-fetcher.tsx index b65e888..c31b0c3 100644 --- a/WebServices/client-frontend/src/apicalls/api-fetcher.tsx +++ b/WebServices/client-frontend/src/apicalls/api-fetcher.tsx @@ -1,5 +1,5 @@ "use server"; -// import { retrieveAccessToken } from "@/apicalls/cookies/token"; +import { retrieveAccessToken } from "@/apicalls/cookies/token"; const defaultHeaders = { accept: "application/json", @@ -48,7 +48,7 @@ const fetchData = async ( cache: cache ? "force-cache" : "no-cache", }; - if (method !== "GET" && payload) { + if (method === "POST" && payload) { fetchOptions.body = JSON.stringify(payload); } @@ -73,10 +73,10 @@ const updateDataWithToken = async ( method: string = "POST", cache: boolean = false ) => { - // const accessToken = (await retrieveAccessToken()) || ""; + const accessToken = (await retrieveAccessToken()) || ""; const headers = { ...defaultHeaders, - // "evyos-session-key": accessToken, + "eys-acs-tkn": accessToken, }; try { @@ -110,10 +110,10 @@ const fetchDataWithToken = async ( method: string = "POST", cache: boolean = false ) => { - // const accessToken = (await retrieveAccessToken()) || ""; + const accessToken = (await retrieveAccessToken()) || ""; const headers = { ...defaultHeaders, - // "evyos-session-key": accessToken, + "eys-acs-tkn": accessToken, }; try { @@ -123,7 +123,7 @@ const fetchDataWithToken = async ( cache: cache ? "force-cache" : "no-cache", }; - if (method !== "GET" && payload) { + if (method === "POST" && payload) { fetchOptions.body = JSON.stringify(payload); } diff --git a/WebServices/client-frontend/src/apicalls/cookies/token.tsx b/WebServices/client-frontend/src/apicalls/cookies/token.tsx new file mode 100644 index 0000000..e4dc29e --- /dev/null +++ b/WebServices/client-frontend/src/apicalls/cookies/token.tsx @@ -0,0 +1,116 @@ +"use server"; +import { fetchDataWithToken, fetchData } from "../api-fetcher"; +import { baseUrlAuth, tokenSecret } from "../basics"; +import { cookies } from "next/headers"; +import NextCrypto from "next-crypto"; +import { console } from "inspector"; + +const checkToken = `${baseUrlAuth}/authentication/token/check`; +const nextCrypto = new NextCrypto(tokenSecret); + +async function checkAccessTokenIsValid() { + const response = await fetchDataWithToken(checkToken, {}, "GET", false); + return response?.status === 200 || response?.status === 202 ? true : false; +} + +async function retrieveAccessToken() { + const cookieStore = await cookies(); + const encrpytAccessToken = cookieStore.get("accessToken")?.value || ""; + return encrpytAccessToken + ? await nextCrypto.decrypt(encrpytAccessToken) + : null; +} + +async function retrieveUserType() { + const cookieStore = await cookies(); + const encrpytaccessObject = cookieStore.get("accessObject")?.value || "{}"; + const decrpytUserType = JSON.parse( + (await nextCrypto.decrypt(encrpytaccessObject)) || "{}" + ); + return decrpytUserType ? decrpytUserType : null; +} + +async function retrieveAccessObjects() { + const cookieStore = await cookies(); + const encrpytAccessObject = cookieStore.get("accessObject")?.value || ""; + const decrpytAccessObject = await nextCrypto.decrypt(encrpytAccessObject); + return decrpytAccessObject ? JSON.parse(decrpytAccessObject) : null; +} + +async function retrieveUserSelection() { + const cookieStore = await cookies(); + const encrpytUserSelection = cookieStore.get("userSelection")?.value || ""; + let decrpytUserSelection: any = await nextCrypto.decrypt( + encrpytUserSelection + ); + decrpytUserSelection = decrpytUserSelection + ? JSON.parse(decrpytUserSelection) + : null; + + const userSelection = decrpytUserSelection?.company_uu_id; + + let objectUserSelection = {}; + + if (decrpytUserSelection?.user_type === "employee") { + const accessObjects = (await retrieveAccessObjects()) || {}; + const companyList = accessObjects?.companies_list; + const selectedCompany = companyList.find( + (company: any) => company.uu_id === userSelection + ); + if (selectedCompany) { + objectUserSelection = { + occupantName: `${selectedCompany?.public_name}`, + }; + } + } else if (decrpytUserSelection?.user_type === "occupant") { + const buildPartUUID = userSelection?.build_part_uu_id; + const occupantUUID = userSelection?.occupant_uu_id; + const build_id = userSelection?.build_id; + const accessObjects = (await retrieveAccessObjects()) || {}; + const availableOccupants = accessObjects?.available_occupants[build_id]; + const buildName = availableOccupants?.build_name; + const buildNo = availableOccupants?.build_no; + let selectedOccupant: any = null; + const occupants = availableOccupants?.occupants; + if (occupants) { + selectedOccupant = occupants.find( + (occupant: any) => + occupant.part_uu_id === buildPartUUID && + occupant.uu_id === occupantUUID + ); + } + if (selectedOccupant) { + objectUserSelection = { + buildName: `${buildName} - No:${buildNo}`, + occupantName: `${selectedOccupant?.description} ${selectedOccupant?.part_name}`, + }; + } + } + return { + ...objectUserSelection, + }; +} + +// const avatarInfo = await retrieveAvatarInfo(); +// lang: avatarInfo?.data?.lang +// ? String(avatarInfo?.data?.lang).toLowerCase() +// : undefined, +// avatar: avatarInfo?.data?.avatar, +// fullName: avatarInfo?.data?.full_name, +// async function retrieveAvatarInfo() { +// const response = await fetchDataWithToken( +// `${baseUrlAuth}/authentication/avatar`, +// {}, +// "POST" +// ); +// return response; +// } + +export { + checkAccessTokenIsValid, + retrieveAccessToken, + retrieveUserType, + retrieveAccessObjects, + retrieveUserSelection, + // retrieveavailablePages, +}; diff --git a/WebServices/client-frontend/src/apicalls/login/login.tsx b/WebServices/client-frontend/src/apicalls/login/login.tsx index 2e6018a..8a889c1 100644 --- a/WebServices/client-frontend/src/apicalls/login/login.tsx +++ b/WebServices/client-frontend/src/apicalls/login/login.tsx @@ -49,7 +49,10 @@ async function loginViaAccessKeys(payload: LoginViaAccessKeys) { const loginRespone = response?.data; const accessToken = await nextCrypto.encrypt(loginRespone.access_token); const accessObject = await nextCrypto.encrypt( - JSON.stringify(loginRespone.selection_list) + JSON.stringify({ + userType: loginRespone.user_type, + selectionList:loginRespone.selection_list + }) ); const userProfile = await nextCrypto.encrypt( JSON.stringify(loginRespone.user) @@ -60,6 +63,7 @@ async function loginViaAccessKeys(payload: LoginViaAccessKeys) { value: accessToken, ...cookieObject, }); + console.log("accessObject", accessObject); cookieStore.set({ name: "accessObject", diff --git a/WebServices/client-frontend/src/app/(AuthLayout)/auth/select/page.tsx b/WebServices/client-frontend/src/app/(AuthLayout)/auth/select/page.tsx index abe1a7d..34c6dd2 100644 --- a/WebServices/client-frontend/src/app/(AuthLayout)/auth/select/page.tsx +++ b/WebServices/client-frontend/src/app/(AuthLayout)/auth/select/page.tsx @@ -1,7 +1,48 @@ import React from "react"; +import { + checkAccessTokenIsValid, + retrieveUserType, +} from "@/apicalls/cookies/token"; +import { redirect } from "next/navigation"; +import SelectList from "@/components/auth/select"; -function SelectPage() { - return