3
0
Fork 0
mirror of https://github.com/ZeppelinBot/Zeppelin.git synced 2025-05-11 20:55:01 +00:00

Dashboard work and related

This commit is contained in:
Dragory 2019-06-23 19:18:41 +03:00
parent 7bda2b1763
commit b230a73a6f
44 changed files with 637 additions and 272 deletions

34
src/api/archives.ts Normal file
View file

@ -0,0 +1,34 @@
import express, { Request, Response } from "express";
import { GuildArchives } from "../data/GuildArchives";
import { notFound } from "./responses";
import moment from "moment-timezone";
export function initArchives(app: express.Express) {
const archives = new GuildArchives(null);
// Legacy redirect
app.get("/spam-logs/:id", (req: Request, res: Response) => {
res.redirect("/archives/" + req.params.id);
});
app.get("/archives/:id", async (req: Request, res: Response) => {
const archive = await archives.find(req.params.id);
if (!archive) return notFound(res);
let body = archive.body;
// Add some metadata at the end of the log file (but only if it doesn't already have it directly in the body)
if (archive.body.indexOf("Log file generated on") === -1) {
const createdAt = moment(archive.created_at).format("YYYY-MM-DD [at] HH:mm:ss [(+00:00)]");
body += `\n\nLog file generated on ${createdAt}`;
if (archive.expires_at !== null) {
const expiresAt = moment(archive.expires_at).format("YYYY-MM-DD [at] HH:mm:ss [(+00:00)]");
body += `\nExpires at ${expiresAt}`;
}
}
res.setHeader("Content-Type", "text/plain; charset=UTF-8");
res.end(body);
});
}

View file

