wip: access control

This commit is contained in:
Timothy Jaeryang Baek 2024-11-16 01:24:34 -08:00
parent 4eb8b1450c
commit 240c91e79d
10 changed files with 212 additions and 89 deletions

View File

@ -22,8 +22,11 @@ router = APIRouter()
@router.get("/", response_model=list[GroupResponse])
async def get_groups(user=Depends(get_admin_user)):
return Groups.get_groups()
async def get_groups(user=Depends(get_verified_user)):
if user.role == "admin":
return Groups.get_groups()
else:
return Groups.get_groups_by_member_id(user.id)
############################

View File

@ -31,11 +31,29 @@ async def get_users(skip: int = 0, limit: int = 50, user=Depends(get_admin_user)
return Users.get_users(skip, limit)
############################
# User Groups
############################
@router.get("/groups")
async def get_user_groups(user=Depends(get_verified_user)):
return Users.get_user_groups(user.id)
############################
# User Permissions
############################
@router.get("/permissions")
async def get_user_permissisions(user=Depends(get_verified_user)):
return Users.get_user_groups(user.id)
############################
# User Default Permissions
############################
class WorkspacePermissions(BaseModel):
models: bool
knowledge: bool
@ -54,12 +72,12 @@ class UserPermissions(BaseModel):
chat: ChatPermissions
@router.get("/permissions")
@router.get("/default/permissions")
async def get_user_permissions(request: Request, user=Depends(get_admin_user)):
return request.app.state.config.USER_PERMISSIONS
@router.post("/permissions")
@router.post("/default/permissions")
async def update_user_permissions(
request: Request, form_data: UserPermissions, user=Depends(get_admin_user)
):

View File

@ -967,15 +967,23 @@ async def get_all_models():
custom_model.id == model["id"]
or custom_model.id == model["id"].split(":")[0]
):
model["name"] = custom_model.name
model["info"] = custom_model.model_dump()
if custom_model.is_active:
model["name"] = custom_model.name
model["info"] = custom_model.model_dump()
action_ids = []
if "info" in model and "meta" in model["info"]:
action_ids.extend(model["info"]["meta"].get("actionIds", []))
action_ids = []
if "info" in model and "meta" in model["info"]:
action_ids.extend(
model["info"]["meta"].get("actionIds", [])
)
model["action_ids"] = action_ids
elif custom_model.id not in [model["id"] for model in models]:
model["action_ids"] = action_ids
else:
models.remove(model)
elif custom_model.is_active and (
custom_model.id not in [model["id"] for model in models]
):
owned_by = "openai"
pipe = None
action_ids = []

View File

@ -1,10 +1,11 @@
import { WEBUI_API_BASE_URL } from '$lib/constants';
import { getUserPosition } from '$lib/utils';
export const getUserPermissions = async (token: string) => {
export const getUserGroups = async (token: string) => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/users/permissions`, {
const res = await fetch(`${WEBUI_API_BASE_URL}/users/groups`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
@ -28,10 +29,39 @@ export const getUserPermissions = async (token: string) => {
return res;
};
export const updateUserPermissions = async (token: string, permissions: object) => {
export const getUserDefaultPermissions = async (token: string) => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/users/permissions`, {
const res = await fetch(`${WEBUI_API_BASE_URL}/users/default/permissions`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
}
})
.then(async (res) => {
if (!res.ok) throw await res.json();
return res.json();
})
.catch((err) => {
console.log(err);
error = err.detail;
return null;
});
if (error) {
throw error;
}
return res;
};
export const updateUserDefaultPermissions = async (token: string, permissions: object) => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/users/default/permissions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',

View File

