diff --git a/config.schema.json b/config.schema.json index dafb93c3f..f75ca0d19 100644 --- a/config.schema.json +++ b/config.schema.json @@ -466,7 +466,14 @@ "description": "Additional JWT configuration.", "properties": { "clientID": { "type": "string" }, - "authorityURL": { "type": "string" } + "authorityURL": { "type": "string" }, + "expectedAudience": { "type": "string" }, + "roleMapping": { + "type": "object", + "properties": { + "admin": { "type": "object" } + } + } }, "required": ["clientID", "authorityURL"] } diff --git a/package.json b/package.json index 56c5679dd..5d6890e98 100644 --- a/package.json +++ b/package.json @@ -20,20 +20,25 @@ "require": "./dist/src/db/index.js", "types": "./dist/src/db/index.d.ts" }, + "./plugin": { + "import": "./dist/src/plugin.js", + "require": "./dist/src/plugin.js", + "types": "./dist/src/plugin.d.ts" + }, "./proxy": { "import": "./dist/src/proxy/index.js", "require": "./dist/src/proxy/index.js", "types": "./dist/src/proxy/index.d.ts" }, - "./types": { - "import": "./dist/src/types/models.js", - "require": "./dist/src/types/models.js", - "types": "./dist/src/types/models.d.ts" + "./proxy/actions": { + "import": "./dist/src/proxy/actions/index.js", + "require": "./dist/src/proxy/actions/index.js", + "types": "./dist/src/proxy/actions/index.d.ts" }, - "./plugin": { - "import": "./dist/src/plugin.js", - "require": "./dist/src/plugin.js", - "types": "./dist/src/plugin.d.ts" + "./ui": { + "import": "./dist/src/ui/index.js", + "require": "./dist/src/ui/index.js", + "types": "./dist/src/ui/index.d.ts" } }, "scripts": { diff --git a/packages/git-proxy-cli/index.ts b/packages/git-proxy-cli/index.ts index 5536785f0..31ebc8a4c 100644 --- a/packages/git-proxy-cli/index.ts +++ b/packages/git-proxy-cli/index.ts @@ -5,8 +5,8 @@ import { hideBin } from 'yargs/helpers'; import fs from 'fs'; import util from 'util'; -import { CommitData, PushData } from '@finos/git-proxy/types'; import { PushQuery } from '@finos/git-proxy/db'; +import { Action } from '@finos/git-proxy/proxy/actions'; const GIT_PROXY_COOKIE_FILE = 'git-proxy-cookie'; // GitProxy UI HOST and PORT (configurable via environment variable) @@ -88,74 +88,86 @@ async function getGitPushes(filters: Partial) { try { const cookies = JSON.parse(fs.readFileSync(GIT_PROXY_COOKIE_FILE, 'utf8')); - - const response = await axios.get(`${baseUrl}/api/v1/push/`, { + const { data } = await axios.get(`${baseUrl}/api/v1/push/`, { headers: { Cookie: cookies }, params: filters, }); - const records: PushData[] = []; - response.data.forEach((push: PushData) => { - const record: PushData = { - id: push.id, - repo: push.repo, - branch: push.branch, - commitFrom: push.commitFrom, - commitTo: push.commitTo, - commitData: push.commitData, - diff: push.diff, - error: push.error, - canceled: push.canceled, - rejected: push.rejected, - blocked: push.blocked, - authorised: push.authorised, - attestation: push.attestation, - autoApproved: push.autoApproved, - timestamp: push.timestamp, - url: push.url, - allowPush: push.allowPush, + const records = data.map((push: Action) => { + const { + id, + repo, + branch, + commitFrom, + commitTo, + commitData, + error, + canceled, + rejected, + blocked, + authorised, + attestation, + autoApproved, + timestamp, + url, + allowPush, + lastStep, + } = push; + + return { + id, + repo, + branch, + commitFrom, + commitTo, + commitData: commitData?.map( + ({ + message, + committer, + committerEmail, + author, + authorEmail, + commitTimestamp, + tree, + parent, + }) => ({ + message, + committer, + committerEmail, + author, + authorEmail, + commitTimestamp, + tree, + parent, + }), + ), + error, + canceled, + rejected, + blocked, + authorised, + attestation, + autoApproved, + timestamp, + url, + allowPush, + lastStep: lastStep && { + id: lastStep.id, + content: lastStep.content, + logs: lastStep.logs, + stepName: lastStep.stepName, + error: lastStep.error, + errorMessage: lastStep.errorMessage, + blocked: lastStep.blocked, + blockedMessage: lastStep.blockedMessage, + }, }; - - if (push.lastStep) { - record.lastStep = { - id: push.lastStep?.id, - content: push.lastStep?.content, - logs: push.lastStep?.logs, - stepName: push.lastStep?.stepName, - error: push.lastStep?.error, - errorMessage: push.lastStep?.errorMessage, - blocked: push.lastStep?.blocked, - blockedMessage: push.lastStep?.blockedMessage, - }; - } - - if (push.commitData) { - const commitData: CommitData[] = []; - push.commitData.forEach((pushCommitDataRecord: CommitData) => { - commitData.push({ - message: pushCommitDataRecord.message, - committer: pushCommitDataRecord.committer, - committerEmail: pushCommitDataRecord.committerEmail, - author: pushCommitDataRecord.author, - authorEmail: pushCommitDataRecord.authorEmail, - commitTimestamp: pushCommitDataRecord.commitTimestamp, - tree: pushCommitDataRecord.tree, - parent: pushCommitDataRecord.parent, - commitTs: pushCommitDataRecord.commitTs, - }); - }); - record.commitData = commitData; - } - - records.push(record); }); - console.log(`${util.inspect(records, false, null, false)}`); + console.log(util.inspect(records, false, null, false)); } catch (error: any) { - // default error - const errorMessage = `Error: List: '${error.message}'`; + console.error(`Error: List: '${error.message}'`); process.exitCode = 2; - console.error(errorMessage); } } diff --git a/packages/git-proxy-cli/test/testCliUtils.ts b/packages/git-proxy-cli/test/testCliUtils.ts index fd733f7e4..a99f33bec 100644 --- a/packages/git-proxy-cli/test/testCliUtils.ts +++ b/packages/git-proxy-cli/test/testCliUtils.ts @@ -221,7 +221,6 @@ async function addGitPushToDb( parent: 'parent', author: 'author', committer: 'committer', - commitTs: 'commitTs', message: 'message', authorEmail: 'authorEmail', committerEmail: 'committerEmail', diff --git a/src/config/ConfigLoader.ts b/src/config/ConfigLoader.ts index e09ce81f6..22dd6abfd 100644 --- a/src/config/ConfigLoader.ts +++ b/src/config/ConfigLoader.ts @@ -6,57 +6,10 @@ import { promisify } from 'util'; import { EventEmitter } from 'events'; import envPaths from 'env-paths'; import { GitProxyConfig, Convert } from './generated/config'; +import { Configuration, ConfigurationSource, FileSource, HttpSource, GitSource } from './types'; const execFileAsync = promisify(execFile); -interface GitAuth { - type: 'ssh'; - privateKeyPath: string; -} - -interface HttpAuth { - type: 'bearer'; - token: string; -} - -interface BaseSource { - type: 'file' | 'http' | 'git'; - enabled: boolean; -} - -interface FileSource extends BaseSource { - type: 'file'; - path: string; -} - -interface HttpSource extends BaseSource { - type: 'http'; - url: string; - headers?: Record; - auth?: HttpAuth; -} - -interface GitSource extends BaseSource { - type: 'git'; - repository: string; - branch?: string; - path: string; - auth?: GitAuth; -} - -type ConfigurationSource = FileSource | HttpSource | GitSource; - -export interface ConfigurationSources { - enabled: boolean; - sources: ConfigurationSource[]; - reloadIntervalSeconds: number; - merge?: boolean; -} - -export interface Configuration extends GitProxyConfig { - configurationSources?: ConfigurationSources; -} - // Add path validation helper function isValidPath(filePath: string): boolean { if (!filePath || typeof filePath !== 'string') return false; diff --git a/src/config/env.ts b/src/config/env.ts index 3adb7d2f9..14b63a7f6 100644 --- a/src/config/env.ts +++ b/src/config/env.ts @@ -1,11 +1,4 @@ -export type ServerConfig = { - GIT_PROXY_SERVER_PORT: string | number; - GIT_PROXY_HTTPS_SERVER_PORT: string | number; - GIT_PROXY_UI_HOST: string; - GIT_PROXY_UI_PORT: string | number; - GIT_PROXY_COOKIE_SECRET: string | undefined; - GIT_PROXY_MONGO_CONNECTION_STRING: string; -}; +import { ServerConfig } from './types'; const { GIT_PROXY_SERVER_PORT = 8000, diff --git a/src/config/generated/config.ts b/src/config/generated/config.ts index 4d3493e1a..6f87f0cd1 100644 --- a/src/config/generated/config.ts +++ b/src/config/generated/config.ts @@ -225,6 +225,13 @@ export interface AdConfig { export interface JwtConfig { authorityURL: string; clientID: string; + expectedAudience?: string; + roleMapping?: RoleMapping; + [property: string]: any; +} + +export interface RoleMapping { + admin?: { [key: string]: any }; [property: string]: any; } @@ -754,9 +761,12 @@ const typeMap: any = { [ { json: 'authorityURL', js: 'authorityURL', typ: '' }, { json: 'clientID', js: 'clientID', typ: '' }, + { json: 'expectedAudience', js: 'expectedAudience', typ: u(undefined, '') }, + { json: 'roleMapping', js: 'roleMapping', typ: u(undefined, r('RoleMapping')) }, ], 'any', ), + RoleMapping: o([{ json: 'admin', js: 'admin', typ: u(undefined, m('any')) }], 'any'), OidcConfig: o( [ { json: 'callbackURL', js: 'callbackURL', typ: '' }, diff --git a/src/config/index.ts b/src/config/index.ts index 6c108d3fc..8f40ac3b1 100644 --- a/src/config/index.ts +++ b/src/config/index.ts @@ -2,7 +2,8 @@ import { existsSync, readFileSync } from 'fs'; import defaultSettings from '../../proxy.config.json'; import { GitProxyConfig, Convert } from './generated/config'; -import { ConfigLoader, Configuration } from './ConfigLoader'; +import { ConfigLoader } from './ConfigLoader'; +import { Configuration } from './types'; import { serverConfig } from './env'; import { configFile } from './file'; diff --git a/src/config/types.ts b/src/config/types.ts new file mode 100644 index 000000000..49c7f811b --- /dev/null +++ b/src/config/types.ts @@ -0,0 +1,58 @@ +import { GitProxyConfig } from './generated/config'; + +export type ServerConfig = { + GIT_PROXY_SERVER_PORT: string | number; + GIT_PROXY_HTTPS_SERVER_PORT: string | number; + GIT_PROXY_UI_HOST: string; + GIT_PROXY_UI_PORT: string | number; + GIT_PROXY_COOKIE_SECRET: string | undefined; + GIT_PROXY_MONGO_CONNECTION_STRING: string; +}; + +interface GitAuth { + type: 'ssh'; + privateKeyPath: string; +} + +interface HttpAuth { + type: 'bearer'; + token: string; +} + +interface BaseSource { + type: 'file' | 'http' | 'git'; + enabled: boolean; +} + +export interface FileSource extends BaseSource { + type: 'file'; + path: string; +} + +export interface HttpSource extends BaseSource { + type: 'http'; + url: string; + headers?: Record; + auth?: HttpAuth; +} + +export interface GitSource extends BaseSource { + type: 'git'; + repository: string; + branch?: string; + path: string; + auth?: GitAuth; +} + +export type ConfigurationSource = FileSource | HttpSource | GitSource; + +interface ConfigurationSources { + enabled: boolean; + sources: ConfigurationSource[]; + reloadIntervalSeconds: number; + merge?: boolean; +} + +export interface Configuration extends GitProxyConfig { + configurationSources?: ConfigurationSources; +} diff --git a/src/context.ts b/src/context.ts deleted file mode 100644 index d8302c7cb..000000000 --- a/src/context.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { createContext } from 'react'; -import { UserContextType } from './ui/views/RepoDetails/RepoDetails'; - -export const UserContext = createContext({ - user: { - admin: false, - }, -}); diff --git a/src/db/types.ts b/src/db/types.ts index 0a179b233..e4ae2eab5 100644 --- a/src/db/types.ts +++ b/src/db/types.ts @@ -81,6 +81,15 @@ export class User { } } +export interface PublicUser { + username: string; + displayName: string; + email: string; + title: string; + gitAccount: string; + admin: boolean; +} + export interface Sink { getSessionStore: () => MongoDBStore | undefined; getPushes: (query: Partial) => Promise; diff --git a/src/proxy/actions/Action.ts b/src/proxy/actions/Action.ts index c576bb0e1..bfc80c37e 100644 --- a/src/proxy/actions/Action.ts +++ b/src/proxy/actions/Action.ts @@ -1,20 +1,7 @@ import { processGitURLForNameAndOrg, processUrlPath } from '../routes/helper'; import { Step } from './Step'; - -/** - * Represents a commit. - */ -export interface Commit { - message: string; - committer: string; - committerEmail: string; - tree: string; - parent: string; - author: string; - authorEmail: string; - commitTS?: string; // TODO: Normalize this to commitTimestamp - commitTimestamp?: string; -} +import { CommitData } from '../processors/types'; +import { AttestationFormData } from '../../ui/types'; /** * Class representing a Push. @@ -39,7 +26,7 @@ class Action { rejected: boolean = false; autoApproved: boolean = false; autoRejected: boolean = false; - commitData?: Commit[] = []; + commitData?: CommitData[] = []; commitFrom?: string; commitTo?: string; branch?: string; @@ -47,7 +34,7 @@ class Action { author?: string; user?: string; userEmail?: string; - attestation?: string; + attestation?: AttestationFormData; lastStep?: Step; proxyGitPath?: string; newIdxFiles?: string[]; diff --git a/src/proxy/processors/push-action/checkAuthorEmails.ts b/src/proxy/processors/push-action/checkAuthorEmails.ts index 3c7cbb89c..ab45123d0 100644 --- a/src/proxy/processors/push-action/checkAuthorEmails.ts +++ b/src/proxy/processors/push-action/checkAuthorEmails.ts @@ -1,6 +1,6 @@ import { Action, Step } from '../../actions'; import { getCommitConfig } from '../../../config'; -import { Commit } from '../../actions/Action'; +import { CommitData } from '../types'; import { isEmail } from 'validator'; const commitConfig = getCommitConfig(); @@ -33,7 +33,7 @@ const exec = async (req: any, action: Action): Promise => { const step = new Step('checkAuthorEmails'); const uniqueAuthorEmails = [ - ...new Set(action.commitData?.map((commit: Commit) => commit.authorEmail)), + ...new Set(action.commitData?.map((commitData: CommitData) => commitData.authorEmail)), ]; console.log({ uniqueAuthorEmails }); diff --git a/src/routes.tsx b/src/routes.tsx index 7a2db106e..580c39b70 100644 --- a/src/routes.tsx +++ b/src/routes.tsx @@ -30,7 +30,7 @@ import SettingsView from './ui/views/Settings/Settings'; import { RepoIcon } from '@primer/octicons-react'; import { AccountCircle, Dashboard, Group, Settings } from '@material-ui/icons'; -import { Route } from './types/models'; +import { Route } from './ui/types'; const dashboardRoutes: Route[] = [ { diff --git a/src/service/passport/jwtAuthHandler.ts b/src/service/passport/jwtAuthHandler.ts index bb312e40f..2bcb4ae4c 100644 --- a/src/service/passport/jwtAuthHandler.ts +++ b/src/service/passport/jwtAuthHandler.ts @@ -1,8 +1,7 @@ import { assignRoles, validateJwt } from './jwtUtils'; import type { Request, Response, NextFunction } from 'express'; import { getAPIAuthMethods } from '../../config'; -import { JwtConfig, AuthenticationElement, Type } from '../../config/generated/config'; -import { RoleMapping } from './types'; +import { AuthenticationElement, JwtConfig, RoleMapping, Type } from '../../config/generated/config'; export const type = 'jwt'; diff --git a/src/service/passport/jwtUtils.ts b/src/service/passport/jwtUtils.ts index 8fcf214e4..5fc3a1901 100644 --- a/src/service/passport/jwtUtils.ts +++ b/src/service/passport/jwtUtils.ts @@ -2,7 +2,8 @@ import axios from 'axios'; import jwt, { type JwtPayload } from 'jsonwebtoken'; import jwkToPem from 'jwk-to-pem'; -import { JwkKey, JwksResponse, JwtValidationResult, RoleMapping } from './types'; +import { JwkKey, JwksResponse, JwtValidationResult } from './types'; +import { RoleMapping } from '../../config/generated/config'; /** * Obtain the JSON Web Key Set (JWKS) from the OIDC authority. @@ -80,6 +81,14 @@ export async function validateJwt( * Assign roles to the user based on the role mappings provided in the jwtConfig. * * If no role mapping is provided, the user will not have any roles assigned (i.e. user.admin = false). + * + * For example, the following role mapping will assign the "admin" role to users whose "name" claim is "John Doe": + * + * { + * "admin": { + * "name": "John Doe" + * } + * } * @param {RoleMapping} roleMapping the role mapping configuration * @param {JwtPayload} payload the JWT payload * @param {Record} user the req.user object to assign roles to diff --git a/src/service/passport/types.ts b/src/service/passport/types.ts index d433c782f..59b02deca 100644 --- a/src/service/passport/types.ts +++ b/src/service/passport/types.ts @@ -19,22 +19,6 @@ export type JwtValidationResult = { error: string | null; }; -/** - * The JWT role mapping configuration. - * - * The key is the in-app role name (e.g. "admin"). - * The value is a pair of claim name and expected value. - * - * For example, the following role mapping will assign the "admin" role to users whose "name" claim is "John Doe": - * - * { - * "admin": { - * "name": "John Doe" - * } - * } - */ -export type RoleMapping = Record>; - export type ADProfile = { id?: string; username?: string; diff --git a/src/service/routes/publicApi.ts b/src/service/routes/publicApi.ts index d70b5aa08..1b408a562 100644 --- a/src/service/routes/publicApi.ts +++ b/src/service/routes/publicApi.ts @@ -1,6 +1,6 @@ -import { User } from '../../db/types'; +import { PublicUser, User } from '../../db/types'; -export const toPublicUser = (user: User) => { +export const toPublicUser = (user: User): PublicUser => { return { username: user.username || '', displayName: user.displayName || '', diff --git a/src/service/routes/users.ts b/src/service/routes/users.ts index 40b2ead5d..2e689817e 100644 --- a/src/service/routes/users.ts +++ b/src/service/routes/users.ts @@ -3,7 +3,6 @@ const router = express.Router(); import * as db from '../../db'; import { toPublicUser } from './publicApi'; -import { UserQuery } from '../../db/types'; router.get('/', async (req: Request, res: Response) => { console.log('fetching users'); diff --git a/src/service/routes/utils.ts b/src/service/routes/utils.ts index 3c72064ce..a9c501801 100644 --- a/src/service/routes/utils.ts +++ b/src/service/routes/utils.ts @@ -1,10 +1,8 @@ -interface User { +interface User extends Express.User { username: string; admin?: boolean; } -export function isAdminUser(user: any): user is User & { admin: true } { - return ( - typeof user === 'object' && user !== null && user !== undefined && (user as User).admin === true - ); +export function isAdminUser(user?: Express.User): user is User & { admin: true } { + return user !== null && user !== undefined && (user as User).admin === true; } diff --git a/src/ui/auth/AuthProvider.tsx b/src/ui/auth/AuthProvider.tsx index a2409da60..57e6913c0 100644 --- a/src/ui/auth/AuthProvider.tsx +++ b/src/ui/auth/AuthProvider.tsx @@ -1,18 +1,10 @@ -import React, { createContext, useContext, useState, useEffect } from 'react'; +import React, { useContext, useState, useEffect } from 'react'; import { getUserInfo } from '../services/auth'; -import { UserData } from '../../types/models'; - -interface AuthContextType { - user: UserData | null; - setUser: React.Dispatch; - refreshUser: () => Promise; - isLoading: boolean; -} - -const AuthContext = createContext(undefined); +import { PublicUser } from '../../db/types'; +import { AuthContext } from '../context'; export const AuthProvider: React.FC> = ({ children }) => { - const [user, setUser] = useState(null); + const [user, setUser] = useState(null); const [isLoading, setIsLoading] = useState(true); const refreshUser = async () => { diff --git a/src/ui/components/CustomTabs/CustomTabs.tsx b/src/ui/components/CustomTabs/CustomTabs.tsx index 8cd0c2d81..6a9211ecf 100644 --- a/src/ui/components/CustomTabs/CustomTabs.tsx +++ b/src/ui/components/CustomTabs/CustomTabs.tsx @@ -7,16 +7,17 @@ import Card from '../Card/Card'; import CardBody from '../Card/CardBody'; import CardHeader from '../Card/CardHeader'; import styles from '../../assets/jss/material-dashboard-react/components/customTabsStyle'; +import { SvgIconProps } from '@material-ui/core'; const useStyles = makeStyles(styles as any); type HeaderColor = 'warning' | 'success' | 'danger' | 'info' | 'primary' | 'rose'; -interface TabItem { +export type TabItem = { tabName: string; - tabIcon?: React.ComponentType; + tabIcon?: React.ComponentType; tabContent: React.ReactNode; -} +}; interface CustomTabsProps { headerColor?: HeaderColor; diff --git a/src/ui/components/Navbars/DashboardNavbarLinks.tsx b/src/ui/components/Navbars/DashboardNavbarLinks.tsx index b69cd61c9..2ed5c3d8f 100644 --- a/src/ui/components/Navbars/DashboardNavbarLinks.tsx +++ b/src/ui/components/Navbars/DashboardNavbarLinks.tsx @@ -16,7 +16,7 @@ import { AccountCircle } from '@material-ui/icons'; import { getUser } from '../../services/user'; import axios from 'axios'; import { getAxiosConfig } from '../../services/auth'; -import { UserData } from '../../../types/models'; +import { PublicUser } from '../../../db/types'; import { API_BASE } from '../../apiBase'; @@ -29,10 +29,10 @@ const DashboardNavbarLinks: React.FC = () => { const [, setAuth] = useState(true); const [, setIsLoading] = useState(true); const [, setIsError] = useState(false); - const [data, setData] = useState(null); + const [user, setUser] = useState(null); useEffect(() => { - getUser(setIsLoading, setData, setAuth, setIsError); + getUser(setIsLoading, setUser, setAuth, setIsError); }, []); const handleClickProfile = (event: React.MouseEvent) => { @@ -99,10 +99,10 @@ const DashboardNavbarLinks: React.FC = () => { - {data ? 'My Account' : 'Login'} + {user ? 'My Account' : 'Login'} - {!!data && } - {!!data && ( + {!!user && } + {!!user && ( Logout diff --git a/src/ui/components/Navbars/Navbar.tsx b/src/ui/components/Navbars/Navbar.tsx index 59dc2e110..859b01a50 100644 --- a/src/ui/components/Navbars/Navbar.tsx +++ b/src/ui/components/Navbars/Navbar.tsx @@ -8,7 +8,7 @@ import Hidden from '@material-ui/core/Hidden'; import Menu from '@material-ui/icons/Menu'; import DashboardNavbarLinks from './DashboardNavbarLinks'; import styles from '../../assets/jss/material-dashboard-react/components/headerStyle'; -import { Route } from '../../../types/models'; +import { Route } from '../../types'; const useStyles = makeStyles(styles as any); diff --git a/src/ui/components/Sidebar/Sidebar.tsx b/src/ui/components/Sidebar/Sidebar.tsx index a2f745948..ad698f0b2 100644 --- a/src/ui/components/Sidebar/Sidebar.tsx +++ b/src/ui/components/Sidebar/Sidebar.tsx @@ -9,7 +9,7 @@ import ListItem from '@material-ui/core/ListItem'; import ListItemText from '@material-ui/core/ListItemText'; import Icon from '@material-ui/core/Icon'; import styles from '../../assets/jss/material-dashboard-react/components/sidebarStyle'; -import { Route } from '../../../types/models'; +import { Route } from '../../types'; const useStyles = makeStyles(styles as any); diff --git a/src/ui/context.ts b/src/ui/context.ts new file mode 100644 index 000000000..fcf7a7da5 --- /dev/null +++ b/src/ui/context.ts @@ -0,0 +1,23 @@ +import { createContext } from 'react'; +import { PublicUser } from '../db/types'; + +export const UserContext = createContext({ + user: { + admin: false, + }, +}); + +export interface UserContextType { + user: { + admin: boolean; + }; +} + +export interface AuthContextType { + user: PublicUser | null; + setUser: React.Dispatch; + refreshUser: () => Promise; + isLoading: boolean; +} + +export const AuthContext = createContext(undefined); diff --git a/src/ui/layouts/Dashboard.tsx b/src/ui/layouts/Dashboard.tsx index 777358f42..3666a2bd1 100644 --- a/src/ui/layouts/Dashboard.tsx +++ b/src/ui/layouts/Dashboard.tsx @@ -9,20 +9,15 @@ import Sidebar from '../components/Sidebar/Sidebar'; import routes from '../../routes'; import styles from '../assets/jss/material-dashboard-react/layouts/dashboardStyle'; import logo from '../assets/img/git-proxy.png'; -import { UserContext } from '../../context'; +import { UserContext } from '../context'; import { getUser } from '../services/user'; -import { Route as RouteType } from '../../types/models'; +import { Route as RouteType } from '../types'; +import { PublicUser } from '../../db/types'; interface DashboardProps { [key: string]: any; } -interface UserType { - id?: string; - name?: string; - email?: string; -} - let ps: PerfectScrollbar | undefined; let refresh = false; @@ -33,7 +28,7 @@ const Dashboard: React.FC = ({ ...rest }) => { const mainPanel = useRef(null); const [color] = useState<'purple' | 'blue' | 'green' | 'orange' | 'red'>('blue'); const [mobileOpen, setMobileOpen] = useState(false); - const [user, setUser] = useState({}); + const [user, setUser] = useState({} as PublicUser); const { id } = useParams<{ id?: string }>(); const handleDrawerToggle = () => setMobileOpen((prev) => !prev); diff --git a/src/ui/services/auth.ts b/src/ui/services/auth.ts index b855a26f8..81acd399e 100644 --- a/src/ui/services/auth.ts +++ b/src/ui/services/auth.ts @@ -1,5 +1,5 @@ import { getCookie } from '../utils'; -import { UserData } from '../../types/models'; +import { PublicUser } from '../../db/types'; import { API_BASE } from '../apiBase'; import { AxiosError } from 'axios'; @@ -14,7 +14,7 @@ interface AxiosConfig { /** * Gets the current user's information */ -export const getUserInfo = async (): Promise => { +export const getUserInfo = async (): Promise => { try { const response = await fetch(`${API_BASE}/api/auth/me`, { credentials: 'include', // Sends cookies diff --git a/src/ui/services/config.ts b/src/ui/services/config.ts index 3ececdc0f..ae5ae0203 100644 --- a/src/ui/services/config.ts +++ b/src/ui/services/config.ts @@ -1,11 +1,11 @@ import axios from 'axios'; import { API_BASE } from '../apiBase'; -import { FormQuestion } from '../views/PushDetails/components/AttestationForm'; +import { QuestionFormData } from '../types'; import { UIRouteAuth } from '../../config/generated/config'; const API_V1_BASE = `${API_BASE}/api/v1`; -const setAttestationConfigData = async (setData: (data: FormQuestion[]) => void) => { +const setAttestationConfigData = async (setData: (data: QuestionFormData[]) => void) => { const url = new URL(`${API_V1_BASE}/config/attestation`); await axios(url.toString()).then((response) => { setData(response.data.questions); diff --git a/src/ui/services/git-push.ts b/src/ui/services/git-push.ts index 2b0420680..3de0dac4d 100644 --- a/src/ui/services/git-push.ts +++ b/src/ui/services/git-push.ts @@ -1,13 +1,15 @@ import axios from 'axios'; import { getAxiosConfig, processAuthError } from './auth'; import { API_BASE } from '../apiBase'; +import { Action, Step } from '../../proxy/actions'; +import { PushActionView } from '../types'; const API_V1_BASE = `${API_BASE}/api/v1`; const getPush = async ( id: string, setIsLoading: (isLoading: boolean) => void, - setData: (data: any) => void, + setPush: (push: PushActionView) => void, setAuth: (auth: boolean) => void, setIsError: (isError: boolean) => void, ): Promise => { @@ -15,10 +17,10 @@ const getPush = async ( setIsLoading(true); try { - const response = await axios(url, getAxiosConfig()); - const data = response.data; - data.diff = data.steps.find((x: any) => x.stepName === 'diff'); - setData(data); + const response = await axios(url, getAxiosConfig()); + const data: Action & { diff?: Step } = response.data; + data.diff = data.steps.find((x: Step) => x.stepName === 'diff'); + setPush(data as PushActionView); } catch (error: any) { if (error.response?.status === 401) setAuth(false); else setIsError(true); @@ -29,7 +31,7 @@ const getPush = async ( const getPushes = async ( setIsLoading: (isLoading: boolean) => void, - setData: (data: any) => void, + setPushes: (pushes: PushActionView[]) => void, setAuth: (auth: boolean) => void, setIsError: (isError: boolean) => void, setErrorMessage: (errorMessage: string) => void, @@ -46,8 +48,8 @@ const getPushes = async ( setIsLoading(true); try { - const response = await axios(url.toString(), getAxiosConfig()); - setData(response.data); + const response = await axios(url.toString(), getAxiosConfig()); + setPushes(response.data as PushActionView[]); } catch (error: any) { setIsError(true); diff --git a/src/ui/services/repo.ts b/src/ui/services/repo.ts index 5b168e882..59c68342d 100644 --- a/src/ui/services/repo.ts +++ b/src/ui/services/repo.ts @@ -1,20 +1,21 @@ import axios from 'axios'; import { getAxiosConfig, processAuthError } from './auth.js'; import { API_BASE } from '../apiBase'; -import { RepositoryData, RepositoryDataWithId } from '../views/RepoList/Components/NewRepo'; +import { Repo } from '../../db/types'; +import { RepoView } from '../types'; const API_V1_BASE = `${API_BASE}/api/v1`; const canAddUser = (repoId: string, user: string, action: string) => { const url = new URL(`${API_V1_BASE}/repo/${repoId}`); return axios - .get(url.toString(), getAxiosConfig()) + .get(url.toString(), getAxiosConfig()) .then((response) => { - const data = response.data; + const repo = response.data; if (action === 'authorise') { - return !data.users.canAuthorise.includes(user); + return !repo.users.canAuthorise.includes(user); } else { - return !data.users.canPush.includes(user); + return !repo.users.canPush.includes(user); } }) .catch((error: any) => { @@ -31,7 +32,7 @@ class DupUserValidationError extends Error { const getRepos = async ( setIsLoading: (isLoading: boolean) => void, - setData: (data: any) => void, + setRepos: (repos: RepoView[]) => void, setAuth: (auth: boolean) => void, setIsError: (isError: boolean) => void, setErrorMessage: (errorMessage: string) => void, @@ -40,12 +41,12 @@ const getRepos = async ( const url = new URL(`${API_V1_BASE}/repo`); url.search = new URLSearchParams(query as any).toString(); setIsLoading(true); - await axios(url.toString(), getAxiosConfig()) + await axios(url.toString(), getAxiosConfig()) .then((response) => { - const sortedRepos = response.data.sort((a: RepositoryData, b: RepositoryData) => + const sortedRepos = response.data.sort((a: RepoView, b: RepoView) => a.name.localeCompare(b.name), ); - setData(sortedRepos); + setRepos(sortedRepos); }) .catch((error: any) => { setIsError(true); @@ -63,17 +64,17 @@ const getRepos = async ( const getRepo = async ( setIsLoading: (isLoading: boolean) => void, - setData: (data: any) => void, + setRepo: (repo: RepoView) => void, setAuth: (auth: boolean) => void, setIsError: (isError: boolean) => void, id: string, ): Promise => { const url = new URL(`${API_V1_BASE}/repo/${id}`); setIsLoading(true); - await axios(url.toString(), getAxiosConfig()) + await axios(url.toString(), getAxiosConfig()) .then((response) => { - const data = response.data; - setData(data); + const repo = response.data; + setRepo(repo); }) .catch((error: any) => { if (error.response && error.response.status === 401) { @@ -88,12 +89,12 @@ const getRepo = async ( }; const addRepo = async ( - data: RepositoryData, -): Promise<{ success: boolean; message?: string; repo: RepositoryDataWithId | null }> => { + repo: RepoView, +): Promise<{ success: boolean; message?: string; repo: RepoView | null }> => { const url = new URL(`${API_V1_BASE}/repo`); try { - const response = await axios.post(url.toString(), data, getAxiosConfig()); + const response = await axios.post(url.toString(), repo, getAxiosConfig()); return { success: true, repo: response.data, diff --git a/src/ui/services/user.ts b/src/ui/services/user.ts index 5896b60ea..98e97883e 100644 --- a/src/ui/services/user.ts +++ b/src/ui/services/user.ts @@ -1,6 +1,6 @@ import axios, { AxiosError, AxiosResponse } from 'axios'; import { getAxiosConfig, processAuthError } from './auth'; -import { UserData } from '../../types/models'; +import { PublicUser } from '../../db/types'; import { API_BASE } from '../apiBase'; @@ -8,7 +8,7 @@ type SetStateCallback = (value: T | ((prevValue: T) => T)) => void; const getUser = async ( setIsLoading?: SetStateCallback, - setData?: (userData: UserData) => void, + setUser?: (user: PublicUser) => void, setAuth?: SetStateCallback, setIsError?: SetStateCallback, id: string | null = null, @@ -19,10 +19,10 @@ const getUser = async ( } try { - const response: AxiosResponse = await axios(url, getAxiosConfig()); - const data = response.data; + const response: AxiosResponse = await axios(url, getAxiosConfig()); + const user = response.data; - setData?.(data); + setUser?.(user); setIsLoading?.(false); } catch (error) { const axiosError = error as AxiosError; @@ -37,18 +37,18 @@ const getUser = async ( const getUsers = async ( setIsLoading: SetStateCallback, - setData: SetStateCallback, + setUsers: SetStateCallback, setAuth: SetStateCallback, setErrorMessage: SetStateCallback, ): Promise => { setIsLoading(true); try { - const response: AxiosResponse = await axios( + const response: AxiosResponse = await axios( `${API_BASE}/api/v1/user`, getAxiosConfig(), ); - setData(response.data); + setUsers(response.data); } catch (error) { if (axios.isAxiosError(error)) { if (error.response?.status === 401) { @@ -66,10 +66,10 @@ const getUsers = async ( } }; -const updateUser = async (data: UserData): Promise => { - console.log(data); +const updateUser = async (user: PublicUser): Promise => { + console.log(user); try { - await axios.post(`${API_BASE}/api/auth/gitAccount`, data, getAxiosConfig()); + await axios.post(`${API_BASE}/api/auth/gitAccount`, user, getAxiosConfig()); } catch (error) { const axiosError = error as AxiosError; if (axiosError.response) { diff --git a/src/types/models.ts b/src/ui/types.ts similarity index 58% rename from src/types/models.ts rename to src/ui/types.ts index d583ebd76..cbbc505ee 100644 --- a/src/types/models.ts +++ b/src/ui/types.ts @@ -1,50 +1,36 @@ -import { StepData } from '../proxy/actions/Step'; -import { AttestationData } from '../ui/views/PushDetails/attestation.types'; +import { Action } from '../proxy/actions'; +import { Step } from '../proxy/actions/Step'; +import { Repo } from '../db/types'; -export interface UserData { - id: string; - name: string; - username: string; - email?: string; - displayName?: string; - title?: string; - gitAccount?: string; - admin?: boolean; +export interface PushActionView extends Action { + diff: Step; +} + +export interface RepoView extends Repo { + proxyURL: string; + lastModified?: string; + dateCreated?: string; } -export interface CommitData { - commitTs?: number; - message: string; - committer: string; - committerEmail: string; - tree?: string; - parent?: string; - author: string; - authorEmail: string; - commitTimestamp?: number; +export interface QuestionFormData { + label: string; + checked: boolean; + tooltip: { + text: string; + links?: { + text: string; + url: string; + }[]; + }; } -export interface PushData { - id: string; - url: string; - repo: string; - branch: string; - commitFrom: string; - commitTo: string; - commitData: CommitData[]; - diff: { - content: string; +export interface AttestationFormData { + reviewer: { + username: string; + gitAccount: string; }; - error: boolean; - canceled?: boolean; - rejected?: boolean; - blocked?: boolean; - authorised?: boolean; - attestation?: AttestationData; - autoApproved?: boolean; timestamp: string | Date; - allowPush?: boolean; - lastStep?: StepData; + questions: QuestionFormData[]; } export interface Route { diff --git a/src/ui/utils.tsx b/src/ui/utils.tsx index 20740013f..6a8abfc17 100644 --- a/src/ui/utils.tsx +++ b/src/ui/utils.tsx @@ -1,11 +1,7 @@ import axios from 'axios'; import React from 'react'; -import { - CommitData, - GitHubRepositoryMetadata, - GitLabRepositoryMetadata, - SCMRepositoryMetadata, -} from '../types/models'; +import { GitHubRepositoryMetadata, GitLabRepositoryMetadata, SCMRepositoryMetadata } from './types'; +import { CommitData } from '../proxy/processors/types'; import moment from 'moment'; /** diff --git a/src/ui/views/OpenPushRequests/OpenPushRequests.tsx b/src/ui/views/OpenPushRequests/OpenPushRequests.tsx index a778e08ab..41c2672a8 100644 --- a/src/ui/views/OpenPushRequests/OpenPushRequests.tsx +++ b/src/ui/views/OpenPushRequests/OpenPushRequests.tsx @@ -5,13 +5,7 @@ import PushesTable from './components/PushesTable'; import CustomTabs from '../../components/CustomTabs/CustomTabs'; import Danger from '../../components/Typography/Danger'; import { Visibility, CheckCircle, Cancel, Block } from '@material-ui/icons'; -import { SvgIconProps } from '@material-ui/core'; - -interface TabConfig { - tabName: string; - tabIcon: React.ComponentType; - tabContent: React.ReactNode; -} +import { TabItem } from '../../components/CustomTabs/CustomTabs'; const Dashboard: React.FC = () => { const [errorMessage, setErrorMessage] = useState(null); @@ -20,7 +14,7 @@ const Dashboard: React.FC = () => { setErrorMessage(errorMessage); }; - const tabs: TabConfig[] = [ + const tabs: TabItem[] = [ { tabName: 'Pending', tabIcon: Visibility, diff --git a/src/ui/views/OpenPushRequests/components/PushesTable.tsx b/src/ui/views/OpenPushRequests/components/PushesTable.tsx index 8a15469d0..83cc90be9 100644 --- a/src/ui/views/OpenPushRequests/components/PushesTable.tsx +++ b/src/ui/views/OpenPushRequests/components/PushesTable.tsx @@ -15,7 +15,7 @@ import { getPushes } from '../../../services/git-push'; import { KeyboardArrowRight } from '@material-ui/icons'; import Search from '../../../components/Search/Search'; import Pagination from '../../../components/Pagination/Pagination'; -import { PushData } from '../../../../types/models'; +import { PushActionView } from '../../../types'; import { trimPrefixRefsHeads, trimTrailingDotGit } from '../../../../db/helper'; import { generateAuthorLinks, generateEmailLink } from '../../../utils'; @@ -27,8 +27,8 @@ const useStyles = makeStyles(styles as any); const PushesTable: React.FC = (props) => { const classes = useStyles(); - const [data, setData] = useState([]); - const [filteredData, setFilteredData] = useState([]); + const [pushes, setPushes] = useState([]); + const [filteredData, setFilteredData] = useState([]); const [isLoading, setIsLoading] = useState(false); const [, setIsError] = useState(false); const navigate = useNavigate(); @@ -46,26 +46,26 @@ const PushesTable: React.FC = (props) => { authorised: props.authorised ?? false, rejected: props.rejected ?? false, }; - getPushes(setIsLoading, setData, setAuth, setIsError, props.handleError, query); + getPushes(setIsLoading, setPushes, setAuth, setIsError, props.handleError, query); }, [props]); useEffect(() => { - setFilteredData(data); - }, [data]); + setFilteredData(pushes); + }, [pushes]); useEffect(() => { const lowerCaseTerm = searchTerm.toLowerCase(); const filtered = searchTerm - ? data.filter( + ? pushes.filter( (item) => item.repo.toLowerCase().includes(lowerCaseTerm) || - item.commitTo.toLowerCase().includes(lowerCaseTerm) || - item.commitData[0]?.message.toLowerCase().includes(lowerCaseTerm), + item.commitTo?.toLowerCase().includes(lowerCaseTerm) || + item.commitData?.[0]?.message.toLowerCase().includes(lowerCaseTerm), ) - : data; + : pushes; setFilteredData(filtered); setCurrentPage(1); - }, [searchTerm, data]); + }, [searchTerm, pushes]); const handleSearch = (term: string) => setSearchTerm(term.trim()); @@ -100,19 +100,18 @@ const PushesTable: React.FC = (props) => { {[...currentItems].reverse().map((row) => { const repoFullName = trimTrailingDotGit(row.repo); - const repoBranch = trimPrefixRefsHeads(row.branch); + const repoBranch = trimPrefixRefsHeads(row.branch ?? ''); const repoUrl = row.url; const repoWebUrl = trimTrailingDotGit(repoUrl); // may be used to resolve users to profile links in future // const gitProvider = getGitProvider(repoUrl); // const hostname = new URL(repoUrl).hostname; - const commitTimestamp = - row.commitData[0]?.commitTs || row.commitData[0]?.commitTimestamp; + const commitTimestamp = row.commitData?.[0]?.commitTimestamp; return ( - {commitTimestamp ? moment.unix(commitTimestamp).toString() : 'N/A'} + {commitTimestamp ? moment.unix(Number(commitTimestamp)).toString() : 'N/A'} @@ -130,7 +129,7 @@ const PushesTable: React.FC = (props) => { rel='noreferrer' target='_blank' > - {row.commitTo.substring(0, 8)} + {row.commitTo?.substring(0, 8)} @@ -138,18 +137,18 @@ const PushesTable: React.FC = (props) => { {getUserProfileLink(row.commitData[0].committerEmail, gitProvider, hostname)} */} {generateEmailLink( - row.commitData[0].committer, - row.commitData[0]?.committerEmail, + row.commitData?.[0]?.committer ?? '', + row.commitData?.[0]?.committerEmail ?? '', )} {/* render github/gitlab profile links in future {getUserProfileLink(row.commitData[0].authorEmail, gitProvider, hostname)} */} - {generateAuthorLinks(row.commitData)} + {generateAuthorLinks(row.commitData ?? [])} - {row.commitData[0]?.message || 'N/A'} - {row.commitData.length} + {row.commitData?.[0]?.message || 'N/A'} + {row.commitData?.length ?? 0} @@ -243,17 +227,17 @@ const RepoDetails: React.FC = () => { - {data.users.canPush.map((row) => ( - + {repo.users?.canPush?.map((username) => ( + - + {user.admin && ( @@ -271,10 +255,10 @@ const RepoDetails: React.FC = () => { setConfirmDeleteOpen(false)} - onConfirm={() => removeRepository(data._id)} + onConfirm={() => removeRepository(repo._id!)} /> ); diff --git a/src/ui/views/RepoList/Components/NewRepo.tsx b/src/ui/views/RepoList/Components/NewRepo.tsx index 6758a1bb1..e29f8244f 100644 --- a/src/ui/views/RepoList/Components/NewRepo.tsx +++ b/src/ui/views/RepoList/Components/NewRepo.tsx @@ -15,28 +15,16 @@ import { addRepo } from '../../../services/repo'; import { makeStyles } from '@material-ui/core/styles'; import styles from '../../../assets/jss/material-dashboard-react/views/dashboardStyle'; import { RepoIcon } from '@primer/octicons-react'; +import { RepoView } from '../../../types'; interface AddRepositoryDialogProps { open: boolean; onClose: () => void; - onSuccess: (data: RepositoryDataWithId) => void; + onSuccess: (repo: RepoView) => void; } -export interface RepositoryData { - _id?: string; - project: string; - name: string; - url: string; - maxUser: number; - lastModified?: string; - dateCreated?: string; - proxyURL?: string; -} - -export type RepositoryDataWithId = Required> & RepositoryData; - interface NewRepoProps { - onSuccess: (data: RepositoryDataWithId) => Promise; + onSuccess: (repo: RepoView) => Promise; } const useStyles = makeStyles(styles as any); @@ -55,8 +43,8 @@ const AddRepositoryDialog: React.FC = ({ open, onClose onClose(); }; - const handleSuccess = (data: RepositoryDataWithId) => { - onSuccess(data); + const handleSuccess = (repo: RepoView) => { + onSuccess(repo); setTip(true); }; @@ -67,25 +55,26 @@ const AddRepositoryDialog: React.FC = ({ open, onClose }; const add = async () => { - const data: RepositoryData = { + const repo: RepoView = { project: project.trim(), name: name.trim(), url: url.trim(), - maxUser: 1, + proxyURL: '', + users: { canPush: [], canAuthorise: [] }, }; - if (data.project.length === 0 || data.project.length > 100) { + if (repo.project.length === 0 || repo.project.length > 100) { setError('Project name length must be between 1 and 100 characters'); return; } - if (data.name.length === 0 || data.name.length > 100) { + if (repo.name.length === 0 || repo.name.length > 100) { setError('Repository name length must be between 1 and 100 characters'); return; } try { - const parsedUrl = new URL(data.url); + const parsedUrl = new URL(repo.url); if (!parsedUrl.pathname.endsWith('.git')) { setError('Invalid git URL - Git URLs should end with .git'); return; @@ -95,7 +84,7 @@ const AddRepositoryDialog: React.FC = ({ open, onClose return; } - const result = await addRepo(data); + const result = await addRepo(repo); if (result.success && result.repo) { handleSuccess(result.repo); handleClose(); diff --git a/src/ui/views/RepoList/Components/RepoOverview.tsx b/src/ui/views/RepoList/Components/RepoOverview.tsx index 2191c05db..4c647fb8a 100644 --- a/src/ui/views/RepoList/Components/RepoOverview.tsx +++ b/src/ui/views/RepoList/Components/RepoOverview.tsx @@ -5,9 +5,13 @@ import GridItem from '../../../components/Grid/GridItem'; import { CodeReviewIcon, LawIcon, PeopleIcon } from '@primer/octicons-react'; import CodeActionButton from '../../../components/CustomButtons/CodeActionButton'; import { languageColors } from '../../../../constants/languageColors'; -import { RepositoriesProps } from '../repositories.types'; +import { RepoView, SCMRepositoryMetadata } from '../../../types'; import { fetchRemoteRepositoryData } from '../../../utils'; -import { SCMRepositoryMetadata } from '../../../../types/models'; + +export interface RepositoriesProps { + repo: RepoView; + [key: string]: unknown; +} const Repositories: React.FC = (props) => { const [remoteRepoData, setRemoteRepoData] = React.useState(null); @@ -16,24 +20,24 @@ const Repositories: React.FC = (props) => { useEffect(() => { prepareRemoteRepositoryData(); - }, [props.data.project, props.data.name, props.data.url]); + }, [props.repo.project, props.repo.name, props.repo.url]); const prepareRemoteRepositoryData = async () => { try { - const { url: remoteUrl } = props.data; + const { url: remoteUrl } = props.repo; if (!remoteUrl) return; setRemoteRepoData( - await fetchRemoteRepositoryData(props.data.project, props.data.name, remoteUrl), + await fetchRemoteRepositoryData(props.repo.project, props.repo.name, remoteUrl), ); } catch (error: any) { console.warn( - `Unable to fetch repository data for ${props.data.project}/${props.data.name} from '${remoteUrl}' - this may occur if the project is private or from an SCM vendor that is not supported.`, + `Unable to fetch repository data for ${props.repo.project}/${props.repo.name} from '${remoteUrl}' - this may occur if the project is private or from an SCM vendor that is not supported.`, ); } }; - const { url: remoteUrl, proxyURL } = props?.data || {}; + const { url: remoteUrl, proxyURL } = props?.repo || {}; const parsedUrl = new URL(remoteUrl); const cloneURL = `${proxyURL}/${parsedUrl.host}${parsedUrl.port ? `:${parsedUrl.port}` : ''}${parsedUrl.pathname}`; @@ -41,9 +45,9 @@ const Repositories: React.FC = (props) => {
- + - {props.data.project}/{props.data.name} + {props.repo.project}/{props.repo.name} {remoteRepoData?.parentName && ( @@ -93,12 +97,12 @@ const Repositories: React.FC = (props) => { )} {' '} - {props.data?.users?.canPush?.length || 0} + {props.repo?.users?.canPush?.length || 0} {' '} - {props.data?.users?.canAuthorise?.length || 0} + {props.repo?.users?.canAuthorise?.length || 0} {remoteRepoData?.lastUpdated && ( diff --git a/src/ui/views/RepoList/Components/Repositories.tsx b/src/ui/views/RepoList/Components/Repositories.tsx index fe93eb766..a72cd2fc5 100644 --- a/src/ui/views/RepoList/Components/Repositories.tsx +++ b/src/ui/views/RepoList/Components/Repositories.tsx @@ -8,9 +8,10 @@ import styles from '../../../assets/jss/material-dashboard-react/views/dashboard import { getRepos } from '../../../services/repo'; import GridContainer from '../../../components/Grid/GridContainer'; import GridItem from '../../../components/Grid/GridItem'; -import NewRepo, { RepositoryDataWithId } from './NewRepo'; +import NewRepo from './NewRepo'; +import { RepoView } from '../../../types'; import RepoOverview from './RepoOverview'; -import { UserContext } from '../../../../context'; +import { UserContext, UserContextType } from '../../../context'; import Search from '../../../components/Search/Search'; import Pagination from '../../../components/Pagination/Pagination'; import Filtering, { FilterOption, SortOrder } from '../../../components/Filtering/Filtering'; @@ -19,7 +20,7 @@ import Danger from '../../../components/Typography/Danger'; interface GridContainerLayoutProps { classes: any; openRepo: (repo: string) => void; - data: RepositoryDataWithId[]; + repos: RepoView[]; repoButton: React.ReactNode; onSearch: (query: string) => void; currentPage: number; @@ -31,18 +32,11 @@ interface GridContainerLayoutProps { key: string; } -interface UserContextType { - user: { - admin: boolean; - [key: string]: any; - }; -} - export default function Repositories(): React.ReactElement { const useStyles = makeStyles(styles as any); const classes = useStyles(); - const [data, setData] = useState([]); - const [filteredData, setFilteredData] = useState([]); + const [repos, setRepos] = useState([]); + const [filteredRepos, setFilteredRepos] = useState([]); const [, setAuth] = useState(true); const [isLoading, setIsLoading] = useState(false); const [isError, setIsError] = useState(false); @@ -57,9 +51,9 @@ export default function Repositories(): React.ReactElement { useEffect(() => { getRepos( setIsLoading, - (data: RepositoryDataWithId[]) => { - setData(data); - setFilteredData(data); + (repos: RepoView[]) => { + setRepos(repos); + setFilteredRepos(repos); }, setAuth, setIsError, @@ -67,20 +61,20 @@ export default function Repositories(): React.ReactElement { ); }, []); - const refresh = async (repo: RepositoryDataWithId): Promise => { - const updatedData = [...data, repo]; - setData(updatedData); - setFilteredData(updatedData); + const refresh = async (repo: RepoView): Promise => { + const updatedRepos = [...repos, repo]; + setRepos(updatedRepos); + setFilteredRepos(updatedRepos); }; const handleSearch = (query: string): void => { setCurrentPage(1); if (!query) { - setFilteredData(data); + setFilteredRepos(repos); } else { const lowercasedQuery = query.toLowerCase(); - setFilteredData( - data.filter( + setFilteredRepos( + repos.filter( (repo) => repo.name.toLowerCase().includes(lowercasedQuery) || repo.project.toLowerCase().includes(lowercasedQuery), @@ -90,35 +84,35 @@ export default function Repositories(): React.ReactElement { }; const handleFilterChange = (filterOption: FilterOption, sortOrder: SortOrder): void => { - const sortedData = [...data]; + const sortedRepos = [...repos]; switch (filterOption) { case 'Date Modified': - sortedData.sort( + sortedRepos.sort( (a, b) => new Date(a.lastModified || 0).getTime() - new Date(b.lastModified || 0).getTime(), ); break; case 'Date Created': - sortedData.sort( + sortedRepos.sort( (a, b) => new Date(a.dateCreated || 0).getTime() - new Date(b.dateCreated || 0).getTime(), ); break; case 'Alphabetical': - sortedData.sort((a, b) => a.name.localeCompare(b.name)); + sortedRepos.sort((a, b) => a.name.localeCompare(b.name)); break; default: break; } if (sortOrder === 'desc') { - sortedData.reverse(); + sortedRepos.reverse(); } - setFilteredData(sortedData); + setFilteredRepos(sortedRepos); }; const handlePageChange = (page: number): void => setCurrentPage(page); const startIdx = (currentPage - 1) * itemsPerPage; - const paginatedData = filteredData.slice(startIdx, startIdx + itemsPerPage); + const paginatedRepos = filteredRepos.slice(startIdx, startIdx + itemsPerPage); if (isLoading) return
Loading...
; if (isError) return {errorMessage}; @@ -135,11 +129,11 @@ export default function Repositories(): React.ReactElement { key: 'x', classes: classes, openRepo: openRepo, - data: paginatedData, + repos: paginatedRepos, repoButton: addrepoButton, onSearch: handleSearch, currentPage: currentPage, - totalItems: filteredData.length, + totalItems: filteredRepos.length, itemsPerPage: itemsPerPage, onPageChange: handlePageChange, onFilterChange: handleFilterChange, @@ -159,10 +153,13 @@ function getGridContainerLayOut(props: GridContainerLayoutProps): React.ReactEle > - {props.data.map((row) => { - if (row.url) { + {props.repos.map((repo) => { + if (repo.url) { return ( - + ); } return null; diff --git a/src/ui/views/RepoList/repositories.types.ts b/src/ui/views/RepoList/repositories.types.ts deleted file mode 100644 index 2e7660147..000000000 --- a/src/ui/views/RepoList/repositories.types.ts +++ /dev/null @@ -1,15 +0,0 @@ -export interface RepositoriesProps { - data: { - _id: string; - project: string; - name: string; - url: string; - proxyURL: string; - users?: { - canPush?: string[]; - canAuthorise?: string[]; - }; - }; - - [key: string]: unknown; -} diff --git a/src/ui/views/User/UserProfile.tsx b/src/ui/views/User/UserProfile.tsx index 89b8a1bf9..93d468980 100644 --- a/src/ui/views/User/UserProfile.tsx +++ b/src/ui/views/User/UserProfile.tsx @@ -7,16 +7,15 @@ import CardBody from '../../components/Card/CardBody'; import Button from '../../components/CustomButtons/Button'; import FormLabel from '@material-ui/core/FormLabel'; import { getUser, updateUser } from '../../services/user'; -import { UserContext } from '../../../context'; +import { UserContext, UserContextType } from '../../context'; -import { UserData } from '../../../types/models'; +import { PublicUser } from '../../../db/types'; import { makeStyles } from '@material-ui/core/styles'; import { LogoGithubIcon } from '@primer/octicons-react'; import CloseRounded from '@material-ui/icons/CloseRounded'; import { Check, Save } from '@material-ui/icons'; import { TextField, Theme } from '@material-ui/core'; -import { UserContextType } from '../RepoDetails/RepoDetails'; const useStyles = makeStyles((theme: Theme) => ({ root: { @@ -29,7 +28,7 @@ const useStyles = makeStyles((theme: Theme) => ({ export default function UserProfile(): React.ReactElement { const classes = useStyles(); - const [data, setData] = useState(null); + const [user, setUser] = useState(null); const [auth, setAuth] = useState(true); const [isLoading, setIsLoading] = useState(true); const [isError, setIsError] = useState(false); @@ -42,9 +41,9 @@ export default function UserProfile(): React.ReactElement { useEffect(() => { getUser( setIsLoading, - (userData: UserData) => { - setData(userData); - setGitAccount(userData.gitAccount || ''); + (user: PublicUser) => { + setUser(user); + setGitAccount(user.gitAccount || ''); }, setAuth, setIsError, @@ -58,16 +57,16 @@ export default function UserProfile(): React.ReactElement { if (!auth && window.location.pathname === '/dashboard/profile') { return ; } - if (!data) return
No user data available
; + if (!user) return
No user data available
; const updateProfile = async (): Promise => { try { const updatedData = { - ...data, + ...user, gitAccount: escapeHTML(gitAccount), }; await updateUser(updatedData); - setData(updatedData); + setUser(updatedData); navigate(`/dashboard/profile`); } catch { setIsError(true); @@ -107,43 +106,43 @@ export default function UserProfile(): React.ReactElement { paddingTop: '10px', }} > - {data.gitAccount && ( + {user.gitAccount && ( {`${data.displayName}'s )} Name - {data.displayName} + {user.displayName} Role - {data.title} + {user.title} E-mail - {data.email} + {user.email} - {data.gitAccount && ( + {user.gitAccount && ( GitHub Username - {data.gitAccount} + {user.gitAccount} )} Administrator - {data.admin ? ( + {user.admin ? ( diff --git a/src/ui/views/UserList/Components/UserList.tsx b/src/ui/views/UserList/Components/UserList.tsx index ac98fe7a1..94b8fecb2 100644 --- a/src/ui/views/UserList/Components/UserList.tsx +++ b/src/ui/views/UserList/Components/UserList.tsx @@ -17,13 +17,13 @@ import Pagination from '../../../components/Pagination/Pagination'; import { CloseRounded, Check, KeyboardArrowRight } from '@material-ui/icons'; import Search from '../../../components/Search/Search'; import Danger from '../../../components/Typography/Danger'; -import { UserData } from '../../../../types/models'; +import { PublicUser } from '../../../../db/types'; const useStyles = makeStyles(styles as any); const UserList: React.FC = () => { const classes = useStyles(); - const [data, setData] = useState([]); + const [users, setUsers] = useState([]); const [, setAuth] = useState(true); const [isLoading, setIsLoading] = useState(false); const [errorMessage, setErrorMessage] = useState(''); @@ -35,13 +35,13 @@ const UserList: React.FC = () => { const openUser = (username: string) => navigate(`/dashboard/user/${username}`, { replace: true }); useEffect(() => { - getUsers(setIsLoading, setData, setAuth, setErrorMessage); + getUsers(setIsLoading, setUsers, setAuth, setErrorMessage); }, []); if (isLoading) return
Loading...
; if (errorMessage) return {errorMessage}; - const filteredUsers = data.filter( + const filteredUsers = users.filter( (user) => (user.displayName && user.displayName.toLowerCase().includes(searchQuery.toLowerCase())) || (user.username && user.username.toLowerCase().includes(searchQuery.toLowerCase())), @@ -78,24 +78,24 @@ const UserList: React.FC = () => { - {currentItems.map((row) => ( - - {row.displayName} - {row.title} + {currentItems.map((user) => ( + + {user.displayName} + {user.title} - {row.email} + {user.email} - {row.gitAccount} + {user.gitAccount} - {row.admin ? ( + {user.admin ? ( ) : ( @@ -105,7 +105,7 @@ const UserList: React.FC = () => {