Merge branch 'vue3-wip' into vue3

This commit is contained in:
Kloon ImKloon 2023-09-11 11:28:35 +02:00
parent db6b627b69
commit 910db80068
No known key found for this signature in database
GPG Key ID: CCF1C86A995C5B6A
11 changed files with 431 additions and 401 deletions

View File

@ -1,11 +1,11 @@
import type { Share } from "@/types"; import type { ApiUrl, IShare } from "@/types";
import { fetchURL, fetchJSON, removePrefix, createURL } from "./utils"; import { fetchURL, fetchJSON, removePrefix, createURL } from "./utils";
export async function list() { export async function list() {
return fetchJSON("/api/shares"); return fetchJSON("/api/shares");
} }
export async function get(url: string) { export async function get(url: ApiUrl) {
url = removePrefix(url); url = removePrefix(url);
return fetchJSON(`/api/share${url}`); return fetchJSON(`/api/share${url}`);
} }
@ -17,7 +17,7 @@ export async function remove(hash: string) {
} }
export async function create( export async function create(
url: string, url: ApiUrl,
password = "", password = "",
expires = "", expires = "",
unit = "hours" unit = "hours"
@ -41,6 +41,6 @@ export async function create(
}); });
} }
export function getShareURL(share: Share) { export function getShareURL(share: IShare) {
return createURL("share/" + share.hash, {}, false); return createURL("share/" + share.hash, {}, false);
} }

View File

@ -1,18 +1,25 @@
<template> <template>
<select v-on:change="change" :value="theme"> <select v-on:change="change" :value="theme">
<option value="">{{ $t("settings.themes.light") }}</option> <option value="">{{ t("settings.themes.light") }}</option>
<option value="dark">{{ $t("settings.themes.dark") }}</option> <option value="dark">{{ t("settings.themes.dark") }}</option>
</select> </select>
</template> </template>
<script> <script setup lang="ts">
export default { import { SelectHTMLAttributes } from "vue";
name: "themes", import { useI18n } from "vue-i18n";
props: ["theme"],
methods: { const { t } = useI18n();
change(event) {
this.$emit("update:theme", event.target.value); defineProps<{
}, theme: any;
}, }>();
const emit = defineEmits<{
(e: "update:theme", val: string | null): void;
}>();
const change = (event: Event) => {
emit("update:theme", (event.target as SelectHTMLAttributes)?.value);
}; };
</script> </script>

View File

