react-router-dom#Navigate JavaScript Examples
The following examples show how to use
react-router-dom#Navigate.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: routes.jsx From ResoBin with MIT License | 6 votes |
DashboardRoutes = () => (
<AnimatedRoutes>
<Route path="/" element={<Home />} />
<Route path="/courses">
<Route path="" element={<CourseFinder />} />
<Route path=":code">
<Route path="" element={<CoursePage />} />
<Route path=":titleSlug" element={<CoursePage />} />
</Route>
</Route>
<Route path="/contribute" element={<Contribute />} />
<Route path="/favourites" element={<Favourites />} />
<Route path="/settings" element={<Settings />} />
<Route path="/contact" element={<Contact />} />
<Route path="/timetable">
<Route path="" element={<Timetable />} />
<Route path="share" element={<TimetableShare />} />
</Route>
<Route path="/logout" element={<Logout />} />
<Route path="/404" element={<NotFound />} />
<Route path="*" element={<Navigate to="/404" replace />} />
</AnimatedRoutes>
)
Example #2
Source File: Shell.js From live-micro-frontends-module-federation-2021-03-18 with MIT License | 6 votes |
Shell = () => (
<ServiceProvider>
<BrowserRouter>
<AppBar />
<div className="container mt-24">
<React.Suspense fallback={"Loading"}>
<Routes>
<Route path="list/*" element={<ProductList />} />
<Route path="detail/*" element={<ProductDetails />} />
<Route path="*" element={<Navigate to="/list" replace />} />
</Routes>
</React.Suspense>
</div>
</BrowserRouter>
</ServiceProvider>
)
Example #3
Source File: Shell.js From live-micro-frontends-module-federation-2021-03-18 with MIT License | 6 votes |
Shell = () => (
<ServiceProvider>
<BrowserRouter>
<AppBar />
<div className="container mt-24">
<React.Suspense fallback={"Loading"}>
<Routes>
<Route path="list/*" element={<ProductList />} />
<Route path="detail/*" element={<ProductDetails />} />
<Route path="*" element={<Navigate to="/list" replace />} />
</Routes>
</React.Suspense>
</div>
</BrowserRouter>
</ServiceProvider>
)
Example #4
Source File: App.js From pro-organiser-application with MIT License | 6 votes |
function App() {
return (
<AuthProvider>
<Router>
<Header />
<Routes>
<Route
exact
path="/"
element={
<PrivateRoute>
<Home />
</PrivateRoute>
}
/>
<Route
path="/createboard"
element={
<PrivateRoute>
<AddBoard />
</PrivateRoute>
}
/>
<Route
path="/board/:name"
element={
<PrivateRoute>
<Board />
</PrivateRoute>
}
/>
<Route path="/signup" element={<SignUp />} />
<Route path="/login" element={<Login />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</Router>
</AuthProvider>
);
}
Example #5
Source File: PrivateRoute.js From pro-organiser-application with MIT License | 6 votes |
PrivateRoute = ({ children }) => {
const { currentUser } = useContext(AuthContext);
let location = useLocation();
if (!currentUser) {
return <Navigate to={'/login'} state={{ from: location }} replace />;
}
return children;
}
Example #6
Source File: Shell.js From module-federation-examples with MIT License | 6 votes |
export default function Shell() {
const drawer = useDrawer();
return (
<ServiceProvider>
<BrowserRouter>
<Viewport>
<Box display="flex" flex={1}>
<AppBar drawer={drawer} />
<AppDrawer drawer={drawer} />
<React.Suspense fallback={'Loading'}>
<Routes>
<Route path="dashboard/*" element={<DashboardService />} />
<Route path="orders/*" element={<OrderService />} />
<Route path="profile/*" element={<ProfilePage />} />
<Route path="*" element={<Navigate to="/dashboard" replace />} />
</Routes>
</React.Suspense>
</Box>
</Viewport>
</BrowserRouter>
</ServiceProvider>
);
}
Example #7
Source File: AuthGuard.jsx From matx-react with MIT License | 6 votes |
AuthGuard = ({ children }) => {
let {
isAuthenticated,
// user
} = useAuth();
const { pathname } = useLocation();
// const routes = flat(AllPages);
// const hasPermission = userHasPermission(pathname, user, routes);
// let authenticated = isAuthenticated && hasPermission;
// // IF YOU NEED ROLE BASED AUTHENTICATION,
// // UNCOMMENT ABOVE LINES
// // AND COMMENT OUT BELOW authenticated VARIABLE
let authenticated = isAuthenticated;
return (
<>
{authenticated ? (
children
) : (
<Navigate replace to="/session/signin" state={{ from: pathname }} />
)}
</>
);
}
Example #8
Source File: routes.js From Django-REST-Framework-React-BoilerPlate with MIT License | 6 votes |
// ----------------------------------------------------------------------
export default function Router() {
return useRoutes([
{
path: '/dashboard',
element: <DashboardLayout />,
children: [
{ path: 'app', element: <DashboardApp /> },
{ path: 'user', element: <User /> },
],
},
{
path: '/',
element: <LogoOnlyLayout />,
children: [
{ path: '/', element: <Navigate to="/dashboard/app" /> },
{ path: 'login', element: <Login /> },
{ path: 'register', element: <Register /> },
{ path: '404', element: <NotFound /> },
{ path: '*', element: <Navigate to="/404" /> },
],
},
{ path: '*', element: <Navigate to="/404" replace /> },
]);
}
Example #9
Source File: PublicRoute.jsx From react-sendbird-messenger with GNU General Public License v3.0 | 6 votes |
export function PublicRoute({ children }) {
let { isAuth } = useAuth()
let location = useLocation()
return isAuth ? (
<Navigate
to={{
pathname: 'dashboard',
state: { from: location },
}}
/>
) : (
children
)
}
Example #10
Source File: PrivateRoute.jsx From react-sendbird-messenger with GNU General Public License v3.0 | 6 votes |
export function PrivateRoute({ children }) {
let { isAuth } = useAuth()
let location = useLocation()
return isAuth ? (
children
) : (
<Navigate
to={{
pathname: '/',
state: { from: location },
}}
/>
)
}
Example #11
Source File: routes.jsx From matx-react with MIT License | 6 votes |
routes = [
{
element: (
<AuthGuard>
<MatxLayout />
</AuthGuard>
),
children: [...dashboardRoutes, ...chartsRoute, ...materialRoutes],
},
...sessionRoutes,
{ path: '/', element: <Navigate to="dashboard/default" /> },
{ path: '*', element: <NotFound /> },
]
Example #12
Source File: PrivateRoute.jsx From ResoBin with MIT License | 6 votes |
PrivateRoute = ({ component: RouteComponent, redirectTo }) => {
const isAuthenticated = useSelector(selectIsAuthenticated)
const dispatch = useDispatch()
const location = useLocation()
useEffect(() => {
dispatch(getAuthStatusAction())
}, [dispatch])
if (isAuthenticated === null) return null
if (isAuthenticated) return <RouteComponent />
return (
<Navigate
to={redirectTo}
replace
state={{
from: location.pathname + location.search + location.hash,
}}
/>
)
}
Example #13
Source File: index.jsx From amazon-ivs-feed-web-demo with MIT No Attribution | 6 votes |
ReactDOM.render( <React.StrictMode> <Router> <MobileBreakpointProvider> <StreamProvider> <Routes> <Route path="/" element={<Navigate replace to="/0" />} /> <Route path="/:id" element={<App />} /> </Routes> </StreamProvider> </MobileBreakpointProvider> </Router> </React.StrictMode>, document.getElementById('root') );
Example #14
Source File: RequireAuth.js From citu-api with MIT License | 6 votes |
RequireAuth = ({ allowedRoles }) => {
const { auth } = useAuth();
const location = useLocation();
return (
auth?.user
? <Outlet />
: <Navigate to="/login" state={{ from: location }} replace />
);
}
Example #15
Source File: routes.js From course-manager with MIT License | 6 votes |
// ----------------------------------------------------------------------
export default function Router() {
return useRoutes([
{
path: '/dashboard',
element: <DashboardLayout />,
children: [
{ path: '/', element: <Navigate to="/dashboard/app" replace /> },
{ path: 'app', element: <DashboardApp /> },
{
path: 'user',
element: <UserList />
},
{
path: 'user/create',
element: <UserCreate />
},
{ path: 'courses', element: <CourseList /> },
{ path: 'courses/create', element: <CourseCreate /> },
{ path: 'courses/:id', element: <CourseEdit /> },
{ path: 'blog', element: <Blog /> }
]
},
{
path: '/',
element: <LogoOnlyLayout />,
children: [
{ path: 'login', element: <Login /> },
{ path: 'register', element: <Register /> },
{ path: '404', element: <NotFound /> },
{ path: '/', element: <Navigate to="/dashboard" /> },
{ path: '*', element: <Navigate to="/404" /> }
]
},
{ path: '*', element: <Navigate to="/404" replace /> }
]);
}
Example #16
Source File: CoursePage.jsx From ResoBin with MIT License | 5 votes |
CoursePage = () => {
const location = useLocation()
const { code, titleSlug } = useParams()
const [courseData, setCourseData] = useState({})
const [loading, setLoading] = useState(true)
useEffect(() => {
const getCourseData = async () => {
try {
setLoading(true)
const response = await API.courses.read({ code })
setCourseData(response)
} catch (error) {
toast({ status: 'error', content: error })
} finally {
setLoading(false)
}
}
getCourseData()
}, [code])
if (loading) return <LoaderAnimation />
if (isEmpty(courseData)) return <Navigate to="/404" replace />
// ? redirect to canonical URL (eg: /courses/CL152/introduction-to-chemical-engineering)
if (titleSlug !== kebabCase(courseData.title)) {
const pathname = coursePageUrl(courseData.code, courseData.title)
return <Navigate to={{ ...location, pathname }} replace />
}
return (
<PageContainer>
<Helmet>
<title>{`${courseData.code}: ${courseData.title} - ResoBin`}</title>
<meta property="description" content={courseData.description} />
</Helmet>
<CoursePageContainer courseData={courseData} />
</PageContainer>
)
}
Example #17
Source File: Details.js From web-client with Apache License 2.0 | 5 votes |
ReportTemplateDetails = () => {
const navigate = useNavigate();
const { templateId } = useParams();
const [vulnerability] = useFetch(`/vulnerabilities/${templateId}`)
const cloneProject = async (templateId) => {
secureApiFetch(`/vulnerabilities/${templateId}/clone`, { method: 'POST' })
.then(resp => resp.json())
.then(data => {
navigate(`/vulnerabilities/${data.vulnerabilityId}/edit`);
});
}
const destroy = useDelete('/vulnerabilities/', () => {
navigate('/vulnerabilities/templates');
});
if (!vulnerability) return <Loading />
if (vulnerability && !vulnerability.is_template) {
return <Navigate to={`/vulnerabilities/${vulnerability.id}`} />
}
return (
<>
<div>
<div className='heading'>
<Breadcrumb>
<Link to="/vulnerabilities">Vulnerabilities</Link>
<Link to="/vulnerabilities/templates">Templates</Link>
</Breadcrumb>
<ButtonGroup>
<PrimaryButton onClick={() => cloneProject(vulnerability.id)} leftIcon={<IconPlusCircle />}>Clone and edit</PrimaryButton>
<RestrictedComponent roles={['administrator', 'superuser', 'user']}>
<LinkButton href={`/vulnerabilities/${vulnerability.id}/edit`}>Edit</LinkButton>
<DeleteButton onClick={() => destroy(vulnerability.id)} />
</RestrictedComponent>
</ButtonGroup>
</div>
<article>
<PageTitle value={`${vulnerability.summary} vulnerability template`} />
<Title type='Vulnerability template' title={vulnerability.summary} icon={<IconFlag />} />
<Tabs>
<TabList>
<Tab>Description</Tab>
<Tab>Remediation</Tab>
</TabList>
<TabPanels>
<TabPanel>
</TabPanel>
<TabPanel>
</TabPanel>
</TabPanels>
</Tabs>
</article>
</div>
</>
)
}
Example #18
Source File: Details.js From web-client with Apache License 2.0 | 5 votes |
VulnerabilityTemplateDetails = () => {
const navigate = useNavigate();
const { templateId } = useParams();
const [vulnerability] = useFetch(`/vulnerabilities/${templateId}`)
const cloneProject = async (templateId) => {
secureApiFetch(`/vulnerabilities/${templateId}/clone`, { method: 'POST' })
.then(resp => resp.json())
.then(data => {
navigate(`/vulnerabilities/${data.vulnerabilityId}/edit`);
});
}
const destroy = useDelete('/vulnerabilities/', () => {
navigate('/vulnerabilities/templates');
});
if (!vulnerability) return <Loading />
if (vulnerability && !vulnerability.is_template) {
return <Navigate to={`/vulnerabilities/${vulnerability.id}`} />
}
return (
<>
<div>
<div className='heading'>
<Breadcrumb>
<Link to="/vulnerabilities">Vulnerabilities</Link>
<Link to="/vulnerabilities/templates">Templates</Link>
</Breadcrumb>
<ButtonGroup>
<PrimaryButton onClick={() => cloneProject(vulnerability.id)} leftIcon={<IconPlusCircle />}>Clone and edit</PrimaryButton>
<RestrictedComponent roles={['administrator', 'superuser', 'user']}>
<LinkButton href={`/vulnerabilities/${vulnerability.id}/edit`}>Edit</LinkButton>
<DeleteButton onClick={() => destroy(vulnerability.id)} />
</RestrictedComponent>
</ButtonGroup>
</div>
<article>
<PageTitle value={`${vulnerability.summary} vulnerability template`} />
<Title type='Vulnerability template' title={vulnerability.summary} icon={<IconFlag />} />
<Tabs>
<TabList>
<Tab>Description</Tab>
<Tab>Remediation</Tab>
</TabList>
<TabPanels>
<TabPanel>
<VulnerabilityDescriptionPanel vulnerability={vulnerability} />
</TabPanel>
<TabPanel>
<VulnerabilityRemediationPanel vulnerability={vulnerability} />
</TabPanel>
</TabPanels>
</Tabs>
</article>
</div>
</>
)
}
Example #19
Source File: Home.js From ReactJS-Projects with MIT License | 5 votes |
Home = () => {
const context = useContext(UserContext)
const [query, setQuery] = useState("")
const [user, setUser] = useState(null)
const fetchDetails = async () => {
try {
const { data } = await Axios.get(`https://api.github.com/users/${query}`)
setUser(data)
console.log(data)
} catch (err) {
toast("Unable to locate the user", {
type: "error"
})
}
}
if (!context.user?.uid) {
return <Navigate to="/signin" />
}
return (
<Container>
<Row className=" mt-3">
<Col md="5">
<InputGroup>
<Input
type="text"
value={query}
placeholder="Please provide the username"
onChange={e => setQuery(e.target.value)}
/>
<InputGroupAddon addonType="append">
<Button onClick={fetchDetails} color="primary">Fetch User</Button>
</InputGroupAddon>
</InputGroup>
{user ?
<UserCard user={user} /> :
null
}
</Col>
<Col md="7">
{user ? <Details apiUrl={user.repos_url} /> : null}
</Col>
</Row>
</Container>
);
}
Example #20
Source File: Details.js From web-client with Apache License 2.0 | 5 votes |
TemplateDetails = () => {
const navigate = useNavigate();
const { templateId } = useParams();
const [template] = useFetch(`/projects/${templateId}`)
const cloneProject = async (templateId) => {
secureApiFetch(`/projects/${templateId}/clone`, { method: 'POST' })
.then(resp => resp.json())
.then(data => {
navigate(`/projects/${data.projectId}/edit`);
});
}
const destroy = useDelete('/projects/', () => {
navigate('/projects/templates');
});
if (template && !template.is_template) {
return <Navigate to={`/projects/${template.id}`} />
}
return <>
<div className='heading'>
<Breadcrumb>
<Link to="/projects">Projects</Link>
<Link to="/projects/templates">Templates</Link>
</Breadcrumb>
{template &&
<ButtonGroup>
<PrimaryButton onClick={() => cloneProject(template.id)} leftIcon={<IconPlusCircle />}>Create project from template</PrimaryButton>
<LinkButton href={`/projects/${template.id}/edit`}>Edit</LinkButton>
<DeleteButton onClick={() => destroy(template.id)} />
</ButtonGroup>
}
</div>
{!template ?
<Loading /> :
<article>
<PageTitle value={`${template.name} project template`} />
<Title title={template.name} type='Project template' icon={<IconFolder />} />
<Tabs>
<TabList>
<Tab>Details</Tab>
<Tab>Tasks</Tab>
</TabList>
<TabPanels>
<TabPanel><ProjectDetailsTab project={template} /></TabPanel>
<TabPanel><ProjectTasks project={template} /></TabPanel>
</TabPanels>
</Tabs>
</article>}
</>
}
Example #21
Source File: Enrollment.js From datapass with GNU Affero General Public License v3.0 | 5 votes |
Enrollment = () => {
const { enrollmentId } = useParams();
const [fetchEnrollmentError, setFetchEnrollmentError] = useState(false);
const [fetchEnrollmentNotFound, setFetchEnrollmentNotFound] = useState(false);
const [targetApi, setTargetApi] = useState(null);
const fetchEnrollment = async ({ enrollmentId }) => {
try {
setFetchEnrollmentError(false);
setFetchEnrollmentNotFound(false);
const { target_api } = await getUserEnrollment(enrollmentId);
setTargetApi(target_api);
} catch (e) {
if (e.response && e.response.status === 404) {
setFetchEnrollmentNotFound(true);
} else {
setFetchEnrollmentError(true);
}
}
};
useEffect(() => {
if (enrollmentId) {
fetchEnrollment({ enrollmentId });
}
}, [enrollmentId]);
if (enrollmentId && targetApi) {
return (
<Navigate
to={{
pathname: `/${targetApi.replace(/_/g, '-')}/${enrollmentId}`,
}}
replace
/>
);
}
if (fetchEnrollmentNotFound) {
return <NotFound />;
}
if (fetchEnrollmentError) {
return (
<div className="full-page">
<Alert title="Erreur" type="error">
Erreur inconnue lors de la récupération de l’habilitation.
</Alert>
</div>
);
}
return (
<div className="full-page">
<Loader />
</div>
);
}
Example #22
Source File: CopyEnrollment.js From datapass with GNU Affero General Public License v3.0 | 5 votes |
CopyEnrollment = () => {
const { enrollmentId } = useParams();
const [copyErrorMessage, setCopyErrorMessage] = useState(null);
const [copiedEnrollmentId, setCopiedEnrollmentId] = useState(null);
const [copiedTargetApi, setCopiedTargetApi] = useState(null);
const triggerEnrollmentCopy = async ({ enrollmentId }) => {
try {
setCopyErrorMessage(null);
const { id, target_api } = await copyEnrollment({
id: enrollmentId,
});
setCopiedEnrollmentId(id);
setCopiedTargetApi(target_api);
} catch (e) {
if (getErrorMessages(e)[0]) {
setCopyErrorMessage(getErrorMessages(e)[0]);
} else {
setCopyErrorMessage(
'Erreur inconnue lors de la copie de l’habilitation.'
);
}
}
};
useEffect(() => {
if (enrollmentId) {
triggerEnrollmentCopy({ enrollmentId });
}
}, [enrollmentId]);
if (copiedEnrollmentId && copiedTargetApi) {
return (
<Navigate
to={{
pathname: `/${copiedTargetApi.replace(
/_/g,
'-'
)}/${copiedEnrollmentId}`,
state: { source: 'copy-authorization-request' },
}}
replace
/>
);
}
if (copyErrorMessage) {
return (
<div className="full-page">
<Alert title="Erreur" type="error">
<Linkify
message={`${copyErrorMessage} L’habilitation #${enrollmentId} n’a pas été copiée.`}
/>
</Alert>
</div>
);
}
return (
<div className="full-page">
<Loader />
</div>
);
}
Example #23
Source File: Details.js From web-client with Apache License 2.0 | 4 votes |
TemplateDetails = () => {
const navigate = useNavigate();
const { templateId } = useParams();
const [vulnerability] = useFetch(`/vulnerabilities/${templateId}`)
const cloneProject = async (templateId) => {
secureApiFetch(`/vulnerabilities/${templateId}/clone`, { method: 'POST' })
.then(resp => resp.json())
.then(data => {
navigate(`/vulnerabilities/${data.vulnerabilityId}/edit`);
});
}
const destroy = useDelete('/vulnerabilities/', () => {
navigate('/vulnerabilities/templates');
});
if (!vulnerability) return <Loading />
if (vulnerability && !vulnerability.is_template) {
return <Navigate to={`/vulnerabilities/${vulnerability.id}`} />
}
return (
<>
<div>
<div className='heading'>
<Breadcrumb>
<Link to="/vulnerabilities">Vulnerabilities</Link>
<Link to="/vulnerabilities/templates">Templates</Link>
</Breadcrumb>
<ButtonGroup>
<PrimaryButton onClick={() => cloneProject(vulnerability.id)} leftIcon={<IconPlusCircle />}> Clone and edit</PrimaryButton>
<RestrictedComponent roles={['administrator', 'superuser', 'user']}>
<LinkButton href={`/vulnerabilities/${vulnerability.id}/edit`}>Edit</LinkButton>
<DeleteButton onClick={() => destroy(vulnerability.id)} />
</RestrictedComponent>
</ButtonGroup>
</div>
<article>
<PageTitle value={`${vulnerability.summary} vulnerability template`} />
<Title type='Vulnerability template' title={vulnerability.summary} icon={<IconFlag />} />
<div className="grid grid-two">
<div>
<h4>Description</h4>
{vulnerability.description ? <ReactMarkdown>{vulnerability.description}</ReactMarkdown> : <EmptyField />}
{vulnerability.solution &&
<>
<h4>Solution</h4>
<ReactMarkdown>{vulnerability.solution}</ReactMarkdown>
</>
}
<h4>Proof of concept</h4>
{vulnerability.proof_of_concept ? <ReactMarkdown>{vulnerability.proof_of_concept}</ReactMarkdown> : <EmptyField />}
<h4>Impact</h4>
{vulnerability.impact ? <ReactMarkdown>{vulnerability.impact}</ReactMarkdown> : <EmptyField />}
<h4>Properties</h4>
<dl>
<dt>Status</dt>
<dd><VulnerabilityStatusBadge vulnerability={vulnerability} /></dd>
<dt>Risk</dt>
<dd><RiskBadge risk={vulnerability.risk} /></dd>
<dt>Category</dt>
<dd>{vulnerability.category_name || '-'}</dd>
<dt><CvssAbbr /> score</dt>
<dd><CvssScore score={vulnerability.cvss_score} /></dd>
<dt>CVSS vector</dt>
<dd><ExternalLink
href={`https://www.first.org/cvss/calculator/3.0#${vulnerability.cvss_vector}`}>{vulnerability.cvss_vector}</ExternalLink>
</dd>
</dl>
</div>
<div>
<h4>Relations</h4>
<dl>
<dt>Created by</dt>
<dd><UserLink userId={vulnerability.creator_uid}>{vulnerability.creator_full_name}</UserLink></dd>
</dl>
<TimestampsSection entity={vulnerability} />
</div>
</div>
</article>
</div>
</>
)
}
Example #24
Source File: Details.js From web-client with Apache License 2.0 | 4 votes |
VulnerabilityDetails = () => {
const navigate = useNavigate();
const { vulnerabilityId } = useParams();
const [vulnerability, updateVulnerability] = useFetch(`/vulnerabilities/${vulnerabilityId}`)
const deleteVulnerability = useDelete(`/vulnerabilities/`)
const parentType = 'vulnerability';
const parentId = vulnerabilityId;
const [attachments, reloadAttachments] = useFetch(`/attachments?parentType=${parentType}&parentId=${parentId}`)
const handleDelete = async () => {
const confirmed = await deleteVulnerability(vulnerabilityId);
if (confirmed)
navigate('/vulnerabilities')
}
const onStatusChange = ev => {
const [status, substatus] = ev.target.value.split('-');
secureApiFetch(`/vulnerabilities/${vulnerability.id}`, {
method: 'PATCH',
body: JSON.stringify({ status, substatus })
})
.then(() => {
actionCompletedToast("The status has been transitioned.");
updateVulnerability()
})
.catch(err => console.error(err))
}
if (!vulnerability) return <Loading />
if (vulnerability && vulnerability.is_template) {
return <Navigate to={`/vulnerabilities/templates/${vulnerability.id}`} />
}
return <div>
<div className='heading'>
<Breadcrumb>
<Link to="/vulnerabilities">Vulnerabilities</Link>
</Breadcrumb>
<HStack alignItems='flex-end'>
<RestrictedComponent roles={['administrator', 'superuser', 'user']}>
<EditButton onClick={(ev) => {
ev.preventDefault();
navigate(`/vulnerabilities/${vulnerability.id}/edit`)
}}>Edit</EditButton>
<label>Transition to
<Select onChange={onStatusChange} value={vulnerability.status + '-' + vulnerability.substatus}>
{VulnerabilityStatuses.map(status =>
<option key={`vulnstatus_${status.id}`} value={status.id}>{status.name}</option>
)}
</Select>
</label>
<DeleteButton onClick={handleDelete} />
</RestrictedComponent>
</HStack>
</div>
<article>
<PageTitle value={`${vulnerability.summary} vulnerability`} />
<Title type='Vulnerability' title={vulnerability.external_id ? <><strong>{vulnerability.external_id.toUpperCase()}</strong> {vulnerability.summary}</> : vulnerability.summary} icon={<IconFlag />} />
<Tag size="sm" colorScheme="blue">{vulnerability.visibility}</Tag> <Tags values={vulnerability.tags} />
<Tabs>
<TabList>
<Tab>Description</Tab>
<Tab>Remediation</Tab>
<Tab>Notes</Tab>
<Tab>Attachments</Tab>
</TabList>
<TabPanels>
<TabPanel>
<VulnerabilityDescriptionPanel vulnerability={vulnerability} />
</TabPanel>
<TabPanel>
<VulnerabilityRemediationPanel vulnerability={vulnerability} />
</TabPanel>
<TabPanel>
<VulnerabilitiesNotesTab vulnerability={vulnerability} />
</TabPanel>
<TabPanel>
<AttachmentsDropzone parentType={parentType} parentId={parentId} onUploadFinished={reloadAttachments} />
<h4><IconDocument />Attachment list</h4>
<AttachmentsTable attachments={attachments} reloadAttachments={reloadAttachments} />
</TabPanel>
</TabPanels>
</Tabs>
</article>
</div >
}
Example #25
Source File: Details.js From web-client with Apache License 2.0 | 4 votes |
ProjectDetails = () => {
const navigate = useNavigate();
const { projectId } = useParams();
const { colorMode } = useColorMode()
const [project, updateProject] = useFetch(`/projects/${projectId}`)
const [users] = useFetch(`/projects/${projectId}/users`)
const destroy = useDelete(`/projects/`, updateProject);
const handleGenerateReport = () => {
navigate(`/projects/${project.id}/report`)
}
const handleManageTeam = () => {
navigate(`/projects/${project.id}/membership`)
}
const onArchiveButtonClick = (project) => {
secureApiFetch(`/projects/${project.id}`, {
method: 'PATCH',
body: JSON.stringify({ archived: !project.archived })
})
.then(() => {
updateProject();
actionCompletedToast('The project has been updated.');
})
.catch(err => console.error(err))
}
if (project && project.is_template) {
return <Navigate to={`/projects/templates/${project.id}`} />
}
return <>
<div className='heading'>
<Breadcrumb>
<Link to="/projects">Projects</Link>
</Breadcrumb>
{project && <>
<PageTitle value={`${project.name} project`} />
<ProjectTeam project={project} users={users} />
<ButtonGroup isAttached>
<RestrictedComponent roles={['administrator', 'superuser', 'user']}>
{!project.archived && <>
<LinkButton href={`/projects/${project.id}/edit`}>Edit</LinkButton>
<SecondaryButton onClick={handleGenerateReport} leftIcon={<IconClipboardCheck />}>Report</SecondaryButton>
<SecondaryButton onClick={handleManageTeam} leftIcon={<IconUserGroup />}>Membership</SecondaryButton>
</>}
<Menu>
<MenuButton as={IconButton} aria-label='Options' icon={<FontAwesomeIcon icon={faEllipsis} />} variant='outline' />
<MenuList>
<MenuItem onClick={() => onArchiveButtonClick(project)}>{project.archived ? 'Unarchive' : 'Archive'}</MenuItem>
<MenuItem icon={<FontAwesomeIcon icon={faTrash} />} color={colorMode === "light" ? "red.500" : "red.400"} onClick={() => destroy(project.id)}>Delete</MenuItem>
</MenuList>
</Menu>
</RestrictedComponent>
</ButtonGroup>
</>}
</div>
{!project ? <Loading /> :
<>
<Title title={project.name} type="Project" icon={<IconFolder />} />
<Tabs>
<TabList>
<Tab>Details</Tab>
<Tab>Targets</Tab>
<Tab>Tasks</Tab>
<Tab>Vulnerabilities</Tab>
<Tab>Notes</Tab>
<Tab>Attachments</Tab>
<Tab>Vault</Tab>
</TabList>
<TabPanels>
<TabPanel><ProjectDetailsTab project={project} /></TabPanel>
<TabPanel><ProjectTargets project={project} /></TabPanel>
<TabPanel><ProjectTasks project={project} /></TabPanel>
<TabPanel><ProjectVulnerabilities project={project} /></TabPanel>
<TabPanel><ProjectNotesTab project={project} /></TabPanel>
<TabPanel><ProjectAttachmentsTab project={project} /></TabPanel>
<TabPanel><ProjectVaultTab project={project} /></TabPanel>
</TabPanels>
</Tabs>
</>
}
</>
}
Example #26
Source File: Login.js From pro-organiser-application with MIT License | 4 votes |
Login = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState(null);
const [isLogging, setIsLogging] = useState(false);
let navigate = useNavigate();
function handleLogin() {
if (!email || !password) {
return setError('All fields are required');
}
setIsLogging(true);
firebaseApp
.auth()
.signInWithEmailAndPassword(email, password)
.then(() => {
setIsLogging(false);
navigate('/');
})
.catch((err) => {
setError('Something wrong with your email or Password. Try again!');
setIsLogging(false);
});
}
function handleAlertClose() {
setError('');
}
const { currentUser } = useContext(AuthContext);
const handleGuestLogin = () => {
setIsLogging(true);
const auth = getAuth();
firebaseApp
.auth(auth)
.signInAnonymously()
.then(() => {
setIsLogging(false);
navigate('/');
})
.catch((err) => {
setError('Something wrong with your email or Password. Try again!');
setIsLogging(false);
});
};
if (currentUser) {
return <Navigate to="/" />;
}
return (
<div className={styles.formContainer}>
<div className={styles.formHeader}>Login</div>
{error && (
<Alert type="error" canClose={handleAlertClose}>
{error}
</Alert>
)}
<div className={styles.formGroup}>
<label htmlFor="email">Email</label>
<input
type="email"
name="email"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="[email protected]"
/>
</div>
<div className={styles.formGroup}>
<label htmlFor="password">Password</label>
<input
type="password"
name="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="******"
/>
</div>
<div className={styles.formGroup}>
<button
className={commonStyle.info}
disabled={isLogging}
onClick={handleLogin}
>
{isLogging ? 'Logging in..' : 'Login'}
</button>
</div>
<div className={styles.meta}>
Dont have an account? <Link to="/signup">Sign up</Link>.
</div>
<div className={styles.meta}>
Just want to check the website?{' '}
<button onClick={handleGuestLogin}>Continue as guest</button>
</div>
</div>
);
}
Example #27
Source File: SignUp.js From pro-organiser-application with MIT License | 4 votes |
SignUp = () => {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState(null);
let navigate = useNavigate();
function handleSignUp() {
if (!email || !password || !name) {
return setError('All fields are required');
}
firebaseApp
.auth()
.createUserWithEmailAndPassword(email, password)
.then(() => {
const user = firebaseApp.auth().currentUser;
user
.updateProfile({ displayName: name })
.then(() => {
navigate('/');
})
.catch((err) => {
throw Error(err);
});
})
.catch((err) => {
setError(err.message);
});
}
function handleAlertClose() {
setError('');
}
const { currentUser } = useContext(AuthContext);
if (currentUser) {
return <Navigate to="/" />;
}
return (
<div className={styles.formContainer}>
<div className={styles.formHeader}>Getting started</div>
{error && (
<Alert type="error" canClose={handleAlertClose}>
{error}
</Alert>
)}
<div className={styles.formGroup}>
<label htmlFor="name">Name</label>
<input
type="text"
name="name"
id="name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Your Name"
/>
</div>
<div className={styles.formGroup}>
<label htmlFor="email">Email</label>
<input
type="email"
name="email"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="[email protected]"
/>
</div>
<div className={styles.formGroup}>
<label htmlFor="password">Password</label>
<input
type="password"
name="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="******"
/>
</div>
<div className={styles.formGroup}>
<button className={commonStyle.info} onClick={handleSignUp}>
Sign Up
</button>
</div>
<div className={styles.meta}>
Have an account? <Link to="/login">login now</Link>.
</div>
</div>
);
}
Example #28
Source File: ProtectedRoutes.js From radio-logger with GNU General Public License v3.0 | 4 votes |
ProtectedRoute = ({ auth, component: Component, ...rest }) => {
var login = localStorage.getItem('token');
return auth === true ? <Outlet /> : <Navigate to='/' replace />;
}
Example #29
Source File: Signup.js From ReactJS-Projects with MIT License | 4 votes |
Signup = () => {
const context = useContext(UserContext)
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
const handleSignup = () => {
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then(res => {
console.log(res)
context.setUser({
email: res.user.email,
uid: res.user.uid
})
})
.catch(err => {
console.log(err);
toast(err.message, {
type: 'error'
})
})
}
const handleFormSubmit = e => {
e.preventDefault()
handleSignup()
}
if (context.user?.uid) {
return (
<Navigate to="/" replace />
)
}
return (
<Container className='text-center'>
<Row>
<Col lg={6} className='offset-lg-3 mt-5'>
<Card>
<Form onSubmit={handleFormSubmit}>
<CardHeader className=''>SignUp here</CardHeader>
<CardBody>
<FormGroup row>
<Label for='email' sm={3}>
Email
</Label>
<Col sm={9}>
<Input
type='email'
name='email'
id='email'
placeholder='Your Email'
value={email}
onChange={e => setEmail(e.target.value)}
/>
</Col>
</FormGroup>
<FormGroup row>
<Label for='password' sm={3}>
Password
</Label>
<Col sm={9}>
<Input
type='password'
name='password'
id='password'
placeholder='Your Password'
value={password}
onChange={e => setPassword(e.target.value)}
/>
</Col>
</FormGroup>
</CardBody>
<CardFooter>
<Button type='submit' block color='primary'>
Sign Up
</Button>
</CardFooter>
</Form>
</Card>
</Col>
</Row>
</Container>
);
}