Skip to content

Commit

Permalink
fix: token bug and remove console.logs (keephq#159)
Browse files Browse the repository at this point in the history
  • Loading branch information
talboren authored Jun 4, 2023
1 parent 4868ef2 commit d60ff4c
Show file tree
Hide file tree
Showing 15 changed files with 172 additions and 155 deletions.
30 changes: 16 additions & 14 deletions keep-ui/app/github-post-installation/page.tsx
Original file line number Diff line number Diff line change
@@ -1,34 +1,36 @@
import { getServerSession } from "../../utils/customAuth";
import { redirect } from 'next/navigation';
import { redirect } from "next/navigation";
import { getApiURL } from "../../utils/apiUrl";
export default async function GithubPostInstallationPage({
searchParams,
searchParams,
}: {
searchParams: { installation_id: string, setup_action: string },
searchParams: { installation_id: string; setup_action: string };
}) {
// https://github.com/nextauthjs/next-auth/pull/5792
const accessToken = (await getServerSession({
callbacks: { session: ({ token }) => token },
}))?.accessToken;
const accessToken = (
await getServerSession({
callbacks: { session: ({ token }) => token },
})
)?.accessToken;

let installedSuccessfully = false;
try {
const apiUrl = getApiURL();
installedSuccessfully = await fetch(`${apiUrl}/tenant/github`, {
method: 'POST',
method: "POST",
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify(searchParams)
body: JSON.stringify(searchParams),
})
.then(res => {
.then((res) => {
if (!res.ok) {
throw new Error(`HTTP error ${res.status}`);
}
return res.json();
})
.then(data => data.success);
.then((data) => data.success);

// Handle successful installation
if (installedSuccessfully) {
Expand All @@ -44,5 +46,5 @@ export default async function GithubPostInstallationPage({
}
return <div>502 backend error</div>;
}
redirect('/');
};
redirect("/");
}
5 changes: 3 additions & 2 deletions keep-ui/app/nav.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import Navbar from './navbar';
import { getServerSession } from '../utils/customAuth';
import { authOptions } from '../pages/api/auth/[...nextauth]';

export default async function Nav() {
const session = await getServerSession();
return <Navbar user={session?.user} />;
const session = await getServerSession(authOptions);
return <Navbar session={session} />;
}
9 changes: 5 additions & 4 deletions keep-ui/app/navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,19 @@
import PHProvider from "./posthog-client";
import { SessionProvider } from "next-auth/react";
import NavbarInner from "./navbar-inner";
import { Session } from "next-auth";

const isSingleTenant = process.env.NEXT_PUBLIC_AUTH_ENABLED == "false";

export default function Navbar({ user }: { user: any }) {
export default function Navbar({ session }: { session: Session | null }) {
return isSingleTenant ? (
<PHProvider>
<NavbarInner user={user} />
<NavbarInner user={session?.user} />
</PHProvider>
) : (
<SessionProvider>
<SessionProvider session={session}>
<PHProvider>
<NavbarInner user={user} />
<NavbarInner user={session?.user} />
</PHProvider>
</SessionProvider>
);
Expand Down
6 changes: 2 additions & 4 deletions keep-ui/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,15 @@ import ErrorComponent from "./error";
import PostHogClient from "./posthog-server";
import { getApiURL } from "../utils/apiUrl";
import Frill from "./frill";
import { authOptions } from "../pages/api/auth/[...nextauth]";

export const metadata = {
title: "Keep Console",
description: "Alerting and on-call management for modern engineering teams.",
};

export default async function IndexPage() {
// https://github.com/nextauthjs/next-auth/pull/5792
const accessToken = await getServerSession({
callbacks: { session: ({ token }) => token },
});
const accessToken = await getServerSession(authOptions);

let isGitHubPluginInstalled = false;
try {
Expand Down
19 changes: 6 additions & 13 deletions keep-ui/app/providers/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,17 @@ import { Card, Title, Text } from "@tremor/react";
import ProvidersTable from "./table";
import { getServerSession } from "../../utils/customAuth";
import { getApiURL } from "../../utils/apiUrl";
import { authOptions } from "../../pages/api/auth/[...nextauth]";

export default async function ProvidersPage() {
console.log("Rendering dashboard page");
// get the session so we will be able to pass it to the SessionProvider
const session = await getServerSession();
const session = await getServerSession(authOptions);
// force get session to get a token
const accessToken = (
await getServerSession({
callbacks: { session: ({ token }) => token },
})
)?.accessToken;

let installed_providers = [];
const accessToken = session?.accessToken;
let installedProviders = [];
// Now let's fetch the providers status from the backend
try {
const apiUrl = getApiURL();
installed_providers = await fetch(`${apiUrl}/providers`, {
installedProviders = await fetch(`${apiUrl}/providers`, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
Expand All @@ -31,13 +25,12 @@ export default async function ProvidersPage() {
return <div>502 backend error</div>;
}

console.log("Dashboard | session:", session);
return (
<main className="p-4 md:p-10 mx-auto max-w-7xl">
<Title>Providers</Title>
<Text>Connect providers to Keep to make your alerts better.</Text>
<Card className="mt-6">
<ProvidersTable installed_providers={installed_providers} />
<ProvidersTable session={session} installedProviders={installedProviders} />
</Card>
</main>
);
Expand Down
26 changes: 11 additions & 15 deletions keep-ui/app/providers/provider-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import React, { useState } from "react";
import { useSession } from "../../utils/customAuth";
import { Provider } from "./provider-row";
import { getApiURL } from "../../utils/apiUrl";
import Alert from './alert';
import Alert from "./alert";
import "./provider-form.css";

type ProviderFormProps = {
Expand All @@ -25,16 +25,11 @@ const ProviderForm = ({
});
const [formErrors, setFormErrors] = useState({});
const [testResult, setTestResult] = useState("");
const [connectResult, setConnectResult] = useState("");
const [alertData, setAlertData] = useState([]);
const [isConnected, setIsConnected] = useState(false);

const { data: session, status, update } = useSession();
// @ts-ignore
if (!session?.accessToken) {
console.log("No session access token, refreshing session from the server");
update();
}

// update();
// TODO - fix the typing here
// @ts-ignore
Expand Down Expand Up @@ -121,9 +116,7 @@ const ProviderForm = ({

const handleTestClick = async () => {
try {
const data = await validateAndSubmit(
`${getApiURL()}/providers/test`
);
const data = await validateAndSubmit(`${getApiURL()}/providers/test`);
if (data && data.alerts) {
console.log("Test succeessful");
setTestResult("success");
Expand All @@ -132,7 +125,7 @@ const ProviderForm = ({
setTestResult("error");
}
} catch (error) {
setFormErrors({"error": error.toString()})
setFormErrors({ error: error.toString() });
console.error("Test failed:", error);
}
};
Expand All @@ -141,13 +134,13 @@ const ProviderForm = ({
validateAndSubmit(`${getApiURL()}/providers/install`)
.then((data) => {
console.log("Connect Result:", data);
setConnectResult(data.result);
setIsConnected(true);
})
.catch((error) => {
console.error("Connect failed:", error);
});
};

console.log("ProviderForm component loaded");

return (
Expand All @@ -156,7 +149,8 @@ const ProviderForm = ({
{provider.authentication.map((method) => (
<div className="form-group" key={method.name}>
<label htmlFor={method.name}>
{method.desc}{method.required !== false ? "" : " (optional)"}:
{method.desc}
{method.required !== false ? "" : " (optional)"}:
</label>
<input
type={method.type}
Expand Down Expand Up @@ -189,7 +183,9 @@ const ProviderForm = ({
</div>
</form>
{formErrors.error && (
<div className="error-message">Error while testing the provider: &quot;{formErrors.error}&quot;</div>
<div className="error-message">
Error while testing the provider: &quot;{formErrors.error}&quot;
</div>
)}
{testResult === "success" && (
<div>
Expand All @@ -205,7 +201,7 @@ const ProviderForm = ({
</thead>
<tbody>
{alertData.map((alert) => (
<tr key={alert.id}>
<tr key={alert.id || Math.random()}>
<Alert alert={alert} provider={formValues.provider_id} />
</tr>
))}
Expand Down
60 changes: 42 additions & 18 deletions keep-ui/app/providers/provider-row.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
// @ts-nocheck
import React, { useState, useEffect } from 'react';
import { TableRow, TableCell } from '@tremor/react';
import Image from 'next/image';
import './providers.css';
import ProviderForm from './provider-form';
import React, { useState, useEffect } from "react";
import { TableRow, TableCell } from "@tremor/react";
import Image from "next/image";
import "./providers.css";
import ProviderForm from "./provider-form";

type AuthenticationMethod = {
name: string;
Expand All @@ -12,6 +11,7 @@ type AuthenticationMethod = {
placeholder?: string;
validation?: (value: string) => boolean;
required?: boolean;
value?: string;
};

export type Provider = {
Expand All @@ -35,18 +35,21 @@ const ProviderRow = ({ provider }: ProviderRowProps) => {
setExpanded(!expanded);
};

const onFormChange = (formValues) => {
const onFormChange = (formValues: any) => {
setFormData(formValues);
};

// Update formData with authentication data
useEffect(() => {
if (provider.connected) {
const authenticationData = provider.authentication.reduce((data, method) => {
const { name } = method;
const value = method.value || '';
return { ...data, [name]: value };
}, {});
const authenticationData = provider.authentication.reduce(
(data, method) => {
const { name } = method;
const value = method.value || "";
return { ...data, [name]: value };
},
{}
);
setFormData(authenticationData);
}
}, [provider.connected, provider.authentication]);
Expand All @@ -55,22 +58,39 @@ const ProviderRow = ({ provider }: ProviderRowProps) => {

return (
<>
<TableRow className={`table-row ${provider.connected ? 'connected' : ''}`}>
<TableRow
className={`table-row ${provider.connected ? "connected" : ""} ${
isComingSoonProvider ? "coming-soon" : ""
}`}
>
<TableCell className="icon-cell">
<div className="icon-wrapper">
<Image src={provider.icon} alt={provider.name} width={150} height={150} />
<Image
src={provider.icon}
alt={provider.name}
width={150}
height={150}
/>
</div>
<div className="provider-info">
<div className="provider-name">{provider.name}</div>
</div>
</TableCell>
<TableCell className="expand-cell">
{isComingSoonProvider ? (
<div className="coming-soon-label">🚧 Coming Soon 🚧</div>
<div className="coming-soon-label">Coming Soon 🚧</div>
) : (
<div className="expand-button-container">
<button type="button" className="expand-button" onClick={handleExpand}>
{expanded ? 'Collapse' : provider.connected ? 'Disconnect' : 'Connect'}
<button
type="button"
className="expand-button"
onClick={handleExpand}
>
{expanded
? "Collapse"
: provider.connected
? "Expand"
: "Connect"}
</button>
</div>
)}
Expand All @@ -80,7 +100,11 @@ const ProviderRow = ({ provider }: ProviderRowProps) => {
<TableRow>
<TableCell colSpan={2}>
<div className="expanded-content">
<ProviderForm provider={provider} formData={formData} onFormChange={onFormChange} />
<ProviderForm
provider={provider}
formData={formData}
onFormChange={onFormChange}
/>
</div>
</TableCell>
</TableRow>
Expand Down
4 changes: 4 additions & 0 deletions keep-ui/app/providers/providers.css
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@
background-color: lightgreen;
}

.coming-soon {
opacity: 0.6;
}

.coming-soon-label {
display: inline-block;
background-color: #f27e12;
Expand Down
Loading

0 comments on commit d60ff4c

Please sign in to comment.