Skip to content

Commit

Permalink
almost working oauth except for 500 ERROR AGHGHJGHGH
Browse files Browse the repository at this point in the history
  • Loading branch information
Ianyourgod committed Mar 25, 2024
1 parent 38f24a2 commit 3b136df
Show file tree
Hide file tree
Showing 6 changed files with 126 additions and 2 deletions.
41 changes: 40 additions & 1 deletion api/db/UserManager.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
require('dotenv').config();
const { randomBytes } = require('node:crypto');
const bcrypt = require('bcrypt');
const { MongoClient } = require('mongodb');
Expand All @@ -6,6 +7,8 @@ const path = require('path');
const fs = require('fs');
var prompt = require('prompt-sync')();

// scratch oauth name: Penguinmod-BA-Ianyourgod-Dev
// scratch oauth redir: http://localhost:8080/api/v1/users/login

function generateId() {
const rn = [
Expand Down Expand Up @@ -46,6 +49,7 @@ class UserManager {
this.reports = this.db.collection('reports');
this.projects = this.db.collection('projects');
this.messages = this.db.collection('messages');
this.oauthStates = this.db.collection('oauthStates');
this.illegalList = this.db.collection('illegalList');
if (!this.illegalList.findOne({ id: "illegalWords" })) {
this.illegalList.insertMany([
Expand Down Expand Up @@ -74,6 +78,7 @@ class UserManager {
await this.reports.deleteMany({});
await this.projects.deleteMany({});
await this.messages.deleteMany({});
await this.oauthStates.deleteMany({});
await this.illegalList.deleteMany({});
this.illegalList.insertMany([
{ id: "illegalWords", items: [] },
Expand Down Expand Up @@ -127,7 +132,8 @@ class UserManager {
cubes: 0,
firstLogin: Date.now(),
lastLogin: Date.now(),
lastUpload: 0
lastUpload: 0,
OAuth2State: generateId()
});
return token;
}
Expand Down Expand Up @@ -1045,6 +1051,39 @@ class UserManager {
potentiallyUnsafeWordsSpacedOut: potentiallyUnsafeWordsSpacedOut
}
}

async verifyOAuth2State(state) {
const result = await this.oauthStates.findOne({ state: state });

return result ? true : false;
}

async generateOAuth2State() {
const state = generateId();

await this.oauthStates.insertOne({ state: state });

return state;
}

async makeOAuth2Request(code, method) {
switch (method) {
case "scratch":
const response = await fetch(`https://oauth2.scratch-wiki.info/w/rest.php/soa2/v0/tokens`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
client_id: Number(process.env.ScratchOauth2ClientID),
client_secret: process.env.ScratchOauth2ClientSecret,
code: code,
scopes: ["identify"]
})
}).then(res => res.json());
return response;
}
}
}

module.exports = UserManager;
34 changes: 34 additions & 0 deletions api/v1/routes/users/OAuthlogin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
module.exports = (app, utils) => {
app.get("/api/v1/users/oauthlogin", async function (req, res) {
const packet = req.query;

const state = packet.state;
const code = packet.code;

if (!state || !code) {
utils.error(res, 400, "InvalidData");
return;
}

if (!await utils.UserManager.verifyOAuth2State(state)) {
utils.error(res, 400, "InvalidData");
return;
}

// now make the request
const response = await utils.UserManager.makeOAuth2Request(code, "scratch");

console.log(response.access_token);

const username = await fetch("https://oauth2.scratch-wiki.info/w/rest.php/soa2/v0/user", {
headers: {
Authorization: `Bearer ${btoa(response.access_token)}`
}
}).then(res => res.status);

console.log(username);

res.status(200);
res.send("hi");
});
}
24 changes: 24 additions & 0 deletions api/v1/routes/users/oauth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
module.exports = (app, utils) => {
app.get("/api/v1/users/oauth", async function (req, res) {
// get the method
const packet = req.query;

const method = packet.method;

if (!method) {
utils.error(res, 400, "InvalidData");
return;
}

// using switch case cuz erm i like it
switch (method) {
case "scratch":
let state = await utils.UserManager.generateOAuth2State();
res.redirect(`https://oauth2.scratch-wiki.info/wiki/Special:ScratchOAuth2/authorize?client_id=${utils.env.ScratchOauth2ClientID}&redirect_uri=https://projects.penguinmod.com/api/v1/users/oauthlogin&scopes=identify&state=${state}`);
break;
default:
utils.error(res, 400, "InvalidData");
return;
}
});
}
24 changes: 24 additions & 0 deletions api/v1/routes/users/oauthlocal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
module.exports = (app, utils) => {
app.get("/api/v1/users/oauthlocal", async function (req, res) {
// get the method
const packet = req.query;

const method = packet.method;

if (!method) {
utils.error(res, 400, "InvalidData");
return;
}

// using switch case cuz erm i like it
switch (method) {
case "scratch":
let state = await utils.UserManager.generateOAuth2State();
res.redirect(`https://oauth2.scratch-wiki.info/wiki/Special:ScratchOAuth2/authorize?client_id=${utils.env.ScratchOauth2ClientID}&redirect_uri=http://localhost:8080/api/v1/users/oauthlogin&scopes=identify&state=${state}`);
break;
default:
utils.error(res, 400, "InvalidData");
return;
}
});
}
3 changes: 2 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ const UserManager = new um();
escapeXML: functions.escapeXML,
generateProfileJSON: functions.generateProfileJSON,
safeZipParse: functions.safeZipParse,
error: error
error: error,
env: process.env
});

app.listen(PORT, () => {
Expand Down
2 changes: 2 additions & 0 deletions test.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
<input id="password" type="password" placeholder="Password">
<button onclick="createAccount()">Create Account</button>

<a href="/api/v1/users/oauthlocal?method=scratch">Login with Scratch</a>

<script>
function createAccount() {
var username = document.getElementById('username').value;
Expand Down

0 comments on commit 3b136df

Please sign in to comment.