⚡️⚡️⚡️ 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
feat(web): password creation for oauth/sso users without having to reset it
daniel31x13fed669318fa9
diff --git a/apps/web/lib/api/controllers/users/userId/deleteUserById.ts b/apps/web/lib/api/controllers/users/userId/deleteUserById.tsindex c70ae98d..5bf9d493 100644--- a/apps/web/lib/api/controllers/users/userId/deleteUserById.ts+++ b/apps/web/lib/api/controllers/users/userId/deleteUserById.ts@@ -53,7 +53,7 @@ export default async function deleteUserById(} else {return {response:- "User has no password. Please reset your password from the forgot password page.",+ "User has no password. Please create one from the password settings page.",status: 401,};}diff --git a/apps/web/lib/api/controllers/users/userId/getUserById.ts b/apps/web/lib/api/controllers/users/userId/getUserById.tsindex 7e95c7b5..e5da22b8 100644--- a/apps/web/lib/api/controllers/users/userId/getUserById.ts+++ b/apps/web/lib/api/controllers/users/userId/getUserById.ts@@ -3,7 +3,7 @@ import { prisma } from "@linkwarden/prisma";import { GetUserByIdResponse } from "@linkwarden/types/global";export default async function getUserById(userId: number) {- const [user, firstUnIndexedLinks] = await Promise.all([+ const [user, firstUnIndexedLinks, oauthAccountCount] = await Promise.all([prisma.user.findUnique({where: {id: userId,@@ -29,6 +29,17 @@ export default async function getUserById(userId: number) {],},}),+ prisma.account.count({+ where: {+ userId,+ type: {+ in: ["oauth", "oidc"],+ },+ },+ select: {+ provider: true,+ },+ }),]);if (!user) return { response: "User not found.", status: 404 };@@ -48,6 +59,8 @@ export default async function getUserById(userId: number) {email: parentSubscription?.user.email,},},+ hasPassword: !!password,+ hasOAuthAccount: oauthAccountCount.provider > 0,hasUnIndexedLinks: !!firstUnIndexedLinks,};diff --git a/apps/web/lib/api/controllers/users/userId/updateUserById.ts b/apps/web/lib/api/controllers/users/userId/updateUserById.tsindex abc82ea1..3230f5f5 100644--- a/apps/web/lib/api/controllers/users/userId/updateUserById.ts+++ b/apps/web/lib/api/controllers/users/userId/updateUserById.ts@@ -99,8 +99,20 @@ export default async function updateUserById(const user = await prisma.user.findUnique({where: { id: userId },+ include: {+ accounts: {+ select: {+ type: true,+ },+ },+ },});+ const hasOAuthAccount =+ user?.accounts.some((account) =>+ ["oauth", "oidc"].includes(account.type)+ ) || false;+if (user && user.email && data.email && data.email !== user.email) {if (!data.password) {return {@@ -113,7 +125,7 @@ export default async function updateUserById(if (!user.password) {return {response:- "User has no password. Please reset your password from the forgot password page.",+ "User has no password. Please create one from the password settings page.",status: 400,};}@@ -137,28 +149,30 @@ export default async function updateUserById(// Password Settingsif (data.newPassword || data.oldPassword) {- if (!data.oldPassword || !data.newPassword)+ const isCreatingPassword = !user?.password && hasOAuthAccount;++ if (!data.newPassword || (!isCreatingPassword && !data.oldPassword))return {response: "Please fill out all the fields.",status: 400,};- else if (!user?.password)+ else if (!user?.password && !isCreatingPassword)return {response:- "User has no password. Please reset your password from the forgot password page.",+ "User has no password. Please create one from the password settings page.",status: 400,};- else if (!bcrypt.compareSync(data.oldPassword, user.password))+ else if (+ !isCreatingPassword &&+ user?.password &&+ data.oldPassword &&+ !bcrypt.compareSync(data.oldPassword, user.password)+ )return {response: "Old password is incorrect.",status: 400,};- else if (data.newPassword?.length < 8)- return {- response: "Password must be at least 8 characters.",- status: 400,- };- else if (data.newPassword === data.oldPassword)+ else if (!isCreatingPassword && data.newPassword === data.oldPassword)return {response: "New password must be different from the old password.",status: 400,@@ -248,6 +262,8 @@ export default async function updateUserById(email: parentSubscription?.user.email,},},+ hasPassword: !!password,+ hasOAuthAccount,dashboardSections: dashboardSections,};diff --git a/apps/web/pages/settings/password.tsx b/apps/web/pages/settings/password.tsxindex 3adddb17..669c6ab1 100644--- a/apps/web/pages/settings/password.tsx+++ b/apps/web/pages/settings/password.tsx@@ -17,11 +17,12 @@ const Page: NextPageWithLayout = () => {const [submitLoader, setSubmitLoader] = useState(false);const { data: account } = useUser();const updateUser = useUpdateUser();+ const canCreatePassword = !!account?.hasOAuthAccount && !account?.hasPassword;const submit = async () => {if (!account?.id) return;- if (newPassword === "" || oldPassword === "") {+ if (newPassword === "" || (!canCreatePassword && oldPassword === "")) {return toast.error(t("fill_all_fields"));}if (newPassword.length < 8) return toast.error(t("password_length_error"));@@ -36,7 +37,7 @@ const Page: NextPageWithLayout = () => {username: account.username,email: account.email,newPassword,- oldPassword,+ oldPassword: canCreatePassword ? undefined : oldPassword,},{onSettled: (data, error) => {@@ -61,25 +62,33 @@ const Page: NextPageWithLayout = () => {<div className="flex items-center gap-2"><i className="bi-lock text-primary text-2xl"></i><p className="capitalize text-3xl font-thin inline">- {t("change_password")}+ {canCreatePassword ? t("create_password") : t("change_password")}</p></div><Separator className="my-3" />- <p className="mb-3">{t("password_change_instructions")}</p>+ <p className="mb-3">+ {canCreatePassword+ ? t("password_create_instructions")+ : t("password_change_instructions")}+ </p><div className="w-full flex flex-col gap-2 justify-between max-w-screen-sm">- <p>{t("old_password")}</p>-- <TextInput- value={oldPassword}- className="bg-base-200"- onChange={(e) => setOldPassword(e.target.value)}- placeholder="••••••••••••••"- type="password"- />-- <p className="mt-3">{t("new_password")}</p>+ {!canCreatePassword && (+ <>+ <p>{t("old_password")}</p>++ <TextInput+ value={oldPassword}+ className="bg-base-200"+ onChange={(e) => setOldPassword(e.target.value)}+ placeholder="••••••••••••••"+ type="password"+ />+ </>+ )}++ <p className={canCreatePassword ? "" : "mt-3"}>{t("new_password")}</p><TextInputvalue={newPassword}@@ -91,7 +100,9 @@ const Page: NextPageWithLayout = () => {<ButtononClick={submit}- disabled={submitLoader || !oldPassword || !newPassword}+ disabled={+ submitLoader || !newPassword || (!canCreatePassword && !oldPassword)+ }variant="accent"className="mt-3 w-full sm:w-fit">diff --git a/apps/web/public/locales/en/common.json b/apps/web/public/locales/en/common.jsonindex 0d1f6adb..2e292da1 100644--- a/apps/web/public/locales/en/common.json+++ b/apps/web/public/locales/en/common.json@@ -148,9 +148,11 @@"feedback_placeholder": "e.g. I needed a feature that...","delete_your_account": "Delete Your Account","change_password": "Change Password",+ "create_password": "Create Password","password_length_error": "Passwords must be at least 8 characters.","applying_changes": "Applying...","password_change_instructions": "To change your password, please fill out the following. Your password should be at least 8 characters.",+ "password_create_instructions": "Create a password for your account. You can use it to sign in and to confirm sensitive actions like deleting your account.","old_password": "Old Password","new_password": "New Password","preference": "Preference",diff --git a/packages/router/user.tsx b/packages/router/user.tsxindex 38eeef1c..a4b91be4 100644--- a/packages/router/user.tsx+++ b/packages/router/user.tsx@@ -76,8 +76,13 @@ const useUpdateUser = () => {},onMutate: async (user) => {await queryClient.cancelQueries({ queryKey: ["user"] });+ const safeUser = { ...user };+ delete safeUser.password;+ delete safeUser.oldPassword;+ delete safeUser.newPassword;+queryClient.setQueryData(["user"], (oldData: any) => {- return { ...oldData, ...user };+ return { ...oldData, ...safeUser };});},});diff --git a/packages/types/global.ts b/packages/types/global.tsindex a09db28d..32715bfc 100644--- a/packages/types/global.ts+++ b/packages/types/global.ts@@ -234,5 +234,7 @@ export type GetUserByIdResponse = Omit<User, "password"> &};} & {dashboardSections: DashboardSection[];+ hasPassword: boolean;+ hasOAuthAccount: boolean;hasUnIndexedLinks: boolean;};