Modrinth OAuth support
This commit is contained in:
parent
b72301bea2
commit
52e28067d8
10 changed files with 125 additions and 66 deletions
|
|
@ -16,7 +16,7 @@ const getNextQueuePlace = async () => {
|
||||||
export default async (req: Request, res: Response) => {
|
export default async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
if (
|
if (
|
||||||
!req.body.githubPat ||
|
!req.body.oauthToken ||
|
||||||
!req.body.curseforgeSlug ||
|
!req.body.curseforgeSlug ||
|
||||||
!req.body.modrinthId
|
!req.body.modrinthId
|
||||||
) {
|
) {
|
||||||
|
|
@ -25,7 +25,7 @@ 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: githubPat: string, curseforgeSlug: string, modrinthId: string",
|
"Required params: oauthToken: string, curseforgeSlug: string, modrinthId: string",
|
||||||
].join(" ")
|
].join(" ")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
@ -33,7 +33,7 @@ export default async (req: Request, res: Response) => {
|
||||||
const fern = new Fernet(process.env.SECRET);
|
const fern = new Fernet(process.env.SECRET);
|
||||||
|
|
||||||
const newJob = new Job({
|
const newJob = new Job({
|
||||||
githubPat: fern.encrypt(req.body.githubPat),
|
oauthToken: fern.encrypt(req.body.oauthToken),
|
||||||
curseforgeSlug: req.body.curseforgeSlug,
|
curseforgeSlug: req.body.curseforgeSlug,
|
||||||
modrinthId: req.body.modrinthId,
|
modrinthId: req.body.modrinthId,
|
||||||
queuePlace: await getNextQueuePlace(),
|
queuePlace: await getNextQueuePlace(),
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ import Status from "../status";
|
||||||
|
|
||||||
export type JobType = Document & {
|
export type JobType = Document & {
|
||||||
jobId: string;
|
jobId: string;
|
||||||
githubPat: string;
|
oauthToken: string;
|
||||||
curseforgeSlug: string;
|
curseforgeSlug: string;
|
||||||
modrinthId: string;
|
modrinthId: string;
|
||||||
logs: string;
|
logs: string;
|
||||||
|
|
@ -18,7 +18,7 @@ const JobSchema = new Schema<JobType>({
|
||||||
default: shortid.generate,
|
default: shortid.generate,
|
||||||
required: true,
|
required: true,
|
||||||
},
|
},
|
||||||
githubPat: {
|
oauthToken: {
|
||||||
type: String,
|
type: String,
|
||||||
required: true,
|
required: true,
|
||||||
},
|
},
|
||||||
|
|
|
||||||
|
|
@ -65,3 +65,13 @@ 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;
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import React, { useState } from 'react';
|
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 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'));
|
||||||
|
|
@ -31,18 +32,6 @@ export default ({ dark, override, propagateOnHide }) => {
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<ul>
|
<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>
|
<li>
|
||||||
The CurseForge Slug for your Mod. This can be found in the General Settings for your
|
The CurseForge Slug for your Mod. This can be found in the General Settings for your
|
||||||
project page
|
project page
|
||||||
|
|
@ -78,6 +67,12 @@ 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>
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -8,17 +8,65 @@ 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';
|
||||||
|
|
||||||
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);
|
||||||
const [modals, setModals] = useState({ info: false, mpid: false });
|
const [modals, setModals] = useState({ info: false, mpid: false });
|
||||||
const [jobId, setJobId] = useState(window.localStorage.getItem('last-jobid'));
|
const [jobId, setJobId] = useState(window.localStorage.getItem('last-jobid'));
|
||||||
const [formData, setFormData] = useState({
|
const [formData, setFormData] = useState({
|
||||||
githubPat: '',
|
|
||||||
curseforgeSlug: '',
|
curseforgeSlug: '',
|
||||||
modrinthId: '',
|
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
|
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
|
||||||
window.document.scrollingElement.setAttribute('data-bs-theme', dark ? 'dark' : 'light');
|
window.document.scrollingElement.setAttribute('data-bs-theme', dark ? 'dark' : 'light');
|
||||||
|
|
@ -36,25 +84,6 @@ export default () => {
|
||||||
return () => pref.removeEventListener('change', onChange);
|
return () => pref.removeEventListener('change', onChange);
|
||||||
}, [dark, setDark]);
|
}, [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 (
|
return (
|
||||||
<div className="ctm-root">
|
<div className="ctm-root">
|
||||||
<Info
|
<Info
|
||||||
|
|
@ -83,23 +112,6 @@ export default () => {
|
||||||
igrator
|
igrator
|
||||||
</p>
|
</p>
|
||||||
<Form onSubmit={makeJob} className="juse-form">
|
<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.Group className="mb-3" controlId="slug">
|
||||||
<Form.Label>CurseForge Project Slug</Form.Label>
|
<Form.Label>CurseForge Project Slug</Form.Label>
|
||||||
<Form.Control
|
<Form.Control
|
||||||
|
|
|
||||||
41
frontend/src/shared/index.js
Normal file
41
frontend/src/shared/index.js
Normal 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;
|
||||||
|
};
|
||||||
|
|
@ -2,6 +2,7 @@
|
||||||
Houses commonly used dataclasses and Enums
|
Houses commonly used dataclasses and Enums
|
||||||
Author: oitsjustjose @ modrinth/curseforge/twitter
|
Author: oitsjustjose @ modrinth/curseforge/twitter
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
from typing import List
|
from typing import List
|
||||||
|
|
@ -23,7 +24,7 @@ class Status(Enum):
|
||||||
class Job:
|
class Job:
|
||||||
"""A single job"""
|
"""A single job"""
|
||||||
|
|
||||||
github_pat: str
|
oauth_token: str
|
||||||
curseforge_slug: str
|
curseforge_slug: str
|
||||||
modrinth_id: str
|
modrinth_id: str
|
||||||
job_id: str = ""
|
job_id: str = ""
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@
|
||||||
Houses API Tools when communicating with the RESTful API
|
Houses API Tools when communicating with the RESTful API
|
||||||
Author: oitsjustjose @ modrinth/curseforge/twitter
|
Author: oitsjustjose @ modrinth/curseforge/twitter
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from os import environ as env
|
from os import environ as env
|
||||||
from typing import Dict, List, Union
|
from typing import Dict, List, Union
|
||||||
|
|
||||||
|
|
@ -54,7 +55,7 @@ class MgmtApiHelper:
|
||||||
def _dict_to_job(self, data: Dict) -> Job:
|
def _dict_to_job(self, data: Dict) -> Job:
|
||||||
"""Converts a dictionary (from mongo) into a Job"""
|
"""Converts a dictionary (from mongo) into a Job"""
|
||||||
return Job(
|
return Job(
|
||||||
github_pat=self._fernet.decrypt(data["githubPat"]),
|
oauth_token=self._fernet.decrypt(data["oauthToken"]),
|
||||||
curseforge_slug=data["curseforgeSlug"],
|
curseforge_slug=data["curseforgeSlug"],
|
||||||
modrinth_id=data["modrinthId"],
|
modrinth_id=data["modrinthId"],
|
||||||
logs=data["logs"] if "logs" in data else [],
|
logs=data["logs"] if "logs" in data else [],
|
||||||
|
|
|
||||||
|
|
@ -97,7 +97,7 @@ class FastProvider(MgmtApiLogger):
|
||||||
response = requests.post(
|
response = requests.post(
|
||||||
"https://api.modrinth.com/v2/version",
|
"https://api.modrinth.com/v2/version",
|
||||||
timeout=30,
|
timeout=30,
|
||||||
headers={"Authorization": self._job.github_pat},
|
headers={"Authorization": self._job.oauth_token},
|
||||||
files=[
|
files=[
|
||||||
("data", (None, payload, None)),
|
("data", (None, payload, None)),
|
||||||
("files", (jar_fn, jar_data, "application/octet-stream")),
|
("files", (jar_fn, jar_data, "application/octet-stream")),
|
||||||
|
|
@ -179,9 +179,7 @@ class FastProvider(MgmtApiLogger):
|
||||||
status = (
|
status = (
|
||||||
Status.PARTIAL_FAIL
|
Status.PARTIAL_FAIL
|
||||||
if any_succ and any_fail
|
if any_succ and any_fail
|
||||||
else Status.SUCCESS
|
else Status.SUCCESS if any_succ and not any_fail else Status.FAIL
|
||||||
if any_succ and not any_fail
|
|
||||||
else Status.FAIL
|
|
||||||
)
|
)
|
||||||
|
|
||||||
return status
|
return status
|
||||||
|
|
@ -206,5 +204,7 @@ class FastProvider(MgmtApiLogger):
|
||||||
return "downloadUrl" in data[0]
|
return "downloadUrl" in data[0]
|
||||||
return False
|
return False
|
||||||
except TimeoutError:
|
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
|
return False
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@
|
||||||
@description: A SLOW working mod migrator from Curse to Modrinth
|
@description: A SLOW working mod migrator from Curse to Modrinth
|
||||||
This one is used if you're a jerk and disable third party launchers
|
This one is used if you're a jerk and disable third party launchers
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
from os import environ as env
|
from os import environ as env
|
||||||
from os import makedirs, path
|
from os import makedirs, path
|
||||||
|
|
@ -219,7 +220,7 @@ class SlowProvider(MgmtApiLogger):
|
||||||
response = requests.post(
|
response = requests.post(
|
||||||
"https://api.modrinth.com/v2/version",
|
"https://api.modrinth.com/v2/version",
|
||||||
timeout=30,
|
timeout=30,
|
||||||
headers={"Authorization": self._job.github_pat},
|
headers={"Authorization": self._job.oauth_token},
|
||||||
files=[
|
files=[
|
||||||
("data", (None, payload, None)),
|
("data", (None, payload, None)),
|
||||||
("files", (fpath, jar_data, "application/octet-stream")),
|
("files", (fpath, jar_data, "application/octet-stream")),
|
||||||
|
|
@ -263,9 +264,7 @@ class SlowProvider(MgmtApiLogger):
|
||||||
status = (
|
status = (
|
||||||
Status.PARTIAL_FAIL
|
Status.PARTIAL_FAIL
|
||||||
if any_succ and any_fail
|
if any_succ and any_fail
|
||||||
else Status.SUCCESS
|
else Status.SUCCESS if any_succ and not any_fail else Status.FAIL
|
||||||
if any_succ and not any_fail
|
|
||||||
else Status.FAIL
|
|
||||||
)
|
)
|
||||||
rmdir(f"./out/{self._job.curseforge_slug}")
|
rmdir(f"./out/{self._job.curseforge_slug}")
|
||||||
return status
|
return status
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue