Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bugfix/fix bulk/cancel invite #161

Merged
merged 3 commits into from
Oct 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions backend/ee/enmedd/db/teamspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,8 @@ def _add_user__teamspace_relationships__no_commit(
if creator_id is None:
return []

if user_ids and creator_id not in user_ids:
user_ids.append(creator_id)
# if creator_id not in user_ids:
# user_ids.append(creator_id)

relationships = [
User__Teamspace(
Expand Down
29 changes: 14 additions & 15 deletions backend/ee/enmedd/server/workspace/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
from enmedd.auth.users import current_admin_user
from enmedd.db.engine import get_session
from enmedd.db.models import User
from enmedd.db.workspace import get_workspace_for_user_by_id
from enmedd.db.workspace import get_workspace_settings
from enmedd.db.workspace import insert_workspace
from enmedd.db.workspace import upsert_workspace
Expand Down Expand Up @@ -106,20 +105,20 @@ def put_settings(
)


@basic_router.get("/{workspace_id}")
def fetch_settings_by_id(
workspace_id: int,
_: User = Depends(current_admin_user),
db_session: Session = Depends(get_session),
) -> Workspaces:
db_workspace = get_workspace_for_user_by_id(
workspace_id=workspace_id, db_session=db_session, user=_
)
if db_workspace is None:
raise HTTPException(
status_code=404, detail=f"Workspace with id '{workspace_id}' not found"
)
return Workspaces.from_model(db_workspace)
# @basic_router.get("/{workspace_id}")
# def fetch_settings_by_id(
# workspace_id: int,
# _: User = Depends(current_admin_user),
# db_session: Session = Depends(get_session),
# ) -> Workspaces:
# db_workspace = get_workspace_for_user_by_id(
# workspace_id=workspace_id, db_session=db_session, user=_
# )
# if db_workspace is None:
# raise HTTPException(
# status_code=404, detail=f"Workspace with id '{workspace_id}' not found"
# )
# return Workspaces.from_model(db_workspace)


@basic_router.get("")
Expand Down
43 changes: 43 additions & 0 deletions backend/ee/enmedd/server/workspace/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ def store_analytics_script(analytics_script_upload: AnalyticsScriptUpload) -> No


_LOGO_FILENAME = "__logo__"
_PROFILE_FILENAME = "__profile__"


def is_valid_file_type(filename: str) -> bool:
Expand Down Expand Up @@ -100,3 +101,45 @@ def upload_logo(
file_type=file_type,
)
return True


def upload_profile(
db_session: Session,
file: UploadFile | str,
) -> bool:
content: IO[Any]

if isinstance(file, str):
logger.info(f"Uploading logo from local path {file}")
if not os.path.isfile(file) or not is_valid_file_type(file):
logger.error(
"Invalid file type- only .png, .jpg, and .jpeg files are allowed"
)
return False

with open(file, "rb") as file_handle:
file_content = file_handle.read()
content = BytesIO(file_content)
display_name = file
file_type = guess_file_type(file)

else:
logger.info("Uploading logo from uploaded file")
if not file.filename or not is_valid_file_type(file.filename):
raise HTTPException(
status_code=400,
detail="Invalid file type- only .png, .jpg, and .jpeg files are allowed",
)
content = file.file
display_name = file.filename
file_type = file.content_type or "image/jpeg"

file_store = get_default_file_store(db_session)
file_store.save_file(
file_name=_PROFILE_FILENAME,
content=content,
display_name=display_name,
file_origin=FileOrigin.OTHER,
file_type=file_type,
)
return True
1 change: 1 addition & 0 deletions backend/enmedd/db/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1204,6 +1204,7 @@ class PGFileStore(Base):
file_type: Mapped[str] = mapped_column(String, default="text/plain")
file_metadata: Mapped[JSON_ro] = mapped_column(postgresql.JSONB(), nullable=True)
lobj_oid: Mapped[int] = mapped_column(Integer, nullable=False)
user_id: Mapped[UUID | None] = mapped_column(ForeignKey("user.id"), nullable=True)


# EE features
Expand Down
2 changes: 1 addition & 1 deletion backend/enmedd/dynamic_configs/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def store(self, key: str, val: JSON_ro, encrypt: bool = False) -> None:
) # type: ignore
session.query(KVStore).filter_by(key=key).delete() # just in case
session.add(obj)
session.commit()
session.commit()

def load(self, key: str) -> JSON_ro:
with self.get_session() as session:
Expand Down
28 changes: 27 additions & 1 deletion backend/enmedd/server/manage/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
from fastapi import Body
from fastapi import Depends
from fastapi import HTTPException
from fastapi import Response
from fastapi import status
from fastapi import UploadFile
from fastapi_users.password import PasswordHelper
from pydantic import BaseModel
from sqlalchemy import delete
Expand All @@ -19,6 +21,8 @@
from sqlalchemy.orm import Session

from ee.enmedd.db.api_key import is_api_key_email_address
from ee.enmedd.server.workspace.store import _PROFILE_FILENAME
from ee.enmedd.server.workspace.store import upload_profile
from enmedd.auth.invited_users import generate_invite_email
from enmedd.auth.invited_users import get_invited_users
from enmedd.auth.invited_users import send_invite_user_email
Expand Down Expand Up @@ -46,6 +50,7 @@
from enmedd.db.users import get_user_by_email
from enmedd.db.users import list_users
from enmedd.dynamic_configs.factory import get_dynamic_config_store
from enmedd.file_store.file_store import get_default_file_store
from enmedd.server.manage.models import AllUsersResponse
from enmedd.server.manage.models import OTPVerificationRequest
from enmedd.server.manage.models import UserByEmail
Expand Down Expand Up @@ -293,7 +298,6 @@ def remove_invited_user(
) -> int:
print(f"Removing user with the email: {user_email}")
user_emails = get_invited_users()
print(f"Invited users: {str(user_emails)}")
remaining_users = [user for user in user_emails if user != user_email.user_email]
return write_invited_users(remaining_users)

Expand Down Expand Up @@ -373,6 +377,28 @@ async def get_user_role(user: User = Depends(current_user)) -> UserRoleResponse:
return UserRoleResponse(role=user.role)


@router.put("/me/profile")
def put_profile(
file: UploadFile,
db_session: Session = Depends(get_session),
_: User | None = Depends(current_user),
) -> None:
upload_profile(file=file, db_session=db_session)


@router.get("/me/profile")
def fetch_profile(
db_session: Session = Depends(get_session),
_: User | None = Depends(current_user), # Ensure that the user is authenticated
) -> Response:
try:
file_store = get_default_file_store(db_session)
file_io = file_store.read_file(_PROFILE_FILENAME, mode="b")
return Response(content=file_io.read(), media_type="image/jpeg")
except Exception:
raise HTTPException(status_code=404, detail="No logo file found")


@router.get("/me")
def verify_user_logged_in(
user: User | None = Depends(optional_user),
Expand Down
40 changes: 27 additions & 13 deletions web/src/app/admin/users/PedingInvites.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ const RemoveUserButton = ({

export const PendingInvites = ({ q }: { q: string }) => {
const { toast } = useToast();
const [selectedUser, setSelectedUser] = useState<User | null>(null);
const [invitedPage, setInvitedPage] = useState(1);
const [acceptedPage, setAcceptedPage] = useState(1);
const [searchQuery, setSearchQuery] = useState("");
Expand Down Expand Up @@ -107,6 +108,7 @@ export const PendingInvites = ({ q }: { q: string }) => {
description: "The invited user has been removed from your list",
variant: "success",
});
mutate();
setIsCancelModalVisible(false);
};

Expand Down Expand Up @@ -163,36 +165,48 @@ export const PendingInvites = ({ q }: { q: string }) => {
</TableCell>
<TableCell>
<div className="flex gap-2 justify-end">
{/* <Button>Resend Invite</Button> */}
<CustomModal
trigger={
<Button
variant="destructive"
onClick={() => setIsCancelModalVisible(true)}
onClick={() => {
setIsCancelModalVisible(true);
setSelectedUser(user);
}}
>
Cancel Invite
</Button>
}
title="Revoke Invite"
onClose={() => setIsCancelModalVisible(false)}
onClose={() => {
setIsCancelModalVisible(false);
setSelectedUser(null);
}}
open={isCancelModalVisible}
>
<div>
<p>
Revoking on invite will no longer allow this
Revoking an invite will no longer allow this
person to become a member of your space. You
can always invite the again if you change your
mind.{" "}
can always invite them again if you change
your mind.
</p>

<div className="flex gap-2 pt-8 justify-end">
<Button>Keep Member</Button>
<RemoveUserButton
user={user}
onSuccess={onRemovalSuccess}
onError={onRemovalError}
key={user.id}
/>
<Button
onClick={() =>
setIsCancelModalVisible(false)
}
>
Keep Member
</Button>
{selectedUser && (
<RemoveUserButton
user={selectedUser}
onSuccess={onRemovalSuccess}
onError={onRemovalError}
/>
)}
</div>
</div>
</CustomModal>
Expand Down
24 changes: 23 additions & 1 deletion web/src/app/auth/2factorverification/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
} from "@/components/ui/input-otp";
import { ShieldEllipsis } from "lucide-react";
import Link from "next/link";
import { useState } from "react";
import { useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useToast } from "@/hooks/use-toast";
import { Spinner } from "@/components/Spinner";
Expand All @@ -23,6 +23,28 @@ const Page = () => {
const searchParams = useSearchParams();
const user_email = searchParams.get("email");

const handleBackButton = async () => {
const response = await fetch("/auth/logout", {
method: "POST",
credentials: "include",
});
router.push("/auth/login");
return response;
};

useEffect(() => {
const handleUnload = (e: BeforeUnloadEvent) => {
e.preventDefault();
handleBackButton();
};

window.addEventListener("beforeunload", handleUnload);

return () => {
window.removeEventListener("beforeunload", handleUnload);
};
}, []);

const handleContinue = async () => {
try {
const response = await fetch("/api/users/verify-otp", {
Expand Down
58 changes: 54 additions & 4 deletions web/src/app/profile/tabContent/profileTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@

import { Button } from "@/components/ui/button";
import { User as UserTypes } from "@/lib/types";
import { User } from "lucide-react";
import { Upload, User } from "lucide-react";
import { UserProfile } from "@/components/UserProfile";
import { CombinedSettings } from "@/components/settings/lib";
import { useState } from "react";
import { Input } from "@/components/ui/input";
import { useToast } from "@/hooks/use-toast";
import Image from "next/image";

export default function ProfileTab({
user,
Expand All @@ -22,6 +23,7 @@ export default function ProfileTab({
const [fullName, setFullName] = useState(user?.full_name || "");
const [companyName, setCompanyName] = useState(user?.company_name || "");
const [email, setEmail] = useState(user?.email || "");
const [selectedFile, setSelectedFile] = useState<File | null>(null);

const handleSaveChanges = async () => {
const updatedUser = {
Expand All @@ -48,9 +50,40 @@ export default function ProfileTab({
variant: "destructive",
});
}

if (selectedFile) {
const formData = new FormData();
formData.append("file", selectedFile);
setSelectedFile(null);
const response = await fetch("/api/me/profile", {
method: "PUT",
body: formData,
});
if (!response.ok) {
const errorMsg = (await response.json()).detail;
alert(`Failed to upload logo. ${errorMsg}`);
return;
}
}
setIsEditing(false);
};

const UploadProfilePhoto = () => {
setIsEditing(true);

const input = document.createElement("input");
input.type = "file";
input.accept = "image/*";
input.onchange = (e) => {
const target = e.target as HTMLInputElement;
if (target.files) {
const file = target.files[0];
setSelectedFile(file);
}
};
input.click();
};

return (
<>
<div className="flex py-8 border-b">
Expand All @@ -62,10 +95,27 @@ export default function ProfileTab({
This will be displayed on your profile.
</p>
</div>
<div className="flex items-center justify-between gap-3 md:w-[500px]">
<div
className="flex items-center justify-between gap-3 md:w-[100px] cursor-pointer"
onClick={UploadProfilePhoto}
>
<div className="flex items-center justify-center rounded-full h-[65px] w-[65px] shrink-0 aspect-square text-2xl font-normal">
{user && user.full_name ? (
<UserProfile size={65} user={user} textSize="text-2xl" />
{selectedFile ? (
<Image
src={URL.createObjectURL(selectedFile)}
alt="Profile"
className="rounded-full object-cover"
width={65}
height={65}
/>
) : user && user.full_name ? (
<Image
src={"/api/me/profile"}
alt="Profile"
className="rounded-full object-cover"
width={65}
height={65}
/>
) : (
<User size={25} className="mx-auto" />
)}
Expand Down
Loading