Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(ACC-584): ensure session continuity #715

Merged
merged 2 commits into from
Aug 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Dockerfile.saas
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM node:20-alpine3.20 as build
FROM node:20-alpine3.20 AS build

# LABELS
LABEL \
Expand Down
2 changes: 1 addition & 1 deletion Dockerfile.standalone
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM node:20-alpine3.20 as build
FROM node:20-alpine3.20 AS build

# LABELS
LABEL \
Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@
"vite": "^5.3.5",
"vitest": "^2.0.5"
},
"overrides": {
"rollup": "npm:@rollup/wasm-node"
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": "eslint --cache --fix"
}
Expand Down
22 changes: 12 additions & 10 deletions src/pages/auth/LoginPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,13 @@ import { Alert, Button, Checkbox, Col, Divider, Form, Image, Input, Layout, noti
import { useState, useCallback, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { AMUI_URL, isSaasBuild } from '../../services/BaseService';
import {
AMUI_URL,
NMUI_ACCESS_TOKEN_LOCALSTORAGE_KEY,
NMUI_USERNAME_LOCALSTORAGE_KEY,
NMUI_USER_LOCALSTORAGE_KEY,
isSaasBuild,
} from '../../services/BaseService';
import { extractErrorMsg } from '@/utils/ServiceUtils';
import { UsersService } from '@/services/UsersService';
import { User, UserRole } from '@/models/User';
Expand Down Expand Up @@ -57,26 +63,22 @@ export default function LoginPage(props: LoginPageProps) {
setIsUserDeniedFromDashboard(true);
return;
}
store.setStore({ user, userPlatformRole });

store.setStore({ user });
window?.localStorage?.setItem(NMUI_USER_LOCALSTORAGE_KEY, JSON.stringify(user));
} catch (err) {
notify.error({ message: 'Failed to get user details', description: extractErrorMsg(err as any) });
}
};

// const checkLoginErrorMessage = (err: string) => {
// if (err.toLowerCase() === USER_ERROR_MESSAGE.toLowerCase()) {
// setIsUserLoggingIn(true);
// return;
// }
// setIsUserLoggingIn(false);
// };

