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

feat: new auth manager uncomplicated #558

Merged
merged 4 commits into from
Oct 15, 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
11 changes: 5 additions & 6 deletions apps/router/src/api/GatewayApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ import {
} from '@fedimint/types';
import { GatewayConfig } from '../types/gateway';

export const SESSION_STORAGE_KEY = 'gateway-ui-key';

// GatewayApi is an implementation of the ApiInterface
export class GatewayApi {
private baseUrl: string;
private id: string;

constructor(config: GatewayConfig) {
this.baseUrl = config.baseUrl;
this.id = config.id;
}

// Tests a provided password or the one in session storage
Expand All @@ -35,7 +35,7 @@ export class GatewayApi {
}

// Replace with temp password to check.
sessionStorage.setItem(SESSION_STORAGE_KEY, tempPassword);
sessionStorage.setItem(this.id, tempPassword);

try {
await this.fetchInfo();
Expand All @@ -49,11 +49,11 @@ export class GatewayApi {
};

private getPassword = (): string | null => {
return sessionStorage.getItem(SESSION_STORAGE_KEY);
return sessionStorage.getItem(this.id) || null;
};

clearPassword = () => {
sessionStorage.removeItem(SESSION_STORAGE_KEY);
sessionStorage.removeItem(this.id);
};

private post = async (api: string, body: unknown): Promise<Response> => {
Expand Down Expand Up @@ -406,7 +406,6 @@ export class GatewayApi {

if (res.ok) {
const result = await res.json();
console.log('sendPaymentV2 result:', result);
return Promise.resolve(result);
}

Expand Down
31 changes: 17 additions & 14 deletions apps/router/src/api/GuardianApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,14 @@ import {
SharedRpc,
} from '../types/guardian';

export const SESSION_STORAGE_KEY = 'guardian-ui-key';

export class GuardianApi {
private websocket: JsonRpcWebsocket | null = null;
private connectPromise: Promise<JsonRpcWebsocket> | null = null;
private guardianConfig: GuardianConfig;

constructor(private guardianConfig: GuardianConfig) {}
constructor(guardianConfig: GuardianConfig) {
this.guardianConfig = guardianConfig;
}

/*** WebSocket methods ***/

Expand Down Expand Up @@ -82,13 +83,8 @@ export class GuardianApi {
return true;
};

public getPassword = (): string | null => {
return sessionStorage.getItem(SESSION_STORAGE_KEY);
};

public testPassword = async (password: string): Promise<boolean> => {
// Replace with password to check.
sessionStorage.setItem(SESSION_STORAGE_KEY, password);
this.setSessionPassword(password);

// Attempt a 'status' rpc call with the temporary password.
try {
Expand All @@ -102,7 +98,7 @@ export class GuardianApi {
};

private clearPassword = () => {
sessionStorage.removeItem(SESSION_STORAGE_KEY);
sessionStorage.removeItem(this.guardianConfig.id);
};

/*** Shared RPC methods */
Expand All @@ -118,10 +114,16 @@ export class GuardianApi {

/*** Setup RPC methods ***/

public setPassword = async (password: string): Promise<void> => {
// Save password to session storage so that it's included in the r[c] call
sessionStorage.setItem(SESSION_STORAGE_KEY, password);
public getPassword = (): string | null => {
return sessionStorage.getItem(this.guardianConfig.id) || null;
};

public setSessionPassword = (password: string): void => {
sessionStorage.setItem(this.guardianConfig.id, password);
};

public setPassword = async (password: string): Promise<void> => {
this.setSessionPassword(password);
try {
await this.call(SetupRpc.setPassword);
} catch (err) {
Expand Down Expand Up @@ -297,14 +299,15 @@ export class GuardianApi {
params: unknown = null
): Promise<T> => {
try {
const password = this.getPassword();
if (!this.guardianConfig?.baseUrl) {
throw new Error('guardian baseUrl not found in config');
}
const websocket = await this.connect();
// console.log('method', method);
const response = await websocket.call(method, [
{
auth: this.getPassword() || null,
auth: password || null,
params,
},
]);
Expand Down
111 changes: 0 additions & 111 deletions apps/router/src/api/ServiceCheckApi.ts

This file was deleted.

10 changes: 5 additions & 5 deletions apps/router/src/context/AppContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -185,16 +185,17 @@ export const AppContextProvider: React.FC<AppContextProviderProps> = ({
service.baseUrl.startsWith('http');
const addService = async (service: Service) => {
const id = await sha256Hash(service.baseUrl);
const newService = { ...service, id };

if (isGuardian(service)) {
if (isGuardian(newService)) {
dispatch({
type: APP_ACTION_TYPE.ADD_GUARDIAN,
payload: { id, guardian: { config: service as GuardianConfig } },
payload: { id, guardian: { config: newService as GuardianConfig } },
});
} else if (isGateway(service)) {
} else if (isGateway(newService)) {
dispatch({
type: APP_ACTION_TYPE.ADD_GATEWAY,
payload: { id, gateway: { config: service as GatewayConfig } },
payload: { id, gateway: { config: newService as GatewayConfig } },
});
} else {
throw new Error(`Invalid service baseUrl in config.json: ${service}`);
Expand Down Expand Up @@ -225,7 +226,6 @@ export const AppContextProvider: React.FC<AppContextProviderProps> = ({
handleConfig(data);
} catch (error) {
console.error('Error parsing config JSON:', error);
console.log('Raw config content:', text);
}
})
.catch((error) => {
Expand Down
4 changes: 2 additions & 2 deletions apps/router/src/context/guardian/SetupContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { randomNames } from '../../guardian-ui/setup/randomNames';
import {
FollowerConfigs,
HostConfigs,
useGuardianApi,
useGuardianContext,
useHandleBackgroundGuardianSetupActions,
useHandleSetupServerStatus,
useUpdateLocalStorageOnSetupStateChange,
Expand Down Expand Up @@ -123,7 +123,7 @@ export const SetupContextProvider: React.FC<SetupContextProviderProps> = ({
initServerStatus,
children,
}: SetupContextProviderProps) => {
const api = useGuardianApi();
const { api } = useGuardianContext();
const [state, dispatch] = useReducer(reducer, {
...initialState,
password: api.getPassword() || initialState.password,
Kodylow marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
24 changes: 11 additions & 13 deletions apps/router/src/context/hooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,21 +81,19 @@ export const useGuardianDispatch = (): Dispatch<GuardianAppAction> => {
};

export const useLoadGuardian = (): void => {
const guardianApi = useGuardianApi();
const guardianState = useGuardianState();
const dispatch = useGuardianDispatch();
const { api, state, id, dispatch } = useGuardianContext();
useEffect(() => {
const load = async () => {
try {
await guardianApi.connect();
const server = (await guardianApi.status()).server;
await api.connect();
const server = (await api.status()).server;

// If they're at a point where a password has been configured, make
// sure they have a valid password set. If not, set needsAuth.
if (server !== GuardianServerStatus.AwaitingPassword) {
const password = guardianApi.getPassword();
const password = api.getPassword();
const hasValidPassword = password
? await guardianApi.testPassword(password)
? await api.testPassword(password)
: false;
if (!hasValidPassword) {
dispatch({
Expand Down Expand Up @@ -129,10 +127,10 @@ export const useLoadGuardian = (): void => {
}
};

if (guardianState.status === GuardianStatus.Loading) {
if (state.status === GuardianStatus.Loading) {
load().catch((err) => console.error(err));
}
}, [guardianState.status, guardianApi, dispatch]);
}, [state.status, api, dispatch, id]);
};

export const useGuardianContext = (): GuardianContextValue => {
Expand Down Expand Up @@ -441,10 +439,10 @@ export const useGatewayInfo = (): GatewayInfo => {
};

export const useLoadGateway = () => {
const state = useGatewayState();
const dispatch = useGatewayDispatch();

const api = useGatewayApi();
const { state, dispatch, api, id } = useGatewayContext();
if (sessionStorage.getItem(id)) {
state.needsAuth = false;
}

useEffect(() => {
if (!state.needsAuth) {
Expand Down
3 changes: 2 additions & 1 deletion apps/router/src/gateway-ui/Gateway.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { Login } from '@fedimint/ui';
import { GATEWAY_APP_ACTION_TYPE } from '../types/gateway';

export const Gateway = () => {
const { state, dispatch, api } = useGatewayContext();
const { state, dispatch, api, id } = useGatewayContext();
const [showConnectFed, setShowConnectFed] = useState(false);
const [walletModalState, setWalletModalState] = useState<WalletModalState>({
isOpen: false,
Expand All @@ -30,6 +30,7 @@ export const Gateway = () => {
if (state.needsAuth) {
return (
<Login
serviceId={id}
checkAuth={api.testPassword}
setAuthenticated={() =>
dispatch({
Expand Down
4 changes: 3 additions & 1 deletion apps/router/src/guardian-ui/Guardian.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { GUARDIAN_APP_ACTION_TYPE, GuardianStatus } from '../types/guardian';
import { formatApiErrorMessage } from './utils/api';

export const Guardian: React.FC = () => {
const { api, state, dispatch } = useGuardianContext();
const { api, state, dispatch, id } = useGuardianContext();
useLoadGuardian();
const { t } = useTranslation();

Expand All @@ -37,6 +37,7 @@ export const Guardian: React.FC = () => {
if (state.needsAuth) {
return (
<Login
serviceId={id}
checkAuth={(password) => api.testPassword(password || '')}
setAuthenticated={() =>
dispatch({
Expand Down Expand Up @@ -78,6 +79,7 @@ export const Guardian: React.FC = () => {
api,
dispatch,
t,
id,
]);

return (
Expand Down
Loading
Loading