⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.
TypeScript bookmarkbookmark-managercollaborationnextjsreact-nativeread-it-laterself-hostedtypescript
many improvements
Daniel7912815c9efe
diff --git a/components/Modal/User/ChangePassword.tsx b/components/Modal/User/ChangePassword.tsxindex 5ccfe080..c299a432 100644--- a/components/Modal/User/ChangePassword.tsx+++ b/components/Modal/User/ChangePassword.tsx@@ -23,7 +23,7 @@ export default function ChangePassword({const [submitLoader, setSubmitLoader] = useState(false);const { account, updateAccount } = useAccountStore();- const { update } = useSession();+ const { update, data } = useSession();useEffect(() => {if (@@ -57,9 +57,7 @@ export default function ChangePassword({user.name !== account.name) {update({- username: user.username,- email: user.email,- name: user.name,+ id: data?.user.id,});signOut();diff --git a/components/Modal/User/PrivacySettings.tsx b/components/Modal/User/PrivacySettings.tsxindex 79dbb5a7..6047448b 100644--- a/components/Modal/User/PrivacySettings.tsx+++ b/components/Modal/User/PrivacySettings.tsx@@ -18,7 +18,7 @@ export default function PrivacySettings({setUser,user,}: Props) {- const { update } = useSession();+ const { update, data } = useSession();const { account, updateAccount } = useAccountStore();const [submitLoader, setSubmitLoader] = useState(false);@@ -66,9 +66,7 @@ export default function PrivacySettings({user.name !== account.name) {update({- username: user.username,- email: user.email,- name: user.name,+ id: data?.user.id,});signOut();diff --git a/components/Modal/User/ProfileSettings.tsx b/components/Modal/User/ProfileSettings.tsxindex cee20bdf..76b5fe40 100644--- a/components/Modal/User/ProfileSettings.tsx+++ b/components/Modal/User/ProfileSettings.tsx@@ -23,7 +23,7 @@ export default function ProfileSettings({setUser,user,}: Props) {- const { update } = useSession();+ const { update, data } = useSession();const { account, updateAccount } = useAccountStore();const [profileStatus, setProfileStatus] = useState(true);@@ -84,9 +84,7 @@ export default function ProfileSettings({user.name !== account.name) {update({- username: user.username,- email: user.email,- name: user.name,+ id: data?.user.id,});signOut();@@ -158,7 +156,7 @@ export default function ProfileSettings({<p className="text-sm text-sky-500 mb-2">Username</p><inputtype="text"- value={user.username}+ value={user.username || ""}onChange={(e) => setUser({ ...user, username: e.target.value })}className="w-full rounded-md p-2 border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"/>diff --git a/layouts/AuthRedirect.tsx b/layouts/AuthRedirect.tsxindex 35c2cebd..a5fd1ade 100644--- a/layouts/AuthRedirect.tsx+++ b/layouts/AuthRedirect.tsx@@ -14,11 +14,26 @@ export default function AuthRedirect({ children }: Props) {const { status, data } = useSession();const [redirect, setRedirect] = useState(true);+ const emailEnabled = process.env.NEXT_PUBLIC_EMAIL_PROVIDER;+useInitialData();useEffect(() => {if (!router.pathname.startsWith("/public")) {- if (status === "authenticated" && data.user.isSubscriber === false) {+ if (+ emailEnabled &&+ status === "authenticated" &&+ (data.user.isSubscriber === true ||+ data.user.isSubscriber === undefined) &&+ !data.user.username+ ) {+ router.push("/choose-username").then(() => {+ setRedirect(false);+ });+ } else if (+ status === "authenticated" &&+ data.user.isSubscriber === false+ ) {router.push("/subscribe").then(() => {setRedirect(false);});@@ -28,6 +43,7 @@ export default function AuthRedirect({ children }: Props) {router.pathname === "/register" ||router.pathname === "/confirmation" ||router.pathname === "/subscribe" ||+ router.pathname === "/choose-username" ||router.pathname === "/forgot")) {router.push("/").then(() => {diff --git a/lib/api/paymentCheckout.ts b/lib/api/paymentCheckout.tsindex 9c2893cc..34f8e860 100644--- a/lib/api/paymentCheckout.ts+++ b/lib/api/paymentCheckout.ts@@ -10,12 +10,6 @@ export default async function paymentCheckout(apiVersion: "2022-11-15",});- // const a = await stripe.prices.retrieve("price_1NTn3PDaRUw6CJPLkw4dcwlJ");-- // const listBySub = await stripe.subscriptions.list({- // customer: "cus_OGUzJrRea8Qbxx",- // });-const listByEmail = await stripe.customers.list({email: email.toLowerCase(),expand: ["data.subscriptions"],@@ -23,31 +17,6 @@ export default async function paymentCheckout(const isExistingCostomer = listByEmail?.data[0]?.id || undefined;- // const hasPreviouslySubscribed = listByEmail.data.find((customer, i) => {- // const hasValidSubscription = customer.subscriptions?.data.some(- // (subscription) => {- // return subscription?.items?.data?.some(- // (subscriptionItem) => subscriptionItem?.plan?.id === priceId- // );- // }- // );-- // return (- // customer.email?.toLowerCase() === email.toLowerCase() &&- // hasValidSubscription- // );- // });-- // const previousSubscriptionId =- // hasPreviouslySubscribed?.subscriptions?.data[0].id;-- // if (previousSubscriptionId) {- // console.log(previousSubscriptionId);- // const subscription = await stripe.subscriptions.resume(- // previousSubscriptionId- // );- // }-const TRIAL_PERIOD_DAYS = process.env.TRIAL_PERIOD_DAYS;const session = await stripe.checkout.sessions.create({customer: isExistingCostomer ? isExistingCostomer : undefined,diff --git a/pages/api/auth/[...nextauth].ts b/pages/api/auth/[...nextauth].tsindex 6de9f510..e760f2e5 100644--- a/pages/api/auth/[...nextauth].ts+++ b/pages/api/auth/[...nextauth].ts@@ -126,11 +126,20 @@ export const authOptions: AuthOptions = {if (trigger === "signIn") {token.id = user.id;token.username = (user as any).username;- } else if (trigger === "update" && session?.name && session?.username) {- // Note, that `session` can be any arbitrary object, remember to validate it!- token.name = session.name;- token.username = session.username.toLowerCase();- token.email = session.email.toLowerCase();+ } else if (trigger === "update" && token.id) {+ console.log(token);++ const user = await prisma.user.findUnique({+ where: {+ id: token.id as number,+ },+ });++ if (user) {+ token.name = user.name;+ token.username = user.username?.toLowerCase();+ token.email = user.email?.toLowerCase();+ }}return token;},diff --git a/pages/api/auth/register.ts b/pages/api/auth/register.tsindex 44406ee6..4abf03e9 100644--- a/pages/api/auth/register.ts+++ b/pages/api/auth/register.ts@@ -11,7 +11,7 @@ interface Data {interface User {name: string;- username: string;+ username?: string;email?: string;password: string;}@@ -23,7 +23,7 @@ export default async function Index(const body: User = req.body;const checkHasEmptyFields = emailEnabled- ? !body.username || !body.password || !body.name || !body.email+ ? !body.password || !body.name || !body.email: !body.username || !body.password || !body.name;if (checkHasEmptyFields)@@ -31,30 +31,9 @@ export default async function Index(.status(400).json({ response: "Please fill out all the fields." });- const tenMinutesAgo = new Date(Date.now() - 10 * 60 * 1000);-- // Remove user's who aren't verified for more than 10 minutes- if (emailEnabled)- await prisma.user.deleteMany({- where: {- OR: [- {- email: body.email,- },- {- username: body.username,- },- ],- createdAt: {- lt: tenMinutesAgo,- },- emailVerified: null,- },- });-const checkUsername = RegExp("^[a-z0-9_-]{3,31}$");- if (!checkUsername.test(body.username))+ if (!emailEnabled && !checkUsername.test(body.username || ""))return res.status(400).json({response:"Username has to be between 3-30 characters, no spaces and special characters are allowed.",@@ -63,18 +42,11 @@ export default async function Index(const checkIfUserExists = await prisma.user.findFirst({where: emailEnabled? {- OR: [- {- username: body.username.toLowerCase(),- },- {- email: body.email?.toLowerCase(),- },- ],+ email: body.email?.toLowerCase(),emailVerified: { not: null },}: {- username: body.username.toLowerCase(),+ username: (body.username as string).toLowerCase(),},});@@ -86,8 +58,10 @@ export default async function Index(await prisma.user.create({data: {name: body.name,- username: body.username.toLowerCase(),- email: body.email?.toLowerCase(),+ username: emailEnabled+ ? undefined+ : (body.username as string).toLowerCase(),+ email: emailEnabled ? body.email?.toLowerCase() : undefined,password: hashedPassword,},});diff --git a/pages/api/routes/users/index.ts b/pages/api/routes/users/index.tsindex 2a1ecc19..74461507 100644--- a/pages/api/routes/users/index.ts+++ b/pages/api/routes/users/index.ts@@ -32,7 +32,7 @@ export default async function users(req: NextApiRequest, res: NextApiResponse) {username: session.user.username,});return res.status(users.status).json({ response: users.response });- } else if (req.method === "PUT" && !req.body.password) {+ } else if (req.method === "PUT") {const updated = await updateUser(req.body, session.user);return res.status(updated.status).json({ response: updated.response });}diff --git a/pages/choose-username.tsx b/pages/choose-username.tsxnew file mode 100644index 00000000..7c426cb0--- /dev/null+++ b/pages/choose-username.tsx@@ -0,0 +1,108 @@+import SubmitButton from "@/components/SubmitButton";+import { signOut } from "next-auth/react";+import Image from "next/image";+import { useEffect, useState } from "react";+import { toast } from "react-hot-toast";+import { useSession } from "next-auth/react";+import { useRouter } from "next/router";+import useAccountStore from "@/store/account";++export default function Subscribe() {+ const [submitLoader, setSubmitLoader] = useState(false);+ const [inputedUsername, setInputedUsername] = useState("");++ const { data, status, update } = useSession();++ const { updateAccount, account } = useAccountStore();++ useEffect(() => {+ console.log(data?.user);+ }, [status]);++ async function submitUsername() {+ setSubmitLoader(true);++ const redirectionToast = toast.loading("Applying...");++ const response = await updateAccount({+ ...account,+ username: inputedUsername,+ });++ if (response.ok) {+ toast.success("Username Applied!");++ update({+ id: data?.user.id,+ });++ signOut();+ } else toast.error(response.data as string);+ toast.dismiss(redirectionToast);+ setSubmitLoader(false);+ }++ return (+ <>+ <div className="p-2 mt-10 mx-auto flex flex-col gap-3 justify-between sm:w-[28rem] w-80 bg-slate-50 rounded-md border border-sky-100">+ <div className="flex flex-col gap-2 justify-between items-center mb-5">+ <Image+ src="/linkwarden.png"+ width={1694}+ height={483}+ alt="Linkwarden"+ className="h-12 w-fit mx-auto"+ />++ <div className="text-center">+ <p className="text-3xl text-sky-500">One Last Step...</p>+ <p className="font-semibold text-sky-400">+ Please choose a username to start using your account.+ </p>+ </div>+ </div>++ <div>+ <p className="text-sm text-sky-500 w-fit font-semibold mb-1">+ Username+ </p>++ <input+ type="text"+ placeholder="john"+ value={inputedUsername}+ onChange={(e) => setInputedUsername(e.target.value)}+ className="w-full rounded-md p-2 mx-auto border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"+ />+ </div>++ <p className="text-gray-500 text-center">+ Note that you will have to log back in to complete the process.+ </p>+ <div>+ <p className="text-md text-gray-500 mt-1">+ Feel free to reach out to us at{" "}+ <a className="font-semibold" href="mailto:[email protected]">+ </a>{" "}+ in case of any issues.+ </p>+ </div>++ <SubmitButton+ onClick={submitUsername}+ label="Choose Username"+ className="mt-2 w-full text-center"+ loading={submitLoader}+ />++ <div+ onClick={() => signOut()}+ className="w-fit mx-auto cursor-pointer text-gray-500 font-semibold "+ >+ Sign Out+ </div>+ </div>+ </>+ );+}diff --git a/pages/register.tsx b/pages/register.tsxindex 2edada5c..4ae3fe2b 100644--- a/pages/register.tsx+++ b/pages/register.tsx@@ -9,7 +9,7 @@ const emailEnabled = process.env.NEXT_PUBLIC_EMAIL_PROVIDER;type FormData = {name: string;- username: string;+ username?: string;email?: string;password: string;passwordConfirmation: string;@@ -20,7 +20,7 @@ export default function Register() {const [form, setForm] = useState<FormData>({name: "",- username: "",+ username: emailEnabled ? undefined : "",email: emailEnabled ? "" : undefined,password: "",passwordConfirmation: "",@@ -31,7 +31,6 @@ export default function Register() {if (emailEnabled) {return (form.name !== "" &&- form.username !== "" &&form.email !== "" &&form.password !== "" &&form.passwordConfirmation !== ""@@ -122,19 +121,21 @@ export default function Register() {/></div>- <div>- <p className="text-sm text-sky-500 w-fit font-semibold mb-1">- Username- </p>+ {emailEnabled ? undefined : (+ <div>+ <p className="text-sm text-sky-500 w-fit font-semibold mb-1">+ Username+ </p>- <input- type="text"- placeholder="john"- value={form.username}- onChange={(e) => setForm({ ...form, username: e.target.value })}- className="w-full rounded-md p-2 mx-auto border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"- />- </div>+ <input+ type="text"+ placeholder="john"+ value={form.username}+ onChange={(e) => setForm({ ...form, username: e.target.value })}+ className="w-full rounded-md p-2 mx-auto border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"+ />+ </div>+ )}{emailEnabled ? (<div>diff --git a/pages/subscribe.tsx b/pages/subscribe.tsxindex 4d4697b1..c1b427ee 100644--- a/pages/subscribe.tsx+++ b/pages/subscribe.tsx@@ -12,10 +12,6 @@ export default function Subscribe() {const { data, status } = useSession();const router = useRouter();- useEffect(() => {- console.log(data?.user);- }, [status]);-async function loginUser() {setSubmitLoader(true);@@ -52,7 +48,7 @@ export default function Subscribe() {You will be redirected to Stripe.</p><p className="text-md text-gray-500 mt-1">- feel free to reach out to us at{" "}+ Feel free to reach out to us at{" "}<a className="font-semibold" href="mailto:[email protected]"></a>{" "}diff --git a/prisma/migrations/20230715102805_init/migration.sql b/prisma/migrations/20230719181459_init/migration.sqlsimilarity index 99%rename from prisma/migrations/20230715102805_init/migration.sqlrename to prisma/migrations/20230719181459_init/migration.sqlindex 408f99fe..1b7dfcf5 100644--- a/prisma/migrations/20230715102805_init/migration.sql+++ b/prisma/migrations/20230719181459_init/migration.sql@@ -30,7 +30,7 @@ CREATE TABLE "Session" (CREATE TABLE "User" ("id" SERIAL NOT NULL,"name" TEXT NOT NULL,- "username" TEXT NOT NULL,+ "username" TEXT,"email" TEXT,"emailVerified" TIMESTAMP(3),"image" TEXT,diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex a3882aaf..43d8b90e 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -38,7 +38,7 @@ model User {id Int @id @default(autoincrement())name String- username String @unique+ username String? @uniqueemail String? @uniqueemailVerified DateTime?diff --git a/store/account.ts b/store/account.tsindex ae088063..638848c2 100644--- a/store/account.ts+++ b/store/account.ts@@ -3,7 +3,7 @@ import { AccountSettings } from "@/types/global";type ResponseObject = {ok: boolean;- data: object | string;+ data: Omit<AccountSettings, "password"> | object | string;};type AccountStore = {