@ -1,6 +1,6 @@
<template> <template>
<div> <div>
<p v-if="!isDefault"> <p v-if="!isDefault && props.user !== null">
<label for="username">{{ $t("settings.username") }}</label> <label for="username">{{ $t("settings.username") }}</label>
<input <input
class="input input--block" class="input input--block"
@ -24,7 +24,7 @@
<p> <p>
<label for="scope">{{ $t("settings.scope") }}</label> <label for="scope">{{ $t("settings.scope") }}</label>
<input <input
:disabled="createUserDirData" :disabled="createUserDirData ?? false"
:placeholder="scopePlaceholder" :placeholder="scopePlaceholder"
class="input input--block" class="input input--block"
type="text" type="text"
@ -56,7 +56,7 @@
</p> </p>
<permissions v-model:perm="user.perm" /> <permissions v-model:perm="user.perm" />
<commands v-if="isExecEnabled" v-model:commands="user.commands" /> <commands v-if="enableExec" v-model:commands="user.commands" />
<div v-if="!isDefault"> <div v-if="!isDefault">
<h3>{{ $t("settings.rules") }}</h3> <h3>{{ $t("settings.rules") }}</h3>
@ -66,54 +66,53 @@
</div> </div>
</template> </template>
<script> <script setup lang="ts">
import Languages from "./Languages.vue"; import Languages from "./Languages.vue";
import Rules from "./Rules.vue"; import Rules from "./Rules.vue";
import Permissions from "./Permissions.vue"; import Permissions from "./Permissions.vue";
import Commands from "./Commands.vue"; import Commands from "./Commands.vue";
import { enableExec } from "@/utils/constants"; import { enableExec } from "@/utils/constants";
import { computed, onMounted, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { IUser } from "@/types";
export default { const { t } = useI18n();
name: "user",
data: () => { const createUserDirData = ref<boolean | null>(null);
return { const originalUserScope = ref<string | null>(null);
createUserDirData: false,
originalUserScope: "/", const props = defineProps<{
}; user: IUser;
}, isNew: boolean;
components: { isDefault: boolean;
Permissions, createUserDir?: boolean;
Languages, }>();
Rules,
Commands, onMounted(() => {
}, originalUserScope.value = props.user.scope;
props: ["user", "createUserDir", "isNew", "isDefault"], createUserDirData.value = props.createUserDir;
created() { });
this.originalUserScope = this.user.scope;
this.createUserDirData = this.createUserDir; const passwordPlaceholder = computed(() =>
}, props.isNew ? "" : t("settings.avoidChanges")
computed: { );
passwordPlaceholder() { const scopePlaceholder = computed(() =>
return this.isNew ? "" : this.$t("settings.avoidChanges"); createUserDirData.value ? t("settings.userScopeGenerationPlaceholder") : ""
}, );
scopePlaceholder() { const displayHomeDirectoryCheckbox = computed(
return this.createUserDir () => props.isNew && createUserDirData.value
? this.$t("settings.userScopeGenerationPlaceholder") );
: "";
}, watch(props.user, () => {
displayHomeDirectoryCheckbox() { if (!props.user.perm.admin) return;
return this.isNew && this.createUserDir; props.user.lockPassword = false;
}, });
isExecEnabled: () => enableExec,
}, watch(createUserDirData, () => {
watch: { if (props.user?.scope) {
"user.perm.admin": function () { props.user.scope = createUserDirData.value
if (!this.user.perm.admin) return; ? ""
this.user.lockPassword = false; : originalUserScope.value ?? "";
}, }
createUserDirData() { });
this.user.scope = this.createUserDirData ? "" : this.originalUserScope;
},
},
};
</script> </script>

View File

@ -1,4 +1,4 @@
import type { User } from "@/types"; import type { IUser } from "@/types";
import { defineStore } from "pinia"; import { defineStore } from "pinia";
import dayjs from "dayjs"; import dayjs from "dayjs";
import i18n, { detectLocale } from "@/i18n"; import i18n, { detectLocale } from "@/i18n";
@ -7,7 +7,7 @@ import { cloneDeep } from "lodash-es";
export const useAuthStore = defineStore("auth", { export const useAuthStore = defineStore("auth", {
// convert to a function // convert to a function
state: (): { state: (): {
user: User | null; user: IUser | null;
jwt: string; jwt: string;
} => ({ } => ({
user: null, user: null,
@ -19,24 +19,26 @@ export const useAuthStore = defineStore("auth", {
}, },
actions: { actions: {
// no context as first argument, use `this` instead // no context as first argument, use `this` instead
setUser(value: User) { setUser(user: IUser | null) {
if (value === null) { if (user === null) {
this.user = null; this.user = null;
return; return;
} }
const locale = value.locale || detectLocale(); const locale = user.locale || detectLocale();
dayjs.locale(locale); dayjs.locale(locale);
// according to doc u only need .value if legacy: false
// in createI18n but they lied
// https://vue-i18n.intlify.dev/guide/essentials/scope.html#local-scope-1
//@ts-ignore //@ts-ignore
i18n.global.locale = locale; i18n.global.locale = locale;
this.user = value; this.user = user;
}, },
updateUser(value: User) { updateUser(user: Partial<IUser>) {
if (typeof value !== "object" || !value) return; if (user.locale) {
this.setUser(cloneDeep(value)); dayjs.locale(user.locale);
//@ts-ignore
i18n.global.locale = user.locale;
}
this.user = { ...this.user, ...cloneDeep(user) } as IUser;
}, },
// easily reset state using `$reset` // easily reset state using `$reset`
clearUser() { clearUser() {

View File

@ -1,3 +1,5 @@
export type ApiUrl = string; // Can also be set as a path eg: "path1" | "path2"
export type ApiMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH"; export type ApiMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
export type ApiContent = export type ApiContent =
@ -21,7 +23,7 @@ export type ChecksumAlgs = "md5" | "sha1" | "sha256" | "sha512";
type inline = any; type inline = any;
export interface Share { export interface IShare {
expire: any; expire: any;
hash: string; hash: string;
path: string; path: string;

View File

@ -1,7 +1,16 @@
export interface User { export interface IUser {
id: number; id: number;
username: string;
password: string;
scope: string;
locale: string; locale: string;
perm: Permissions; perm: Permissions;
commands: string[];
rules: IRule[];
lockPassword: boolean;
hideDotfiles: boolean;
singleClick: boolean;
dateFormat: boolean;
} }
export interface Permissions { export interface Permissions {
@ -18,3 +27,19 @@ export interface Permissions {
shell: boolean; shell: boolean;
upload: boolean; upload: boolean;
} }
export interface UserSorting {
by: string;
asc: boolean;
}
export interface IRule {
allow: boolean;
path: string;
regex: boolean;
regexp: IRegexp;
}
interface IRegexp {
raw: string;
}

View File

@ -257,8 +257,8 @@ const commandObject = ref<{
}>({}); }>({});
const shellValue = ref<string>(""); const shellValue = ref<string>("");
const $showSuccess = inject<IToastSuccess>("$showSuccess") as IToastSuccess; const $showError = inject<IToastError>("$showError")!;
const $showError = inject<IToastError>("$showError") as IToastError; const $showSuccess = inject<IToastSuccess>("$showSuccess")!;
const { t } = useI18n(); const { t } = useI18n();

View File

@ -3,23 +3,23 @@
<div class="column"> <div class="column">
<form class="card" @submit="updateSettings"> <form class="card" @submit="updateSettings">
<div class="card-title"> <div class="card-title">
<h2>{{ $t("settings.profileSettings") }}</h2> <h2>{{ t("settings.profileSettings") }}</h2>
</div> </div>
<div class="card-content"> <div class="card-content">
<p> <p>
<input type="checkbox" v-model="hideDotfiles" /> <input type="checkbox" v-model="hideDotfiles" />
{{ $t("settings.hideDotfiles") }} {{ t("settings.hideDotfiles") }}
</p> </p>
<p> <p>
<input type="checkbox" v-model="singleClick" /> <input type="checkbox" v-model="singleClick" />
{{ $t("settings.singleClick") }} {{ t("settings.singleClick") }}
</p> </p>
<p> <p>
<input type="checkbox" v-model="dateFormat" /> <input type="checkbox" v-model="dateFormat" />
{{ $t("settings.setDateFormat") }} {{ t("settings.setDateFormat") }}
</p> </p>
<h3>{{ $t("settings.language") }}</h3> <h3>{{ t("settings.language") }}</h3>
<languages <languages
class="input input--block" class="input input--block"
v-model:locale="locale" v-model:locale="locale"
@ -30,30 +30,34 @@
<input <input
class="button button--flat" class="button button--flat"
type="submit" type="submit"
:value="$t('buttons.update')" :value="t('buttons.update')"
/> />
</div> </div>
</form> </form>
</div> </div>
<div class="column"> <div class="column">
<form class="card" v-if="!user.lockPassword" @submit="updatePassword"> <form
class="card"
v-if="!authStore.user?.lockPassword"
@submit="updatePassword"
>
<div class="card-title"> <div class="card-title">
<h2>{{ $t("settings.changePassword") }}</h2> <h2>{{ t("settings.changePassword") }}</h2>
</div> </div>
<div class="card-content"> <div class="card-content">
<input <input
:class="passwordClass" :class="passwordClass"
type="password" type="password"
:placeholder="$t('settings.newPassword')" :placeholder="t('settings.newPassword')"
v-model="password" v-model="password"
name="password" name="password"
/> />
<input <input
:class="passwordClass" :class="passwordClass"
type="password" type="password"
:placeholder="$t('settings.newPasswordConfirm')" :placeholder="t('settings.newPasswordConfirm')"
v-model="passwordConf" v-model="passwordConf"
name="password" name="password"
/> />
@ -63,7 +67,7 @@
<input <input
class="button button--flat" class="button button--flat"
type="submit" type="submit"
:value="$t('buttons.update')" :value="t('buttons.update')"
/> />
</div> </div>
</form> </form>
@ -71,102 +75,108 @@
</div> </div>
</template> </template>
<script> <script setup lang="ts">
import { mapActions, mapState, mapWritableState } from "pinia";
import { useAuthStore } from "@/stores/auth"; import { useAuthStore } from "@/stores/auth";
import { useLayoutStore } from "@/stores/layout"; import { useLayoutStore } from "@/stores/layout";
import { users as api } from "@/api"; import { users as api } from "@/api";
import Languages from "@/components/settings/Languages.vue"; import Languages from "@/components/settings/Languages.vue";
import i18n, { rtlLanguages } from "@/i18n"; // import i18n, { rtlLanguages } from "@/i18n";
import { inject, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import type { IToastError, IToastSuccess } from "@/types";
export default { const layoutStore = useLayoutStore();
name: "settings", const authStore = useAuthStore();
components: { const { t } = useI18n();
Languages,
}, const $showError = inject<IToastError>("$showError")!;
data: function () { const $showSuccess = inject<IToastSuccess>("$showSuccess")!;
return {
password: "", const password = ref<string>("");
passwordConf: "", const passwordConf = ref<string>("");
hideDotfiles: false, const hideDotfiles = ref<boolean>(false);
singleClick: false, const singleClick = ref<boolean>(false);
dateFormat: false, const dateFormat = ref<boolean>(false);
locale: "", const locale = ref<string>("");
};
}, // ...mapState(useAuthStore, ["user"]),
inject: ["$showError", "$showSuccess"], // ...mapWritableState(useLayoutStore, ["loading"]),
computed: { //...mapActions(useAuthStore, ["updateUser"]),
...mapState(useAuthStore, ["user"]),
...mapWritableState(useLayoutStore, ["loading"]), const passwordClass = () => {
passwordClass() {
const baseClass = "input input--block"; const baseClass = "input input--block";
if (this.password === "" && this.passwordConf === "") { if (password.value === "" && passwordConf.value === "") {
return baseClass; return baseClass;
} }
if (this.password === this.passwordConf) { if (password.value === passwordConf.value) {
return `${baseClass} input--green`; return `${baseClass} input--green`;
} }
return `${baseClass} input--red`; return `${baseClass} input--red`;
}, };
},
created() { onMounted(() => {
this.loading = true; layoutStore.loading = true;
this.locale = this.user.locale; if (authStore.user === null) return false;
this.hideDotfiles = this.user.hideDotfiles; locale.value = authStore.user.locale;
this.singleClick = this.user.singleClick; hideDotfiles.value = authStore.user.hideDotfiles;
this.dateFormat = this.user.dateFormat; singleClick.value = authStore.user.singleClick;
this.loading = false; dateFormat.value = authStore.user.dateFormat;
}, layoutStore.loading = false;
methods: { });
...mapActions(useAuthStore, ["updateUser"]),
async updatePassword(event) { const updatePassword = async (event: Event) => {
event.preventDefault(); event.preventDefault();
if (this.password !== this.passwordConf || this.password === "") { if (
password.value !== passwordConf.value ||
password.value === "" ||
authStore.user === null
) {
return; return;
} }
try { try {
const data = { id: this.user.id, password: this.password }; const data = { id: authStore.user.id, password: password.value };
await api.update(data, ["password"]); await api.update(data, ["password"]);
this.updateUser(data); authStore.updateUser(data);
this.$showSuccess(this.$t("settings.passwordUpdated")); $showSuccess(t("settings.passwordUpdated"));
} catch (e) { } catch (e: any) {
this.$showError(e); $showError(e);
} }
}, };
async updateSettings(event) { const updateSettings = async (event: Event) => {
event.preventDefault(); event.preventDefault();
try { try {
if (authStore.user === null) throw "User is not set";
const data = { const data = {
id: this.user.id, id: authStore.user.id,
locale: this.locale, locale: locale.value,
hideDotfiles: this.hideDotfiles, hideDotfiles: hideDotfiles.value,
singleClick: this.singleClick, singleClick: singleClick.value,
dateFormat: this.dateFormat, dateFormat: dateFormat.value,
}; };
const shouldReload = // TODO don't know what this is doing
rtlLanguages.includes(data.locale) !== const shouldReload = false;
rtlLanguages.includes(i18n.locale); // rtlLanguages.includes(data.locale) !==
// rtlLanguages.includes(i18n.locale);
await api.update(data, [ await api.update(data, [
"locale", "locale",
"hideDotfiles", "hideDotfiles",
"singleClick", "singleClick",
"dateFormat", "dateFormat",
]); ]);
this.updateUser(data); authStore.updateUser(data);
if (shouldReload) { if (shouldReload) {
location.reload(); location.reload();
} }
this.$showSuccess(this.$t("settings.settingsUpdated")); $showSuccess(t("settings.settingsUpdated"));
} catch (e) { } catch (e: any) {
this.$showError(e); $showError(e);
} }
},
},
}; };
</script> </script>

View File

@ -1,18 +1,20 @@
<template> <template>
<errors v-if="error" :errorCode="error.status" /> <errors v-if="error" :errorCode="error.status" />
<div class="row" v-else-if="!loading"> <div class="row" v-else-if="!layoutStore.loading">
<div class="column"> <div class="column">
<div class="card"> <div class="card">
<div class="card-title"> <div class="card-title">
<h2>{{ $t("settings.shareManagement") }}</h2> <h2>{{ t("settings.shareManagement") }}</h2>
</div> </div>
<div class="card-content full" v-if="links.length > 0"> <div class="card-content full" v-if="links.length > 0">
<table> <table>
<tr> <tr>
<th>{{ $t("settings.path") }}</th> <th>{{ t("settings.path") }}</th>
<th>{{ $t("settings.shareDuration") }}</th> <th>{{ t("settings.shareDuration") }}</th>
<th v-if="user.perm.admin">{{ $t("settings.username") }}</th> <th v-if="authStore.user?.perm.admin">
{{ t("settings.username") }}
</th>
<th></th> <th></th>
<th></th> <th></th>
</tr> </tr>
@ -25,15 +27,15 @@
<template v-if="link.expire !== 0">{{ <template v-if="link.expire !== 0">{{
humanTime(link.expire) humanTime(link.expire)
}}</template> }}</template>
<template v-else>{{ $t("permanent") }}</template> <template v-else>{{ t("permanent") }}</template>
</td> </td>
<td v-if="user.perm.admin">{{ link.username }}</td> <td v-if="authStore.user?.perm.admin">{{ link.username }}</td>
<td class="small"> <td class="small">
<button <button
class="action" class="action"
@click="deleteLink($event, link)" @click="deleteLink($event, link)"
:aria-label="$t('buttons.delete')" :aria-label="t('buttons.delete')"
:title="$t('buttons.delete')" :title="t('buttons.delete')"
> >
<i class="material-icons">delete</i> <i class="material-icons">delete</i>
</button> </button>
@ -42,8 +44,8 @@
<button <button
class="action copy-clipboard" class="action copy-clipboard"
:data-clipboard-text="buildLink(link)" :data-clipboard-text="buildLink(link)"
:aria-label="$t('buttons.copyToClipboard')" :aria-label="t('buttons.copyToClipboard')"
:title="$t('buttons.copyToClipboard')" :title="t('buttons.copyToClipboard')"
> >
<i class="material-icons">content_paste</i> <i class="material-icons">content_paste</i>
</button> </button>
@ -53,94 +55,88 @@
</div> </div>
<h2 class="message" v-else> <h2 class="message" v-else>
<i class="material-icons">sentiment_dissatisfied</i> <i class="material-icons">sentiment_dissatisfied</i>
<span>{{ $t("files.lonely") }}</span> <span>{{ t("files.lonely") }}</span>
</h2> </h2>
</div> </div>
</div> </div>
</div> </div>
</template> </template>
<script> <script setup lang="ts">
import { mapState, mapWritableState } from "pinia";
import { useAuthStore } from "@/stores/auth"; import { useAuthStore } from "@/stores/auth";
import { useLayoutStore } from "@/stores/layout"; import { useLayoutStore } from "@/stores/layout";
import { share as api, users } from "@/api"; import { share as api, users } from "@/api";
import dayjs from "dayjs"; import dayjs from "dayjs";
import Clipboard from "clipboard"; import Clipboard from "clipboard";
import Errors from "@/views/Errors.vue"; import Errors from "@/views/Errors.vue";
import { inject, onBeforeUnmount, ref, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import type { IShare, IToastError, IToastSuccess } from "@/types";
export default { const $showError = inject<IToastError>("$showError")!;
name: "shares", const $showSuccess = inject<IToastSuccess>("$showSuccess")!;
components: { const { t } = useI18n();
Errors,
}, const layoutStore = useLayoutStore();
inject: ["$showError", "$showSuccess"], const authStore = useAuthStore();
computed: {
...mapState(useAuthStore, ["user"]), // ...mapState(useAuthStore, ["user"]),
...mapWritableState(useLayoutStore, ["loading"]), // ...mapWritableState(useLayoutStore, ["loading"]),
}, const error = ref<any>(null);
data: function () { const links = ref<any[]>([]);
return { const clip = ref<Clipboard | null>(null);
error: null,
links: [], onMounted(async () => {
clip: null, layoutStore.loading = true;
};
},
async created() {
this.loading = true;
try { try {
let links = await api.list(); let newLinks = await api.list();
if (this.user.perm.admin) { if (authStore.user?.perm.admin) {
let userMap = new Map(); let userMap = new Map();
for (let user of await users.getAll()) for (let user of await users.getAll())
userMap.set(user.id, user.username); userMap.set(user.id, user.username);
for (let link of links) for (let link of newLinks)
link.username = userMap.has(link.userID) link.username = userMap.has(link.userID)
? userMap.get(link.userID) ? userMap.get(link.userID)
: ""; : "";
} }
this.links = links; links.value = newLinks;
} catch (e) { } catch (e: any) {
this.error = e; error.value = e;
} finally { } finally {
this.loading = false; layoutStore.loading = false;
} }
}, clip.value = new Clipboard(".copy-clipboard");
mounted() { clip.value.on("success", () => {
this.clip = new Clipboard(".copy-clipboard"); $showSuccess(t("success.linkCopied"));
this.clip.on("success", () => {
this.$showSuccess(this.$t("success.linkCopied"));
}); });
}, });
beforeUnmount() {
this.clip.destroy(); onBeforeUnmount(() => clip.value?.destroy());
},
methods: { const deleteLink = async (event: Event, link: any) => {
deleteLink: async function (event, link) {
event.preventDefault(); event.preventDefault();
this.showHover({ layoutStore.showHover({
prompt: "share-delete", prompt: "share-delete",
confirm: () => { confirm: () => {
this.closeHovers(); layoutStore.closeHovers();
try { try {
api.remove(link.hash); api.remove(link.hash);
this.links = this.links.filter((item) => item.hash !== link.hash); links.value = links.value.filter((item) => item.hash !== link.hash);
this.$showSuccess(this.$t("settings.shareDeleted")); $showSuccess(t("settings.shareDeleted"));
} catch (e) { } catch (e: any) {
this.$showError(e); $showError(e);
} }
}, },
}); });
}, };
humanTime(time) { const humanTime = (time: number) => {
return dayjs(time * 1000).fromNow(); return dayjs(time * 1000).fromNow();
}, };
buildLink(share) {
const buildLink = (share: IShare) => {
return api.getShareURL(share); return api.getShareURL(share);
},
},
}; };
</script> </script>

View File

@ -1,14 +1,14 @@
<template> <template>
<errors v-if="error" :errorCode="error.status" /> <errors v-if="error" :errorCode="error.status" />
<div class="row" v-else-if="!loading"> <div class="row" v-else-if="!layoutStore.loading">
<div class="column"> <div class="column">
<form @submit="save" class="card"> <form @submit="save" class="card">
<div class="card-title"> <div class="card-title">
<h2 v-if="user.id === 0">{{ $t("settings.newUser") }}</h2> <h2 v-if="user?.id === 0">{{ $t("settings.newUser") }}</h2>
<h2 v-else>{{ $t("settings.user") }} {{ user.username }}</h2> <h2 v-else>{{ $t("settings.user") }} {{ user?.username }}</h2>
</div> </div>
<div class="card-content"> <div class="card-content" v-if="user">
<user-form <user-form
v-model:user="user" v-model:user="user"
v-model:createUserDir="createUserDir" v-model:createUserDir="createUserDir"
@ -46,7 +46,7 @@
</form> </form>
</div> </div>
<div v-if="show === 'deleteUser'" class="card floating"> <div v-if="layoutStore.show === 'deleteUser'" class="card floating">
<div class="card-content"> <div class="card-content">
<p>Are you sure you want to delete this user?</p> <p>Are you sure you want to delete this user?</p>
</div> </div>
@ -54,7 +54,7 @@
<div class="card-action"> <div class="card-action">
<button <button
class="button button--flat button--grey" class="button button--flat button--grey"
@click="closeHovers" @click="layoutStore.closeHovers"
v-focus v-focus
:aria-label="$t('buttons.cancel')" :aria-label="$t('buttons.cancel')"
:title="$t('buttons.cancel')" :title="$t('buttons.cancel')"
@ -69,59 +69,51 @@
</div> </div>
</template> </template>
<script> <script setup lang="ts">
import { mapActions, mapState, mapWritableState } from "pinia";
import { useAuthStore } from "@/stores/auth"; import { useAuthStore } from "@/stores/auth";
import { useLayoutStore } from "@/stores/layout"; import { useLayoutStore } from "@/stores/layout";
import { users as api, settings } from "@/api"; import { users as api, settings } from "@/api";
import UserForm from "@/components/settings/UserForm.vue"; import UserForm from "@/components/settings/UserForm.vue";
import Errors from "@/views/Errors.vue"; import Errors from "@/views/Errors.vue";
import { cloneDeep } from "lodash-es"; import { computed, inject, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import type { IToastError, IToastSuccess, IUser } from "@/types";
export default { const error = ref<any | null>(null);
name: "user", const originalUser = ref<IUser | null>(null);
components: { const user = ref<IUser | null>(null);
UserForm, const createUserDir = ref<boolean>(false);
Errors,
}, const $showError = inject<IToastError>("$showError")!;
data: () => { const $showSuccess = inject<IToastSuccess>("$showSuccess")!;
return {
error: null, const authStore = useAuthStore();
originalUser: null, const layoutStore = useLayoutStore();
user: {}, const route = useRoute();
createUserDir: false, const router = useRouter();
}; const { t } = useI18n();
},
created() { onMounted(() => {
this.fetchData(); fetchData();
}, });
inject: ["$showError", "$showSuccess"],
computed: { const isNew = computed(() => route.path === "/settings/users/new");
...mapState(useAuthStore, { sUser: "user" }),
...mapState(useLayoutStore, ["show"]), watch(route, () => fetchData());
...mapWritableState(useLayoutStore, ["loading"]), watch(user, () => {
isNew() { if (!user.value?.perm.admin) return;
return this.$route.path === "/settings/users/new"; user.value.lockPassword = false;
}, });
},
watch: { const fetchData = async () => {
$route: "fetchData", layoutStore.loading = true;
"user.perm.admin": function () {
if (!this.user.perm.admin) return;
this.user.lockPassword = false;
},
},
methods: {
...mapActions(useAuthStore, ["setUser"]),
...mapActions(useLayoutStore, ["closeHovers", "showHover"]),
async fetchData() {
this.loading = true;
try { try {
if (this.isNew) { if (isNew.value) {
let { defaults, createUserDir } = await settings.get(); let { defaults, _createUserDir } = await settings.get();
this.createUserDir = createUserDir; createUserDir.value = _createUserDir;
this.user = { user.value = {
...defaults, ...defaults,
username: "", username: "",
passsword: "", passsword: "",
@ -130,56 +122,60 @@ export default {
id: 0, id: 0,
}; };
} else { } else {
const id = this.$route.params.id; const id = Array.isArray(route.params.id)
this.user = { ...(await api.get(id)) }; ? route.params.id.join("")
: route.params.id;
user.value = { ...(await api.get(parseInt(id))) };
} }
} catch (e) { } catch (e) {
this.error = e; error.value = e;
} finally { } finally {
this.loading = false; layoutStore.loading = false;
} }
},
deletePrompt() {
this.showHover("deleteUser");
},
async deleteUser(event) {
event.preventDefault();
try {
await api.remove(this.user.id);
this.$router.push({ path: "/settings/users" });
this.$showSuccess(this.$t("settings.userDeleted"));
} catch (e) {
e.message === "403"
? this.$showError(this.$t("errors.forbidden"), false)
: this.$showError(e);
}
},
async save(event) {
event.preventDefault();
let user = {
...this.originalUser,
...this.user,
}; };
const deletePrompt = () => layoutStore.showHover("deleteUser");
const deleteUser = async (e: Event) => {
e.preventDefault();
if (user.value === null) {
return false;
}
try { try {
if (this.isNew) { await api.remove(user.value.id);
const loc = await api.create(user); router.push({ path: "/settings/users" });
this.$router.push({ path: loc }); $showSuccess(t("settings.userDeleted"));
this.$showSuccess(this.$t("settings.userCreated")); } catch (e: any) {
e.message === "403" ? $showError(t("errors.forbidden")) : $showError(e);
}
};
const save = async (event: Event) => {
event.preventDefault();
if (originalUser.value === null || user.value === null) {
return false;
}
try {
if (isNew.value) {
const newUser: IUser = {
...originalUser.value,
...user.value,
};
const loc = (await api.create(newUser)) as string;
router.push({ path: loc });
$showSuccess(t("settings.userCreated"));
} else { } else {
await api.update(user); await api.update(user);
if (user.id === this.sUser.id) { if (user.value.id === authStore.user?.id) {
this.setUser({ ...cloneDeep(user) }); authStore.updateUser(user.value);
} }
this.$showSuccess(this.$t("settings.userUpdated")); $showSuccess(t("settings.userUpdated"));
} }
} catch (e) { } catch (e: any) {
this.$showError(e); $showError(e);
} }
},
},
}; };
</script> </script>

View File

@ -1,13 +1,13 @@
<template> <template>
<errors v-if="error" :errorCode="error.status" /> <errors v-if="error" :errorCode="error.status" />
<div class="row" v-else-if="!loading"> <div class="row" v-else-if="!layoutStore.loading">
<div class="column"> <div class="column">
<div class="card"> <div class="card">
<div class="card-title"> <div class="card-title">
<h2>{{ $t("settings.users") }}</h2> <h2>{{ t("settings.users") }}</h2>
<router-link to="/settings/users/new" <router-link to="/settings/users/new"
><button class="button"> ><button class="button">
{{ $t("buttons.new") }} {{ t("buttons.new") }}
</button></router-link </button></router-link
> >
</div> </div>
@ -15,9 +15,9 @@
<div class="card-content full"> <div class="card-content full">
<table> <table>
<tr> <tr>
<th>{{ $t("settings.username") }}</th> <th>{{ t("settings.username") }}</th>
<th>{{ $t("settings.admin") }}</th> <th>{{ t("settings.admin") }}</th>
<th>{{ $t("settings.scope") }}</th> <th>{{ t("settings.scope") }}</th>
<th></th> <th></th>
</tr> </tr>
@ -41,36 +41,29 @@
</div> </div>
</template> </template>
<script> <script setup lang="ts">
import { mapWritableState } from "pinia";
import { useLayoutStore } from "@/stores/layout"; import { useLayoutStore } from "@/stores/layout";
import { users as api } from "@/api"; import { users as api } from "@/api";
import Errors from "@/views/Errors.vue"; import Errors from "@/views/Errors.vue";
import { onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import type { IUser } from "@/types";
export default { const error = ref<any>(null);
name: "users", const users = ref<IUser[]>([]);
components: {
Errors, const layoutStore = useLayoutStore();
}, const { t } = useI18n();
data: function () {
return { onMounted(async () => {
error: null, layoutStore.loading = true;
users: [],
};
},
async created() {
this.loading = true;
try { try {
this.users = await api.getAll(); users.value = await api.getAll();
} catch (e) { } catch (e: any) {
this.error = e; error.value = e;
} finally { } finally {
this.loading = false; layoutStore.loading = false;
} }
}, });
computed: {
...mapWritableState(useLayoutStore, ["loading"]),
},
};
</script> </script>