More Cleanup & Fixes

This commit is contained in:
oitsjustjose 2024-12-31 17:22:29 -06:00
commit 6ad5f703db
6 changed files with 77 additions and 78 deletions

View file

@ -3,6 +3,12 @@ import Job from "../../models/Job";
import Status from "../../status"; import Status from "../../status";
import { Fernet } from "fernet-nodejs"; import { Fernet } from "fernet-nodejs";
type OAuthTokenResponse = {
access_token: string;
token_type: string;
expires_in: number;
};
const getNextQueuePlace = async () => { const getNextQueuePlace = async () => {
const allActiveJobs = await Job.find({ status: Status.ENQUEUED }).sort({ const allActiveJobs = await Job.find({ status: Status.ENQUEUED }).sort({
queuePlace: "desc", queuePlace: "desc",
@ -16,7 +22,7 @@ const getNextQueuePlace = async () => {
export default async (req: Request, res: Response) => { export default async (req: Request, res: Response) => {
try { try {
if ( if (
!req.body.oauthToken || !req.body.clientOauthCode ||
!req.body.curseforgeSlug || !req.body.curseforgeSlug ||
!req.body.modrinthId !req.body.modrinthId
) { ) {
@ -25,15 +31,37 @@ export default async (req: Request, res: Response) => {
.send( .send(
[ [
"Missing a required parameter in the JSON body", "Missing a required parameter in the JSON body",
"Required params: oauthToken: string, curseforgeSlug: string, modrinthId: string", "Required params: clientOauthCode: string, curseforgeSlug: string, modrinthId: string",
].join(" ") ].join(" ")
); );
} }
const fern = new Fernet(process.env.SECRET); const response = await fetch(
"https://api.modrinth.com/_internal/oauth/token",
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: process.env.MODRINTH_OAUTH_CLIENT_SECRET,
},
body: new URLSearchParams({
code: req.body.clientOauthCode,
client_id: process.env.MODRINTH_OAUTH_CLIENT_ID,
redirect_uri: "https://ctm.oitsjustjose.com/",
grant_type: "authorization_code",
}),
}
);
if (!response.ok) {
return res.status(400).send(response);
}
const body = (await response.json()) as OAuthTokenResponse;
const fern = new Fernet(process.env.SECRET);
const newJob = new Job({ const newJob = new Job({
oauthToken: fern.encrypt(req.body.oauthToken), oauthToken: fern.encrypt(body.access_token),
curseforgeSlug: req.body.curseforgeSlug, curseforgeSlug: req.body.curseforgeSlug,
modrinthId: req.body.modrinthId, modrinthId: req.body.modrinthId,
queuePlace: await getNextQueuePlace(), queuePlace: await getNextQueuePlace(),

View file

@ -65,13 +65,3 @@ button.info svg {
button svg { button svg {
vertical-align: top; vertical-align: top;
} }
button.modrinth {
background-color: #1bd96a;
color: black;
}
button.modrinth:hover {
background-color: #14a551;
color: black;
}

View file

@ -1,7 +1,6 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import { Modal, Image, Button } from 'react-bootstrap'; import { Image, Modal } from 'react-bootstrap';
import ThirdPartyHelp from '../../img/cftpd.png'; import ThirdPartyHelp from '../../img/cftpd.png';
import { DoModrinthOauth } from '../../shared';
export default ({ dark, override, propagateOnHide }) => { export default ({ dark, override, propagateOnHide }) => {
const [show, setShow] = useState(!window.localStorage.getItem('info-dismissed')); const [show, setShow] = useState(!window.localStorage.getItem('info-dismissed'));
@ -67,12 +66,6 @@ export default ({ dark, override, propagateOnHide }) => {
</li> </li>
<li>Share this tool on Twitter, Discord or whatever you please! </li> <li>Share this tool on Twitter, Discord or whatever you please! </li>
</ul> </ul>
<div className="w-100 d-flex justify-content-center align-items-center">
<Button variant="success" className="modrinth" onClick={DoModrinthOauth}>
Authenticate with Modrinth
</Button>
</div>
</Modal.Body> </Modal.Body>
</Modal> </Modal>
); );

View file

@ -8,7 +8,7 @@ import OutputLog from '../components/OutputLog';
import Info from '../components/Help/Info'; import Info from '../components/Help/Info';
import HeaderImg from '../img/ctm.png'; import HeaderImg from '../img/ctm.png';
import ModrinthProjId from '../components/Help/ModrinthProjId'; import ModrinthProjId from '../components/Help/ModrinthProjId';
import { DoModrinthOauth, GetModrinthOauth, ModrinthOauthCallbackHandler } from '../shared'; import { CreateModrinthUri, ModrinthOauthCallbackHandler } from '../shared';
export default () => { export default () => {
const [dark, setDark] = useState(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches); const [dark, setDark] = useState(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches);
@ -19,22 +19,28 @@ export default () => {
modrinthId: '', modrinthId: '',
}); });
const makeJob = async (evt) => { /*
Begins the Modrinth OAuth flow, creating a URL with a callback that has the
data we need in the query params and will return back with the client's
oauth code that will be needed back on the backend
*/
const startOauthFlow = (evt) => {
evt && evt.preventDefault(); evt && evt.preventDefault();
if (!formData.curseforgeSlug.length) return;
if (!formData.modrinthId.length) return;
/* OAuth block to verify we're logged in */ const uri = CreateModrinthUri(formData.curseforgeSlug, formData.modrinthId);
const oauthToken = GetModrinthOauth(); window.location.href = uri;
if (!oauthToken) { };
DoModrinthOauth(formData.curseforgeSlug, formData.modrinthId);
return; useEffect(() => { // Handle the Modrinth OAuth callback
} const internalCreateJob = async (formDataIn) => {
if (!formDataIn.curseforgeSlug.length) return;
if (!formDataIn.modrinthId.length) return;
if (!formDataIn.code.length) return;
const body = { const body = {
curseforgeSlug: formData.curseforgeSlug, curseforgeSlug: formDataIn.curseforgeSlug,
modrinthId: formData.modrinthId, modrinthId: formDataIn.modrinthId,
oauthToken, clientOauthCode: formDataIn.code,
}; };
const resp = await fetch('/api/v1/jobs', { const resp = await fetch('/api/v1/jobs', {
@ -50,12 +56,10 @@ export default () => {
} }
}; };
useEffect(() => { // Handle the Modrinth OAuth callback
const newFormData = ModrinthOauthCallbackHandler(); const newFormData = ModrinthOauthCallbackHandler();
if (!newFormData) return () => { }; if (!newFormData) return () => { };
setFormData({ ...newFormData }); internalCreateJob(newFormData);
makeJob();
// Push state w/o URLQuery to avoid infinite reload of the page // Push state w/o URLQuery to avoid infinite reload of the page
if (window.history.pushState) { if (window.history.pushState) {
@ -65,7 +69,7 @@ export default () => {
} }
return () => { }; return () => { };
}, [ModrinthOauthCallbackHandler, setFormData, makeJob]); }, [ModrinthOauthCallbackHandler]);
useEffect(() => { // DARK MODE STUFF HERE useEffect(() => { // DARK MODE STUFF HERE
// Set initial state before even bothering with the update state // Set initial state before even bothering with the update state
@ -111,7 +115,7 @@ export default () => {
<b>M</b> <b>M</b>
igrator igrator
</p> </p>
<Form onSubmit={makeJob} className="juse-form"> <Form onSubmit={startOauthFlow} className="juse-form">
<Form.Group className="mb-3" controlId="slug"> <Form.Group className="mb-3" controlId="slug">
<Form.Label>CurseForge Project Slug</Form.Label> <Form.Label>CurseForge Project Slug</Form.Label>
<Form.Control <Form.Control

View file

@ -1,29 +1,15 @@
const OAUTH_KEY = 'modrinth-oauth-token';
/** /**
* Creates a modrinth URI with a given URL encoded callback * Creates a modrinth URI with a given URL encoded callback
* @param {string | null} curseforgeSlug * @param {string | null} curseforgeSlug
* @param {string | null} modrinthId * @param {string | null} modrinthId
* @returns {string} The callback URI * @returns {string} The callback URI
*/ */
const CreateModrinthUri = (curseforgeSlug, modrinthId) => { export const CreateModrinthUri = (curseforgeSlug, modrinthId) => {
console.log(process.env);
const uri = new URL(`${window.location.origin}${window.location.pathname}`); const uri = new URL(`${window.location.origin}${window.location.pathname}`);
curseforgeSlug && curseforgeSlug.length && uri.searchParams.set('curseforgeSlug', curseforgeSlug); uri.searchParams.set('curseforgeSlug', curseforgeSlug);
modrinthId && curseforgeSlug.length && uri.searchParams.set('modrinthId', modrinthId); uri.searchParams.set('modrinthId', modrinthId);
return `https://modrinth.com/auth/authorize?client_id=50zijYLk&redirect_uri=${encodeURIComponent(uri.toString())}&scope=PROJECT_WRITE+VERSION_CREATE`; return `https://modrinth.com/auth/authorize?client_id=${process.env.REACT_APP_MODRINTH_OAUTH_CLIENT_ID}&redirect_uri=${encodeURIComponent(uri.toString())}&scope=PROJECT_WRITE+VERSION_CREATE`;
};
export const GetModrinthOauth = () => window.localStorage.getItem(OAUTH_KEY);
/**
*
* @param {string | null} curseforgeSlug
* @param {string | null} modrinthId
* @returns
*/
export const DoModrinthOauth = (curseforgeSlug, modrinthId) => {
const uri = CreateModrinthUri(curseforgeSlug, modrinthId);
window.location.href = uri;
}; };
/** /**
@ -32,10 +18,6 @@ export const DoModrinthOauth = (curseforgeSlug, modrinthId) => {
export const ModrinthOauthCallbackHandler = () => { export const ModrinthOauthCallbackHandler = () => {
const params = new URLSearchParams(window.location.search); const params = new URLSearchParams(window.location.search);
if (!params.has('code')) return null; if (!params.has('code')) return null;
window.localStorage.setItem(OAUTH_KEY, params.get('code'));
params.delete('code');
const ret = Object.fromEntries(params); const ret = Object.fromEntries(params);
return Object.keys(ret).length ? ret : null; return Object.keys(ret).length ? ret : null;
}; };

View file

@ -9,3 +9,5 @@ __pycache__
.envrc .envrc
*.jar *.jar
.venv