added collaboration mode for collections

This commit is contained in:
Daniel 2023-04-27 00:10:48 +03:30
parent e715756cbe
commit cc8e8dbe9a
16 changed files with 279 additions and 37 deletions

View File

@ -5,9 +5,10 @@
import React, { useState } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faPlus } from "@fortawesome/free-solid-svg-icons";
import { faClose, faPlus } from "@fortawesome/free-solid-svg-icons";
import useCollectionStore from "@/store/collections";
import { NewCollection } from "@/types/global";
import { useSession } from "next-auth/react";
type Props = {
toggleCollectionModal: Function;
@ -17,10 +18,15 @@ export default function AddCollection({ toggleCollectionModal }: Props) {
const [newCollection, setNewCollection] = useState<NewCollection>({
name: "",
description: "",
members: [],
});
const [memberEmail, setMemberEmail] = useState("");
const { addCollection } = useCollectionStore();
const session = useSession();
const submitCollection = async () => {
console.log(newCollection);
@ -29,6 +35,14 @@ export default function AddCollection({ toggleCollectionModal }: Props) {
if (response) toggleCollectionModal();
};
const getUserByEmail = async (email: string) => {
const response = await fetch(`/api/routes/users?email=${email}`);
const data = await response.json();
return data.response;
};
return (
<div className="flex flex-col gap-3 sm:w-[35rem] w-80">
<p className="font-bold text-sky-300 mb-2 text-center">New Collection</p>
@ -59,6 +73,176 @@ export default function AddCollection({ toggleCollectionModal }: Props) {
/>
</div>
<hr className="border rounded my-2" />
<div className="flex gap-5 items-center justify-between">
<p className="text-sm font-bold text-sky-300">Members</p>
<input
value={memberEmail}
onChange={(e) => {
setMemberEmail(e.target.value);
}}
onKeyDown={async (e) => {
const checkIfMemberAlreadyExists = newCollection.members.find(
(e) => e.email === memberEmail
);
const ownerEmail = session.data?.user.email;
if (
e.key === "Enter" &&
// no duplicate members
!checkIfMemberAlreadyExists &&
// member can't be empty
memberEmail.trim() !== "" &&
// member can't be the owner
memberEmail.trim() !== ownerEmail
) {
// Lookup, get data/err, list ...
const user = await getUserByEmail(memberEmail.trim());
if (user.email) {
const newMember = {
name: user.name,
email: user.email,
canCreate: false,
canUpdate: false,
canDelete: false,
};
setNewCollection({
...newCollection,
members: [...newCollection.members, newMember],
});
setMemberEmail("");
}
}
}}
type="text"
placeholder="Email (Optional)"
className="w-56 sm:w-96 rounded-md p-3 border-sky-100 border-solid border text-sm outline-none focus:border-sky-500 duration-100"
/>
</div>
{newCollection.members[0] ? (
<p className="text-center text-sky-500 text-xs sm:text-sm">
(All Members will have <b>Read</b> access to this collection.)
</p>
) : null}
{newCollection.members.map((e, i) => {
return (
<div
key={i}
className="border p-2 rounded-md border-sky-100 flex items-center justify-between"
>
<div>
<p className="text-sm font-bold text-sky-500">{e.name}</p>
<p className="text-sky-900">{e.email}</p>
</div>
<div className="relative">
<FontAwesomeIcon
icon={faClose}
className="absolute right-0 top-0 text-gray-500 h-4 hover:text-red-500 duration-100 cursor-pointer"
title="Remove Member"
onClick={() => {
const updatedMembers = newCollection.members.filter(
(member) => {
return member.email !== e.email;
}
);
setNewCollection({
...newCollection,
members: updatedMembers,
});
}}
/>
<p className="font-bold text-sm text-gray-500">Permissions</p>
<p className="text-xs text-gray-400 mb-2">(Click to toggle.)</p>
<label className="cursor-pointer mr-1">
<input
type="checkbox"
id="canCreate"
className="peer sr-only"
checked={e.canCreate}
onChange={() => {
const updatedMembers = newCollection.members.map(
(member) => {
if (member.email === e.email) {
return { ...member, canCreate: !e.canCreate };
}
return member;
}
);
setNewCollection({
...newCollection,
members: updatedMembers,
});
}}
/>
<span className="text-sky-900 peer-checked:bg-sky-500 text-sm hover:bg-sky-200 duration-75 peer-checked:text-white rounded p-1 select-none">
Create
</span>
</label>
<label className="cursor-pointer mr-1">
<input
type="checkbox"
id="canUpdate"
className="peer sr-only"
checked={e.canUpdate}
onChange={() => {
const updatedMembers = newCollection.members.map(
(member) => {
if (member.email === e.email) {
return { ...member, canUpdate: !e.canUpdate };
}
return member;
}
);
setNewCollection({
...newCollection,
members: updatedMembers,
});
}}
/>
<span className="text-sky-900 peer-checked:bg-sky-500 text-sm hover:bg-sky-200 duration-75 peer-checked:text-white rounded p-1 select-none">
Update
</span>
</label>
<label className="cursor-pointer mr-1">
<input
type="checkbox"
id="canDelete"
className="peer sr-only"
checked={e.canDelete}
onChange={() => {
const updatedMembers = newCollection.members.map(
(member) => {
if (member.email === e.email) {
return { ...member, canDelete: !e.canDelete };
}
return member;
}
);
setNewCollection({
...newCollection,
members: updatedMembers,
});
}}
/>
<span className="text-sky-900 peer-checked:bg-sky-500 text-sm hover:bg-sky-200 duration-75 peer-checked:text-white rounded p-1 select-none">
Delete
</span>
</label>
</div>
</div>
);
})}
<div
className="mx-auto mt-2 bg-sky-500 text-white flex items-center gap-2 py-2 px-5 rounded-md select-none font-bold cursor-pointer duration-100 hover:bg-sky-400"
onClick={submitCollection}

View File

View File

@ -8,7 +8,13 @@ import { prisma } from "@/lib/api/db";
export default async function (userId: number) {
const collections = await prisma.collection.findMany({
where: {
ownerId: userId,
OR: [
{ ownerId: userId },
{ members: { some: { user: { id: userId } } } },
],
},
include: {
members: true,
},
});

View File

@ -4,10 +4,10 @@
// You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
import { prisma } from "@/lib/api/db";
import { Collection } from "@prisma/client";
import { NewCollection } from "@/types/global";
import { existsSync, mkdirSync } from "fs";
export default async function (collection: Collection, userId: number) {
export default async function (collection: NewCollection, userId: number) {
if (!collection || collection.name.trim() === "")
return {
response: "Please enter a valid collection.",
@ -41,6 +41,14 @@ export default async function (collection: Collection, userId: number) {
},
name: collection.name,
description: collection.description,
members: {
create: collection.members.map((e) => ({
user: { connect: { email: e.email } },
canCreate: e.canCreate,
canUpdate: e.canUpdate,
canDelete: e.canDelete,
})),
},
},
});

View File

@ -7,15 +7,12 @@ import { prisma } from "@/lib/api/db";
import { ExtendedLink } from "@/types/global";
import fs from "fs";
import { Link, UsersAndCollections } from "@prisma/client";
import hasAccessToCollection from "@/lib/api/hasAccessToCollection";
import getPermission from "@/lib/api/getPermission";
export default async function (link: ExtendedLink, userId: number) {
if (!link) return { response: "Please choose a valid link.", status: 401 };
const collectionIsAccessible = await hasAccessToCollection(
userId,
link.collectionId
);
const collectionIsAccessible = await getPermission(userId, link.collectionId);
const memberHasAccess = collectionIsAccessible?.members.some(
(e: UsersAndCollections) => e.userId === userId && e.canDelete

View File

@ -9,7 +9,7 @@ import getTitle from "../../getTitle";
import archive from "../../archive";
import { Link, UsersAndCollections } from "@prisma/client";
import AES from "crypto-js/aes";
import hasAccessToCollection from "@/lib/api/hasAccessToCollection";
import getPermission from "@/lib/api/getPermission";
export default async function (link: ExtendedLink, userId: number) {
link.collection.name = link.collection.name.trim();
@ -21,7 +21,7 @@ export default async function (link: ExtendedLink, userId: number) {
}
if (link.collection.ownerId) {
const collectionIsAccessible = await hasAccessToCollection(
const collectionIsAccessible = await getPermission(
userId,
link.collection.id
);

View File

@ -6,15 +6,12 @@
import { prisma } from "@/lib/api/db";
import { ExtendedLink } from "@/types/global";
import { Link, UsersAndCollections } from "@prisma/client";
import hasAccessToCollection from "@/lib/api/hasAccessToCollection";
import getPermission from "@/lib/api/getPermission";
export default async function (link: ExtendedLink, userId: number) {
if (!link) return { response: "Please choose a valid link.", status: 401 };
const collectionIsAccessible = await hasAccessToCollection(
userId,
link.collectionId
);
const collectionIsAccessible = await getPermission(userId, link.collectionId);
const memberHasAccess = collectionIsAccessible?.members.some(
(e: UsersAndCollections) => e.userId === userId && e.canUpdate

View File

@ -0,0 +1,22 @@
// Copyright (C) 2022-present Daniel31x13 <daniel31x13@gmail.com>
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
import { prisma } from "@/lib/api/db";
export default async function (email: string) {
const user = await prisma.user.findUnique({
where: {
email,
},
});
const unsensitiveUserInfo = {
name: user?.name,
email: user?.email,
createdAt: user?.createdAt,
};
return { response: unsensitiveUserInfo || null, status: 200 };
}

View File

@ -10,7 +10,7 @@ import AES from "crypto-js/aes";
import enc from "crypto-js/enc-utf8";
import path from "path";
import fs from "fs";
import hasAccessToCollection from "@/lib/api/hasAccessToCollection";
import getPermission from "@/lib/api/getPermission";
export default async function (req: NextApiRequest, res: NextApiResponse) {
if (!req.query.params)
@ -23,7 +23,7 @@ export default async function (req: NextApiRequest, res: NextApiResponse) {
if (!session?.user?.email)
return res.status(401).json({ response: "You must be logged in." });
const collectionIsAccessible = await hasAccessToCollection(
const collectionIsAccessible = await getPermission(
session.user.id,
Number(collectionId)
);

View File

@ -8,14 +8,7 @@ import { getServerSession } from "next-auth/next";
import { authOptions } from "pages/api/auth/[...nextauth]";
import getTags from "@/lib/api/controllers/tags/getTags";
type Data = {
response: object[] | string;
};
export default async function (
req: NextApiRequest,
res: NextApiResponse<Data>
) {
export default async function (req: NextApiRequest, res: NextApiResponse) {
const session = await getServerSession(req, res, authOptions);
if (!session?.user?.email) {

View File

@ -0,0 +1,23 @@
// Copyright (C) 2022-present Daniel31x13 <daniel31x13@gmail.com>
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next";
import { authOptions } from "pages/api/auth/[...nextauth]";
import getUsers from "@/lib/api/controllers/users/getUsers";
export default async function (req: NextApiRequest, res: NextApiResponse) {
const session = await getServerSession(req, res, authOptions);
if (!session?.user?.email) {
return res.status(401).json({ response: "You must be logged in." });
}
// get unsensitive user info by email
if (req.method === "GET") {
const users = await getUsers(req.query.email as string);
return res.status(users.status).json({ response: users.response });
}
}

View File

@ -24,7 +24,6 @@ export default function () {
async function registerUser() {
let success: boolean = false;
console.log(form);
if (form.name != "" && form.email != "" && form.password != "") {
await fetch("/api/auth/register", {

View File

@ -5,13 +5,13 @@
import { create } from "zustand";
import { Collection } from "@prisma/client";
import { NewCollection } from "@/types/global";
import { ExtendedCollection, NewCollection } from "@/types/global";
type CollectionStore = {
collections: Collection[];
collections: ExtendedCollection[];
setCollections: () => void;
addCollection: (body: NewCollection) => Promise<boolean>;
updateCollection: (collection: Collection) => void;
// updateCollection: (collection: Collection) => void;
removeCollection: (collectionId: number) => void;
};
@ -44,12 +44,12 @@ const useCollectionStore = create<CollectionStore>()((set) => ({
return response.ok;
},
updateCollection: (collection) =>
set((state) => ({
collections: state.collections.map((c) =>
c.id === collection.id ? collection : c
),
})),
// updateCollection: (collection) =>
// set((state) => ({
// collections: state.collections.map((c) =>
// c.id === collection.id ? collection : c
// ),
// })),
removeCollection: (collectionId) => {
set((state) => ({
collections: state.collections.filter((c) => c.id !== collectionId),

View File

@ -79,6 +79,8 @@ const useLinkStore = create<LinkStore>()((set) => ({
const data = await response.json();
console.log(data);
if (response.ok) {
set((state) => ({
links: state.links.filter((e) => e.id !== link.id),

View File

@ -3,7 +3,7 @@
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
import { Collection, Link, Tag } from "@prisma/client";
import { Collection, Link, Tag, UsersAndCollections } from "@prisma/client";
export interface ExtendedLink extends Link {
tags: Tag[];
@ -24,4 +24,15 @@ export interface NewLink {
export interface NewCollection {
name: string;
description: string;
members: {
name: string;
email: string;
canCreate: boolean;
canUpdate: boolean;
canDelete: boolean;
}[];
}
export interface ExtendedCollection extends Collection {
members: UsersAndCollections[];
}