@ -2,9 +2,11 @@ import express, { Request, Response } from "express";
import passport from "passport";
import OAuth2Strategy from "passport-oauth2";
import CustomStrategy from "passport-custom";
import { DashboardLogins, DashboardLoginUserData } from "../data/DashboardLogins";
import { ApiLogins } from "../data/ApiLogins";
import pick from "lodash.pick";
import https from "https";
import { ApiUserInfo } from "../data/ApiUserInfo";
import { ApiUserInfoData } from "../data/entities/ApiUserInfo";
const DISCORD_API_URL = "https://discordapp.com/api";
@ -53,7 +55,8 @@ export function initAuth(app: express.Express) {
passport.serializeUser((user, done) => done(null, user));
passport.deserializeUser((user, done) => done(null, user));
const dashboardLogins = new DashboardLogins();
const apiLogins = new ApiLogins();
const apiUserInfo = new ApiUserInfo();
// Initialize API tokens
passport.use(
@ -62,7 +65,7 @@ export function initAuth(app: express.Express) {
const apiKey = req.header("X-Api-Key");
if (!apiKey) return cb();
const userId = await dashboardLogins.getUserIdByApiKey(apiKey);
const userId = await apiLogins.getUserIdByApiKey(apiKey);
if (userId) {
return cb(null, { userId });
}
@ -72,6 +75,7 @@ export function initAuth(app: express.Express) {
);
// Initialize OAuth2 for Discord login
// When the user logs in through OAuth2, we create them a "login" (= api token) and update their user info in the DB
passport.use(
new OAuth2Strategy(
{
@ -84,10 +88,10 @@ export function initAuth(app: express.Express) {
},
async (accessToken, refreshToken, profile, cb) => {
const user = await simpleDiscordAPIRequest(accessToken, "users/@me");
const userData = pick(user, ["username", "discriminator", "avatar"]) as DashboardLoginUserData;
const apiKey = await dashboardLogins.addLogin(user.id, userData);
const apiKey = await apiLogins.addLogin(user.id);
const userData = pick(user, ["username", "discriminator", "avatar"]) as ApiUserInfoData;
await apiUserInfo.update(user.id, userData);
// TODO: Revoke access token, we don't need it anymore
console.log("done, calling cb with", apiKey);
cb(null, { apiKey });
},
),
@ -108,7 +112,7 @@ export function initAuth(app: express.Express) {
return res.status(400).json({ error: "No key supplied" });
}
const userId = await dashboardLogins.getUserIdByApiKey(key);
const userId = await apiLogins.getUserIdByApiKey(key);
if (!userId) {
return res.json({ valid: false });
}

View file

@ -2,35 +2,35 @@ import express from "express";
import passport from "passport";
import { AllowedGuilds } from "../data/AllowedGuilds";
import { requireAPIToken } from "./auth";
import { DashboardUsers } from "../data/DashboardUsers";
import { ApiPermissions } from "../data/ApiPermissions";
import { clientError, ok, unauthorized } from "./responses";
import { Configs } from "../data/Configs";
import { DashboardRoles } from "../data/DashboardRoles";
import { ApiRoles } from "../data/ApiRoles";
export function initGuildsAPI(app: express.Express) {
const guildAPIRouter = express.Router();
requireAPIToken(guildAPIRouter);
const allowedGuilds = new AllowedGuilds();
const dashboardUsers = new DashboardUsers();
const apiPermissions = new ApiPermissions();
const configs = new Configs();
guildAPIRouter.get("/guilds/available", async (req, res) => {
const guilds = await allowedGuilds.getForDashboardUser(req.user.userId);
const guilds = await allowedGuilds.getForApiUser(req.user.userId);
res.json(guilds);
});
guildAPIRouter.get("/guilds/:guildId/config", async (req, res) => {
const dbUser = await dashboardUsers.getByGuildAndUserId(req.params.guildId, req.user.userId);
if (!dbUser) return unauthorized(res);
const permissions = await apiPermissions.getByGuildAndUserId(req.params.guildId, req.user.userId);
if (!permissions) return unauthorized(res);
const config = await configs.getActiveByKey(`guild-${req.params.guildId}`);
res.json({ config: config ? config.config : "" });
});
guildAPIRouter.post("/guilds/:guildId/config", async (req, res) => {
const dbUser = await dashboardUsers.getByGuildAndUserId(req.params.guildId, req.user.userId);
if (!dbUser || DashboardRoles[dbUser.role] < DashboardRoles.Editor) return unauthorized(res);
const permissions = await apiPermissions.getByGuildAndUserId(req.params.guildId, req.user.userId);
if (!permissions || ApiRoles[permissions.role] < ApiRoles.Editor) return unauthorized(res);
const config = req.body.config;
if (config == null) return clientError(res, "No config supplied");

View file

@ -1,9 +1,12 @@
import { error, notFound } from "./responses";
require("dotenv").config();
import express from "express";
import cors from "cors";
import { initAuth } from "./auth";
import { initGuildsAPI } from "./guilds";
import { initArchives } from "./archives";
import { connect } from "../data/db";
console.log("Connecting to database...");
@ -19,16 +22,23 @@ connect().then(() => {
initAuth(app);
initGuildsAPI(app);
initArchives(app);
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.json({ error: err.message });
});
// Default route
app.get("/", (req, res) => {
res.end({ status: "cookies" });
});
// Error response
app.use((err, req, res, next) => {
error(res, err.message, err.status || 500);
});
// 404 response
app.use((req, res, next) => {
return notFound(res);
});
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`API server listening on port ${port}`));
});

View file

@ -4,8 +4,20 @@ export function unauthorized(res: Response) {
res.status(403).json({ error: "Unauthorized" });
}
export function error(res: Response, message: string, statusCode: number = 500) {
res.status(statusCode).json({ error: message });
}
export function serverError(res: Response, message: string) {
error(res, message, 500);
}
export function clientError(res: Response, message: string) {
res.status(400).json({ error: message });
error(res, message, 400);
}
export function notFound(res: Response) {
res.status(404).json({ error: "Not found" });
}
export function ok(res: Response) {