fix: preserve SSO identities and polish sharing interface
This commit is contained in:
1 parent
2e3b56f250
commit
bd9bf33bc9
22 files changed
+430
-106
No files matched your search
@@ -1,5 +1,9 @@
|
||||
# Вход через SSO
|
||||
|
||||
При входе профиль дополнительно загружается через OIDC UserInfo: имя пользователя, полное имя и email. `sub` обязан совпадать с проверенным ID token; роли берутся только из подписанного токена. Внутренний ключ `sso:…` хранится отдельно от отображаемого имени и не изменяется при сохранении настроек.
|
||||
|
||||
Повторный вход использует тот же локальный ID. Если предыдущая версия уже создала несколько записей с одинаковым ключом, используется самая ранняя запись, включая после перезапуска; существующие дубли, их настройки и публичные ссылки автоматически не удаляются. В списке пользователей отображаются ID записей. Перед обновлением сохраните резервную копию базы.
|
||||
|
||||
Поддерживается OpenID Connect Authorization Code Flow с PKCE S256. Настройка выполняется через `filebrowser init`, который создаёт `.filebrowser.json` и печатает callback URL. Подробности — [установка](deployment.md).
|
||||
|
||||
Проверяются state, nonce, RSA-подпись, issuer, audience, срок действия ID token и привязка access token через at_hash. Идентичность привязана к issuer и стабильному sub. Логин или почта, совпавшие с прежним локальным аккаунтом, не дают доступ к нему.
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 31 KiB |
@@ -4,7 +4,10 @@
|
||||
<template v-if="isLoggedIn">
|
||||
<button @click="toAccountSettings" class="action">
|
||||
<i class="material-icons">person</i>
|
||||
<span>{{ user.username }}</span>
|
||||
<span class="sidebar-profile"
|
||||
><strong>{{ user.username }}</strong
|
||||
><small v-if="user.profileName">{{ user.profileName }}</small></span
|
||||
>
|
||||
</button>
|
||||
<button
|
||||
class="action"
|
||||
@@ -86,31 +89,22 @@
|
||||
</template>
|
||||
|
||||
<div
|
||||
class="credits"
|
||||
v-if="isFiles && !disableUsedPercentage"
|
||||
style="width: 90%; margin: 2em 2.5em 3em 2.5em"
|
||||
class="disk-usage"
|
||||
v-if="isFiles && !disableUsedPercentage && usage.total !== '0 B'"
|
||||
>
|
||||
<progress-bar :val="usage.usedPercentage" size="small"></progress-bar>
|
||||
<br />
|
||||
{{ $t("sidebar.diskUsed", { used: usage.used, total: usage.total }) }}
|
||||
<div class="disk-usage-heading">
|
||||
<span>{{ $t("sso.storage") }}</span
|
||||
><strong>{{ usage.usedPercentage }}%</strong>
|
||||
</div>
|
||||
<progress
|
||||
:value="usage.usedPercentage"
|
||||
max="100"
|
||||
:aria-label="$t('sso.storage')"
|
||||
></progress>
|
||||
<small>{{
|
||||
$t("sidebar.diskUsed", { used: usage.used, total: usage.total })
|
||||
}}</small>
|
||||
</div>
|
||||
|
||||
<p class="credits">
|
||||
<span>
|
||||
<span v-if="disableExternal">File Browser</span>
|
||||
<a
|
||||
v-else
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
href="https://github.com/filebrowser/filebrowser"
|
||||
>File Browser</a
|
||||
>
|
||||
<span> {{ " " }} {{ version }}</span>
|
||||
</span>
|
||||
<span>
|
||||
<a @click="help">{{ $t("sidebar.help") }}</a>
|
||||
</span>
|
||||
</p>
|
||||
</nav>
|
||||
</template>
|
||||
|
||||
@@ -123,17 +117,14 @@ import { useLayoutStore } from "@/stores/layout";
|
||||
|
||||
import * as auth from "@/utils/auth";
|
||||
import {
|
||||
version,
|
||||
signup,
|
||||
hideLoginButton,
|
||||
disableExternal,
|
||||
disableUsedPercentage,
|
||||
noAuth,
|
||||
logoutPage,
|
||||
loginPage,
|
||||
} from "@/utils/constants";
|
||||
import { files as api } from "@/api";
|
||||
import ProgressBar from "@/components/ProgressBar.vue";
|
||||
import prettyBytes from "pretty-bytes";
|
||||
|
||||
const USAGE_DEFAULT = { used: "0 B", total: "0 B", usedPercentage: 0 };
|
||||
@@ -144,9 +135,6 @@ export default {
|
||||
const usage = reactive(USAGE_DEFAULT);
|
||||
return { usage, usageAbortController: new AbortController() };
|
||||
},
|
||||
components: {
|
||||
ProgressBar,
|
||||
},
|
||||
inject: ["$showError"],
|
||||
computed: {
|
||||
...mapState(useAuthStore, ["user", "isLoggedIn"]),
|
||||
@@ -157,8 +145,6 @@ export default {
|
||||
},
|
||||
signup: () => signup,
|
||||
hideLoginButton: () => hideLoginButton,
|
||||
version: () => version,
|
||||
disableExternal: () => disableExternal,
|
||||
disableUsedPercentage: () => disableUsedPercentage,
|
||||
canLogout: () => !noAuth && (loginPage || logoutPage !== "/login"),
|
||||
},
|
||||
@@ -182,7 +168,13 @@ export default {
|
||||
usageStats = {
|
||||
used: prettyBytes(usage.used, { binary: true }),
|
||||
total: prettyBytes(usage.total, { binary: true }),
|
||||
usedPercentage: Math.round((usage.used / usage.total) * 100),
|
||||
usedPercentage:
|
||||
usage.total > 0
|
||||
? Math.min(
|
||||
100,
|
||||
Math.max(0, Math.round((usage.used / usage.total) * 100))
|
||||
)
|
||||
: 0,
|
||||
};
|
||||
} finally {
|
||||
return Object.assign(this.usage, usageStats);
|
||||
|
||||
@@ -6,34 +6,40 @@
|
||||
|
||||
<template v-if="listing">
|
||||
<div class="card-content">
|
||||
<table>
|
||||
<tr>
|
||||
<th>#</th>
|
||||
<th>{{ $t("settings.shareDuration") }}</th>
|
||||
<th></th>
|
||||
<th></th>
|
||||
<th></th>
|
||||
</tr>
|
||||
|
||||
<tr v-for="link in links" :key="link.hash">
|
||||
<td>{{ link.hash }}</td>
|
||||
<td>
|
||||
<template v-if="link.expire !== 0">{{
|
||||
humanTime(link.expire)
|
||||
}}</template>
|
||||
<template v-else>{{ $t("permanent") }}</template>
|
||||
</td>
|
||||
<td class="small">
|
||||
<div class="share-links">
|
||||
<article
|
||||
v-for="link in links"
|
||||
:key="link.hash"
|
||||
class="share-link-card"
|
||||
>
|
||||
<div class="share-link-details">
|
||||
<a
|
||||
:href="buildLink(link)"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="share-link-name"
|
||||
>/s/{{ link.hash }}</a
|
||||
>
|
||||
<small
|
||||
><i class="material-icons" aria-hidden="true">schedule</i
|
||||
>{{ link.expire ? humanTime(link.expire) : $t("permanent")
|
||||
}}<i
|
||||
v-if="link.hasPassword"
|
||||
class="material-icons"
|
||||
:title="$t('login.password')"
|
||||
>lock</i
|
||||
></small
|
||||
>
|
||||
</div>
|
||||
<div class="share-link-actions">
|
||||
<button
|
||||
class="action"
|
||||
:aria-label="$t('buttons.copyToClipboard')"
|
||||
:title="$t('buttons.copyToClipboard')"
|
||||
@click="copyToClipboard(buildLink(link))"
|
||||
>
|
||||
<i class="material-icons">content_paste</i>
|
||||
<i class="material-icons">link</i>
|
||||
</button>
|
||||
</td>
|
||||
<td class="small">
|
||||
<button
|
||||
class="action"
|
||||
:aria-label="$t('buttons.copyDownloadLinkToClipboard')"
|
||||
@@ -41,21 +47,19 @@
|
||||
:disabled="!!link.hasPassword"
|
||||
@click="copyToClipboard(buildDownloadLink(link))"
|
||||
>
|
||||
<i class="material-icons">content_paste_go</i>
|
||||
<i class="material-icons">download</i>
|
||||
</button>
|
||||
</td>
|
||||
<td class="small">
|
||||
<button
|
||||
class="action"
|
||||
@click="deleteLink($event, link)"
|
||||
class="action share-link-delete"
|
||||
:aria-label="$t('buttons.delete')"
|
||||
:title="$t('buttons.delete')"
|
||||
@click="deleteLink($event, link)"
|
||||
>
|
||||
<i class="material-icons">delete</i>
|
||||
<i class="material-icons">delete_outline</i>
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card-action">
|
||||
|
||||
@@ -1,4 +1,159 @@
|
||||
/* Lightweight workspace: system fonts, solid surfaces, no blur or filter layers. */
|
||||
.user-record-id {
|
||||
display: block;
|
||||
color: var(--textPrimary);
|
||||
font-size: 11px;
|
||||
}
|
||||
.without-sidebar main {
|
||||
width: auto;
|
||||
max-width: 1200px;
|
||||
margin: 0 auto 24px;
|
||||
padding-inline: 24px;
|
||||
}
|
||||
.without-sidebar .menu-button {
|
||||
display: none;
|
||||
}
|
||||
.sidebar-profile {
|
||||
display: inline-flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
max-width: calc(100% - 38px);
|
||||
}
|
||||
.sidebar-profile strong,
|
||||
.sidebar-profile small {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.sidebar-profile small {
|
||||
color: var(--textPrimary);
|
||||
font-weight: 400;
|
||||
font-size: 11px;
|
||||
}
|
||||
nav .disk-usage {
|
||||
margin: 28px 4px 12px;
|
||||
padding: 14px;
|
||||
border: 1px solid var(--borderPrimary);
|
||||
border-radius: 12px;
|
||||
background: var(--background);
|
||||
}
|
||||
.disk-usage-heading {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
font-size: 12px;
|
||||
color: var(--textSecondary);
|
||||
}
|
||||
.disk-usage progress {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 6px;
|
||||
margin: 10px 0;
|
||||
border: 0;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
background: var(--borderPrimary);
|
||||
accent-color: var(--blue);
|
||||
}
|
||||
.disk-usage progress::-webkit-progress-bar {
|
||||
background: var(--borderPrimary);
|
||||
}
|
||||
.disk-usage progress::-webkit-progress-value {
|
||||
background: var(--blue);
|
||||
border-radius: 8px;
|
||||
}
|
||||
.disk-usage progress::-moz-progress-bar {
|
||||
background: var(--blue);
|
||||
border-radius: 8px;
|
||||
}
|
||||
.disk-usage small {
|
||||
display: block;
|
||||
font-size: 11px;
|
||||
color: var(--textPrimary);
|
||||
}
|
||||
.profile-summary {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
padding-bottom: 20px;
|
||||
margin-bottom: 20px;
|
||||
border-bottom: 1px solid var(--divider);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.profile-summary strong {
|
||||
font-size: 20px;
|
||||
color: var(--textSecondary);
|
||||
}
|
||||
#share.card {
|
||||
width: min(620px, calc(100vw - 32px));
|
||||
max-width: calc(100vw - 32px);
|
||||
}
|
||||
#share .card-content {
|
||||
padding: 20px;
|
||||
}
|
||||
.share-links {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
}
|
||||
.share-link-card {
|
||||
padding: 14px;
|
||||
border: 1px solid var(--borderPrimary);
|
||||
border-radius: 10px;
|
||||
background: var(--background);
|
||||
}
|
||||
.share-link-details {
|
||||
min-width: 0;
|
||||
}
|
||||
.share-link-name {
|
||||
display: block;
|
||||
overflow-wrap: anywhere;
|
||||
color: var(--textSecondary);
|
||||
font-weight: 600;
|
||||
}
|
||||
.share-link-details small {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-top: 7px;
|
||||
color: var(--textPrimary);
|
||||
}
|
||||
.share-link-details small i {
|
||||
font-size: 16px;
|
||||
}
|
||||
.share-link-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 6px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.share-link-actions .action {
|
||||
border: 1px solid var(--borderPrimary);
|
||||
border-radius: 8px;
|
||||
width: 38px;
|
||||
height: 36px;
|
||||
padding: 4px;
|
||||
}
|
||||
.share-link-actions .action:hover {
|
||||
background: var(--hover);
|
||||
}
|
||||
.share-link-actions .share-link-delete {
|
||||
color: var(--red);
|
||||
}
|
||||
.share-link-actions .action:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: default;
|
||||
}
|
||||
.share__box__info {
|
||||
max-width: 560px;
|
||||
}
|
||||
.share__box__center svg {
|
||||
max-width: min(240px, 100%);
|
||||
height: auto;
|
||||
padding: 12px;
|
||||
background: white;
|
||||
border-radius: 10px;
|
||||
}
|
||||
.share__box__icon i {
|
||||
font-size: 80px;
|
||||
}
|
||||
:root {
|
||||
--blue: #3563e9;
|
||||
--dark-blue: #244bc2;
|
||||
|
||||
@@ -200,7 +200,7 @@
|
||||
"allowNew": "Create new files and directories",
|
||||
"allowPublish": "Publish new posts and pages",
|
||||
"allowSignup": "Allow users to signup",
|
||||
"hideLoginButton": "Hide the login button from public pages",
|
||||
"hideLoginButton": "Hide the sidebar on public pages",
|
||||
"avoidChanges": "(leave blank to avoid changes)",
|
||||
"branding": "Branding",
|
||||
"brandingDirectoryPath": "Branding directory path",
|
||||
@@ -247,10 +247,10 @@
|
||||
"execute": "Execute commands",
|
||||
"modify": "Edit files",
|
||||
"rename": "Rename or move files and directories",
|
||||
"share": "Share files (require download permission)"
|
||||
"share": "Share files (requires download permission)"
|
||||
},
|
||||
"permissions": "Permissions",
|
||||
"permissionsHelp": "You can set the user to be an administrator or choose the permissions individually. If you select \"Administrator\", all of the other options will be automatically checked. The management of users remains a privilege of an administrator.\n",
|
||||
"permissionsHelp": "File access permissions. Administrators are determined by SSO roles.",
|
||||
"profileSettings": "Profile Settings",
|
||||
"redirectAfterCopyMove": "Redirect to destination after copy/move",
|
||||
"ruleExample1": "prevents the access to any dotfile (such as .git, .gitignore) in every folder.\n",
|
||||
@@ -260,7 +260,7 @@
|
||||
"scope": "Scope",
|
||||
"setDateFormat": "Set exact date format",
|
||||
"settingsUpdated": "Settings updated!",
|
||||
"shareDuration": "Share Duration",
|
||||
"shareDuration": "Link expiration",
|
||||
"shareManagement": "Share Management",
|
||||
"shareDeleted": "Share deleted!",
|
||||
"singleClick": "Use single clicks to open files and directories",
|
||||
@@ -318,6 +318,17 @@
|
||||
"shortHint": "2–64 letters, digits, underscores or hyphens. Public names are discoverable; protect sensitive shares with a password.",
|
||||
"workspace": "Your workspace",
|
||||
"toggleTheme": "Switch theme",
|
||||
"itemsCount": "{count} items"
|
||||
"itemsCount": "{count} items",
|
||||
"storage": "Storage",
|
||||
"editorTheme": "The editor follows the interface theme automatically."
|
||||
},
|
||||
"permissions": {
|
||||
"create": "Create files and directories",
|
||||
"delete": "Delete files and directories",
|
||||
"download": "Download",
|
||||
"execute": "Execute commands",
|
||||
"modify": "Edit files",
|
||||
"rename": "Rename or move files and directories",
|
||||
"share": "Share files (requires download permission)"
|
||||
}
|
||||
}
|
||||
@@ -200,7 +200,7 @@
|
||||
"allowNew": "Создание новых файлов или каталогов",
|
||||
"allowPublish": "Публикация новых записей и страниц",
|
||||
"allowSignup": "Разрешить пользователям регистрироваться",
|
||||
"hideLoginButton": "Спрятать кнопку входа с публичных страниц",
|
||||
"hideLoginButton": "Спрятать боковое меню с публичных страниц",
|
||||
"avoidChanges": "(оставьте поле пустым, чтобы избежать изменений)",
|
||||
"branding": "Брендинг",
|
||||
"brandingDirectoryPath": "Путь к каталогу брендов",
|
||||
@@ -247,10 +247,10 @@
|
||||
"execute": "Выполнять команды",
|
||||
"modify": "Редактировать файлы",
|
||||
"rename": "Переименовывать или перемещать файлы и каталоги",
|
||||
"share": "Share files (require download permission)"
|
||||
"share": "Делиться файлами (требует разрешения на скачивание)"
|
||||
},
|
||||
"permissions": "Права доступа",
|
||||
"permissionsHelp": "Можно настроить пользователя как администратора или выбрать разрешения индивидуально. При выборе \"Администратор\", все остальные параметры будут автоматически выбраны. Управление пользователями - привилегия администратора.\n",
|
||||
"permissionsHelp": "Права на работу с файлами. Администраторы определяются ролями SSO.",
|
||||
"profileSettings": "Настройки профиля",
|
||||
"redirectAfterCopyMove": "Redirect to destination after copy/move",
|
||||
"ruleExample1": "предотвратить доступ к любому скрытому файлу (например: .git, .gitignore) в каждой папке.\n",
|
||||
@@ -260,7 +260,7 @@
|
||||
"scope": "Область",
|
||||
"setDateFormat": "Установить точный формат даты",
|
||||
"settingsUpdated": "Настройки применены!",
|
||||
"shareDuration": "Время расшаренной ссылки",
|
||||
"shareDuration": "Срок действия ссылки",
|
||||
"shareManagement": "Управление расшаренными ссылками",
|
||||
"shareDeleted": "Расшаренная ссылка удалена!",
|
||||
"singleClick": "Открытие файлов и каталогов одним кликом",
|
||||
@@ -283,7 +283,7 @@
|
||||
"currentPassword": "Your Current Password"
|
||||
},
|
||||
"sidebar": {
|
||||
"diskUsed": "{used} of {total} used",
|
||||
"diskUsed": "Занято {used} из {total}",
|
||||
"help": "Помощь",
|
||||
"hugoNew": "Hugo New",
|
||||
"login": "Войти",
|
||||
@@ -315,6 +315,17 @@
|
||||
"shortHint": "2–64 латинские буквы, цифры, дефис или подчёркивание. Для конфиденциальных файлов установите пароль ссылки.",
|
||||
"workspace": "Файловое пространство",
|
||||
"toggleTheme": "Переключить тему",
|
||||
"itemsCount": "Объектов: {count}"
|
||||
"itemsCount": "Объектов: {count}",
|
||||
"storage": "Хранилище",
|
||||
"editorTheme": "Тема редактора автоматически соответствует теме интерфейса."
|
||||
},
|
||||
"permissions": {
|
||||
"create": "Создавать файлы и каталоги",
|
||||
"delete": "Удалять файлы и каталоги",
|
||||
"download": "Скачивать",
|
||||
"execute": "Выполнять команды",
|
||||
"modify": "Редактировать файлы",
|
||||
"rename": "Переименовывать или перемещать файлы и каталоги",
|
||||
"share": "Делиться файлами (требует разрешения на скачивание)"
|
||||
}
|
||||
}
|
||||
Vendored
+2
@@ -1,5 +1,7 @@
|
||||
interface IUser {
|
||||
displayName?: string;
|
||||
profileName?: string;
|
||||
email?: string;
|
||||
id: number;
|
||||
username: string;
|
||||
password: string;
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import "ace-builds";
|
||||
import { themesByName } from "ace-builds/src-noconflict/ext-themelist";
|
||||
import "ace-builds/src-noconflict/theme-chrome";
|
||||
import "ace-builds/src-noconflict/theme-twilight";
|
||||
import { getTheme } from "./theme";
|
||||
|
||||
export const getEditorTheme = (themeName: string) => {
|
||||
const key = themeName.replace(/^ace\/theme\//, "");
|
||||
if (themesByName[key] !== undefined) return `ace/theme/${key}`;
|
||||
export const getEditorTheme = () => {
|
||||
return getTheme() === "dark" ? "ace/theme/twilight" : "ace/theme/chrome";
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<div>
|
||||
<div :class="{ 'without-sidebar': hideSidebar }">
|
||||
<div v-if="uploadStore.totalBytes" class="progress">
|
||||
<div
|
||||
v-bind:style="{
|
||||
@@ -7,7 +7,7 @@
|
||||
}"
|
||||
></div>
|
||||
</div>
|
||||
<sidebar></sidebar>
|
||||
<sidebar v-if="!hideSidebar"></sidebar>
|
||||
<main>
|
||||
<router-view></router-view>
|
||||
<shell
|
||||
@@ -30,7 +30,7 @@ import Sidebar from "@/components/Sidebar.vue";
|
||||
import Prompts from "@/components/prompts/Prompts.vue";
|
||||
import Shell from "@/components/Shell.vue";
|
||||
import UploadFiles from "@/components/prompts/UploadFiles.vue";
|
||||
import { enableExec } from "@/utils/constants";
|
||||
import { enableExec, hideLoginButton } from "@/utils/constants";
|
||||
import { computed, watch } from "vue";
|
||||
import { useRoute } from "vue-router";
|
||||
|
||||
@@ -39,6 +39,7 @@ const authStore = useAuthStore();
|
||||
const fileStore = useFileStore();
|
||||
const uploadStore = useUploadStore();
|
||||
const route = useRoute();
|
||||
const hideSidebar = computed(() => route.name === "Share" && hideLoginButton);
|
||||
|
||||
const sentPercent = computed(() =>
|
||||
((uploadStore.sentBytes / uploadStore.totalBytes) * 100).toFixed(2)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<div>
|
||||
<header-bar showMenu showLogo>
|
||||
<header-bar :showMenu="!hideLoginButton" showLogo>
|
||||
<title />
|
||||
|
||||
<action
|
||||
@@ -301,6 +301,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { hideLoginButton } from "@/utils/constants";
|
||||
import { pub as api } from "@/api";
|
||||
import { filesize } from "@/utils";
|
||||
import dayjs from "dayjs";
|
||||
|
||||
@@ -113,6 +113,9 @@ const route = useRoute();
|
||||
const router = useRouter();
|
||||
|
||||
const editor = ref<Ace.Editor | null>(null);
|
||||
const themeObserver = new MutationObserver(() => {
|
||||
editor.value?.setTheme(getEditorTheme());
|
||||
});
|
||||
const fontSize = ref(parseInt(localStorage.getItem("editorFontSize") || "14"));
|
||||
|
||||
const isPreview = ref(false);
|
||||
@@ -191,6 +194,7 @@ onMounted(() => {
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
themeObserver.disconnect();
|
||||
window.removeEventListener("keydown", keyEvent);
|
||||
window.removeEventListener("beforeunload", handlePageChange);
|
||||
editor.value?.destroy();
|
||||
@@ -217,12 +221,16 @@ onBeforeRouteUpdate((to, from, next) => {
|
||||
});
|
||||
|
||||
const initEditor = (fileContent: string) => {
|
||||
themeObserver.observe(document.documentElement, {
|
||||
attributes: true,
|
||||
attributeFilter: ["class"],
|
||||
});
|
||||
editor.value = ace.edit("editor", {
|
||||
value: fileContent,
|
||||
showPrintMargin: false,
|
||||
useWorker: false,
|
||||
readOnly: fileStore.req?.type === "textImmutable",
|
||||
theme: getEditorTheme(authStore.user?.aceEditorTheme ?? ""),
|
||||
theme: getEditorTheme(),
|
||||
mode: modelist.getModeForPath(fileStore.req!.name).mode,
|
||||
wrap: true,
|
||||
enableBasicAutocompletion: true,
|
||||
|
||||
@@ -7,6 +7,14 @@
|
||||
</div>
|
||||
|
||||
<div class="card-content">
|
||||
<div class="profile-summary">
|
||||
<strong>{{ authStore.user?.username }}</strong
|
||||
><span v-if="authStore.user?.profileName">{{
|
||||
authStore.user.profileName
|
||||
}}</span
|
||||
><span v-if="authStore.user?.email">{{ authStore.user.email }}</span
|
||||
><small>{{ t("sso.managed") }}</small>
|
||||
</div>
|
||||
<p>
|
||||
<input type="checkbox" name="hideDotfiles" v-model="hideDotfiles" />
|
||||
{{ t("settings.hideDotfiles") }}
|
||||
@@ -33,12 +41,7 @@
|
||||
v-model:locale="locale"
|
||||
></languages>
|
||||
|
||||
<h3>{{ t("settings.aceEditorTheme") }}</h3>
|
||||
<AceEditorTheme
|
||||
class="input input--block"
|
||||
v-model:aceEditorTheme="aceEditorTheme"
|
||||
id="aceTheme"
|
||||
></AceEditorTheme>
|
||||
<p class="field-hint">{{ t("sso.editorTheme") }}</p>
|
||||
</div>
|
||||
|
||||
<div class="card-action">
|
||||
@@ -58,7 +61,6 @@
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { useLayoutStore } from "@/stores/layout";
|
||||
import { users as api } from "@/api";
|
||||
import AceEditorTheme from "@/components/settings/AceEditorTheme.vue";
|
||||
import Languages from "@/components/settings/Languages.vue";
|
||||
import { inject, onMounted, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
|
||||
@@ -17,7 +17,10 @@
|
||||
</tr>
|
||||
|
||||
<tr v-for="user in users" :key="user.id">
|
||||
<td>{{ user.displayName || user.username }}</td>
|
||||
<td>
|
||||
{{ user.displayName || user.username
|
||||
}}<small class="user-record-id">ID {{ user.id }}</small>
|
||||
</td>
|
||||
<td>{{ user.scope }}</td>
|
||||
<td class="small">
|
||||
<router-link :to="'/settings/users/' + user.id"
|
||||
|
||||
@@ -17,6 +17,8 @@ type userInfo struct {
|
||||
HideDotfiles bool `json:"hideDotfiles"`
|
||||
DateFormat bool `json:"dateFormat"`
|
||||
Username string `json:"username"`
|
||||
ProfileName string `json:"profileName,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
AceEditorTheme string `json:"aceEditorTheme"`
|
||||
}
|
||||
|
||||
|
||||
+58
-9
@@ -31,6 +31,8 @@ type sessionIdentity struct {
|
||||
type ssoClaims struct {
|
||||
Subject string `json:"sub"`
|
||||
Username string `json:"preferred_username"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
Roles []string `json:"roles"`
|
||||
}
|
||||
type loginAttempt struct {
|
||||
@@ -57,6 +59,7 @@ type SSO struct {
|
||||
server *settings.Server
|
||||
mu sync.Mutex
|
||||
provision sync.Mutex
|
||||
userIDs map[string]uint
|
||||
attempts map[string]loginAttempt
|
||||
sessions map[[32]byte]*ssoSession
|
||||
}
|
||||
@@ -101,6 +104,12 @@ func NewSSO(ctx context.Context, store *storage.Storage, server *settings.Server
|
||||
return nil, err
|
||||
}
|
||||
for _, u := range legacy {
|
||||
if s.userIDs == nil {
|
||||
s.userIDs = map[string]uint{}
|
||||
}
|
||||
if previous, ok := s.userIDs[u.Username]; !ok || u.ID < previous {
|
||||
s.userIDs[u.Username] = u.ID
|
||||
}
|
||||
if u.Password != "!sso-disabled" || !u.LockPassword || u.Perm.Execute || len(u.Commands) > 0 || u.Perm.Admin {
|
||||
u.Password = "!sso-disabled"
|
||||
u.LockPassword = true
|
||||
@@ -219,6 +228,35 @@ func (s *SSO) callback(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "Invalid SSO expiry", 401)
|
||||
return
|
||||
}
|
||||
// Fetch profile data as VTNL Panel does, retaining signed identity and roles.
|
||||
var metadata struct {
|
||||
UserInfoURL string `json:"userinfo_endpoint"`
|
||||
}
|
||||
if err = s.provider.Claims(&metadata); err != nil {
|
||||
http.Error(w, "Invalid SSO metadata", 401)
|
||||
return
|
||||
}
|
||||
if metadata.UserInfoURL != "" {
|
||||
profile, profileErr := s.provider.UserInfo(ctx, oauth2.StaticTokenSource(token))
|
||||
if profileErr != nil || profile.Subject != claims.Subject {
|
||||
http.Error(w, "Invalid SSO profile", 401)
|
||||
return
|
||||
}
|
||||
var info ssoClaims
|
||||
if err = profile.Claims(&info); err != nil {
|
||||
http.Error(w, "Invalid SSO profile claims", 401)
|
||||
return
|
||||
}
|
||||
if claims.Username == "" {
|
||||
claims.Username = info.Username
|
||||
}
|
||||
if claims.Name == "" {
|
||||
claims.Name = info.Name
|
||||
}
|
||||
if claims.Email == "" {
|
||||
claims.Email = info.Email
|
||||
}
|
||||
}
|
||||
identity, err := s.provisionUser(claims)
|
||||
if err != nil {
|
||||
http.Error(w, "Cannot provision SSO user", 500)
|
||||
@@ -250,7 +288,11 @@ func (s *SSO) provisionUser(c ssoClaims) (sessionIdentity, error) {
|
||||
// Namespace by issuer and subject, never by a renameable login or email.
|
||||
identityHash := sha256.Sum256([]byte(s.issuer + "\x00" + c.Subject))
|
||||
username := "sso:" + base64.RawURLEncoding.EncodeToString(identityHash[:])
|
||||
u, err := s.store.Users.Get(s.server.Root, s.server.FollowExternalSymlinks, username)
|
||||
var lookup interface{} = username
|
||||
if id, ok := s.userIDs[username]; ok {
|
||||
lookup = id
|
||||
}
|
||||
u, err := s.store.Users.Get(s.server.Root, s.server.FollowExternalSymlinks, lookup)
|
||||
if errors.Is(err, fberrors.ErrNotExist) {
|
||||
st, err := s.store.Settings.Get()
|
||||
if err != nil {
|
||||
@@ -269,19 +311,26 @@ func (s *SSO) provisionUser(c ssoClaims) (sessionIdentity, error) {
|
||||
if err = s.store.Users.SaveProvisioned(u, derived); err != nil {
|
||||
return sessionIdentity{}, err
|
||||
}
|
||||
if s.userIDs == nil {
|
||||
s.userIDs = map[string]uint{}
|
||||
}
|
||||
s.userIDs[username] = u.ID
|
||||
} else if err != nil {
|
||||
return sessionIdentity{}, err
|
||||
}
|
||||
if u.DisplayName != c.Username {
|
||||
u.DisplayName = c.Username
|
||||
if err = s.store.Users.Update(u, "DisplayName"); err != nil {
|
||||
return sessionIdentity{}, err
|
||||
}
|
||||
}
|
||||
name := c.Username
|
||||
if name == "" {
|
||||
name = c.Name
|
||||
}
|
||||
if name == "" {
|
||||
name = c.Subject
|
||||
}
|
||||
if u.DisplayName != name || u.ProfileName != c.Name || u.Email != c.Email {
|
||||
u.DisplayName, u.ProfileName, u.Email = name, c.Name, c.Email
|
||||
if err = s.store.Users.Update(u, "DisplayName", "ProfileName", "Email"); err != nil {
|
||||
return sessionIdentity{}, err
|
||||
}
|
||||
}
|
||||
return sessionIdentity{ID: u.ID, Name: name, Admin: ssoAdmin(c.Roles)}, nil
|
||||
}
|
||||
|
||||
@@ -384,8 +433,8 @@ func applySSOIdentity(u *users.User, i sessionIdentity) {
|
||||
u.Perm.Execute = false
|
||||
u.LockPassword = true
|
||||
u.Commands = []string{}
|
||||
u.Username = i.Name
|
||||
u.DisplayName = i.Name
|
||||
}
|
||||
func ssoUserInfo(u *users.User) userInfo {
|
||||
return userInfo{ID: u.ID, Username: u.Username, Locale: u.Locale, ViewMode: u.ViewMode, SingleClick: u.SingleClick, RedirectAfterCopyMove: u.RedirectAfterCopyMove, Perm: u.Perm, Commands: []string{}, LockPassword: true, HideDotfiles: u.HideDotfiles, DateFormat: u.DateFormat, AceEditorTheme: u.AceEditorTheme}
|
||||
return userInfo{ID: u.ID, Username: u.DisplayName, ProfileName: u.ProfileName, Email: u.Email, Locale: u.Locale, ViewMode: u.ViewMode, SingleClick: u.SingleClick, RedirectAfterCopyMove: u.RedirectAfterCopyMove, Perm: u.Perm, Commands: []string{}, LockPassword: true, HideDotfiles: u.HideDotfiles, DateFormat: u.DateFormat, AceEditorTheme: u.AceEditorTheme}
|
||||
}
|
||||
+45
-2
@@ -29,6 +29,7 @@ func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var issuer, nonce, challenge string
|
||||
profileSubject := "subject-123"
|
||||
roles := []string{"FS Admin"}
|
||||
enabled := true
|
||||
provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -51,7 +52,7 @@ func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
t.Error("client authentication mismatch")
|
||||
}
|
||||
hash := sha256.Sum256([]byte("access"))
|
||||
claims := map[string]any{"iss": issuer, "aud": "client", "sub": "subject-123", "preferred_username": "alice", "roles": roles, "nonce": nonce, "exp": time.Now().Add(5 * time.Minute).Unix(), "iat": time.Now().Unix(), "at_hash": base64.RawURLEncoding.EncodeToString(hash[:16])}
|
||||
claims := map[string]any{"iss": issuer, "aud": "client", "sub": "subject-123", "roles": roles, "nonce": nonce, "exp": time.Now().Add(5 * time.Minute).Unix(), "iat": time.Now().Unix(), "at_hash": base64.RawURLEncoding.EncodeToString(hash[:16])}
|
||||
b, _ := json.Marshal(claims)
|
||||
signed, _ := signer.Sign(b)
|
||||
token, _ := signed.CompactSerialize()
|
||||
@@ -61,7 +62,10 @@ func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(ssoClaims{Subject: "subject-123", Username: "alice", Roles: roles})
|
||||
if r.Header.Get("Authorization") != "Bearer access" {
|
||||
t.Error("missing UserInfo bearer")
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(ssoClaims{Subject: profileSubject, Username: "alice", Name: "Alice Example", Email: "alice@example.test", Roles: []string{"User"}})
|
||||
default:
|
||||
w.WriteHeader(404)
|
||||
}
|
||||
@@ -116,6 +120,25 @@ func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
if check.Code != 200 || !strings.Contains(check.Body.String(), `"admin":true`) {
|
||||
t.Fatalf("session: %d %s", check.Code, check.Body.String())
|
||||
}
|
||||
if !strings.Contains(check.Body.String(), `"username":"alice"`) || !strings.Contains(check.Body.String(), `"email":"alice@example.test"`) {
|
||||
t.Fatalf("UserInfo profile not loaded: %s", check.Body.String())
|
||||
}
|
||||
// Repeated logins after changing preferences retain one local identity.
|
||||
var firstID uint
|
||||
for i := 0; i < 3; i++ {
|
||||
identity, err := s.provisionUser(ssoClaims{Subject: "subject-123", Username: "alice"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if i == 0 {
|
||||
firstID = identity.ID
|
||||
} else if identity.ID != firstID {
|
||||
t.Fatal("new user on repeated login")
|
||||
}
|
||||
if err = st.Users.Update(&users.User{ID: identity.ID, Username: "alice", Locale: "ru"}, "Locale"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
roles = []string{"User"}
|
||||
check = request("GET", "/api/session")
|
||||
if check.Code != 200 || !strings.Contains(check.Body.String(), `"admin":true`) {
|
||||
@@ -143,7 +166,27 @@ func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
if w.Code != 400 {
|
||||
t.Fatal("callback replay accepted")
|
||||
}
|
||||
login = httptest.NewRecorder()
|
||||
h.ServeHTTP(login, httptest.NewRequest("GET", "/auth/login", nil))
|
||||
u, _ = url.Parse(login.Header().Get("Location"))
|
||||
nonce, challenge = u.Query().Get("nonce"), u.Query().Get("code_challenge")
|
||||
profileSubject = "another-subject"
|
||||
callback = httptest.NewRequest("GET", "/auth/callback?code=test&state="+u.Query().Get("state"), nil)
|
||||
callback.AddCookie(login.Result().Cookies()[0])
|
||||
w = httptest.NewRecorder()
|
||||
h.ServeHTTP(w, callback)
|
||||
if w.Code != 401 {
|
||||
t.Fatal("mismatched UserInfo subject accepted")
|
||||
}
|
||||
// Expired/idle sessions are rejected, even with an otherwise valid cookie.
|
||||
restarted, err := NewSSO(context.Background(), st, &settings.Server{Root: root}, SSOConfig{Issuer: issuer, ClientID: "client", ClientSecret: "secret", PublicURL: "http://127.0.0.1:9111"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
identity, err := restarted.provisionUser(ssoClaims{Subject: "subject-123", Username: "alice"})
|
||||
if err != nil || identity.ID != firstID {
|
||||
t.Fatalf("identity changed after restart: %+v %v", identity, err)
|
||||
}
|
||||
sessionKey := sha256.Sum256([]byte(sessionCookie.Value))
|
||||
for _, tc := range []struct{ expires, touched time.Time }{{time.Now().Add(-time.Second), time.Now()}, {time.Now().Add(time.Hour), time.Now().Add(-31 * time.Minute)}} {
|
||||
s.mu.Lock()
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
param([string]$Version = '3.0.0-sso.1')
|
||||
param([string]$Version = '3.0.0-sso.2')
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repo = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
|
||||
Push-Location $repo
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
VERSION="${VERSION:-3.0.0-sso.1}"
|
||||
VERSION="${VERSION:-3.0.0-sso.2}"
|
||||
COMMIT=$(git rev-parse --short HEAD)
|
||||
(cd frontend && pnpm install --frozen-lockfile && pnpm run build)
|
||||
mkdir -p build/release/linux-amd64
|
||||
|
||||
@@ -78,6 +78,12 @@ func (st usersBackend) Update(user *users.User, fields ...string) error {
|
||||
if len(fields) == 0 {
|
||||
return st.Save(user)
|
||||
}
|
||||
// Storm extracts every index from the object passed to UpdateField, even
|
||||
// for a non-indexed field. Never index partial/request presentation data.
|
||||
current, err := st.GetBy(user.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, field := range fields {
|
||||
userField := reflect.ValueOf(user).Elem().FieldByName(field)
|
||||
@@ -85,7 +91,8 @@ func (st usersBackend) Update(user *users.User, fields ...string) error {
|
||||
return fmt.Errorf("invalid field: %s", field)
|
||||
}
|
||||
val := userField.Interface()
|
||||
if err := st.db.UpdateField(user, field, val); err != nil {
|
||||
reflect.ValueOf(current).Elem().FieldByName(field).Set(userField)
|
||||
if err := st.db.UpdateField(current, field, val); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,35 @@ import (
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
func TestPartialUserUpdatePreservesIdentityIndex(t *testing.T) {
|
||||
db, err := storm.Open(filepath.Join(t.TempDir(), "db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
st, err := NewStorage(db)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u := &users.User{Username: "sso:stable-subject", Password: "!sso-disabled", Scope: "/", Locale: "en"}
|
||||
if err = st.Users.Save(u); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The session/API uses a presentation name and may omit other fields.
|
||||
for _, presentation := range []string{"Alice", "", "Alice Renamed"} {
|
||||
if err = st.Users.Update(&users.User{ID: u.ID, Username: presentation, Locale: "ru"}, "Locale"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := st.Users.Get("", false, "sso:stable-subject")
|
||||
if err != nil {
|
||||
t.Fatalf("identity lookup lost after preference update: %v", err)
|
||||
}
|
||||
if got.ID != u.ID || got.Username != u.Username || got.Locale != "ru" {
|
||||
t.Fatalf("unexpected user: %+v", got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GetByScope must match case-insensitively: on a case-insensitive filesystem
|
||||
// two scopes that differ only in case resolve to the same home directory, so
|
||||
// the provisioning collision check has to treat them as the same scope.
|
||||
|
||||
@@ -22,6 +22,8 @@ type User struct {
|
||||
ID uint `storm:"id,increment" json:"id"`
|
||||
Username string `storm:"unique" json:"username"`
|
||||
DisplayName string `json:"displayName,omitempty"`
|
||||
ProfileName string `json:"profileName,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Password string `json:"password"`
|
||||
Scope string `json:"scope"`
|
||||
Locale string `json:"locale"`
|
||||
|
||||
Reference in new issue
Block a user