setup route for first user

This commit is contained in:
Julian Krauser 2024-08-25 13:37:23 +02:00
parent 91ff0835fb
commit 6d9e75bb0c
20 changed files with 455 additions and 30 deletions

1
.env.example Normal file
View file

@ -0,0 +1 @@
SERVER_ADDRESS = serveradress

4
.gitignore vendored
View file

@ -38,4 +38,6 @@ coverage
*.sln
*.sw?
*.tsbuildinfo
*.tsbuildinfo
.env

View file

@ -1,3 +1,22 @@
# member-administration-ui
Mitgliederverwaltung
Memberadministration
## Installation
### Requirements
1. Access to the internet
### Configuration
1. Copy the .env.example file to .env and fill in the required information
2. Install all packages via `npm install`
3. Start the backend application
4. Start the application
5. Run `npm run dev` to run inside dev-environment
### Usage
1. Open the browser and navigate to `http://localhost:5173` or the URL you specified in the server configuration
2. Go to route `/setup` to create the first user (this path is disabled after the first user is created)

View file

@ -1,4 +1,7 @@
<template>
<Modal />
<ContextMenu />
<Header @contextmenu.prevent />
<div class="grow overflow-x-hidden overflow-y-auto p-2 md:p-4" @contextmenu.prevent>
<RouterView />
@ -14,6 +17,8 @@ import Footer from "./components/Footer.vue";
import { mapState } from "pinia";
import { useAuthStore } from "./stores/auth";
import { isAuthenticatedPromise } from "./router/authGuards";
import ContextMenu from "./components/ContextMenu.vue";
import Modal from "./components/Modal.vue";
</script>
<script lang="ts">
@ -25,6 +30,7 @@ export default defineComponent({
if (!this.authCheck && localStorage.getItem("access_token")) {
isAuthenticatedPromise().catch(() => {
localStorage.removeItem("access_token");
localStorage.removeItem("refresh_token");
});
}
},

View file

@ -0,0 +1,48 @@
<template>
<div
ref="contextMenu"
class="absolute flex flex-col gap-1 border border-gray-400 bg-white rounded-md select-none text-left shadow-md z-50 p-1"
v-show="show"
:style="contextMenuStyle"
@contextmenu.prevent
@click="closeContextMenu"
>
<component :is="component_ref" :data="data" />
<!-- <template v-for="item in contextMenu" :key="item">
<hr v-if="item.separator" />
<div v-else class="flex flex-row gap-2 rounded-md p-1 px-2 items-center"
:class="typeof item.click == 'function' ? 'cursor-pointer hover:bg-gray-200' : ''" @click="item.click">
<font-awesome-icon v-if="item.icon" class="text-md" :icon="[item.stroke || 'far', item.icon]" />
<span class="font-normal">{{ item.title }}</span>
</div>
</template> -->
</div>
</template>
<script setup lang="ts">
import { mapState, mapActions } from "pinia";
import { useContextMenuStore } from "../stores/context-menu";
</script>
<script lang="ts">
export default {
computed: {
...mapState(useContextMenuStore, ["show", "contextMenuStyle", "component_ref", "data"]),
},
methods: {
...mapActions(useContextMenuStore, ["closeContextMenu"]),
},
mounted() {
document.body.addEventListener("click", (event) => {
if (!(this.$refs.contextMenu as HTMLElement)?.contains(event.target as HTMLElement)) {
this.closeContextMenu();
}
});
// document.body.addEventListener("contextmenu", (event) => {
// if (!this.$refs.contextMenu?.contains(event.target)) {
// this.closeContextMenu();
// }
// });
},
};
</script>

27
src/components/Modal.vue Normal file
View file

@ -0,0 +1,27 @@
<template>
<div
ref="contextMenu"
class="absolute inset-0 w-full h-full flex justify-center items-center bg-black/50 select-none z-50 p-2"
v-show="show"
@contextmenu.prevent
@click="closeModal"
>
<component :is="component_ref" :data="data" @click.stop class="p-4 bg-white rounded-lg" />
</div>
</template>
<script setup lang="ts">
import { mapState, mapActions } from "pinia";
import { useModalStore } from "../stores/modal";
</script>
<script lang="ts">
export default {
computed: {
...mapState(useModalStore, ["show", "component_ref", "data"]),
},
methods: {
...mapActions(useModalStore, ["closeModal"]),
},
};
</script>

View file

@ -29,29 +29,34 @@ export async function isAuthenticatedPromise(): Promise<Payload> {
return new Promise<Payload>(async (resolve, reject) => {
const auth = useAuthStore();
const account = useAccountStore();
let decoded = jwtDecode<Payload>(localStorage.getItem("accessToken") ?? "");
let decoded: Payload | string = "";
try {
decoded = jwtDecode<Payload>(localStorage.getItem("accessToken") ?? "");
} catch (error) {
reject("failed");
}
auth.setSuccess();
if (typeof decoded == "string" || !decoded) {
reject("failed");
}
} else {
// check jwt expiry
const exp = decoded.exp ?? 0;
const localTimezoneOffset = new Date().getTimezoneOffset();
const correctedLocalTime = new Date().getTime() + localTimezoneOffset * 60000;
if (exp < Math.floor(correctedLocalTime / 1000)) {
await refreshToken()
.then(() => {
console.log("fetched new token");
})
.catch(() => {
reject("expired");
});
}
// check jwt expiry
const exp = decoded.exp ?? 0;
const localTimezoneOffset = new Date().getTimezoneOffset();
const correctedLocalTime = new Date().getTime() + localTimezoneOffset * 60000;
if (exp < Math.floor(correctedLocalTime / 1000)) {
await refreshToken()
.then(() => {
console.log("fetched new token");
})
.catch(() => {
reject("expired");
});
var { firstname, lastname, mail, username } = decoded;
account.setAccountData(firstname, lastname, mail, username);
resolve(decoded);
}
var { firstname, lastname, mail, username } = decoded;
account.setAccountData(firstname, lastname, mail, username);
resolve(decoded);
});
}

View file

@ -3,6 +3,7 @@ import Login from "../views/Login.vue";
import { isAuthenticated } from "./authGuards";
import { loadAccountData } from "./accountGuard";
import { isSetup } from "./setupGuard";
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
@ -16,6 +17,25 @@ const router = createRouter({
name: "login",
component: Login,
},
{
path: "/setup",
name: "setup",
component: () => import("../views/RouterView.vue"),
beforeEnter: [isSetup],
children: [
{
path: "",
name: "setup-create",
component: () => import("../views/setup/Setup.vue"),
},
{
path: "verify",
name: "setup-verify",
component: () => import("../views/setup/Verify.vue"),
props: (route) => ({ mail: route.query.mail, token: route.query.token }),
},
],
},
{
path: "/admin",
name: "admin",

16
src/router/setupGuard.ts Normal file
View file

@ -0,0 +1,16 @@
import NProgress from "nprogress";
import { http } from "../serverCom";
export async function isSetup(to: any, from: any, next: any) {
NProgress.start();
await http
.get("/setup")
.then(() => {
NProgress.done();
next();
})
.catch(() => {
NProgress.done();
next({ name: "login" });
});
}

View file

@ -1,7 +1,9 @@
import axios from "axios";
let devMode = process.env.NODE_ENV === "development";
const http = axios.create({
baseURL: "http://localhost:5000",
baseURL: devMode ? "http://localhost:5000" : server_adress,
headers: {
"Cache-Control": "no-cache",
Pragma: "no-cache",
@ -30,7 +32,7 @@ http.interceptors.response.use(
return response;
},
async (error) => {
if (error.config.url.includes("/auth")) {
if (!error.config.url.includes("/admin")) {
return Promise.reject(error);
}

View file

@ -44,6 +44,11 @@ export const useNavigationStore = defineStore("navigation", {
title: "Einstellungen",
levelDefault: "#qualification",
},
{
key: "user",
title: "Benutzer",
levelDefault: "#user",
},
] as Array<topLevelNavigationModel>,
navigation: {
club: {
@ -112,6 +117,7 @@ export const useNavigationStore = defineStore("navigation", {
],
},
} as navigationModel,
componentOverwrite: null as null | any,
};
},
getters: {
@ -144,6 +150,12 @@ export const useNavigationStore = defineStore("navigation", {
setTopLevelNav(topLeveLinks: Array<topLevelNavigationModel>) {
this.topLevel = topLeveLinks;
},
setComponentOverwrite(component: any) {
this.componentOverwrite = component;
},
resetComponentOverwrite() {
this.componentOverwrite = null;
},
resetNavigation() {
this.$reset();
},

View file

@ -0,0 +1,32 @@
import { defineStore } from "pinia";
export const useContextMenuStore = defineStore("context-menu", {
state: () => {
return {
contextX: 0,
contextY: 0,
show: false,
component_ref: null as any,
data: null as any,
};
},
getters: {
contextMenuStyle: (state) => {
return `left: ${state.contextX}px; top: ${state.contextY}px`;
},
},
actions: {
openContextMenu(e: MouseEvent, content: { component_ref: any; data: any }) {
this.component_ref = content.component_ref;
this.data = content.data;
this.contextX = e.pageX;
this.contextY = e.pageY;
this.show = true;
},
closeContextMenu() {
this.component_ref = null;
this.data = null;
this.show = false;
},
},
});

23
src/stores/modal.ts Normal file
View file

@ -0,0 +1,23 @@
import { defineStore } from "pinia";
export const useModalStore = defineStore("modal", {
state: () => {
return {
show: false,
component_ref: null as any,
data: null as any,
};
},
actions: {
openModal(component_ref: any, data?: any) {
this.component_ref = component_ref;
this.data = data;
this.show = true;
},
closeModal() {
this.component_ref = null;
this.data = null;
this.show = false;
},
},
});

View file

@ -1,6 +1,6 @@
<template>
<div v-if="!defaultRoute && showBack" class="flex md:hidden flex-row items-baseline">
<p v-if="!defaultRoute && showBack" class="text-indigo-500" @click="setLink(null)">zur Übersicht</p>
<p v-if="!defaultRoute && showBack" class="text-primary" @click="setLink(null)">zur Übersicht</p>
</div>
<slot v-if="headerInsert" name="headerInsert"></slot>
<div

View file

@ -66,7 +66,6 @@ export default defineComponent({
})
.then((result) => {
this.loginStatus = "success";
console.log(result);
localStorage.setItem("accessToken", result.data.accessToken),
localStorage.setItem("refreshToken", result.data.refreshToken),
setTimeout(() => {

View file

@ -15,7 +15,7 @@
</SidebarTemplate>
</template>
<template #main>
<component v-if="activeLink?.component" :is="activeLink.component" />
<component v-if="display" :is="displayed" />
<div v-else class="w-full h-full bg-white rounded-lg"></div>
</template>
</SidebarLayout>
@ -39,7 +39,22 @@ export default defineComponent({
},
},
computed: {
...mapState(useNavigationStore, ["activeNavigationObject", "activeTopLevelObject", "activeLink"]),
...mapState(useNavigationStore, [
"activeNavigationObject",
"activeTopLevelObject",
"activeLink",
"componentOverwrite",
]),
display(): boolean {
return this.activeLink?.component || this.componentOverwrite;
},
displayed() {
if (this.componentOverwrite != null) {
return this.componentOverwrite;
} else {
return this.activeLink?.component;
}
},
},
created() {
this.setLink(this.activeTopLevelObject.levelDefault);

View file

@ -1,11 +1,11 @@
<template>
<MainTemplate>
<template v-slot:topBar>
<template #topBar>
<div class="flex flex-row items-center justify-between pt-5 pb-3 px-7">
<h1 class="font-bold text-xl h-8">Übersicht</h1>
</div>
</template>
<template v-slot:diffMain>
<template #diffMain>
<div class="flex flex-col gap-2 justify-center items-center h-full"></div>
</template>
</MainTemplate>

85
src/views/setup/Setup.vue Normal file
View file

@ -0,0 +1,85 @@
<template>
<div class="grow flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
<div class="max-w-md w-full space-y-8 pb-20">
<div class="flex flex-col items-center gap-4">
<img src="/FFW-Logo.svg" alt="LOGO" class="h-36" />
<h2 class="text-center text-5xl font-extrabold text-gray-900">Einrichtung</h2>
</div>
<form class="flex flex-col gap-2" @submit.prevent="setup">
<div class="-space-y-px">
<div>
<input id="username" name="username" type="text" required placeholder="Benutzer" class="!rounded-b-none" />
</div>
<div>
<input id="mail" name="mail" type="email" required placeholder="Mailadresse" class="!rounded-none" />
</div>
<div>
<input id="firstname" name="firstname" type="text" required placeholder="Vorname" class="!rounded-none" />
</div>
<div>
<input id="lastname" name="lastname" type="text" required placeholder="Nachname" class="!rounded-t-none" />
</div>
</div>
<div class="flex flex-row gap-2">
<button type="submit" primary :disabled="setupStatus == 'loading' || setupStatus == 'success'">
Admin-Account anlegen
</button>
<Spinner v-if="setupStatus == 'loading'" class="my-auto" />
<SuccessCheckmark v-else-if="setupStatus == 'success'" />
<FailureXMark v-else-if="setupStatus == 'failed'" />
</div>
<p v-if="setupMessage" class="text-center">{{ setupMessage }}</p>
</form>
<div class="flex flex-col text-gray-400 text-sm mt-4 items-center">
<div class="flex flex-row gap-2 justify-center">
<a href="#">Datenschutz</a>
<a href="#">Impressum</a>
</div>
<a href="#"> &copy; Admin-Portal by JK Effects </a>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { defineComponent } from "vue";
import Spinner from "@/components/Spinner.vue";
import SuccessCheckmark from "@/components/SuccessCheckmark.vue";
import FailureXMark from "@/components/FailureXMark.vue";
</script>
<script lang="ts">
export default defineComponent({
data() {
return {
setupStatus: undefined as undefined | "loading" | "success" | "failed",
setupMessage: "" as string,
};
},
methods: {
setup(e: any) {
let formData = e.target.elements;
this.setupStatus = "loading";
this.setupMessage = "";
this.$http
.post(`/setup`, {
username: formData.username.value,
mail: formData.mail.value,
firstname: formData.firstname.value,
lastname: formData.lastname.value,
})
.then((result) => {
this.setupStatus = "success";
this.setupMessage = "Sie haben einen Verifizierungslink per Mail erhalten.";
})
.catch((err) => {
this.setupStatus = "failed";
this.setupMessage = err.response.data;
});
},
},
});
</script>

112
src/views/setup/Verify.vue Normal file
View file

@ -0,0 +1,112 @@
<template>
<div class="grow flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
<div class="max-w-md w-full space-y-8 pb-20">
<div class="flex flex-col items-center gap-4">
<img src="/FFW-Logo.svg" alt="LOGO" class="h-36" />
<h2 class="text-center text-5xl font-extrabold text-gray-900">Einrichtung</h2>
</div>
<div v-if="verification == 'loading'" class="flex flex-col gap-2 items-center">
<p class="w-fit">Einrichtungslink wird verifiziert</p>
<Spinner class="my-auto" />
</div>
<div v-else-if="verification == 'failed'" class="flex flex-col gap-2 items-center">
<p class="w-fit">Einrichtungslink nicht gültig</p>
<RouterLink to="/setup" class="text-primary">Zum Einrichtungsstart</RouterLink>
</div>
<form v-else class="flex flex-col gap-2" @submit.prevent="setup">
<img :src="verification" alt="totp" class="w-56 h-56 self-center" />
<div class="-space-y-px">
<div>
<input id="totp" name="totp" type="text" required placeholder="TOTP" />
</div>
</div>
<div class="flex flex-row gap-2">
<button type="submit" primary :disabled="setupStatus == 'loading' || setupStatus == 'success'">
Admin-Account fertigstellen
</button>
<Spinner v-if="setupStatus == 'loading'" class="my-auto" />
<SuccessCheckmark v-else-if="setupStatus == 'success'" />
<FailureXMark v-else-if="setupStatus == 'failed'" />
</div>
<p v-if="setupError" class="text-center">{{ setupError }}</p>
<RouterLink to="/setup" class="text-primary self-end">Zum Einrichtungsstart</RouterLink>
</form>
<div class="flex flex-col text-gray-400 text-sm mt-4 items-center">
<div class="flex flex-row gap-2 justify-center">
<a href="#">Datenschutz</a>
<a href="#">Impressum</a>
</div>
<a href="#"> &copy; Admin-Portal by JK Effects </a>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { defineComponent } from "vue";
import Spinner from "@/components/Spinner.vue";
import SuccessCheckmark from "@/components/SuccessCheckmark.vue";
import FailureXMark from "@/components/FailureXMark.vue";
import { RouterLink } from "vue-router";
</script>
<script lang="ts">
export default defineComponent({
props: {
token: String,
mail: String,
},
data() {
return {
verification: "loading" as string | "loading" | "failed",
setupStatus: undefined as undefined | "loading" | "success" | "failed",
setupError: "" as string,
};
},
mounted() {
this.$http
.post(`/setup/verify`, {
token: this.token,
mail: this.mail,
})
.then((result) => {
setTimeout(() => {
this.verification = result.data;
}, 1000);
})
.catch((err) => {
setTimeout(() => {
this.verification = "failed";
}, 1000);
});
},
methods: {
setup(e: any) {
let formData = e.target.elements;
this.setupStatus = "loading";
this.setupError = "";
this.$http
.put(`/setup`, {
token: this.token,
mail: this.mail,
totp: formData.totp.value,
})
.then((result) => {
this.setupStatus = "success";
localStorage.setItem("accessToken", result.data.accessToken);
localStorage.setItem("refreshToken", result.data.refreshToken);
setTimeout(() => {
this.$router.push(`/admin`);
}, 1000);
})
.catch((err) => {
this.setupStatus = "failed";
this.setupError = err.response.data;
});
},
},
});
</script>

View file

@ -1,6 +1,6 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
"include": ["env.d.ts", "src/**/*", "src/**/*.vue", "config.example.ts", "config.ts"],
"exclude": ["src/**/__tests__/*"],
"compilerOptions": {
"composite": true,
@ -9,6 +9,7 @@
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
},
"types": ["node"]
}
}