@syzy/apphost 1.0.17 → 1.0.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/App.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  import React from 'react';
2
2
  export declare const componentMap: Record<string, React.ComponentType<any>>;
3
- declare function App({ isSessionReady }: any): import("react/jsx-runtime").JSX.Element;
4
- export default App;
3
+ declare const _default: (props: any) => import("react/jsx-runtime").JSX.Element;
4
+ export default _default;
package/dist/App.js CHANGED
@@ -1,12 +1,18 @@
1
- import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
- import React from 'react';
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ // import { configureAmplify } from "./config/amplifyConfig.ts";
3
+ import { Route, Routes } from 'react-router-dom';
4
+ import { useCurrentUser } from './hooks/useCurrentUser';
5
+ import { withSyzyAuth } from './hoc/withSyzyAuth';
6
+ import React, { useState } from 'react';
3
7
  import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
4
- import LoadingSpinner from './components/Loader/Loader';
5
- import Home from './components/Home/Home';
6
8
  import BranchMapping from './components/Mappings/BranchMapping/Branch';
7
9
  import MappingFormBranchUser from './components/Mappings/BranchMapping/MappingFormBranchUser';
8
10
  import ComponentRoleMapping from './components/Mappings/ComponentMapping/ComponentRoleMapping';
9
11
  import MappingFormUserRole from './components/Mappings/RoleMapping/MappingFormUserRole';
