Dashboard work and related
This commit is contained in:
parent
7bda2b1763
commit
b230a73a6f
44 changed files with 637 additions and 272 deletions
7
dashboard/.editorconfig
Normal file
7
dashboard/.editorconfig
Normal file
|
@ -0,0 +1,7 @@
|
||||||
|
root = true
|
||||||
|
|
||||||
|
[*]
|
||||||
|
end_of_line = lf
|
||||||
|
insert_final_newline = true
|
||||||
|
indent_style = space
|
||||||
|
indent_size = 2
|
19
dashboard/package-lock.json
generated
19
dashboard/package-lock.json
generated
|
@ -2020,6 +2020,16 @@
|
||||||
"integrity": "sha1-hZgoeOIbmOHGZCXgPQF0eI9Wnug=",
|
"integrity": "sha1-hZgoeOIbmOHGZCXgPQF0eI9Wnug=",
|
||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
|
"bulma": {
|
||||||
|
"version": "0.7.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/bulma/-/bulma-0.7.5.tgz",
|
||||||
|
"integrity": "sha512-cX98TIn0I6sKba/DhW0FBjtaDpxTelU166pf7ICXpCCuplHWyu6C9LYZmL5PEsnePIeJaiorsTEzzNk3Tsm1hw=="
|
||||||
|
},
|
||||||
|
"bulmaswatch": {
|
||||||
|
"version": "0.7.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/bulmaswatch/-/bulmaswatch-0.7.2.tgz",
|
||||||
|
"integrity": "sha512-qickVpky/vv/PX/G7DVz1UpYPncJIjoxbovVELf48tgZ7Fd8UAzfWLSzniPWHwPt1YAq/UX9CGTtcl0AbxSMYg=="
|
||||||
|
},
|
||||||
"cache-base": {
|
"cache-base": {
|
||||||
"version": "1.0.1",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/cache-base/-/cache-base-1.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/cache-base/-/cache-base-1.0.1.tgz",
|
||||||
|
@ -6551,6 +6561,15 @@
|
||||||
"clones": "^1.2.0"
|
"clones": "^1.2.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"sass": {
|
||||||
|
"version": "1.21.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/sass/-/sass-1.21.0.tgz",
|
||||||
|
"integrity": "sha512-67hIIOZZtarbhI2aSgKBPDUgn+VqetduKoD+ZSYeIWg+ksNioTzeX+R2gUdebDoolvKNsQ/GY9NDxctbXluTNA==",
|
||||||
|
"dev": true,
|
||||||
|
"requires": {
|
||||||
|
"chokidar": "^2.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"sax": {
|
"sax": {
|
||||||
"version": "1.2.4",
|
"version": "1.2.4",
|
||||||
"resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz",
|
"resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz",
|
||||||
|
|
|
@ -13,9 +13,12 @@
|
||||||
"babel-plugin-transform-object-rest-spread": "^6.26.0",
|
"babel-plugin-transform-object-rest-spread": "^6.26.0",
|
||||||
"babel-plugin-transform-runtime": "^6.23.0",
|
"babel-plugin-transform-runtime": "^6.23.0",
|
||||||
"parcel-bundler": "^1.12.3",
|
"parcel-bundler": "^1.12.3",
|
||||||
|
"sass": "^1.21.0",
|
||||||
"vue-template-compiler": "^2.6.10"
|
"vue-template-compiler": "^2.6.10"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"bulma": "^0.7.5",
|
||||||
|
"bulmaswatch": "^0.7.2",
|
||||||
"js-cookie": "^2.2.0",
|
"js-cookie": "^2.2.0",
|
||||||
"vue": "^2.6.10",
|
"vue": "^2.6.10",
|
||||||
"vue-codemirror": "^4.0.6",
|
"vue-codemirror": "^4.0.6",
|
||||||
|
|
|
@ -1,15 +1,25 @@
|
||||||
import { NavigationGuard } from "vue-router";
|
import { NavigationGuard } from "vue-router";
|
||||||
import { RootStore } from "./store";
|
import { RootStore } from "./store";
|
||||||
|
|
||||||
export const authGuard: NavigationGuard = async (to, from, next) => {
|
const isAuthenticated = async () => {
|
||||||
if (RootStore.state.auth.apiKey) return next(); // We have an API key -> authenticated
|
if (RootStore.state.auth.apiKey) return true; // We have an API key -> authenticated
|
||||||
if (RootStore.state.auth.loadedInitialAuth) return next("/login"); // No API key and initial auth data was already loaded -> not authenticated
|
if (RootStore.state.auth.loadedInitialAuth) return false; // No API key and initial auth data was already loaded -> not authenticated
|
||||||
await RootStore.dispatch("auth/loadInitialAuth"); // Initial auth data wasn't loaded yet (per above check) -> load it now
|
await RootStore.dispatch("auth/loadInitialAuth"); // Initial auth data wasn't loaded yet (per above check) -> load it now
|
||||||
if (RootStore.state.auth.apiKey) return next();
|
if (RootStore.state.auth.apiKey) return true;
|
||||||
next("/login"); // Still no API key -> not authenticated
|
return false; // Still no API key -> not authenticated
|
||||||
|
};
|
||||||
|
|
||||||
|
export const authGuard: NavigationGuard = async (to, from, next) => {
|
||||||
|
if (await isAuthenticated()) return next();
|
||||||
|
next("/");
|
||||||
};
|
};
|
||||||
|
|
||||||
export const loginCallbackGuard: NavigationGuard = async (to, from, next) => {
|
export const loginCallbackGuard: NavigationGuard = async (to, from, next) => {
|
||||||
await RootStore.dispatch("auth/setApiKey", to.query.apiKey);
|
await RootStore.dispatch("auth/setApiKey", to.query.apiKey);
|
||||||
next("/dashboard");
|
next("/dashboard");
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const authRedirectGuard: NavigationGuard = async (to, form, next) => {
|
||||||
|
if (await isAuthenticated()) return next("/dashboard");
|
||||||
|
window.location.href = `${process.env.API_URL}/auth/login`;
|
||||||
|
};
|
||||||
|
|
|
@ -1,3 +1,6 @@
|
||||||
<template>
|
<template>
|
||||||
<router-view></router-view>
|
<router-view></router-view>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
</script>
|
||||||
|
|
|
@ -1,36 +1,46 @@
|
||||||
<template>
|
<template>
|
||||||
<div v-if="loading">
|
<div class="dashboard">
|
||||||
Loading...
|
<nav class="navbar" role="navigation" aria-label="main navigation">
|
||||||
</div>
|
<div class="container">
|
||||||
<div v-else>
|
<div class="navbar-brand">
|
||||||
<h1>Guilds</h1>
|
<div class="navbar-item">
|
||||||
<table v-for="guild in guilds">
|
<img class="dashboard-logo" src="../img/logo.png" aria-hidden="true">
|
||||||
<tr>
|
<h1 class="dashboard-title">Zeppelin Dashboard</h1>
|
||||||
<td>{{ guild.guild_id }}</td>
|
</div>
|
||||||
<td>{{ guild.name }}</td>
|
</div>
|
||||||
<td>
|
|
||||||
<a v-bind:href="'/dashboard/guilds/' + guild.guild_id + '/config'">Config</a>
|
<div class="navbar-menu is-active">
|
||||||
</td>
|
<div class="navbar-start">
|
||||||
</tr>
|
<router-link to="/dashboard" class="navbar-item">Guilds</router-link>
|
||||||
</table>
|
<a href="#" class="navbar-item">Docs</a>
|
||||||
|
<a href="#" class="navbar-item">Log out</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<div class="section">
|
||||||
|
<div class="container">
|
||||||
|
<router-view></router-view>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<style scoped>
|
||||||
import {mapState} from "vuex";
|
.dashboard-logo {
|
||||||
|
margin-right: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
export default {
|
.dashboard-title {
|
||||||
async mounted() {
|
font-weight: 600;
|
||||||
await this.$store.dispatch("guilds/loadAvailableGuilds");
|
}
|
||||||
this.loading = false;
|
</style>
|
||||||
},
|
|
||||||
data() {
|
<script>
|
||||||
return { loading: true };
|
export default {
|
||||||
},
|
async mounted() {
|
||||||
computed: {
|
await import("../style/dashboard.scss");
|
||||||
...mapState('guilds', {
|
}
|
||||||
guilds: 'available',
|
};
|
||||||
}),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
</script>
|
</script>
|
||||||
|
|
|
@ -3,14 +3,23 @@
|
||||||
Loading...
|
Loading...
|
||||||
</div>
|
</div>
|
||||||
<div v-else>
|
<div v-else>
|
||||||
<h1>Config for {{ guild.name }}</h1>
|
<h2 class="title is-1">Config for {{ guild.name }}</h2>
|
||||||
<codemirror v-model="editableConfig" :options="cmConfig"></codemirror>
|
<codemirror v-model="editableConfig" :options="cmConfig"></codemirror>
|
||||||
<button v-on:click="save" :disabled="saving">Save</button>
|
<button class="button" v-on:click="save" :disabled="saving">Save</button>
|
||||||
<span v-if="saving">Saving...</span>
|
<span v-if="saving">Saving...</span>
|
||||||
<span v-else-if="saved">Saved!</span>
|
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.vue-codemirror {
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
>>> .CodeMirror {
|
||||||
|
height: 70vh;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
import {mapState} from "vuex";
|
import {mapState} from "vuex";
|
||||||
import { codemirror } from "vue-codemirror";
|
import { codemirror } from "vue-codemirror";
|
||||||
|
@ -37,7 +46,6 @@
|
||||||
return {
|
return {
|
||||||
loading: true,
|
loading: true,
|
||||||
saving: false,
|
saving: false,
|
||||||
saved: false,
|
|
||||||
editableConfig: null,
|
editableConfig: null,
|
||||||
cmConfig: {
|
cmConfig: {
|
||||||
indentWithTabs: false,
|
indentWithTabs: false,
|
||||||
|
@ -51,7 +59,7 @@
|
||||||
computed: {
|
computed: {
|
||||||
...mapState('guilds', {
|
...mapState('guilds', {
|
||||||
guild() {
|
guild() {
|
||||||
return this.$store.state.guilds.available.find(g => g.guild_id === this.$route.params.guildId);
|
return this.$store.state.guilds.available.find(g => g.id === this.$route.params.guildId);
|
||||||
},
|
},
|
||||||
config() {
|
config() {
|
||||||
return this.$store.state.guilds.configs[this.$route.params.guildId];
|
return this.$store.state.guilds.configs[this.$route.params.guildId];
|
||||||
|
@ -65,9 +73,7 @@
|
||||||
guildId: this.$route.params.guildId,
|
guildId: this.$route.params.guildId,
|
||||||
config: this.editableConfig,
|
config: this.editableConfig,
|
||||||
});
|
});
|
||||||
this.saving = false;
|
this.$router.push("/dashboard");
|
||||||
this.saved = true;
|
|
||||||
setTimeout(() => this.saved = false, 2500);
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
};
|
};
|
61
dashboard/src/components/DashboardGuildList.vue
Normal file
61
dashboard/src/components/DashboardGuildList.vue
Normal file
|
@ -0,0 +1,61 @@
|
||||||
|
<template>
|
||||||
|
<div v-if="loading">
|
||||||
|
Loading...
|
||||||
|
</div>
|
||||||
|
<div v-else>
|
||||||
|
<h2 class="title is-2">Guilds</h2>
|
||||||
|
<table class="table">
|
||||||
|
<tr v-for="guild in guilds">
|
||||||
|
<td>
|
||||||
|
<img v-if="guild.icon" class="guild-logo" :src="guild.icon" :aria-label="'Logo for guild ' + guild.name">
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<div class="guild-name">{{ guild.name }}</div>
|
||||||
|
<div class="guild-id">{{ guild.id }}</div>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<router-link class="button" :to="'/dashboard/guilds/' + guild.id + '/config'">Config</router-link>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.table td {
|
||||||
|
vertical-align: middle;
|
||||||
|
}
|
||||||
|
|
||||||
|
.guild-logo {
|
||||||
|
display: block;
|
||||||
|
width: 42px;
|
||||||
|
border-radius: 50%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.guild-name {
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.guild-id {
|
||||||
|
color: hsla(220, 100%, 95%, 0.6);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
import {mapState} from "vuex";
|
||||||
|
|
||||||
|
export default {
|
||||||
|
async mounted() {
|
||||||
|
await this.$store.dispatch("guilds/loadAvailableGuilds");
|
||||||
|
this.loading = false;
|
||||||
|
},
|
||||||
|
data() {
|
||||||
|
return { loading: true };
|
||||||
|
},
|
||||||
|
computed: {
|
||||||
|
...mapState('guilds', {
|
||||||
|
guilds: 'available',
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
</script>
|
|
@ -1,11 +0,0 @@
|
||||||
<template>
|
|
||||||
<p>Redirecting...</p>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
export default {
|
|
||||||
created() {
|
|
||||||
this.$router.push('/login');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
</script>
|
|
|
@ -1,14 +0,0 @@
|
||||||
<template>
|
|
||||||
<a v-bind:href="env.API_URL + '/auth/login'">Login</a>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
export default {
|
|
||||||
|
|
||||||
computed: {
|
|
||||||
blah() {
|
|
||||||
return this.$state.apiKey;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
</script>
|
|
19
dashboard/src/components/Splash.vue
Normal file
19
dashboard/src/components/Splash.vue
Normal file
|
@ -0,0 +1,19 @@
|
||||||
|
<template>
|
||||||
|
<div class="splash">
|
||||||
|
<div class="wrapper">
|
||||||
|
<img class="logo" src="../img/logo.png" alt="Zeppelin Logo">
|
||||||
|
<h1>Zeppelin</h1>
|
||||||
|
<div class="description">
|
||||||
|
Zeppelin is a private moderation bot for Discord, designed with large servers and reliability in mind.
|
||||||
|
</div>
|
||||||
|
<div class="actions">
|
||||||
|
<a class="btn" href="/login">Dashboard</a>
|
||||||
|
<a class="btn disabled" href="#">Docs</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
import "../style/splash.scss";
|
||||||
|
</script>
|
BIN
dashboard/src/img/logo.png
Normal file
BIN
dashboard/src/img/logo.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 26 KiB |
|
@ -1,3 +1,5 @@
|
||||||
|
import "./style/base.scss";
|
||||||
|
|
||||||
import Vue from "vue";
|
import Vue from "vue";
|
||||||
import { RootStore } from "./store";
|
import { RootStore } from "./store";
|
||||||
import { router } from "./routes";
|
import { router } from "./routes";
|
||||||
|
|
|
@ -1,30 +1,37 @@
|
||||||
import Vue from "vue";
|
import Vue from "vue";
|
||||||
import VueRouter, { RouteConfig } from "vue-router";
|
import VueRouter, { RouteConfig } from "vue-router";
|
||||||
import Index from "./components/Index.vue";
|
import Splash from "./components/Splash.vue";
|
||||||
import Login from "./components/Login.vue";
|
import Login from "./components/Login.vue";
|
||||||
import LoginCallback from "./components/LoginCallback.vue";
|
import LoginCallback from "./components/LoginCallback.vue";
|
||||||
import GuildConfigEditor from "./components/GuildConfigEditor.vue";
|
import DashboardGuildList from "./components/DashboardGuildList.vue";
|
||||||
|
import DashboardGuildConfigEditor from "./components/DashboardGuildConfigEditor.vue";
|
||||||
import Dashboard from "./components/Dashboard.vue";
|
import Dashboard from "./components/Dashboard.vue";
|
||||||
import { authGuard, loginCallbackGuard } from "./auth";
|
import { authGuard, authRedirectGuard, loginCallbackGuard } from "./auth";
|
||||||
|
|
||||||
Vue.use(VueRouter);
|
Vue.use(VueRouter);
|
||||||
|
|
||||||
const publicRoutes: RouteConfig[] = [
|
|
||||||
{ path: "/", component: Index },
|
|
||||||
{ path: "/login", component: Login },
|
|
||||||
{ path: "/login-callback", beforeEnter: loginCallbackGuard },
|
|
||||||
];
|
|
||||||
|
|
||||||
const authenticatedRoutes: RouteConfig[] = [
|
|
||||||
{ path: "/dashboard", component: Dashboard },
|
|
||||||
{ path: "/dashboard/guilds/:guildId/config", component: GuildConfigEditor },
|
|
||||||
];
|
|
||||||
|
|
||||||
authenticatedRoutes.forEach(route => {
|
|
||||||
route.beforeEnter = authGuard;
|
|
||||||
});
|
|
||||||
|
|
||||||
export const router = new VueRouter({
|
export const router = new VueRouter({
|
||||||
mode: "history",
|
mode: "history",
|
||||||
routes: [...publicRoutes, ...authenticatedRoutes],
|
routes: [
|
||||||
|
{ path: "/", component: Splash },
|
||||||
|
{ path: "/login", beforeEnter: authRedirectGuard },
|
||||||
|
{ path: "/login-callback", beforeEnter: loginCallbackGuard },
|
||||||
|
|
||||||
|
// Dashboard
|
||||||
|
{
|
||||||
|
path: "/dashboard",
|
||||||
|
component: Dashboard,
|
||||||
|
beforeEnter: authGuard,
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
path: "",
|
||||||
|
component: DashboardGuildList,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: "guilds/:guildId/config",
|
||||||
|
component: DashboardGuildConfigEditor,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
});
|
});
|
||||||
|
|
6
dashboard/src/style/base.scss
Normal file
6
dashboard/src/style/base.scss
Normal file
|
@ -0,0 +1,6 @@
|
||||||
|
@import url('https://fonts.googleapis.com/css?family=Open+Sans:300,400,600&display=swap');
|
||||||
|
@import "~bulma/sass/base/minireset";
|
||||||
|
|
||||||
|
body {
|
||||||
|
font: normal 16px/1.4 'Open Sans', sans-serif;
|
||||||
|
}
|
0
dashboard/src/style/dark-bulma-variables.scss
Normal file
0
dashboard/src/style/dark-bulma-variables.scss
Normal file
5
dashboard/src/style/dashboard.scss
Normal file
5
dashboard/src/style/dashboard.scss
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
$family-primary: 'Open Sans', sans-serif;
|
||||||
|
|
||||||
|
@import "~bulmaswatch/superhero/_variables";
|
||||||
|
@import "~bulma/bulma";
|
||||||
|
@import "~bulmaswatch/superhero/_overrides";
|
72
dashboard/src/style/splash.scss
Normal file
72
dashboard/src/style/splash.scss
Normal file
|
@ -0,0 +1,72 @@
|
||||||
|
.splash {
|
||||||
|
width: 100vw;
|
||||||
|
height: 100vh;
|
||||||
|
|
||||||
|
background-color: #7289da;
|
||||||
|
background-image: linear-gradient(225deg, #7289da 0%, #5d70b4 100%);
|
||||||
|
color: #fff;
|
||||||
|
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
|
||||||
|
a {
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wrapper {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: auto 400px;
|
||||||
|
grid-template-rows: auto repeat(4, 1fr);
|
||||||
|
align-items: start;
|
||||||
|
|
||||||
|
.logo {
|
||||||
|
grid-column: 1;
|
||||||
|
grid-row: 1/-1; // Span all
|
||||||
|
|
||||||
|
width: 300px;
|
||||||
|
height: 300px;
|
||||||
|
margin-right: 64px;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
grid-column: 2;
|
||||||
|
|
||||||
|
font-size: 80px;
|
||||||
|
font-weight: 300;
|
||||||
|
margin-top: 40px
|
||||||
|
}
|
||||||
|
|
||||||
|
.description {
|
||||||
|
grid-column: 2;
|
||||||
|
|
||||||
|
color: #f1f5ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.actions {
|
||||||
|
grid-column: 2;
|
||||||
|
|
||||||
|
display: flex;
|
||||||
|
|
||||||
|
.btn {
|
||||||
|
margin: 12px;
|
||||||
|
text-decoration: none;
|
||||||
|
padding: 8px 24px;
|
||||||
|
border: 1px solid #fff;
|
||||||
|
border-radius: 4px;
|
||||||
|
transition: all 120ms ease-in-out;
|
||||||
|
background-color: hsla(0, 0%, 100%, 0.05);
|
||||||
|
|
||||||
|
&:not(.disabled):hover {
|
||||||
|
background-color: hsla(0, 0%, 100%, 0.25);
|
||||||
|
box-shadow: 0 3px 12px -2px hsla(0, 0%, 0%, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
&.disabled {
|
||||||
|
cursor: default;
|
||||||
|
opacity: 0.75;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
34
src/api/archives.ts
Normal file
34
src/api/archives.ts
Normal 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);
|
||||||
|
});
|
||||||
|
}
|
|
@ -2,9 +2,11 @@ import express, { Request, Response } from "express";
|
||||||
import passport from "passport";
|
import passport from "passport";
|
||||||
import OAuth2Strategy from "passport-oauth2";
|
import OAuth2Strategy from "passport-oauth2";
|
||||||
import CustomStrategy from "passport-custom";
|
import CustomStrategy from "passport-custom";
|
||||||
import { DashboardLogins, DashboardLoginUserData } from "../data/DashboardLogins";
|
import { ApiLogins } from "../data/ApiLogins";
|
||||||
import pick from "lodash.pick";
|
import pick from "lodash.pick";
|
||||||
import https from "https";
|
import https from "https";
|
||||||
|
import { ApiUserInfo } from "../data/ApiUserInfo";
|
||||||
|
import { ApiUserInfoData } from "../data/entities/ApiUserInfo";
|
||||||
|
|
||||||
const DISCORD_API_URL = "https://discordapp.com/api";
|
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.serializeUser((user, done) => done(null, user));
|
||||||
passport.deserializeUser((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
|
// Initialize API tokens
|
||||||
passport.use(
|
passport.use(
|
||||||
|
@ -62,7 +65,7 @@ export function initAuth(app: express.Express) {
|
||||||
const apiKey = req.header("X-Api-Key");
|
const apiKey = req.header("X-Api-Key");
|
||||||
if (!apiKey) return cb();
|
if (!apiKey) return cb();
|
||||||
|
|
||||||
const userId = await dashboardLogins.getUserIdByApiKey(apiKey);
|
const userId = await apiLogins.getUserIdByApiKey(apiKey);
|
||||||
if (userId) {
|
if (userId) {
|
||||||
return cb(null, { userId });
|
return cb(null, { userId });
|
||||||
}
|
}
|
||||||
|
@ -72,6 +75,7 @@ export function initAuth(app: express.Express) {
|
||||||
);
|
);
|
||||||
|
|
||||||
// Initialize OAuth2 for Discord login
|
// 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(
|
passport.use(
|
||||||
new OAuth2Strategy(
|
new OAuth2Strategy(
|
||||||
{
|
{
|
||||||
|
@ -84,10 +88,10 @@ export function initAuth(app: express.Express) {
|
||||||
},
|
},
|
||||||
async (accessToken, refreshToken, profile, cb) => {
|
async (accessToken, refreshToken, profile, cb) => {
|
||||||
const user = await simpleDiscordAPIRequest(accessToken, "users/@me");
|
const user = await simpleDiscordAPIRequest(accessToken, "users/@me");
|
||||||
const userData = pick(user, ["username", "discriminator", "avatar"]) as DashboardLoginUserData;
|
const apiKey = await apiLogins.addLogin(user.id);
|
||||||
const apiKey = await dashboardLogins.addLogin(user.id, userData);
|
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
|
// TODO: Revoke access token, we don't need it anymore
|
||||||
console.log("done, calling cb with", apiKey);
|
|
||||||
cb(null, { apiKey });
|
cb(null, { apiKey });
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
|
@ -108,7 +112,7 @@ export function initAuth(app: express.Express) {
|
||||||
return res.status(400).json({ error: "No key supplied" });
|
return res.status(400).json({ error: "No key supplied" });
|
||||||
}
|
}
|
||||||
|
|
||||||
const userId = await dashboardLogins.getUserIdByApiKey(key);
|
const userId = await apiLogins.getUserIdByApiKey(key);
|
||||||
if (!userId) {
|
if (!userId) {
|
||||||
return res.json({ valid: false });
|
return res.json({ valid: false });
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,35 +2,35 @@ import express from "express";
|
||||||
import passport from "passport";
|
import passport from "passport";
|
||||||
import { AllowedGuilds } from "../data/AllowedGuilds";
|
import { AllowedGuilds } from "../data/AllowedGuilds";
|
||||||
import { requireAPIToken } from "./auth";
|
import { requireAPIToken } from "./auth";
|
||||||
import { DashboardUsers } from "../data/DashboardUsers";
|
import { ApiPermissions } from "../data/ApiPermissions";
|
||||||
import { clientError, ok, unauthorized } from "./responses";
|
import { clientError, ok, unauthorized } from "./responses";
|
||||||
import { Configs } from "../data/Configs";
|
import { Configs } from "../data/Configs";
|
||||||
import { DashboardRoles } from "../data/DashboardRoles";
|
import { ApiRoles } from "../data/ApiRoles";
|
||||||
|
|
||||||
export function initGuildsAPI(app: express.Express) {
|
export function initGuildsAPI(app: express.Express) {
|
||||||
const guildAPIRouter = express.Router();
|
const guildAPIRouter = express.Router();
|
||||||
requireAPIToken(guildAPIRouter);
|
requireAPIToken(guildAPIRouter);
|
||||||
|
|
||||||
const allowedGuilds = new AllowedGuilds();
|
const allowedGuilds = new AllowedGuilds();
|
||||||
const dashboardUsers = new DashboardUsers();
|
const apiPermissions = new ApiPermissions();
|
||||||
const configs = new Configs();
|
const configs = new Configs();
|
||||||
|
|
||||||
guildAPIRouter.get("/guilds/available", async (req, res) => {
|
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);
|
res.json(guilds);
|
||||||
});
|
});
|
||||||
|
|
||||||
guildAPIRouter.get("/guilds/:guildId/config", async (req, res) => {
|
guildAPIRouter.get("/guilds/:guildId/config", async (req, res) => {
|
||||||
const dbUser = await dashboardUsers.getByGuildAndUserId(req.params.guildId, req.user.userId);
|
const permissions = await apiPermissions.getByGuildAndUserId(req.params.guildId, req.user.userId);
|
||||||
if (!dbUser) return unauthorized(res);
|
if (!permissions) return unauthorized(res);
|
||||||
|
|
||||||
const config = await configs.getActiveByKey(`guild-${req.params.guildId}`);
|
const config = await configs.getActiveByKey(`guild-${req.params.guildId}`);
|
||||||
res.json({ config: config ? config.config : "" });
|
res.json({ config: config ? config.config : "" });
|
||||||
});
|
});
|
||||||
|
|
||||||
guildAPIRouter.post("/guilds/:guildId/config", async (req, res) => {
|
guildAPIRouter.post("/guilds/:guildId/config", async (req, res) => {
|
||||||
const dbUser = await dashboardUsers.getByGuildAndUserId(req.params.guildId, req.user.userId);
|
const permissions = await apiPermissions.getByGuildAndUserId(req.params.guildId, req.user.userId);
|
||||||
if (!dbUser || DashboardRoles[dbUser.role] < DashboardRoles.Editor) return unauthorized(res);
|
if (!permissions || ApiRoles[permissions.role] < ApiRoles.Editor) return unauthorized(res);
|
||||||
|
|
||||||
const config = req.body.config;
|
const config = req.body.config;
|
||||||
if (config == null) return clientError(res, "No config supplied");
|
if (config == null) return clientError(res, "No config supplied");
|
||||||
|
|
|
@ -1,9 +1,12 @@
|
||||||
|
import { error, notFound } from "./responses";
|
||||||
|
|
||||||
require("dotenv").config();
|
require("dotenv").config();
|
||||||
|
|
||||||
import express from "express";
|
import express from "express";
|
||||||
import cors from "cors";
|
import cors from "cors";
|
||||||
import { initAuth } from "./auth";
|
import { initAuth } from "./auth";
|
||||||
import { initGuildsAPI } from "./guilds";
|
import { initGuildsAPI } from "./guilds";
|
||||||
|
import { initArchives } from "./archives";
|
||||||
import { connect } from "../data/db";
|
import { connect } from "../data/db";
|
||||||
|
|
||||||
console.log("Connecting to database...");
|
console.log("Connecting to database...");
|
||||||
|
@ -19,16 +22,23 @@ connect().then(() => {
|
||||||
|
|
||||||
initAuth(app);
|
initAuth(app);
|
||||||
initGuildsAPI(app);
|
initGuildsAPI(app);
|
||||||
|
initArchives(app);
|
||||||
|
|
||||||
app.use((err, req, res, next) => {
|
// Default route
|
||||||
res.status(err.status || 500);
|
|
||||||
res.json({ error: err.message });
|
|
||||||
});
|
|
||||||
|
|
||||||
app.get("/", (req, res) => {
|
app.get("/", (req, res) => {
|
||||||
res.end({ status: "cookies" });
|
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;
|
const port = process.env.PORT || 3000;
|
||||||
app.listen(port, () => console.log(`API server listening on port ${port}`));
|
app.listen(port, () => console.log(`API server listening on port ${port}`));
|
||||||
});
|
});
|
||||||
|
|
|
@ -4,8 +4,20 @@ export function unauthorized(res: Response) {
|
||||||
res.status(403).json({ error: "Unauthorized" });
|
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) {
|
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) {
|
export function ok(res: Response) {
|
||||||
|
|
|
@ -21,21 +21,25 @@ export class AllowedGuilds extends BaseRepository {
|
||||||
async isAllowed(guildId) {
|
async isAllowed(guildId) {
|
||||||
const count = await this.allowedGuilds.count({
|
const count = await this.allowedGuilds.count({
|
||||||
where: {
|
where: {
|
||||||
guild_id: guildId,
|
id: guildId,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
return count !== 0;
|
return count !== 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
getForDashboardUser(userId) {
|
getForApiUser(userId) {
|
||||||
return this.allowedGuilds
|
return this.allowedGuilds
|
||||||
.createQueryBuilder("allowed_guilds")
|
.createQueryBuilder("allowed_guilds")
|
||||||
.innerJoin(
|
.innerJoin(
|
||||||
"dashboard_users",
|
"api_permissions",
|
||||||
"dashboard_users",
|
"api_permissions",
|
||||||
"dashboard_users.guild_id = allowed_guilds.guild_id AND dashboard_users.user_id = :userId",
|
"api_permissions.guild_id = allowed_guilds.id AND api_permissions.user_id = :userId",
|
||||||
{ userId },
|
{ userId },
|
||||||
)
|
)
|
||||||
.getMany();
|
.getMany();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
updateInfo(id, name, icon) {
|
||||||
|
return this.allowedGuilds.update({ id }, { name, icon });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
import { getRepository, Repository } from "typeorm";
|
import { getRepository, Repository } from "typeorm";
|
||||||
import { DashboardLogin } from "./entities/DashboardLogin";
|
import { ApiLogin } from "./entities/ApiLogin";
|
||||||
import { BaseRepository } from "./BaseRepository";
|
import { BaseRepository } from "./BaseRepository";
|
||||||
import crypto from "crypto";
|
import crypto from "crypto";
|
||||||
import moment from "moment-timezone";
|
import moment from "moment-timezone";
|
||||||
|
@ -9,18 +9,12 @@ import uuidv4 from "uuid/v4";
|
||||||
import { DBDateFormat } from "../utils";
|
import { DBDateFormat } from "../utils";
|
||||||
import { log } from "util";
|
import { log } from "util";
|
||||||
|
|
||||||
export interface DashboardLoginUserData {
|
export class ApiLogins extends BaseRepository {
|
||||||
username: string;
|
private apiLogins: Repository<ApiLogin>;
|
||||||
discriminator: string;
|
|
||||||
avatar: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class DashboardLogins extends BaseRepository {
|
|
||||||
private dashboardLogins: Repository<DashboardLogin>;
|
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
super();
|
super();
|
||||||
this.dashboardLogins = getRepository(DashboardLogin);
|
this.apiLogins = getRepository(ApiLogin);
|
||||||
}
|
}
|
||||||
|
|
||||||
async getUserIdByApiKey(apiKey: string): Promise<string | null> {
|
async getUserIdByApiKey(apiKey: string): Promise<string | null> {
|
||||||
|
@ -29,7 +23,7 @@ export class DashboardLogins extends BaseRepository {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const login = await this.dashboardLogins
|
const login = await this.apiLogins
|
||||||
.createQueryBuilder()
|
.createQueryBuilder()
|
||||||
.where("id = :id", { id: loginId })
|
.where("id = :id", { id: loginId })
|
||||||
.andWhere("expires_at > NOW()")
|
.andWhere("expires_at > NOW()")
|
||||||
|
@ -49,12 +43,12 @@ export class DashboardLogins extends BaseRepository {
|
||||||
return login.user_id;
|
return login.user_id;
|
||||||
}
|
}
|
||||||
|
|
||||||
async addLogin(userId: string, userData: DashboardLoginUserData): Promise<string> {
|
async addLogin(userId: string): Promise<string> {
|
||||||
// Generate random login id
|
// Generate random login id
|
||||||
let loginId;
|
let loginId;
|
||||||
while (true) {
|
while (true) {
|
||||||
loginId = uuidv4();
|
loginId = uuidv4();
|
||||||
const existing = await this.dashboardLogins.findOne({
|
const existing = await this.apiLogins.findOne({
|
||||||
where: {
|
where: {
|
||||||
id: loginId,
|
id: loginId,
|
||||||
},
|
},
|
||||||
|
@ -69,11 +63,10 @@ export class DashboardLogins extends BaseRepository {
|
||||||
const hashedToken = hash.digest("hex");
|
const hashedToken = hash.digest("hex");
|
||||||
|
|
||||||
// Save this to the DB
|
// Save this to the DB
|
||||||
await this.dashboardLogins.insert({
|
await this.apiLogins.insert({
|
||||||
id: loginId,
|
id: loginId,
|
||||||
token: hashedToken,
|
token: hashedToken,
|
||||||
user_id: userId,
|
user_id: userId,
|
||||||
user_data: userData,
|
|
||||||
logged_in_at: moment().format(DBDateFormat),
|
logged_in_at: moment().format(DBDateFormat),
|
||||||
expires_at: moment()
|
expires_at: moment()
|
||||||
.add(1, "day")
|
.add(1, "day")
|
|
@ -1,17 +1,17 @@
|
||||||
import { getRepository, Repository } from "typeorm";
|
import { getRepository, Repository } from "typeorm";
|
||||||
import { DashboardUser } from "./entities/DashboardUser";
|
import { ApiPermission } from "./entities/ApiPermission";
|
||||||
import { BaseRepository } from "./BaseRepository";
|
import { BaseRepository } from "./BaseRepository";
|
||||||
|
|
||||||
export class DashboardUsers extends BaseRepository {
|
export class ApiPermissions extends BaseRepository {
|
||||||
private dashboardUsers: Repository<DashboardUser>;
|
private apiPermissions: Repository<ApiPermission>;
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
super();
|
super();
|
||||||
this.dashboardUsers = getRepository(DashboardUser);
|
this.apiPermissions = getRepository(ApiPermission);
|
||||||
}
|
}
|
||||||
|
|
||||||
getByGuildAndUserId(guildId, userId) {
|
getByGuildAndUserId(guildId, userId) {
|
||||||
return this.dashboardUsers.findOne({
|
return this.apiPermissions.findOne({
|
||||||
where: {
|
where: {
|
||||||
guild_id: guildId,
|
guild_id: guildId,
|
||||||
user_id: userId,
|
user_id: userId,
|
|
@ -1,4 +1,4 @@
|
||||||
export enum DashboardRoles {
|
export enum ApiRoles {
|
||||||
Viewer = 1,
|
Viewer = 1,
|
||||||
Editor,
|
Editor,
|
||||||
Manager,
|
Manager,
|
38
src/data/ApiUserInfo.ts
Normal file
38
src/data/ApiUserInfo.ts
Normal file
|
@ -0,0 +1,38 @@
|
||||||
|
import { getRepository, Repository } from "typeorm";
|
||||||
|
import { ApiUserInfo as ApiUserInfoEntity, ApiUserInfoData } from "./entities/ApiUserInfo";
|
||||||
|
import { BaseRepository } from "./BaseRepository";
|
||||||
|
import { connection } from "./db";
|
||||||
|
import moment from "moment-timezone";
|
||||||
|
import { DBDateFormat } from "../utils";
|
||||||
|
|
||||||
|
export class ApiUserInfo extends BaseRepository {
|
||||||
|
private apiUserInfo: Repository<ApiUserInfoEntity>;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super();
|
||||||
|
this.apiUserInfo = getRepository(ApiUserInfoEntity);
|
||||||
|
}
|
||||||
|
|
||||||
|
get(id) {
|
||||||
|
return this.apiUserInfo.findOne({
|
||||||
|
where: {
|
||||||
|
id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
update(id, data: ApiUserInfoData) {
|
||||||
|
return connection.transaction(async entityManager => {
|
||||||
|
const repo = entityManager.getRepository(ApiUserInfoEntity);
|
||||||
|
|
||||||
|
const existingInfo = await repo.findOne({ where: { id } });
|
||||||
|
const updatedAt = moment().format(DBDateFormat);
|
||||||
|
|
||||||
|
if (existingInfo) {
|
||||||
|
await repo.update({ id }, { data, updated_at: updatedAt });
|
||||||
|
} else {
|
||||||
|
await repo.insert({ id, data, updated_at: updatedAt });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
|
@ -32,6 +32,18 @@ export class Configs extends BaseRepository {
|
||||||
return (await this.getActiveByKey(key)) != null;
|
return (await this.getActiveByKey(key)) != null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getRevisions(key, num = 10) {
|
||||||
|
return this.configs.find({
|
||||||
|
relations: this.getRelations(),
|
||||||
|
where: { key },
|
||||||
|
select: ["id", "key", "is_active", "edited_by", "edited_at"],
|
||||||
|
order: {
|
||||||
|
edited_at: "DESC",
|
||||||
|
},
|
||||||
|
take: num,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
async saveNewRevision(key, config, editedBy) {
|
async saveNewRevision(key, config, editedBy) {
|
||||||
return connection.transaction(async entityManager => {
|
return connection.transaction(async entityManager => {
|
||||||
const repo = entityManager.getRepository(Config);
|
const repo = entityManager.getRepository(Config);
|
||||||
|
|
|
@ -4,7 +4,7 @@ import { Entity, Column, PrimaryColumn, CreateDateColumn } from "typeorm";
|
||||||
export class AllowedGuild {
|
export class AllowedGuild {
|
||||||
@Column()
|
@Column()
|
||||||
@PrimaryColumn()
|
@PrimaryColumn()
|
||||||
guild_id: string;
|
id: string;
|
||||||
|
|
||||||
@Column()
|
@Column()
|
||||||
name: string;
|
name: string;
|
||||||
|
|
25
src/data/entities/ApiLogin.ts
Normal file
25
src/data/entities/ApiLogin.ts
Normal file
|
@ -0,0 +1,25 @@
|
||||||
|
import { Entity, Column, PrimaryColumn, OneToOne, ManyToOne, JoinColumn } from "typeorm";
|
||||||
|
import { ApiUserInfo } from "./ApiUserInfo";
|
||||||
|
|
||||||
|
@Entity("api_logins")
|
||||||
|
export class ApiLogin {
|
||||||
|
@Column()
|
||||||
|
@PrimaryColumn()
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@Column()
|
||||||
|
token: string;
|
||||||
|
|
||||||
|
@Column()
|
||||||
|
user_id: string;
|
||||||
|
|
||||||
|
@Column()
|
||||||
|
logged_in_at: string;
|
||||||
|
|
||||||
|
@Column()
|
||||||
|
expires_at: string;
|
||||||
|
|
||||||
|
@ManyToOne(type => ApiUserInfo, userInfo => userInfo.logins)
|
||||||
|
@JoinColumn({ name: "user_id" })
|
||||||
|
userInfo: ApiUserInfo;
|
||||||
|
}
|
20
src/data/entities/ApiPermission.ts
Normal file
20
src/data/entities/ApiPermission.ts
Normal file
|
@ -0,0 +1,20 @@
|
||||||
|
import { Entity, Column, PrimaryColumn, ManyToOne, JoinColumn } from "typeorm";
|
||||||
|
import { ApiUserInfo } from "./ApiUserInfo";
|
||||||
|
|
||||||
|
@Entity("api_permissions")
|
||||||
|
export class ApiPermission {
|
||||||
|
@Column()
|
||||||
|
@PrimaryColumn()
|
||||||
|
guild_id: string;
|
||||||
|
|
||||||
|
@Column()
|
||||||
|
@PrimaryColumn()
|
||||||
|
user_id: string;
|
||||||
|
|
||||||
|
@Column()
|
||||||
|
role: string;
|
||||||
|
|
||||||
|
@ManyToOne(type => ApiUserInfo, userInfo => userInfo.permissions)
|
||||||
|
@JoinColumn({ name: "user_id" })
|
||||||
|
userInfo: ApiUserInfo;
|
||||||
|
}
|
28
src/data/entities/ApiUserInfo.ts
Normal file
28
src/data/entities/ApiUserInfo.ts
Normal file
|
@ -0,0 +1,28 @@
|
||||||
|
import { Entity, Column, PrimaryColumn, OneToMany } from "typeorm";
|
||||||
|
import { ApiLogin } from "./ApiLogin";
|
||||||
|
import { ApiPermission } from "./ApiPermission";
|
||||||
|
|
||||||
|
export interface ApiUserInfoData {
|
||||||
|
username: string;
|
||||||
|
discriminator: string;
|
||||||
|
avatar: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Entity("api_user_info")
|
||||||
|
export class ApiUserInfo {
|
||||||
|
@Column()
|
||||||
|
@PrimaryColumn()
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@Column("simple-json")
|
||||||
|
data: ApiUserInfoData;
|
||||||
|
|
||||||
|
@Column()
|
||||||
|
updated_at: string;
|
||||||
|
|
||||||
|
@OneToMany(type => ApiLogin, login => login.userInfo)
|
||||||
|
logins: ApiLogin[];
|
||||||
|
|
||||||
|
@OneToMany(type => ApiPermission, perm => perm.userInfo)
|
||||||
|
permissions: ApiPermission[];
|
||||||
|
}
|
|
@ -1,4 +1,5 @@
|
||||||
import { Entity, Column, PrimaryColumn, CreateDateColumn } from "typeorm";
|
import { Entity, Column, PrimaryColumn, CreateDateColumn, ManyToOne, JoinColumn } from "typeorm";
|
||||||
|
import { ApiUserInfo } from "./ApiUserInfo";
|
||||||
|
|
||||||
@Entity("configs")
|
@Entity("configs")
|
||||||
export class Config {
|
export class Config {
|
||||||
|
@ -20,4 +21,8 @@ export class Config {
|
||||||
|
|
||||||
@Column()
|
@Column()
|
||||||
edited_at: string;
|
edited_at: string;
|
||||||
|
|
||||||
|
@ManyToOne(type => ApiUserInfo)
|
||||||
|
@JoinColumn({ name: "edited_by" })
|
||||||
|
userInfo: ApiUserInfo;
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,24 +0,0 @@
|
||||||
import { Entity, Column, PrimaryColumn } from "typeorm";
|
|
||||||
import { DashboardLoginUserData } from "../DashboardLogins";
|
|
||||||
|
|
||||||
@Entity("dashboard_logins")
|
|
||||||
export class DashboardLogin {
|
|
||||||
@Column()
|
|
||||||
@PrimaryColumn()
|
|
||||||
id: string;
|
|
||||||
|
|
||||||
@Column()
|
|
||||||
token: string;
|
|
||||||
|
|
||||||
@Column()
|
|
||||||
user_id: string;
|
|
||||||
|
|
||||||
@Column("simple-json")
|
|
||||||
user_data: DashboardLoginUserData;
|
|
||||||
|
|
||||||
@Column()
|
|
||||||
logged_in_at: string;
|
|
||||||
|
|
||||||
@Column()
|
|
||||||
expires_at: string;
|
|
||||||
}
|
|
|
@ -1,18 +0,0 @@
|
||||||
import { Entity, Column, PrimaryColumn } from "typeorm";
|
|
||||||
|
|
||||||
@Entity("dashboard_users")
|
|
||||||
export class DashboardUser {
|
|
||||||
@Column()
|
|
||||||
@PrimaryColumn()
|
|
||||||
guild_id: string;
|
|
||||||
|
|
||||||
@Column()
|
|
||||||
@PrimaryColumn()
|
|
||||||
user_id: string;
|
|
||||||
|
|
||||||
@Column()
|
|
||||||
username: string;
|
|
||||||
|
|
||||||
@Column()
|
|
||||||
role: string;
|
|
||||||
}
|
|
|
@ -0,0 +1,13 @@
|
||||||
|
import { MigrationInterface, QueryRunner } from "typeorm";
|
||||||
|
|
||||||
|
export class RenameBackendDashboardStuffToAPI1561282151982 implements MigrationInterface {
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<any> {
|
||||||
|
await queryRunner.query(`ALTER TABLE dashboard_users RENAME api_users`);
|
||||||
|
await queryRunner.query(`ALTER TABLE dashboard_logins RENAME api_logins`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<any> {
|
||||||
|
await queryRunner.query(`ALTER TABLE api_users RENAME dashboard_users`);
|
||||||
|
await queryRunner.query(`ALTER TABLE api_logins RENAME dashboard_logins`);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,11 @@
|
||||||
|
import { MigrationInterface, QueryRunner } from "typeorm";
|
||||||
|
|
||||||
|
export class RenameAllowedGuildGuildIdToId1561282552734 implements MigrationInterface {
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<any> {
|
||||||
|
await queryRunner.query("ALTER TABLE `allowed_guilds` CHANGE COLUMN `guild_id` `id` BIGINT(20) NOT NULL FIRST;");
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<any> {
|
||||||
|
await queryRunner.query("ALTER TABLE `allowed_guilds` CHANGE COLUMN `id` `guild_id` BIGINT(20) NOT NULL FIRST;");
|
||||||
|
}
|
||||||
|
}
|
31
src/migrations/1561282950483-CreateApiUserInfoTable.ts
Normal file
31
src/migrations/1561282950483-CreateApiUserInfoTable.ts
Normal file
|
@ -0,0 +1,31 @@
|
||||||
|
import { MigrationInterface, QueryRunner, Table } from "typeorm";
|
||||||
|
|
||||||
|
export class CreateApiUserInfoTable1561282950483 implements MigrationInterface {
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<any> {
|
||||||
|
await queryRunner.createTable(
|
||||||
|
new Table({
|
||||||
|
name: "api_user_info",
|
||||||
|
columns: [
|
||||||
|
{
|
||||||
|
name: "id",
|
||||||
|
type: "bigint",
|
||||||
|
isPrimary: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "data",
|
||||||
|
type: "text",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "updated_at",
|
||||||
|
type: "datetime",
|
||||||
|
default: "now()",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<any> {
|
||||||
|
await queryRunner.dropTable("api_user_info", true);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,11 @@
|
||||||
|
import { MigrationInterface, QueryRunner } from "typeorm";
|
||||||
|
|
||||||
|
export class RenameApiUsersToApiPermissions1561283165823 implements MigrationInterface {
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<any> {
|
||||||
|
await queryRunner.query(`ALTER TABLE api_users RENAME api_permissions`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<any> {
|
||||||
|
await queryRunner.query(`ALTER TABLE api_permissions RENAME api_users`);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,17 @@
|
||||||
|
import { MigrationInterface, QueryRunner } from "typeorm";
|
||||||
|
|
||||||
|
export class DropUserDataFromLoginsAndPermissions1561283405201 implements MigrationInterface {
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<any> {
|
||||||
|
await queryRunner.query("ALTER TABLE `api_logins` DROP COLUMN `user_data`");
|
||||||
|
await queryRunner.query("ALTER TABLE `api_permissions` DROP COLUMN `username`");
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<any> {
|
||||||
|
await queryRunner.query(
|
||||||
|
"ALTER TABLE `api_logins` ADD COLUMN `user_data` TEXT NOT NULL COLLATE 'utf8mb4_swedish_ci' AFTER `user_id`",
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
"ALTER TABLE `api_permissions` ADD COLUMN `username` VARCHAR(255) NOT NULL COLLATE 'utf8mb4_swedish_ci' AFTER `user_id`",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
24
src/plugins/GuildInfoSaver.ts
Normal file
24
src/plugins/GuildInfoSaver.ts
Normal file
|
@ -0,0 +1,24 @@
|
||||||
|
import { ZeppelinPlugin } from "./ZeppelinPlugin";
|
||||||
|
import { AllowedGuilds } from "../data/AllowedGuilds";
|
||||||
|
import { MINUTES } from "../utils";
|
||||||
|
|
||||||
|
export class GuildInfoSaverPlugin extends ZeppelinPlugin {
|
||||||
|
public static pluginName = "guild_info_saver";
|
||||||
|
protected allowedGuilds: AllowedGuilds;
|
||||||
|
private updateInterval;
|
||||||
|
|
||||||
|
onLoad() {
|
||||||
|
this.allowedGuilds = new AllowedGuilds();
|
||||||
|
|
||||||
|
this.updateGuildInfo();
|
||||||
|
this.updateInterval = setInterval(() => this.updateGuildInfo(), 60 * MINUTES);
|
||||||
|
}
|
||||||
|
|
||||||
|
onUnload() {
|
||||||
|
clearInterval(this.updateInterval);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected updateGuildInfo() {
|
||||||
|
this.allowedGuilds.updateInfo(this.guildId, this.guild.name, this.guild.iconURL);
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,92 +0,0 @@
|
||||||
import http, { ServerResponse } from "http";
|
|
||||||
import { GlobalPlugin, IPluginOptions, logger } from "knub";
|
|
||||||
import { GuildArchives } from "../data/GuildArchives";
|
|
||||||
import { sleep } from "../utils";
|
|
||||||
import moment from "moment-timezone";
|
|
||||||
|
|
||||||
const DEFAULT_PORT = 9920;
|
|
||||||
const archivesRegex = /^\/(spam-logs|archives)\/([a-z0-9\-]+)\/?$/i;
|
|
||||||
|
|
||||||
function notFound(res: ServerResponse) {
|
|
||||||
res.statusCode = 404;
|
|
||||||
res.end("Not Found");
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ILogServerPluginConfig {
|
|
||||||
port: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class LogServerPlugin extends GlobalPlugin<ILogServerPluginConfig> {
|
|
||||||
public static pluginName = "log_server";
|
|
||||||
|
|
||||||
protected archives: GuildArchives;
|
|
||||||
protected server: http.Server;
|
|
||||||
|
|
||||||
protected getDefaultOptions(): IPluginOptions<ILogServerPluginConfig> {
|
|
||||||
return {
|
|
||||||
config: {
|
|
||||||
port: DEFAULT_PORT,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async onLoad() {
|
|
||||||
this.archives = new GuildArchives(null);
|
|
||||||
|
|
||||||
this.server = http.createServer(async (req, res) => {
|
|
||||||
const pathMatch = req.url.match(archivesRegex);
|
|
||||||
if (!pathMatch) return notFound(res);
|
|
||||||
|
|
||||||
const logId = pathMatch[2];
|
|
||||||
|
|
||||||
if (pathMatch[1] === "spam-logs") {
|
|
||||||
res.statusCode = 301;
|
|
||||||
res.setHeader("Location", `/archives/${logId}`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (pathMatch) {
|
|
||||||
const log = await this.archives.find(logId);
|
|
||||||
if (!log) return notFound(res);
|
|
||||||
|
|
||||||
let body = log.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 (log.body.indexOf("Log file generated on") === -1) {
|
|
||||||
const createdAt = moment(log.created_at).format("YYYY-MM-DD [at] HH:mm:ss [(+00:00)]");
|
|
||||||
body += `\n\nLog file generated on ${createdAt}`;
|
|
||||||
|
|
||||||
if (log.expires_at !== null) {
|
|
||||||
const expiresAt = moment(log.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);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const port = this.getConfig().port;
|
|
||||||
let retried = false;
|
|
||||||
|
|
||||||
this.server.on("error", async (err: any) => {
|
|
||||||
if (err.code === "EADDRINUSE" && !retried) {
|
|
||||||
logger.info("Got EADDRINUSE, retrying in 2 sec...");
|
|
||||||
retried = true;
|
|
||||||
await sleep(2000);
|
|
||||||
this.server.listen(port);
|
|
||||||
} else {
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
this.server.listen(port);
|
|
||||||
}
|
|
||||||
|
|
||||||
async onUnload() {
|
|
||||||
return new Promise(resolve => {
|
|
||||||
this.server.close(() => resolve());
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -19,9 +19,9 @@ import { SelfGrantableRolesPlugin } from "./SelfGrantableRolesPlugin";
|
||||||
import { RemindersPlugin } from "./Reminders";
|
import { RemindersPlugin } from "./Reminders";
|
||||||
import { WelcomeMessagePlugin } from "./WelcomeMessage";
|
import { WelcomeMessagePlugin } from "./WelcomeMessage";
|
||||||
import { BotControlPlugin } from "./BotControl";
|
import { BotControlPlugin } from "./BotControl";
|
||||||
import { LogServerPlugin } from "./LogServer";
|
|
||||||
import { UsernameSaver } from "./UsernameSaver";
|
import { UsernameSaver } from "./UsernameSaver";
|
||||||
import { CustomEventsPlugin } from "./CustomEvents";
|
import { CustomEventsPlugin } from "./CustomEvents";
|
||||||
|
import { GuildInfoSaverPlugin } from "./GuildInfoSaver";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Plugins available to be loaded for individual guilds
|
* Plugins available to be loaded for individual guilds
|
||||||
|
@ -48,12 +48,14 @@ export const availablePlugins = [
|
||||||
RemindersPlugin,
|
RemindersPlugin,
|
||||||
WelcomeMessagePlugin,
|
WelcomeMessagePlugin,
|
||||||
CustomEventsPlugin,
|
CustomEventsPlugin,
|
||||||
|
GuildInfoSaverPlugin,
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Plugins that are always loaded (subset of the names of the plugins in availablePlugins)
|
* Plugins that are always loaded (subset of the names of the plugins in availablePlugins)
|
||||||
*/
|
*/
|
||||||
export const basePlugins = [
|
export const basePlugins = [
|
||||||
|
GuildInfoSaverPlugin.pluginName,
|
||||||
MessageSaverPlugin.pluginName,
|
MessageSaverPlugin.pluginName,
|
||||||
NameHistoryPlugin.pluginName,
|
NameHistoryPlugin.pluginName,
|
||||||
CasesPlugin.pluginName,
|
CasesPlugin.pluginName,
|
||||||
|
@ -63,4 +65,4 @@ export const basePlugins = [
|
||||||
/**
|
/**
|
||||||
* Available global plugins (can't be loaded per-guild, only globally)
|
* Available global plugins (can't be loaded per-guild, only globally)
|
||||||
*/
|
*/
|
||||||
export const availableGlobalPlugins = [BotControlPlugin, LogServerPlugin, UsernameSaver];
|
export const availableGlobalPlugins = [BotControlPlugin, UsernameSaver];
|
||||||
|
|
Loading…
Add table
Reference in a new issue