updated web select

This commit is contained in:
berkay 2025-04-06 21:52:04 +03:00
parent eef5982e03
commit e4d50306ac
9 changed files with 266 additions and 26 deletions

View File

@ -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,
)

View File

@ -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:

View File

@ -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.")

View File

@ -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);
}

View File

@ -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,
};

View File

@ -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",

View File

@ -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 <div>SelectPage</div>;
async function SelectPage() {
const token_is_valid = await checkAccessTokenIsValid();
const selection = await retrieveUserType();
const isEmployee = selection?.userType == "employee";
const isOccupant = selection?.userType == "occupant";
const selectionList = selection?.selectionList;
if (!selectionList || !token_is_valid) {
redirect("/login/email");
}
return (
<>
<div className="flex flex-col items-center justify-center h-screen">
<div className="text-2xl font-bold">Select your company</div>
<div className="flex flex-col items-center justify-center">
{isEmployee && (
<div className="text-sm text-gray-500 mt-4">
You are logged in as an employee
</div>
)}
{isOccupant && (
<div className="text-sm text-gray-500 mt-4">
You are logged in as an occupant
</div>
)}
<SelectList
isEmployee={isEmployee}
isOccupant={isOccupant}
selectionList={selectionList}
/>
</div>
<div className="text-sm text-gray-500 mt-4"></div>
</div>
</>
);
}
export default SelectPage;

View File

@ -9,9 +9,14 @@ import { z } from "zod";
const loginSchema = z.object({
email: z.string().email("Invalid email address"),
password: z.string().min(5, "Password must be at least 5 characters"),
remember_me: z.boolean().optional().default(false),
});
type LoginFormData = z.infer<typeof loginSchema>;
type LoginFormData = {
email: string;
password: string;
remember_me?: boolean;
};
function Login() {
// Open transition for form login

View File

@ -0,0 +1,60 @@
"use client";
import React from "react";
function SelectList({
selectionList,
isEmployee,
isOccupant,
}: {
selectionList: {
uu_id: string;
public_name: string;
company_type: string;
company_address: string;
}[];
isEmployee: boolean;
isOccupant: boolean;
}) {
const handleClick = (uu_id: string) => {
if (isEmployee) {
console.log("Selected isEmployee uu_id:", uu_id);
} else if (isOccupant) {
console.log("Selected isOccupant uu_id:", uu_id);
}
};
return (
<>
{selectionList.map((item: any, index: number) => (
<div
key={index}
className="w-full p-4 m-2 bg-emerald-300 hover:bg-emerald-500 rounded-lg transition-colors duration-200 cursor-pointer"
onClick={() => handleClick(item.uu_id)}
>
<div className="flex flex-col items-center md:items-start">
<div>
<span className="text-2xl font-medium">{item.public_name}</span>
{""}
<span className="font-medium text-sky-500">
{item.company_type}
</span>
</div>
<div>
<span className="flex gap-2 font-medium text-gray-600 dark:text-gray-400">
<span>{item.uu_id}</span>
</span>
</div>
<div>
<span className="flex gap-2 font-medium text-gray-600 dark:text-gray-400">
<span>{item.company_address}</span>
</span>
</div>
</div>
</div>
))}
</>
);
}
export default SelectList;