- A
- {' '}
-
- GitHub Personal Access Token
-
- {' '}
- 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).
-
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 }) => {
Share this tool on Twitter, Discord or whatever you please!
+
+
+
+
);
diff --git a/frontend/src/pages/Home.jsx b/frontend/src/pages/Home.jsx
index c6b3729..4da3747 100644
--- a/frontend/src/pages/Home.jsx
+++ b/frontend/src/pages/Home.jsx
@@ -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 (
{
igrator
- GitHub Personal Access Token
- setFormData({
- ...formData,
- githubPat: x.target.value,
- })}
- />
-
- This value is encrypted from end-to-end and even in storage
-
-
-
CurseForge Project Slug {
+ 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;
+};
diff --git a/processor/src/common.py b/processor/src/common.py
index 99eff5e..0ed22e5 100644
--- a/processor/src/common.py
+++ b/processor/src/common.py
@@ -2,6 +2,7 @@
Houses commonly used dataclasses and Enums
Author: oitsjustjose @ modrinth/curseforge/twitter
"""
+
from dataclasses import dataclass
from enum import Enum
from typing import List
@@ -23,7 +24,7 @@ class Status(Enum):
class Job:
"""A single job"""
- github_pat: str
+ oauth_token: str
curseforge_slug: str
modrinth_id: str
job_id: str = ""
diff --git a/processor/src/mgmt_tools.py b/processor/src/mgmt_tools.py
index e1c6a09..d72e445 100644
--- a/processor/src/mgmt_tools.py
+++ b/processor/src/mgmt_tools.py
@@ -2,6 +2,7 @@
Houses API Tools when communicating with the RESTful API
Author: oitsjustjose @ modrinth/curseforge/twitter
"""
+
from os import environ as env
from typing import Dict, List, Union
@@ -54,7 +55,7 @@ class MgmtApiHelper:
def _dict_to_job(self, data: Dict) -> Job:
"""Converts a dictionary (from mongo) into a Job"""
return Job(
- github_pat=self._fernet.decrypt(data["githubPat"]),
+ oauth_token=self._fernet.decrypt(data["oauthToken"]),
curseforge_slug=data["curseforgeSlug"],
modrinth_id=data["modrinthId"],
logs=data["logs"] if "logs" in data else [],
diff --git a/processor/src/x_fast_provider.py b/processor/src/x_fast_provider.py
index 4854f62..e08ff32 100644
--- a/processor/src/x_fast_provider.py
+++ b/processor/src/x_fast_provider.py
@@ -97,7 +97,7 @@ class FastProvider(MgmtApiLogger):
response = requests.post(
"https://api.modrinth.com/v2/version",
timeout=30,
- headers={"Authorization": self._job.github_pat},
+ headers={"Authorization": self._job.oauth_token},
files=[
("data", (None, payload, None)),
("files", (jar_fn, jar_data, "application/octet-stream")),
@@ -179,9 +179,7 @@ class FastProvider(MgmtApiLogger):
status = (
Status.PARTIAL_FAIL
if any_succ and any_fail
- else Status.SUCCESS
- if any_succ and not any_fail
- else Status.FAIL
+ else Status.SUCCESS if any_succ and not any_fail else Status.FAIL
)
return status
@@ -206,5 +204,7 @@ class FastProvider(MgmtApiLogger):
return "downloadUrl" in data[0]
return False
except TimeoutError:
- self.logmsg("🕜 Timed out determining if Mod supports third party downloads")
+ self.logmsg(
+ "🕜 Timed out determining if Mod supports third party downloads"
+ )
return False
diff --git a/processor/src/x_slow_provider.py b/processor/src/x_slow_provider.py
index c16b6bf..822b6cd 100644
--- a/processor/src/x_slow_provider.py
+++ b/processor/src/x_slow_provider.py
@@ -4,6 +4,7 @@
@description: A SLOW working mod migrator from Curse to Modrinth
This one is used if you're a jerk and disable third party launchers
"""
+
import json
from os import environ as env
from os import makedirs, path
@@ -219,7 +220,7 @@ class SlowProvider(MgmtApiLogger):
response = requests.post(
"https://api.modrinth.com/v2/version",
timeout=30,
- headers={"Authorization": self._job.github_pat},
+ headers={"Authorization": self._job.oauth_token},
files=[
("data", (None, payload, None)),
("files", (fpath, jar_data, "application/octet-stream")),
@@ -263,9 +264,7 @@ class SlowProvider(MgmtApiLogger):
status = (
Status.PARTIAL_FAIL
if any_succ and any_fail
- else Status.SUCCESS
- if any_succ and not any_fail
- else Status.FAIL
+ else Status.SUCCESS if any_succ and not any_fail else Status.FAIL
)
rmdir(f"./out/{self._job.curseforge_slug}")
return status