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) => {
|
||||
try {
|
||||
if (
|
||||
!req.body.githubPat ||
|
||||
!req.body.oauthToken ||
|
||||
!req.body.curseforgeSlug ||
|
||||
!req.body.modrinthId
|
||||
) {
|
||||
|
|
@ -25,7 +25,7 @@ export default async (req: Request, res: Response) => {
|
|||
.send(
|
||||
[
|
||||
"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(" ")
|
||||
);
|
||||
}
|
||||
|
|
@ -33,7 +33,7 @@ export default async (req: Request, res: Response) => {
|
|||
const fern = new Fernet(process.env.SECRET);
|
||||
|
||||
const newJob = new Job({
|
||||
githubPat: fern.encrypt(req.body.githubPat),
|
||||
oauthToken: fern.encrypt(req.body.oauthToken),
|
||||
curseforgeSlug: req.body.curseforgeSlug,
|
||||
modrinthId: req.body.modrinthId,
|
||||
queuePlace: await getNextQueuePlace(),
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import Status from "../status";
|
|||
|
||||
export type JobType = Document & {
|
||||
jobId: string;
|
||||
githubPat: string;
|
||||
oauthToken: string;
|
||||
curseforgeSlug: string;
|
||||
modrinthId: string;
|
||||
logs: string;
|
||||
|
|
@ -18,7 +18,7 @@ const JobSchema = new Schema<JobType>({
|
|||
default: shortid.generate,
|
||||
required: true,
|
||||
},
|
||||
githubPat: {
|
||||
oauthToken: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
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
|
||||
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 = ""
|
||||
|
|
|
|||
|
|
@ -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 [],
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
Loading…
Reference in a new issue