const onLogin = async () => {
try {
const formData = await form.validateFields();
setIsBasicAuthLoading(true);
const data = await (await AuthService.login(formData)).data;
store.setStore({ jwt: data.Response.AuthToken, username: data.Response.UserName });
window?.localStorage?.setItem(NMUI_ACCESS_TOKEN_LOCALSTORAGE_KEY, data.Response.AuthToken);
window?.localStorage?.setItem(NMUI_USERNAME_LOCALSTORAGE_KEY, data.Response.UserName);
await storeFetchServerConfig();
await getUserAndUpdateInStore(data.Response.UserName);
} catch (err) {
Expand Down
53 changes: 41 additions & 12 deletions src/services/BaseService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,24 @@ export const AMUI_URL = isSaasBuild ? (window as any).NMUI_AMUI_URL : '';

export const INTERCOM_APP_ID = isSaasBuild ? (window as any).NMUI_INTERCOM_APP_ID : '';

export const NMUI_ACCESS_TOKEN_LOCALSTORAGE_KEY = 'nmui-at-lsk';
export const NMUI_USERNAME_LOCALSTORAGE_KEY = 'nmui-un-lsk';
export const NMUI_BASE_URL_LOCALSTORAGE_KEY = 'nmui-burl-lsk';
export const NMUI_TENANT_ID_LOCALSTORAGE_KEY = 'nmui-tid-lsk';
export const NMUI_TENANT_NAME_LOCALSTORAGE_KEY = 'nmui-tn-lsk';
export const NMUI_AMUI_USER_ID_LOCALSTORAGE_KEY = 'nmui-amuiuid-lsk';
export const NMUI_USER_LOCALSTORAGE_KEY = 'nmui-u-lsk';

// function to resolve the particular SaaS tenant's backend URL, ...
export async function setupTenantConfig(): Promise<void> {
if (!isSaasBuild) {
const dynamicBaseUrl = (window as any).NMUI_BACKEND_URL;
const resolvedBaseUrl = dynamicBaseUrl ? `${dynamicBaseUrl}/api` : `${import.meta.env.VITE_BASE_URL}/api`;
useStore.getState().setStore({
baseUrl: resolvedBaseUrl,
jwt: window?.localStorage?.getItem(NMUI_ACCESS_TOKEN_LOCALSTORAGE_KEY) ?? '',
username: window?.localStorage?.getItem(NMUI_USERNAME_LOCALSTORAGE_KEY) ?? '',
user: JSON.parse(window?.localStorage?.getItem(NMUI_USER_LOCALSTORAGE_KEY) ?? 'null'),
});
axiosService.defaults.baseURL = resolvedBaseUrl;
return;
Expand All @@ -35,13 +46,6 @@ export async function setupTenantConfig(): Promise<void> {
const amuiUserId = url.searchParams.get('userId') ?? '';
const isNewTenant = url.searchParams.get('isNewTenant') === 'true';

const resolvedBaseUrl = baseUrl
? baseUrl?.startsWith('https')
? `${baseUrl}/api`
: `https://${baseUrl}/api`
: useStore.getState().baseUrl;
axiosService.defaults.baseURL = resolvedBaseUrl;

truncateQueryParamsFromCurrentUrl();

// let user: User | undefined;
Expand All @@ -57,14 +61,39 @@ export async function setupTenantConfig(): Promise<void> {
// return;
// }

let resolvedBaseUrl;
if (baseUrl) {
resolvedBaseUrl = baseUrl?.startsWith('https') ? `${baseUrl}/api` : `https://${baseUrl}/api`;
window?.localStorage?.setItem(NMUI_BASE_URL_LOCALSTORAGE_KEY, resolvedBaseUrl);
} else {
resolvedBaseUrl = window?.localStorage?.getItem(NMUI_BASE_URL_LOCALSTORAGE_KEY) ?? '';
}
axiosService.defaults.baseURL = resolvedBaseUrl;

if (accessToken) {
window?.localStorage?.setItem(NMUI_ACCESS_TOKEN_LOCALSTORAGE_KEY, accessToken);
}
if (username) {
window?.localStorage?.setItem(NMUI_USERNAME_LOCALSTORAGE_KEY, username);
}
if (tenantId) {
window?.localStorage?.setItem(NMUI_TENANT_ID_LOCALSTORAGE_KEY, tenantId);
}
if (tenantName) {
window?.localStorage?.setItem(NMUI_TENANT_NAME_LOCALSTORAGE_KEY, tenantName);
}
if (amuiUserId) {
window?.localStorage?.setItem(NMUI_AMUI_USER_ID_LOCALSTORAGE_KEY, amuiUserId);
}

useStore.getState().setStore({
baseUrl: resolvedBaseUrl,
jwt: accessToken || useStore.getState().jwt,
tenantId: tenantId || useStore.getState().tenantId,
tenantName: tenantName || useStore.getState().tenantName,
jwt: accessToken || (window?.localStorage?.getItem(NMUI_ACCESS_TOKEN_LOCALSTORAGE_KEY) ?? ''),
tenantId: tenantId || (window?.localStorage?.getItem(NMUI_TENANT_ID_LOCALSTORAGE_KEY) ?? ''),
tenantName: tenantName || (window?.localStorage?.getItem(NMUI_TENANT_NAME_LOCALSTORAGE_KEY) ?? ''),
amuiAuthToken,
username: username || useStore.getState().username,
amuiUserId: amuiUserId || useStore.getState().amuiUserId,
username: username || (window?.localStorage?.getItem(NMUI_USERNAME_LOCALSTORAGE_KEY) ?? ''),
amuiUserId: amuiUserId || (window?.localStorage?.getItem(NMUI_AMUI_USER_ID_LOCALSTORAGE_KEY) ?? ''),
isNewTenant: isNewTenant,
// user,
});
Expand Down
23 changes: 21 additions & 2 deletions src/store/auth.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
import { StateCreator } from 'zustand';
import { TenantConfig } from '../models/ServerConfig';
import { User, UserRole } from '@/models/User';
import { isSaasBuild } from '@/services/BaseService';
import {
NMUI_ACCESS_TOKEN_LOCALSTORAGE_KEY,
NMUI_AMUI_USER_ID_LOCALSTORAGE_KEY,
NMUI_BASE_URL_LOCALSTORAGE_KEY,
NMUI_TENANT_ID_LOCALSTORAGE_KEY,
NMUI_TENANT_NAME_LOCALSTORAGE_KEY,
NMUI_USERNAME_LOCALSTORAGE_KEY,
NMUI_USER_LOCALSTORAGE_KEY,
isSaasBuild,
} from '@/services/BaseService';
import { isValidJwt } from '@/utils/Utils';

export interface IAuthSlice {
Expand Down Expand Up @@ -39,7 +48,10 @@ const createAuthSlice: StateCreator<IAuthSlice, [], [], IAuthSlice> = (set, get)
isLoggedIn() {
// TODO: fix username retrieval for SaaS
return (
!!get().jwt && isValidJwt(get().jwt || '') && (!isSaasBuild ? !!get().user && !!get().userPlatformRole : true)
!!get().baseUrl &&
!!get().jwt &&
isValidJwt(get().jwt || '') &&
(!isSaasBuild ? !!get().user && !!get().userPlatformRole : true)
);
},
setStore(config) {
Expand All @@ -57,6 +69,13 @@ const createAuthSlice: StateCreator<IAuthSlice, [], [], IAuthSlice> = (set, get)
user: null,
userPlatformRole: null,
});
window?.localStorage?.removeItem(NMUI_ACCESS_TOKEN_LOCALSTORAGE_KEY);
window?.localStorage?.removeItem(NMUI_USERNAME_LOCALSTORAGE_KEY);
window?.localStorage?.removeItem(NMUI_BASE_URL_LOCALSTORAGE_KEY);
window?.localStorage?.removeItem(NMUI_TENANT_ID_LOCALSTORAGE_KEY);
window?.localStorage?.removeItem(NMUI_TENANT_NAME_LOCALSTORAGE_KEY);
window?.localStorage?.removeItem(NMUI_AMUI_USER_ID_LOCALSTORAGE_KEY);
window?.localStorage?.removeItem(NMUI_USER_LOCALSTORAGE_KEY);
},
});

Expand Down
25 changes: 9 additions & 16 deletions src/store/store.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import { devtools } from 'zustand/middleware';
import { AppSlice, IAppSlice } from './app';
import { AuthSlice, IAuthSlice } from './auth';
import { HostSlice, IHostSlice } from './hosts';
Expand All @@ -10,21 +10,14 @@ import { INetworksUsecaseSlice, NetworksUsecaseSlice } from './networkusecase';
export const useStore = create<
INodeSlice & IAppSlice & INetworkSlice & IAuthSlice & IHostSlice & INetworksUsecaseSlice
>()(
devtools(
persist(
(...a) => ({
...NodeSlice.createNodeSlice(...a),
...AppSlice.createAppSlice(...a),
...AuthSlice.createAuthSlice(...a),
...NetworkSlice.createNetworkSlice(...a),
...HostSlice.createHostSlice(...a),
...NetworksUsecaseSlice.createNetworkUsecaseSlice(...a),
}),
{
name: 'netmaker-storage',
},
),
),
devtools((...a) => ({
...NodeSlice.createNodeSlice(...a),
...AppSlice.createAppSlice(...a),
...AuthSlice.createAuthSlice(...a),
...NetworkSlice.createNetworkSlice(...a),
...HostSlice.createHostSlice(...a),
...NetworksUsecaseSlice.createNetworkUsecaseSlice(...a),
})),
);

export const BrowserStore = {
Expand Down
Loading