Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use MeshDB Creds in query form #146

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 15 additions & 8 deletions src/components/QueryForm/QueryForm.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use client";

import { submitQueryForm } from "@/lib/api";
import { checkIfLoggedIn, submitQueryForm } from "@/lib/api";
import { QueryFormInput, QueryFormResponse } from "@/lib/io";
import Button from "@mui/material/Button";
import { toastErrorMessage } from "@/components/toastErrorMessage";
Expand Down Expand Up @@ -44,6 +44,17 @@ export function QueryForm() {
showIsDeveloperDialog();
}

async function redirectToLoginIfNecessary() {
const loggedIn = await checkIfLoggedIn();
console.log(`logged in: ${loggedIn}`);

if (!loggedIn) {
const api_base = new URL(`${await getMeshDBAPIEndpoint()}/api/v1/`);
// Not ideal to redirect back to mesh homepage.
window.location.href = new URL("/auth/login?next=/", api_base);
}
}

function parseForm(event: FormEvent<HTMLFormElement>) {
const formData = new FormData(event.currentTarget);
const data: Record<string, string | Blob> = {};
Expand All @@ -54,6 +65,7 @@ export function QueryForm() {
return QueryFormInput.parse(data);
}

// TODO: Check if we need to log in the user
async function sendForm(event: FormEvent<HTMLFormElement>) {
// Clear previous query results
setLegacyQueryResults([]);
Expand Down Expand Up @@ -90,7 +102,6 @@ export function QueryForm() {
route,
queryForm.query_type,
queryForm.data,
queryForm.password,
);
console.log("response is:");
console.log(resp);
Expand Down Expand Up @@ -231,6 +242,8 @@ export function QueryForm() {
},
};

redirectToLoginIfNecessary();

return (
<>
<div className={styles.formBody}>
Expand All @@ -252,12 +265,6 @@ export function QueryForm() {
/>
<div className={styles.horizontal}>
<input type="text" name="data" placeholder={queryLabel} required />
<input
type="password"
name="password"
placeholder="Password"
required
/>
</div>
<div className={styles.centered}>
<label>
Expand Down
61 changes: 22 additions & 39 deletions src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
} from "@/lib/io";
import { z } from "zod";
import { getMeshDBAPIEndpoint } from "./endpoint";
import { parse } from "path";

const get = async <S extends z.Schema>(
url: string,
Expand All @@ -15,51 +16,33 @@ const get = async <S extends z.Schema>(
): Promise<ReturnType<S["parse"]>> => {
const api_base = new URL(`${await getMeshDBAPIEndpoint()}/api/v1/`);
const res = await fetch(new URL(url, api_base), {
headers: {
...(auth && { Authorization: `Bearer ${auth}` }),
},
credentials: "include",
next: nextOptions,
}).catch(console.warn);
if (!res?.ok) throw res;
return schema.parse(await res.json());
};

const post = async <S extends z.Schema>(
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deleting this because we don't use it

url: string,
schema: S,
input: unknown,
auth?: string,
method = "POST",
): Promise<ReturnType<S["parse"]>> => {
console.log("Will POST: " + input);
const api_base = new URL(`${await getMeshDBAPIEndpoint()}/api/v1/`);
const res = await fetch(new URL(url, api_base), {
method,
headers: {
"Content-Type": "application/json",
...(auth && { Authorization: `Bearer ${auth}` }),
},
body: JSON.stringify(input),
}).catch(console.warn);
if (!res?.ok) throw res;
return schema.parse(await res.json());
};

export const submitNNAssignForm = (input: NNAssignFormInput) =>
post(
`/api/v1/nn-assign/`,
NNAssignFormResponse,
NNAssignFormInput.parse(input),
);

export const submitQueryForm = (
export const submitQueryForm = async (
route: string,
input_type: string,
input: string,
password: string,
) =>
get(
`/api/v1/query/${route}/?${input_type}=${input}`,
QueryFormResponse,
password,
);
) => get(`/api/v1/query/${route}/?${input_type}=${input}`, QueryFormResponse);


// FIXME (wdn): This is terrible. It won't work for members who have meshdb accounts
// but don't have permission to use this-or-that form.
export const checkIfLoggedIn = async () => {
// Check if we're logged in
const api_base = new URL(`${await getMeshDBAPIEndpoint()}/api/v1/`);
const checkAuthedRoute = await fetch(new URL("/api/v1/nodes/3", api_base), {
credentials: "include",
});
if (checkAuthedRoute.ok) {
return true;
}

if (checkAuthedRoute.status === 403) {
return false;
}
};
3 changes: 1 addition & 2 deletions src/lib/io.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { z } from "zod";

export const NNAssignFormInput = z.object({
install_number: z.number(),
password: z.string(), // TODO: Salt/hash/whatever this
password: z.string(),
});
export type NNAssignFormInput = z.infer<typeof NNAssignFormInput>;

Expand All @@ -20,7 +20,6 @@ export const QueryFormInput = z.object({
legacy: z.string().optional(),
query_type: z.string(),
data: z.string(),
password: z.string(), // TODO: Salt/hash/whatever this
});
export type QueryFormInput = z.infer<typeof QueryFormInput>;

Expand Down
Loading