social-login-api/index.mjs

84 lines
2.0 KiB
JavaScript

import { config } from "dotenv";
config();
import express from "express";
import jwt from "jsonwebtoken";
import { MongoClient } from "mongodb";
const client = new MongoClient(process.env.MONGODB);
const app = express();
app.get("/", (_, res) =>
res.send(
"social login api\nsource code: https://git.revolt.chat/revolt/social-login-api"
)
);
app.get("/jwt", async (req, res) => {
const token = req.headers["x-session-token"];
if (typeof token === "string") {
const session = await client.db("revolt").collection("sessions").findOne({
token,
});
if (session) {
const user = await client.db("revolt").collection("users").findOne({
_id: session.user_id,
});
if (user) {
res.send(
jwt.sign(
{
id: user._id,
},
process.env.JWT_SECRET
)
);
} else {
res.status(400).send("No user.");
}
} else {
res.status(403).send("No session.");
}
} else {
res.status(400).send("No token.");
}
});
if (typeof process.env.SERVER_TOKEN !== "string")
throw "Must specify server tokens";
const tokens = process.env.SERVER_TOKEN.split(",");
app.post("/info", async (req, res) => {
if (!tokens.includes(req.headers["x-server"])) {
return res.status(403).send("Not server.");
}
const token = req.headers["x-jwt"];
if (token) {
try {
const { id } = jwt.verify(token, process.env.JWT_SECRET);
const user = await client.db("revolt").collection("users").findOne({
_id: id,
});
res.send({
id: user._id,
username: user.username,
displayName: user.display_name ?? null,
discriminator: user.discriminator,
avatar: user.avatar?._id ?? null,
});
} catch (err) {
res.status(400).send("Invalid JWT.");
}
} else {
res.status(400).send("No token.");
}
});
app.listen(50003, () => console.info("listening on :50003"));