@ -1,7 +1,7 @@
<script lang="ts">
import { getBackendConfig, getModelFilterConfig, updateModelFilterConfig } from '$lib/apis';
import { getSignUpEnabledStatus, toggleSignUpEnabledStatus } from '$lib/apis/auths';
import { getUserPermissions, updateUserPermissions } from '$lib/apis/users';
import { getUserDefaultPermissions, updateUserDefaultPermissions } from '$lib/apis/users';
import { onMount, getContext } from 'svelte';
import { models, config } from '$lib/stores';
@ -29,7 +29,7 @@
let chatTemporary = true;
onMount(async () => {
permissions = await getUserPermissions(localStorage.token);
permissions = await getUserDefaultPermissions(localStorage.token);
chatDeletion = permissions?.chat?.deletion ?? true;
chatEdit = permissions?.chat?.editing ?? true;
@ -51,7 +51,7 @@
// console.log('submit');
await setDefaultModels(localStorage.token, defaultModelId);
await updateUserPermissions(localStorage.token, {
await updateUserDefaultPermissions(localStorage.token, {
chat: {
deletion: chatDeletion,
editing: chatEdit,

View File

@ -23,7 +23,7 @@
import GroupItem from './Groups/GroupItem.svelte';
import AddGroupModal from './Groups/AddGroupModal.svelte';
import { createNewGroup, getGroups } from '$lib/apis/groups';
import { getUserPermissions, updateUserPermissions } from '$lib/apis/users';
import { getUserDefaultPermissions, updateUserDefaultPermissions } from '$lib/apis/users';
const i18n = getContext('i18n');
@ -81,7 +81,7 @@
const updateDefaultPermissionsHandler = async (group) => {
console.log(group.permissions);
const res = await updateUserPermissions(localStorage.token, group.permissions).catch(
const res = await updateUserDefaultPermissions(localStorage.token, group.permissions).catch(
(error) => {
toast.error(error);
return null;
@ -99,7 +99,7 @@
await goto('/');
} else {
await setGroups();
defaultPermissions = await getUserPermissions(localStorage.token);
defaultPermissions = await getUserDefaultPermissions(localStorage.token);
}
loaded = true;
});

View File

@ -55,17 +55,15 @@
let selectedModelIdx = 0;
const fuse = new Fuse(
items
.filter((item) => !item.model?.info?.meta?.hidden)
.map((item) => {
const _item = {
...item,
modelName: item.model?.name,
tags: item.model?.info?.meta?.tags?.map((tag) => tag.name).join(' '),
desc: item.model?.info?.meta?.description
};
return _item;
}),
items.map((item) => {
const _item = {
...item,
modelName: item.model?.name,
tags: item.model?.info?.meta?.tags?.map((tag) => tag.name).join(' '),
desc: item.model?.info?.meta?.description
};
return _item;
}),
{
keys: ['value', 'tags', 'modelName'],
threshold: 0.3
@ -76,7 +74,7 @@
? fuse.search(searchValue).map((e) => {
return e.item;
})
: items.filter((item) => !item.model?.info?.meta?.hidden);
: items;
const pullModelHandler = async () => {
const sanitizedModelTag = searchValue.trim().replace(/^ollama\s+(run|pull)\s+/, '');
@ -583,14 +581,3 @@
</slot>
</DropdownMenu.Content>
</DropdownMenu.Root>
<style>
.scrollbar-hidden:active::-webkit-scrollbar-thumb,
.scrollbar-hidden:focus::-webkit-scrollbar-thumb,
.scrollbar-hidden:hover::-webkit-scrollbar-thumb {
visibility: visible;
}
.scrollbar-hidden::-webkit-scrollbar-thumb {
visibility: hidden;
}
</style>

View File

@ -255,7 +255,7 @@
>
<a
class=" flex flex-1 space-x-3.5 cursor-pointer w-full"
href={`/?models=open-webui.${encodeURIComponent(model.id)}`}
href={`/?models=${encodeURIComponent(model.id)}`}
>
<div class=" self-center w-8">
<div

View File

@ -1,6 +1,6 @@
<script lang="ts">
import { onMount, getContext, tick } from 'svelte';
import { models, tools, functions, knowledge as knowledgeCollections } from '$lib/stores';
import { models, tools, functions, knowledge as knowledgeCollections, user } from '$lib/stores';
import AdvancedParams from '$lib/components/chat/Settings/Advanced/AdvancedParams.svelte';
import Tags from '$lib/components/common/Tags.svelte';
@ -98,6 +98,8 @@
info.id = id;
info.name = name;
info.access_control = accessControl;
info.meta.capabilities = capabilities;
if (knowledge.length > 0) {
@ -669,7 +671,9 @@
</div>
<div class="my-2">
<AccessControl bind:accessControl />
<div class="px-3 py-2 bg-gray-50 dark:bg-gray-950 rounded-lg">
<AccessControl bind:accessControl />
</div>
</div>
<div class="my-2 text-gray-300 dark:text-gray-700">

View File

@ -1,31 +1,51 @@
<script lang="ts">
import Tooltip from '$lib/components/common/Tooltip.svelte';
import Plus from '$lib/components/icons/Plus.svelte';
import { getContext, onMount } from 'svelte';
const i18n = getContext('i18n');
import { getGroups } from '$lib/apis/groups';
import Tooltip from '$lib/components/common/Tooltip.svelte';
import Plus from '$lib/components/icons/Plus.svelte';
import UserCircleSolid from '$lib/components/icons/UserCircleSolid.svelte';
import XMark from '$lib/components/icons/XMark.svelte';
export let accessControl = null;
let access = 'private';
let query = '';
let privateAccess = false;
let selectedGroupId = '';
let groups = [];
$: if (privateAccess) {
accessControl = {
read: {
group_ids: []
}
};
} else {
accessControl = null;
}
onMount(async () => {
groups = await getGroups(localStorage.token);
onMount(() => {
if (accessControl === null) {
access = 'public';
privateAccess = false;
} else {
access = 'private';
privateAccess = true;
}
});
</script>
<div class=" rounded-lg flex flex-col gap-3">
<div class=" rounded-lg flex flex-col gap-2">
<div class="">
<div class=" text-sm font-semibold mb-1">{$i18n.t('Visibility')}</div>
<div class="flex gap-2.5 items-center">
<div class="flex gap-2.5 items-center mb-1">
<div>
<div class=" p-2 bg-gray-50 dark:bg-gray-850 rounded-full">
{#if access === 'private'}
<div class=" p-2 bg-black/5 dark:bg-white/5 rounded-full">
{#if privateAccess}
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
@ -63,16 +83,16 @@
<select
id="models"
class="outline-none bg-transparent text-sm font-medium rounded-lg block w-fit pr-10 max-w-full placeholder-gray-400"
bind:value={access}
bind:value={privateAccess}
>
<option class=" text-gray-700" value="private" selected>Private</option>
<option class=" text-gray-700" value="public" selected>Public</option>
<option class=" text-gray-700" value={true} selected>Private</option>
<option class=" text-gray-700" value={false} selected>Public</option>
</select>
<div class=" text-xs text-gray-400 font-medium">
{#if access === 'private'}
{#if privateAccess}
{$i18n.t('Only select users and groups with permission can access')}
{:else if access === 'public'}
{:else}
{$i18n.t('Accessible to all users')}
{/if}
</div>
@ -80,37 +100,90 @@
</div>
</div>
{#if access === 'private'}
{#if privateAccess}
{@const accessGroups = groups.filter((group) =>
accessControl.read.group_ids.includes(group.id)
)}
<div>
<div class=" text-sm font-semibold mb-0.5">{$i18n.t('People with access')}</div>
<div class="">
<div class="flex justify-between mb-1.5">
<div class="text-sm font-semibold">
{$i18n.t('Groups')}
</div>
</div>
<div>
<div class="flex w-full py-1">
<div class="flex flex-1">
<div class=" self-center mr-3">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
class="w-4 h-4"
>
<path
fill-rule="evenodd"
d="M9 3.5a5.5 5.5 0 100 11 5.5 5.5 0 000-11zM2 9a7 7 0 1112.452 4.391l3.328 3.329a.75.75 0 11-1.06 1.06l-3.329-3.328A7 7 0 012 9z"
clip-rule="evenodd"
/>
</svg>
<div class="flex flex-col gap-2">
{#if accessGroups.length > 0}
{#each accessGroups as group}
<div class="flex items-center gap-3 justify-between text-xs w-full transition">
<div class="flex items-center gap-1.5 w-full font-medium">
<div>
<UserCircleSolid className="size-4" />
</div>
<div>
{group.name}
</div>
</div>
<div class="w-full flex justify-end">
<button
class=" rounded-full p-1 hover:bg-gray-100 dark:hover:bg-gray-850 transition"
type="button"
on:click={() => {
accessControl.read.group_ids = accessControl.read.group_ids.filter(
(id) => id !== group.id
);
}}
>
<XMark />
</button>
</div>
</div>
{/each}
{:else}
<div class="flex items-center justify-center">
<div class="text-gray-500 text-xs text-center py-2 px-10">
{$i18n.t('No groups with access, add a group to grant access')}
</div>
</div>
{/if}
</div>
</div>
<hr class=" my-2 border-gray-50 dark:border-gray-900" />
<div class="mb-1">
<div class="flex w-full">
<div class="flex flex-1 items-center">
<div class="w-full">
<select
class="outline-none bg-transparent text-sm font-medium rounded-lg block w-full pr-10 max-w-full dark:placeholder-gray-700"
bind:value={selectedGroupId}
>
<option class=" text-gray-700" value="" disabled selected
>{$i18n.t('Select a group')}</option
>
{#each groups.filter((group) => !accessControl.read.group_ids.includes(group.id)) as group}
<option class=" text-gray-700" value={group.id}>{group.name}</option>
{/each}
</select>
</div>
<input
class=" w-full text-sm pr-4 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none bg-transparent"
bind:value={query}
placeholder={$i18n.t('Add user or groups')}
/>
<div>
<Tooltip content={$i18n.t('Add User/Group')}>
<Tooltip content={$i18n.t('Add Group')}>
<button
class=" p-2 rounded-xl hover:bg-gray-100 dark:bg-gray-900 dark:hover:bg-gray-850 transition font-medium text-sm flex items-center space-x-1"
on:click={() => {}}
class=" p-1 rounded-xl bg-transparent dark:hover:bg-white/5 hover:bg-black/5 transition font-medium text-sm flex items-center space-x-1"
type="button"
on:click={() => {
if (selectedGroupId !== '') {
accessControl.read.group_ids = [
...accessControl.read.group_ids,
selectedGroupId
];
selectedGroupId = '';
}
}}
>
<Plus className="size-3.5" />
</button>