Modrinth OAuth support

This commit is contained in:
oitsjustjose 2024-12-31 16:19:05 -06:00
commit 52e28067d8
10 changed files with 125 additions and 66 deletions

View file

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

View file

@ -1,6 +1,7 @@
import React, { useState } from 'react';
import { Modal, Image } from 'react-bootstrap';
import { Modal, Image, Button } from 'react-bootstrap';
import ThirdPartyHelp from '../../img/cftpd.png';
import { DoModrinthOauth } from '../../shared';
export default ({ dark, override, propagateOnHide }) => {
const [show, setShow] = useState(!window.localStorage.getItem('info-dismissed'));
@ -31,18 +32,6 @@ export default ({ dark, override, propagateOnHide }) => {
</p>
<ul>
<li>
A
{' '}
<a href="https://docs.github.com/en/enterprise-server@3.4/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token" target="_blank" rel="noreferrer">
GitHub Personal Access Token
</a>
{' '}
for the Account you used to log into Modrinth. No
permissions need to be granted to the PAT, this token will be encrypted from end
to end (even in storage), and it will only be used for requests to Modrinth
(feel encouraged to browse this source code to verify).
</li>
<li>
The CurseForge Slug for your Mod. This can be found in the General Settings for your
project page
@ -78,6 +67,12 @@ export default ({ dark, override, propagateOnHide }) => {
</li>
<li>Share this tool on Twitter, Discord or whatever you please! </li>
</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>
);

View file

@ -8,17 +8,65 @@ import OutputLog from '../components/OutputLog';
import Info from '../components/Help/Info';
import HeaderImg from '../img/ctm.png';
import ModrinthProjId from '../components/Help/ModrinthProjId';
import { DoModrinthOauth, GetModrinthOauth, ModrinthOauthCallbackHandler } from '../shared';
export default () => {
const [dark, setDark] = useState(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches);
const [modals, setModals] = useState({ info: false, mpid: false });
const [jobId, setJobId] = useState(window.localStorage.getItem('last-jobid'));
const [formData, setFormData] = useState({
githubPat: '',
curseforgeSlug: '',
modrinthId: '',
});
const makeJob = async (evt) => {
evt && evt.preventDefault();
if (!formData.curseforgeSlug.length) return;
if (!formData.modrinthId.length) return;
/* OAuth block to verify we're logged in */
const oauthToken = GetModrinthOauth();
if (!oauthToken) {
DoModrinthOauth(formData.curseforgeSlug, formData.modrinthId);
return;
}
const body = {
curseforgeSlug: formData.curseforgeSlug,
modrinthId: formData.modrinthId,
oauthToken,
};
const resp = await fetch('/api/v1/jobs', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (resp && resp.ok) {
const data = await resp.text();
setJobId(data);
window.localStorage.setItem('last-jobid', data);
}
};
useEffect(() => { // Handle the Modrinth OAuth callback
const newFormData = ModrinthOauthCallbackHandler();
if (!newFormData) return () => { };
setFormData({ ...newFormData });
makeJob();
// Push state w/o URLQuery to avoid infinite reload of the page
if (window.history.pushState) {
const url = new URL(window.location.href);
url.search = '';
window.history.pushState({ path: url.toString() }, '', url.toString());
}
return () => { };
}, [ModrinthOauthCallbackHandler, setFormData, makeJob]);
useEffect(() => { // DARK MODE STUFF HERE
// Set initial state before even bothering with the update state
window.document.scrollingElement.setAttribute('data-bs-theme', dark ? 'dark' : 'light');
@ -36,25 +84,6 @@ export default () => {
return () => pref.removeEventListener('change', onChange);
}, [dark, setDark]);
const makeJob = async (evt) => {
evt.preventDefault();
if (!formData.githubPat.length) return;
if (!formData.curseforgeSlug.length) return;
if (!formData.modrinthId.length) return;
const resp = await fetch('/api/v1/jobs', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData),
});
if (resp && resp.ok) {
const data = await resp.text();
setJobId(data);
window.localStorage.setItem('last-jobid', data);
}
};
return (
<div className="ctm-root">
<Info
@ -83,23 +112,6 @@ export default () => {
igrator
</p>
<Form onSubmit={makeJob} className="juse-form">
<Form.Group className="mb-3" controlId="githubPat">
<Form.Label>GitHub Personal Access Token</Form.Label>
<Form.Control
type="password"
required
placeholder="This field is required"
value={formData.githubPat}
onChange={(x) => setFormData({
...formData,
githubPat: x.target.value,
})}
/>
<Form.Text className="text-muted">
This value is encrypted from end-to-end and even in storage
</Form.Text>
</Form.Group>
<Form.Group className="mb-3" controlId="slug">
<Form.Label>CurseForge Project Slug</Form.Label>
<Form.Control

View file

@ -0,0 +1,41 @@
const OAUTH_KEY = 'modrinth-oauth-token';
/**
* Creates a modrinth URI with a given URL encoded callback
* @param {string | null} curseforgeSlug
* @param {string | null} modrinthId
* @returns {string} The callback URI
*/
const CreateModrinthUri = (curseforgeSlug, modrinthId) => {
const uri = new URL(`${window.location.origin}${window.location.pathname}`);
curseforgeSlug && curseforgeSlug.length && uri.searchParams.set('curseforgeSlug', curseforgeSlug);
modrinthId && curseforgeSlug.length && uri.searchParams.set('modrinthId', modrinthId);
return `https://modrinth.com/auth/authorize?client_id=50zijYLk&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;
};
/**
* Handles Modrinth's callback after OAuth is completed
*/
export const ModrinthOauthCallbackHandler = () => {
const params = new URLSearchParams(window.location.search);
if (!params.has('code')) return null;
window.localStorage.setItem(OAUTH_KEY, params.get('code'));
params.delete('code');
const ret = Object.fromEntries(params);
return Object.keys(ret).length ? ret : null;
};