Skip to content

Commit 6f56f15

Browse files
authored
Merge pull request #1256 from jescalada/convert-remaining-js-files-to-ts
refactor: convert remaining UI files to TS
2 parents ae97d83 + 8c68e8c commit 6f56f15

File tree

12 files changed

+343
-323
lines changed

12 files changed

+343
-323
lines changed

src/ui/auth/AuthProvider.tsx

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,9 @@
11
import React, { createContext, useContext, useState, useEffect } from 'react';
22
import { getUserInfo } from '../services/auth';
3-
4-
// Interface for when we convert to TypeScript
5-
// interface AuthContextType {
6-
// user: any;
7-
// setUser: (user: any) => void;
8-
// refreshUser: () => Promise<void>;
9-
// isLoading: boolean;
10-
// }
3+
import { UserData } from '../../types/models';
114

125
interface AuthContextType {
13-
user: any;
6+
user: UserData | null;
147
setUser: React.Dispatch<any>;
158
refreshUser: () => Promise<void>;
169
isLoading: boolean;
@@ -19,7 +12,7 @@ interface AuthContextType {
1912
const AuthContext = createContext<AuthContextType | undefined>(undefined);
2013

2114
export const AuthProvider: React.FC<React.PropsWithChildren<object>> = ({ children }) => {
22-
const [user, setUser] = useState<any>(null);
15+
const [user, setUser] = useState<UserData | null>(null);
2316
const [isLoading, setIsLoading] = useState(true);
2417

2518
const refreshUser = async () => {

src/ui/components/RouteGuard/RouteGuard.tsx

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,15 @@
11
import React, { useEffect, useState } from 'react';
22
import { Navigate } from 'react-router-dom';
33
import { useAuth } from '../../auth/AuthProvider';
4-
import { getUIRouteAuth } from '../../services/config';
4+
import { setUIRouteAuthData } from '../../services/config';
5+
import { UIRouteAuth } from '../../../config/generated/config';
56
import CircularProgress from '@material-ui/core/CircularProgress';
67

78
interface RouteGuardProps {
89
component: React.ComponentType<any>;
910
fullRoutePath: string;
1011
}
1112

12-
interface UIRouteAuth {
13-
enabled: boolean;
14-
rules: {
15-
pattern: string;
16-
adminOnly: boolean;
17-
loginRequired: boolean;
18-
}[];
19-
}
20-
2113
const RouteGuard = ({ component: Component, fullRoutePath }: RouteGuardProps) => {
2214
const { user, isLoading } = useAuth();
2315

@@ -26,14 +18,14 @@ const RouteGuard = ({ component: Component, fullRoutePath }: RouteGuardProps) =>
2618
const [authChecked, setAuthChecked] = useState(false);
2719

2820
useEffect(() => {
29-
getUIRouteAuth((uiRouteAuth: UIRouteAuth) => {
21+
setUIRouteAuthData((uiRouteAuth: UIRouteAuth) => {
3022
if (uiRouteAuth?.enabled) {
31-
for (const rule of uiRouteAuth.rules) {
32-
if (new RegExp(rule.pattern).test(fullRoutePath)) {
23+
for (const rule of uiRouteAuth.rules ?? []) {
24+
if (new RegExp(rule.pattern ?? '').test(fullRoutePath)) {
3325
// Allow multiple rules to be applied according to route precedence
3426
// Ex: /dashboard/admin/* will override /dashboard/*
35-
setLoginRequired(loginRequired || rule.loginRequired);
36-
setAdminOnly(adminOnly || rule.adminOnly);
27+
setLoginRequired(loginRequired || rule.loginRequired || false);
28+
setAdminOnly(adminOnly || rule.adminOnly || false);
3729
}
3830
}
3931
}

src/ui/services/auth.js renamed to src/ui/services/auth.ts

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,25 @@
11
import { getCookie } from '../utils';
2+
import { UserData } from '../../types/models';
3+
import { API_BASE } from '../apiBase';
4+
import { AxiosError } from 'axios';
25

3-
const baseUrl = import.meta.env.VITE_API_URI
4-
? `${import.meta.env.VITE_API_URI}`
5-
: `${location.origin}`;
6+
interface AxiosConfig {
7+
withCredentials: boolean;
8+
headers: {
9+
'X-CSRF-TOKEN': string;
10+
Authorization?: string;
11+
};
12+
}
613

714
/**
815
* Gets the current user's information
9-
* @return {Promise<Object>} The user's information
1016
*/
11-
export const getUserInfo = async () => {
17+
export const getUserInfo = async (): Promise<UserData | null> => {
1218
try {
13-
const response = await fetch(`${baseUrl}/api/auth/me`, {
19+
const response = await fetch(`${API_BASE}/api/auth/me`, {
1420
credentials: 'include', // Sends cookies
1521
});
16-
1722
if (!response.ok) throw new Error(`Failed to fetch user info: ${response.statusText}`);
18-
1923
return await response.json();
2024
} catch (error) {
2125
console.error('Error fetching user info:', error);
@@ -25,9 +29,8 @@ export const getUserInfo = async () => {
2529

2630
/**
2731
* Gets the Axios config for the UI
28-
* @return {Object} The Axios config
2932
*/
30-
export const getAxiosConfig = () => {
33+
export const getAxiosConfig = (): AxiosConfig => {
3134
const jwtToken = localStorage.getItem('ui_jwt_token');
3235
return {
3336
withCredentials: true,
@@ -40,11 +43,9 @@ export const getAxiosConfig = () => {
4043

4144
/**
4245
* Processes authentication errors and returns a user-friendly error message
43-
* @param {Object} error - The error object
44-
* @return {string} The error message
4546
*/
46-
export const processAuthError = (error, jwtAuthEnabled = false) => {
47-
let errorMessage = `Failed to authorize user: ${error.response.data.trim()}. `;
47+
export const processAuthError = (error: AxiosError<any>, jwtAuthEnabled = false): string => {
48+
let errorMessage = `Failed to authorize user: ${error.response?.data?.trim() ?? ''}. `;
4849
if (jwtAuthEnabled && !localStorage.getItem('ui_jwt_token')) {
4950
errorMessage +=
5051
'Set your JWT token in the settings page or disable JWT auth in your app configuration.';

src/ui/services/config.js

Lines changed: 0 additions & 35 deletions
This file was deleted.

src/ui/services/config.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import axios from 'axios';
2+
import { API_BASE } from '../apiBase';
3+
import { FormQuestion } from '../views/PushDetails/components/AttestationForm';
4+
import { UIRouteAuth } from '../../config/generated/config';
5+
6+
const API_V1_BASE = `${API_BASE}/api/v1`;
7+
8+
const setAttestationConfigData = async (setData: (data: FormQuestion[]) => void) => {
9+
const url = new URL(`${API_V1_BASE}/config/attestation`);
10+
await axios(url.toString()).then((response) => {
11+
setData(response.data.questions);
12+
});
13+
};
14+
15+
const setURLShortenerData = async (setData: (data: string) => void) => {
16+
const url = new URL(`${API_V1_BASE}/config/urlShortener`);
17+
await axios(url.toString()).then((response) => {
18+
setData(response.data);
19+
});
20+
};
21+
22+
const setEmailContactData = async (setData: (data: string) => void) => {
23+
const url = new URL(`${API_V1_BASE}/config/contactEmail`);
24+
await axios(url.toString()).then((response) => {
25+
setData(response.data);
26+
});
27+
};
28+
29+
const setUIRouteAuthData = async (setData: (data: UIRouteAuth) => void) => {
30+
const url = new URL(`${API_V1_BASE}/config/uiRouteAuth`);
31+
await axios(url.toString()).then((response) => {
32+
setData(response.data);
33+
});
34+
};
35+
36+
export { setAttestationConfigData, setURLShortenerData, setEmailContactData, setUIRouteAuthData };

src/ui/services/git-push.js

Lines changed: 0 additions & 110 deletions
This file was deleted.

0 commit comments

Comments
 (0)