12
+ import Home from './components/Home/Home';
13
+ import LoadingSpinner from './components/Loader/Loader';
14
+ // import { isHostedInContainer } from "./util/hostedinContainer.ts";
15
+ // configureAmplify();
10
16
  export const componentMap = {
11
17
  BranchMapping,
12
18
  MappingFormBranchUser,
@@ -14,7 +20,43 @@ export const componentMap = {
14
20
  ComponentRoleMapping,
15
21
  Home,
16
22
  };
23
+ const flattenRoutes = (items) => {
24
+ const flat = [];
25
+ const walk = (arr) => {
26
+ arr.forEach(item => {
27
+ if (item.path && item.requiredComponent) {
28
+ flat.push(item);
29
+ }
30
+ if (item.children) {
31
+ walk(item.children);
32
+ }
33
+ });
34
+ };
35
+ walk(items);
36
+ return flat;
37
+ };
38
+ const withAccessControl = (Component, props, requiredComponent, allowedComponents) => {
39
+ // Check if the user has access
40
+ const isAllowed = !requiredComponent || (allowedComponents?.includes(requiredComponent));
41
+ if (!isAllowed) {
42
+ return () => (_jsx("div", { className: "text-center mt-5", children: _jsx("h3", { className: "text-danger", children: "You are not allowed to see this page." }) }));
43
+ }
44
+ return () => _jsx(Component, { ...props });
45
+ };
17
46
  function App({ isSessionReady }) {
18
- return (_jsxs(_Fragment, { children: [_jsx("div", { style: { display: "flex", width: "100%" }, children: _jsx("div", { style: { flex: 1, padding: "10px" }, children: !isSessionReady ? (_jsx(LoadingSpinner, {})) : (_jsx(React.Fragment, {})) }) }), _jsx(ReactQueryDevtools, { initialIsOpen: false })] }));
47
+ const { user } = useCurrentUser();
48
+ const [routes, setRoutes] = useState([]);
49
+ const flatRoutes = flattenRoutes(routes);
50
+ // useEffect(() => {
51
+ // isHostedInContainer();
52
+ // configureAmplify();
53
+ // }, []);
54
+ return (_jsxs(_Fragment, { children: [_jsx("div", { style: { display: "flex", width: "100%" }, children: _jsx("div", { style: { flex: 1, padding: "10px" }, children: !isSessionReady ? (_jsx(LoadingSpinner, {})) : (_jsx(React.Fragment, { children: _jsxs(Routes, { children: [flatRoutes.map(({ path, requiredComponent, props }) => {
55
+ const PageComponent = componentMap[requiredComponent];
56
+ if (!PageComponent)
57
+ return null;
58
+ const ProtectedComponent = withAccessControl(PageComponent, props, requiredComponent, user.allowedComponents);
59
+ return _jsx(Route, { path: path, element: _jsx(ProtectedComponent, {}) }, path);
60
+ }), _jsx(Route, { path: "*", element: _jsx("h3", { className: "text-danger", children: "Page Not Found" }) })] }) })) }) }), _jsx(ReactQueryDevtools, { initialIsOpen: false })] }));
19
61
  }
20
- export default App;
62
+ export default withSyzyAuth(App);
@@ -1,4 +1,6 @@
1
1
  import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
2
+ import { EnvConfig } from "../config/EnvConfig";
3
+ import { Client } from "../services/Client.Service";
2
4
  import { initUserMappingDto, transformtoUserMappingDto } from "../domain/model/UserMappingDto";
3
5
  import { initRoleMappingDto, transformtoRoleMappingDto } from "../domain/model/RoleMappingDto";
4
6
  import { initComponentMappingDto, transformtoComponentMappingDto } from "../domain/model/ComponentMappingDto";
@@ -9,8 +11,6 @@ import { logger } from "../util/Logger";
9
11
  import { createBranchMutationGQL, createMapping, updateMapping } from "../customGraphQL/customMutations";
10
12
  import { listBranchesQuery, ListBranchUserMappings, ListComponentRoleMappings, listMapping, ListUserRoleMapping, updateBranchMutationQuery } from "../customGraphQL/customQueries";
11
13
  import { Status } from "../domain/type/StatusEnum";
12
- import { Client } from "../services/Client.Service";
13
- import { EnvConfig } from "../config/EnvConfig";
14
14
  export const MAPPING_RESOURCE = "mapping";
15
15
  export const GET_MAPPING_BY_USERID_QUERYKEY = "mappingbyuserid";
16
16
  export const LIST_BRANCHES_RESOURCE = "branches";
@@ -1,15 +1,16 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
- import { useEffect, useMemo, useState } from "react";
2
+ import { useContext, useMemo, useState } from "react";
3
3
  import MappingForm from "../MappingForm/MappingForm";
4
4
  import FormModal from "../../common/Modal/Modal";
5
5
  import ListTable from "../../common/ListTable/ListTable";
6
6
  import { toast } from "react-toastify";
7
7
  import { MappingTypes } from "../../../domain/type/MappingTypes";
8
- import { getCompoMappingByRoleIdAndCompoIdFun, useCreateMappingMutation, useListComponentRoleMappings, useListProfiles, useUpdateMappingMutation, } from "../../../api/mapping-api";
8
+ import { getCompoMappingByRoleIdAndCompoIdFun, useCreateMappingMutation, useListComponentRoleMappings, useUpdateMappingMutation, } from "../../../api/mapping-api";
9
9
  import { EntityTypes } from "../../../domain/type/EntityTypes";
10
10
  import { Status } from "../../../domain/type/StatusEnum";
11
11
  import { SyzyDate } from "../../../util/SyzyDate";
12
12
  import { DATE_FORMAT_ISO_YYYY_MM_DD_HH_MM_SS } from "../../../util/dateUtils";
13
+ import AppContext from "../../../store/AppContext";
13
14
  import { logger } from "../../../util/Logger";
14
15
  import { componentMap } from "../../../App";
15
16
  import { roles } from "../RoleMapping/MappingFormUserRole";
@@ -18,7 +19,8 @@ import ListHeader from "../../common/ListTable/ListHeader";
18
19
  import { ToastContainer } from "react-toastify";
19
20
  /* ---------------- Component Role Mapping ---------------- */
20
21
  const ComponentRoleMappingPage = () => {
21
- const [users, setUsers] = useState([]);
22
+ const { user } = useContext(AppContext) || {};
23
+ const loggedInUserName = user?.userName;
22
24
  const [showModal, setShowModal] = useState(false);
23
25
  const [editingRow, setEditingRow] = useState();
24
26
  const currentISODate = new SyzyDate().toDateFormatString(DATE_FORMAT_ISO_YYYY_MM_DD_HH_MM_SS);
@@ -26,12 +28,6 @@ const ComponentRoleMappingPage = () => {
26
28
  const createMappingMutation = useCreateMappingMutation();
27
29
  const updateMappingMutation = useUpdateMappingMutation();
28
30
  const tableLoading = isLoading || createMappingMutation.isPending || updateMappingMutation.isPending;
29
- const { data: profiles } = useListProfiles();
30
- useEffect(() => {
31
- if (profiles) {
32
- setUsers(profiles.map((p) => ({ id: p.sk, name: p.name })));
33
- }
34
- }, [profiles]);
35
31
  /* ---------------- Component Options ---------------- */
36
32
  const components = useMemo(() => Object.keys(componentMap).map((key, index) => ({
37
33
  id: `Component#${String(index + 1).padStart(2, "0")}`,
@@ -50,10 +46,9 @@ const ComponentRoleMappingPage = () => {
50
46
  const handleSubmit = async (mappings) => {
51
47
  try {
52
48
  for (const map of mappings) {
53
- const user = users.find(u => u.id === map.sourceId);
54
49
  const role = roles.find(r => r.id === map.targetId);
55
50
  const component = components.find(c => c.id === map.sourceId);
56
- if (!user || !role || !component)
51
+ if (!role || !component || !loggedInUserName)
57
52
  continue;
58
53
  const payload = {
59
54
  pk: role.id,
@@ -67,7 +62,7 @@ const ComponentRoleMappingPage = () => {
67
62
  componentTitle: component.name,
68
63
  status: map.status,
69
64
  createdDt: editingRow?.createdDt || currentISODate,
70
- createdBy: `${user.id}#${user.name}`,
65
+ createdBy: loggedInUserName,
71
66
  disabledDt: map.status === Status.Inactive ? currentISODate : "",
72
67
  };
73
68
  const existing = await getCompoMappingByRoleIdAndCompoIdFun(payload.pk, payload.sk);
@@ -0,0 +1 @@
1
+ export declare function withSyzyAuth<P extends object>(WrappedComponent: React.ComponentType<P>): (props: P) => import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,86 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { useContext, useEffect, useState } from "react";
3
+ import AppContext from "../store/AppContext";
4
+ import LoginForm from "../components/Login/Login";
5
+ import { getCurrentUser } from "aws-amplify/auth";
6
+ import { AppActionEnum } from "../store/AppAction";
7
+ import { Client } from "../services/Client.Service";
8
+ import { fetchAuthSession } from 'aws-amplify/auth';
9
+ import { getComponentsByRoleOnly, getRolesMappingByUserIdAndEntityFun, useGetUserMappingByUserId } from "../api/mapping-api";
10
+ import { EntityTypes } from "../domain/type/EntityTypes";
11
+ import { Status } from "../domain/type/StatusEnum";
12
+ export function withSyzyAuth(WrappedComponent) {
13
+ const ComponentWithAuthenticator = (props) => {
14
+ const [currentUser, setCurrentUser] = useState();
15
+ const { user, dispatch } = useContext(AppContext) || { user: undefined, allowedComponents: undefined, dispatch: undefined };
16
+ const [_isLoggedIn, setIsLoggedIn] = useState(false);
17
+ const [_emailVerifiedStatus, setEmailVerifiedStatus] = useState("");
18
+ const [isSessionReady, setIsSessionReady] = useState(false);
19
+ useEffect(() => {
20
+ if (!user?.userName) {
21
+ setCurrentUser(null);
22
+ setIsSessionReady(false);
23
+ }
24
+ }, [user]);
25
+ const fetchSession = async () => {
26
+ try {
27
+ const session = await getCurrentUser();
28
+ const userInfo = await fetchAuthSession({ forceRefresh: true });
29
+ setEmailVerifiedStatus(userInfo.tokens?.idToken?.payload.email_verified?.toString() ?? "");
30
+ if (session) {
31
+ const userId = session.signInDetails?.loginId ?? session.username;
32
+ setCurrentUser(userId);
33
+ }
34
+ else {
35
+ setCurrentUser(null);
36
+ }
37
+ }
38
+ catch (err) {
39
+ setCurrentUser(null);
40
+ }
41
+ };
42
+ useEffect(() => {
43
+ fetchSession();
44
+ }, []);
45
+ useEffect(() => {
46
+ const stopResetScheduler = Client.startClientResetScheduler();
47
+ return () => stopResetScheduler();
48
+ }, []);
49
+ useEffect(() => {
50
+ setIsLoggedIn(!!user?.userName);
51
+ }, [user]);
52
+ const { userMappingByUserId } = useGetUserMappingByUserId(currentUser ?? "");
53
+ useEffect(() => {
54
+ const updateSession = async () => {
55
+ if (!currentUser)
56
+ return;
57
+ const branchId = userMappingByUserId?.pk ?? "";
58
+ // Fetch roles of this user
59
+ const roleData = await getRolesMappingByUserIdAndEntityFun(branchId, currentUser, EntityTypes.ROLE);
60
+ const activeRoles = roleData.filter(r => r.status === Status.Active);
61
+ const roleNames = activeRoles.map(r => r.roleName);
62
+ // Fetch components for each active role
63
+ const compData = await Promise.all(activeRoles.map(role => getComponentsByRoleOnly(role.roleId)));
64
+ const allowedComponents = compData.flat().map(c => c.componentTitle);
65
+ // Build and dispatch user session
66
+ const userSession = {
67
+ userName: currentUser,
68
+ branchId,
69
+ roles: roleNames,
70
+ allowedComponents: [...new Set(allowedComponents)],
71
+ };
72
+ dispatch?.({ session: userSession, type: AppActionEnum.SignIn });
73
+ setIsSessionReady(true);
74
+ };
75
+ updateSession();
76
+ }, [currentUser, userMappingByUserId]);
77
+ // Login handler
78
+ const login = (loggedIn) => {
79
+ setIsLoggedIn(loggedIn);
80
+ if (loggedIn)
81
+ fetchSession();
82
+ };
83
+ return (_jsx("div", { children: currentUser === null ? _jsx(LoginForm, { login: login }) : _jsx(WrappedComponent, { ...props, isSessionReady: isSessionReady }) }));
84
+ };
85
+ return ComponentWithAuthenticator;
86
+ }
@@ -0,0 +1,3 @@
1
+ export declare const useCurrentUser: () => {
2
+ user: import("../store/AppContextType").AppSession;
3
+ };
@@ -0,0 +1,6 @@
1
+ import { useContext } from "react";
2
+ import AppContext from "../store/AppContext";
3
+ export const useCurrentUser = () => {
4
+ const { user } = useContext(AppContext);
5
+ return { user };
6
+ };
@@ -0,0 +1,3 @@
1
+ export declare const useDispatch: () => {
2
+ dispatch: import("react").Dispatch<import("../store/AppAction").AppAction> | undefined;
3
+ };
@@ -0,0 +1,7 @@
1
+ import { useContext } from "react";
2
+ import AppContext from "../store/AppContext";
3
+ import { defaultSession } from "../store/AppContextType";
4
+ export const useDispatch = () => {
5
+ const { dispatch } = useContext(AppContext) || { user: defaultSession };
6
+ return { dispatch };
7
+ };
@@ -0,0 +1 @@
1
+ export declare function AmIPermitted(componentName: string): boolean;
@@ -0,0 +1,7 @@
1
+ // hooks/usePermissions.ts
2
+ import { useContext } from "react";
3
+ import AppContext from "../store/AppContext";
4
+ export function AmIPermitted(componentName) {
5
+ const { user } = useContext(AppContext) || {};
6
+ return user?.allowedComponents?.includes(componentName) ?? false;
7
+ }
@@ -0,0 +1,11 @@
1
+ import { AppSession } from "./AppContextType";
2
+ export declare enum AppActionEnum {
3
+ SignIn = "SIGNIN",
4
+ SignOut = "SIGNOUT"
5
+ }
6
+ export type AppAction = {
7
+ type: AppActionEnum.SignIn;
8
+ session: AppSession;
9
+ } | {
10
+ type: AppActionEnum.SignOut;
11
+ };
@@ -0,0 +1,5 @@
1
+ export var AppActionEnum;
2
+ (function (AppActionEnum) {
3
+ AppActionEnum["SignIn"] = "SIGNIN";
4
+ AppActionEnum["SignOut"] = "SIGNOUT";
5
+ })(AppActionEnum || (AppActionEnum = {}));
@@ -0,0 +1,3 @@
1
+ import { AppContextProps } from './AppContextType';
2
+ declare const AppContext: import("react").Context<AppContextProps | undefined>;
3
+ export default AppContext;
@@ -0,0 +1,3 @@
1
+ import { createContext } from 'react';
2
+ const AppContext = createContext(undefined);
3
+ export default AppContext;
@@ -0,0 +1,12 @@
1
+ import { AppAction } from "./AppAction";
2
+ export interface AppSession {
3
+ userName: string;
4
+ branchId?: string;
5
+ roles: string[];
6
+ allowedComponents?: string[];
7
+ }
8
+ export declare const defaultSession: AppSession;
9
+ export interface AppContextProps {
10
+ user: AppSession;
11
+ dispatch: React.Dispatch<AppAction>;
12
+ }
@@ -0,0 +1,6 @@
1
+ export const defaultSession = {
2
+ userName: '',
3
+ branchId: undefined,
4
+ roles: [],
5
+ allowedComponents: [],
6
+ };
@@ -0,0 +1,7 @@
1
+ import React, { ReactNode } from "react";
2
+ import 'react-toastify/dist/ReactToastify.css';
3
+ interface AppProviderProps {
4
+ children: ReactNode;
5
+ }
6
+ declare const AppProvider: React.FC<AppProviderProps>;
7
+ export default AppProvider;
@@ -0,0 +1,32 @@
1
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { defaultSession } from "./AppContextType";
3
+ import AppContext from "./AppContext";
4
+ import { ToastContainer } from 'react-toastify';
5
+ import 'react-toastify/dist/ReactToastify.css';
6
+ import { AppActionEnum } from "./AppAction";
7
+ import { sessionStorage } from "aws-amplify/utils";
8
+ import { APPHOSTSESSION_KEY, useSessionReducer } from "./SesssionReducer";
9
+ import { logger } from "../util/Logger";
10
+ const appContextReducer = (state, action) => {
11
+ logger.debug("Action:", action);
12
+ let newState = state;
13
+ switch (action.type) {
14
+ case AppActionEnum.SignIn:
15
+ newState = {
16
+ ...action.session,
17
+ };
18
+ break;
19
+ case AppActionEnum.SignOut:
20
+ newState = { ...defaultSession };
21
+ sessionStorage.clear();
22
+ break;
23
+ default:
24
+ newState = state;
25
+ }
26
+ return newState;
27
+ };
28
+ const AppProvider = ({ children }) => {
29
+ const [state, dispatch] = useSessionReducer(appContextReducer, defaultSession, APPHOSTSESSION_KEY);
30
+ return (_jsxs(_Fragment, { children: [_jsx(ToastContainer, { position: "top-right", autoClose: 5000 }), _jsx(AppContext.Provider, { value: { user: state, dispatch }, children: children })] }));
31
+ };
32
+ export default AppProvider;
@@ -0,0 +1,5 @@
1
+ import React from 'react';
2
+ export declare const HostedInContainerProvider: React.FC<{
3
+ children: React.ReactNode;
4
+ }>;
5
+ export declare const useHostedInContainer: () => boolean;
@@ -0,0 +1,11 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { createContext, useContext } from 'react';
3
+ const HostedInContainerContext = createContext(false);
4
+ export const HostedInContainerProvider = ({ children }) => {
5
+ const isHosted = (() => {
6
+ const urlParams = new URLSearchParams(window.location.search);
7
+ return urlParams.get('hosted_in_container') === 'true';
8
+ })();
9
+ return (_jsx(HostedInContainerContext.Provider, { value: isHosted, children: children }));
10
+ };
11
+ export const useHostedInContainer = () => useContext(HostedInContainerContext);
@@ -0,0 +1,4 @@
1
+ import { Reducer, Dispatch } from 'react';
2
+ import { AppSession } from './AppContextType';
3
+ export declare const APPHOSTSESSION_KEY = "AppHostSession";
4
+ export declare const useSessionReducer: <T extends AppSession, A>(reducer: Reducer<T, A>, initialState: T, storageKey: string) => [T, Dispatch<A>];
@@ -0,0 +1,16 @@
1
+ import { useReducer, useEffect } from 'react';
2
+ export const APPHOSTSESSION_KEY = 'AppHostSession';
3
+ export const useSessionReducer = (reducer, initialState, storageKey) => {
4
+ const [state, dispatch] = useReducer(reducer, initialState, () => {
5
+ const value = localStorage.getItem(storageKey); // use storageKey here
6
+ let retState = { ...initialState };
7
+ if (value) {
8
+ retState = JSON.parse(value);
9
+ }
10
+ return retState;
11
+ });
12
+ useEffect(() => {
13
+ localStorage.setItem(storageKey, JSON.stringify(state)); // same key
14
+ }, [storageKey, state]);
15
+ return [state, dispatch];
16
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@syzy/apphost",
3
- "version": "1.0.17",
3
+ "version": "1.0.18",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "dist/index.js",