⚡️⚡️⚡️ 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(mobile): add signup support
daniel31x13742aa572e303
diff --git a/apps/mobile/app/(tabs)/dashboard/index.tsx b/apps/mobile/app/(tabs)/dashboard/index.tsxindex c659f6e8..b43191fd 100644--- a/apps/mobile/app/(tabs)/dashboard/index.tsx+++ b/apps/mobile/app/(tabs)/dashboard/index.tsx@@ -127,7 +127,7 @@ export default function DashboardScreen() {contentInsetAdjustmentBehavior="automatic">{orderedSections.map((sectionData, i) => {- if (!collections || !collections[0]) return null;+ if (!collections) return null;const collection = collections.find((c) => c.id === sectionData.collectionIddiff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsxindex 36df19bc..611d800e 100644--- a/apps/mobile/app/_layout.tsx+++ b/apps/mobile/app/_layout.tsx@@ -145,6 +145,7 @@ const RootComponent = ({ isLoading }: { isLoading: boolean }) => {}}/><Stack.Screen name="login" />+ <Stack.Screen name="register" /><Stack.Screen name="index" /><Stack.Screen name="incoming" /><Stack.Screen name="+not-found" />diff --git a/apps/mobile/app/login.tsx b/apps/mobile/app/login.tsxindex e042d67b..3a3a5c26 100644--- a/apps/mobile/app/login.tsx+++ b/apps/mobile/app/login.tsx@@ -2,7 +2,7 @@ import { Button } from "@/components/ui/Button";import Input from "@/components/ui/Input";import { rawTheme, ThemeName } from "@/lib/colors";import useAuthStore from "@/store/auth";-import { Redirect } from "expo-router";+import { Redirect, router } from "expo-router";import { useColorScheme } from "nativewind";import { useEffect, useState } from "react";import { View, Text, Dimensions, TouchableOpacity, Image } from "react-native";@@ -65,7 +65,7 @@ export default function HomeScreen() {className="w-[120px] h-[120px] mx-auto"/></View>- <Text className="text-base-100 text-7xl font-bold ml-8">Login</Text>+ <Text className="text-base-100 text-5xl font-bold ml-8">Login</Text><View><TextclassName="text-base-100 text-2xl mx-8 mt-3"@@ -182,6 +182,14 @@ export default function HomeScreen() {><Text className="text-white text-xl">Login</Text></Button>+ <TouchableOpacity+ className="w-fit mx-auto"+ onPress={() => router.replace("/register")}+ >+ <Text className="text-neutral text-center w-fit">+ Don't have an account? Sign up+ </Text>+ </TouchableOpacity><TouchableOpacityclassName="w-fit mx-auto"onPress={() => SheetManager.show("support-sheet")}diff --git a/apps/mobile/app/register.tsx b/apps/mobile/app/register.tsxnew file mode 100644index 00000000..cd24a176--- /dev/null+++ b/apps/mobile/app/register.tsx@@ -0,0 +1,407 @@+import { Button } from "@/components/ui/Button";+import Input from "@/components/ui/Input";+import { rawTheme, ThemeName } from "@/lib/colors";+import useAuthStore from "@/store/auth";+import {+ isAtLeastInstanceVersion,+ type Config,+} from "@linkwarden/router/config";+import { Redirect, router } from "expo-router";+import { useColorScheme } from "nativewind";+import { useEffect, useState } from "react";+import {+ ActivityIndicator,+ Alert,+ Dimensions,+ Image,+ Text,+ TouchableOpacity,+ View,+} from "react-native";+import Svg, { Path } from "react-native-svg";+import {+ KeyboardStickyView,+ KeyboardToolbar,+} from "react-native-keyboard-controller";+import { SafeAreaView } from "react-native-safe-area-context";++const cloudInstance = "https://cloud.linkwarden.app";++const cloudConfig: Config = {+ DISABLE_REGISTRATION: null,+ ADMIN: null,+ RSS_POLLING_INTERVAL_MINUTES: null,+ EMAIL_PROVIDER: true,+ MAX_FILE_BUFFER: null,+ USER_CONTENT_DOMAIN: null,+ AI_ENABLED: null,+ INSTANCE_VERSION: null,+};++const cleanInstance = (instance: string) => instance.trim().replace(/\/+$/, "");++const timeout = () =>+ new Promise<Response>((_, reject) =>+ setTimeout(() => reject(new Error("TIMEOUT")), 30000)+ );++export default function RegisterScreen() {+ const { auth, signUp, requestVerificationEmail } = useAuthStore();+ const { colorScheme } = useColorScheme();+ const [isLoading, setIsLoading] = useState(false);+ const [isConfigLoading, setIsConfigLoading] = useState(false);+ const [config, setConfig] = useState<Config | null>(null);+ const [configInstance, setConfigInstance] = useState("");+ const [configError, setConfigError] = useState("");+ const [sentTo, setSentTo] = useState<{+ email: string;+ instance: string;+ } | null>(null);+ const [form, setForm] = useState({+ name: "",+ username: "",+ email: "",+ password: "",+ passwordConfirmation: "",+ instance: auth.instance || cloudInstance,+ });+ const [showInstanceField, setShowInstanceField] = useState(+ form.instance !== cloudInstance+ );++ const instance = cleanInstance(form.instance);+ const currentConfig =+ instance === cloudInstance+ ? cloudConfig+ : configInstance === instance+ ? config+ : null;+ const emailSignUp = currentConfig?.EMAIL_PROVIDER === true;+ const supportsMobileSignup =+ instance === cloudInstance ||+ isAtLeastInstanceVersion(currentConfig?.INSTANCE_VERSION, "v2.14.3");+ const instanceName =+ instance === cloudInstance ? "cloud.linkwarden.app" : instance;++ useEffect(() => {+ setForm((prev) => ({+ ...prev,+ instance: auth.instance || cloudInstance,+ }));+ }, [auth.instance]);++ useEffect(() => {+ setShowInstanceField(form.instance !== cloudInstance);+ }, [form.instance]);++ useEffect(() => {+ let active = true;++ if (!instance) {+ setConfig(null);+ setConfigInstance("");+ setConfigError("");+ setIsConfigLoading(false);+ return;+ }++ if (instance === cloudInstance) {+ setConfig(null);+ setConfigInstance("");+ setConfigError("");+ setIsConfigLoading(false);+ return;+ }++ setConfig(null);+ setConfigError("");+ setIsConfigLoading(true);++ const timer = setTimeout(async () => {+ try {+ const res = await Promise.race([+ fetch(`${instance}/api/v1/config`),+ timeout(),+ ]);+ const data = await res.json().catch(() => null);++ if (!active) return;++ if (res.ok) {+ const nextConfig = data.response as Config;++ if (+ nextConfig.EMAIL_PROVIDER === true &&+ !isAtLeastInstanceVersion(nextConfig.INSTANCE_VERSION, "v2.15.0")+ ) {+ const reset = () =>+ setForm((prev) => ({ ...prev, instance: cloudInstance }));++ Alert.alert(+ "Sign up through the web",+ "This instance needs to be updated to support mobile sign-up. You can sign up through the web, then come back here to log in.",+ [{ text: "OK", onPress: reset }],+ { onDismiss: reset }+ );+ }++ setConfig(nextConfig);+ setConfigInstance(instance);+ } else {+ setConfigError("Could not load this instance.");+ }+ } catch {+ if (active) setConfigError("Could not reach this instance.");+ } finally {+ if (active) setIsConfigLoading(false);+ }+ }, 400);++ return () => {+ active = false;+ clearTimeout(timer);+ };+ }, [instance]);++ if (auth.status === "authenticated") {+ return <Redirect href="/dashboard" />;+ }++ const register = async () => {+ const email = form.email.toLowerCase().trim();+ const username = form.username.toLowerCase().trim();+ const name = form.name.trim();++ if (!currentConfig)+ return Alert.alert("Error", configError || "Please check the instance.");+ else if (currentConfig.DISABLE_REGISTRATION)+ return Alert.alert("Error", "Registration is disabled on this instance.");+ else if (emailSignUp && !supportsMobileSignup)+ return Alert.alert(+ "Sign up through the web",+ "This instance needs to be updated to support mobile sign-up. You can sign up through the web, then come back here to log in."+ );+ else if (+ !name ||+ !form.password ||+ !form.passwordConfirmation ||+ (emailSignUp ? !email : !username)+ )+ return Alert.alert("Error", "Please fill all fields");+ else if (form.password !== form.passwordConfirmation)+ return Alert.alert("Error", "Passwords don't match");+ else if (form.password.length < 8)+ return Alert.alert("Error", "Password must be at least 8 characters");++ setIsLoading(true);+ const created = await signUp({+ name,+ email: emailSignUp ? email : undefined,+ username: emailSignUp ? undefined : username,+ password: form.password,+ instance,+ });+ setIsLoading(false);++ if (!created) return;++ if (emailSignUp) setSentTo({ email, instance });+ else {+ Alert.alert("Account created", "You can log in now.");+ router.replace("/login");+ }+ };++ return (+ <>+ <KeyboardStickyView className="flex-col justify-end h-full bg-base-100 relative">+ <View className="flex-col justify-end h-full bg-primary relative">+ <View className="my-auto">+ <Image+ source={require("@/assets/images/linkwarden.png")}+ className="w-[120px] h-[120px] mx-auto"+ />+ </View>+ <Text className="text-base-100 text-5xl font-bold ml-8">+ {sentTo ? "Check Email" : "Sign Up"}+ </Text>+ <View>+ <Text+ className="text-base-100 text-2xl mx-8 mt-3"+ numberOfLines={1}+ >+ {sentTo ? sentTo.email : `Sign up to ${instanceName}`}+ </Text>+ {!sentTo && (+ <TouchableOpacity+ onPress={() => {+ if (showInstanceField) {+ setForm({ ...form, instance: cloudInstance });+ }+ setShowInstanceField(!showInstanceField);+ }}+ className="mx-8 mt-1 self-start"+ >+ <Text className="text-neutral-content text-sm">+ {!showInstanceField ? "Change server" : "Use official server"}+ </Text>+ </TouchableOpacity>+ )}+ </View>+ <Svg+ viewBox="0 0 1440 320"+ width={Dimensions.get("screen").width}+ height={Dimensions.get("screen").width * (320 / 1440) + 2}+ >+ <Path+ fill={rawTheme[colorScheme as ThemeName]["base-100"]}+ fillOpacity={1}+ d="M0,256L48,234.7C96,213,192,171,288,176C384,181,480,235,576,266.7C672,299,768,309,864,277.3C960,245,1056,171,1152,122.7C1248,75,1344,53,1392,42.7L1440,32L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z"+ />+ </Svg>+ <SafeAreaView+ edges={["bottom"]}+ className="flex-col justify-end h-auto duration-100 pt-8 bg-base-100 -mt-2 pb-10 gap-3 w-full px-4"+ >+ {sentTo ? (+ <>+ <Text className="text-base-content text-center text-base px-2">+ We sent you a verification link. After verifying your email,+ come back and log in.+ </Text>+ <Button+ variant="accent"+ size="lg"+ isLoading={isLoading}+ onPress={async () => {+ setIsLoading(true);+ await requestVerificationEmail(+ sentTo.email,+ sentTo.instance+ );+ setIsLoading(false);+ }}+ >+ <Text className="text-white text-xl">Resend Email</Text>+ </Button>+ <TouchableOpacity+ className="w-fit mx-auto"+ onPress={() => router.replace("/login")}+ >+ <Text className="text-neutral text-center w-fit">+ Back to login+ </Text>+ </TouchableOpacity>+ </>+ ) : (+ <>+ {showInstanceField && (+ <Input+ className="w-full text-xl p-3 leading-tight h-12"+ textAlignVertical="center"+ placeholder="Instance URL"+ selectTextOnFocus={false}+ value={form.instance}+ autoCapitalize="none"+ onChangeText={(text) =>+ setForm({ ...form, instance: text })+ }+ />+ )}+ {!!configError && (+ <Text className="text-red-500 text-center">+ {configError}+ </Text>+ )}+ {isConfigLoading && instance !== cloudInstance && (+ <View className="flex-row justify-center items-center gap-2">+ <ActivityIndicator />+ <Text className="text-neutral">Checking server...</Text>+ </View>+ )}+ {currentConfig?.DISABLE_REGISTRATION && (+ <Text className="text-neutral text-center">+ Registration is disabled on this instance.+ </Text>+ )}+ {currentConfig?.EMAIL_PROVIDER === true &&+ !supportsMobileSignup && (+ <Text className="text-neutral text-center">+ This instance needs to be updated to support mobile+ sign-up. You can sign up through the web, then come back+ here to log in.+ </Text>+ )}+ <Input+ className="w-full text-xl p-3 leading-tight h-12"+ textAlignVertical="center"+ placeholder="Display Name"+ value={form.name}+ onChangeText={(text) => setForm({ ...form, name: text })}+ />+ {emailSignUp ? (+ <Input+ className="w-full text-xl p-3 leading-tight h-12"+ textAlignVertical="center"+ placeholder="Email"+ value={form.email}+ autoCapitalize="none"+ keyboardType="email-address"+ onChangeText={(text) => setForm({ ...form, email: text })}+ />+ ) : (+ <Input+ className="w-full text-xl p-3 leading-tight h-12"+ textAlignVertical="center"+ placeholder="Username"+ value={form.username}+ autoCapitalize="none"+ onChangeText={(text) =>+ setForm({ ...form, username: text })+ }+ />+ )}+ <Input+ className="w-full text-xl p-3 leading-tight h-12"+ textAlignVertical="center"+ placeholder="Password"+ secureTextEntry+ value={form.password}+ onChangeText={(text) => setForm({ ...form, password: text })}+ />+ <Input+ className="w-full text-xl p-3 leading-tight h-12"+ textAlignVertical="center"+ placeholder="Confirm Password"+ secureTextEntry+ value={form.passwordConfirmation}+ onChangeText={(text) =>+ setForm({ ...form, passwordConfirmation: text })+ }+ />+ <Button+ variant="accent"+ size="lg"+ disabled={isConfigLoading}+ isLoading={isLoading}+ onPress={register}+ >+ <Text className="text-white text-xl">Sign Up</Text>+ </Button>+ <TouchableOpacity+ className="w-fit mx-auto"+ onPress={() => router.replace("/login")}+ >+ <Text className="text-neutral text-center w-fit">+ Already registered?+ </Text>+ </TouchableOpacity>+ </>+ )}+ </SafeAreaView>+ </View>+ </KeyboardStickyView>+ <KeyboardToolbar />+ </>+ );+}diff --git a/apps/mobile/store/auth.ts b/apps/mobile/store/auth.tsindex 2e31ef71..e143b617 100644--- a/apps/mobile/store/auth.ts+++ b/apps/mobile/store/auth.ts@@ -9,6 +9,16 @@ import { clearCache } from "@/lib/cache";import useDataStore from "@/store/data";import { useOfflineSyncStore } from "@/lib/offlineSync";+const cloudInstance = "https://cloud.linkwarden.app";++type SignUpForm = {+ name: string;+ username?: string;+ email?: string;+ password: string;+ instance: string;+};+type AuthStore = {auth: MobileAuth;signIn: (@@ -17,10 +27,47 @@ type AuthStore = {instance: string,token?: string) => Promise<void>;+ signUp: (form: SignUpForm) => Promise<boolean>;+ requestVerificationEmail: (+ email: string,+ instance: string+ ) => Promise<boolean>;signOut: () => Promise<void>;setAuth: () => Promise<void>;};+const timeout = () =>+ new Promise<Response>((_, reject) =>+ setTimeout(() => reject(new Error("TIMEOUT")), 30000)+ );++const requestVerificationEmail = async (email: string, instance: string) => {+ try {+ const res = await Promise.race([+ fetch(`${instance}/api/v1/auth/request-verification-email`, {+ method: "POST",+ body: JSON.stringify({ email }),+ headers: { "Content-Type": "application/json" },+ }),+ timeout(),+ ]);+ const data = await res.json().catch(() => null);++ if (res.ok) return true;++ Alert.alert("Error", data?.response || "Could not send verification email");+ return false;+ } catch (err: any) {+ Alert.alert(+ err?.message === "TIMEOUT" ? "Request timed out" : "Network error",+ err?.message === "TIMEOUT"+ ? "Unable to reach the server in time. Please check your network configuration and try again."+ : "Could not connect to the server. Please check your network configuration and try again."+ );+ return false;+ }+};+const useAuthStore = create<AuthStore>((set) => ({auth: {instance: "",@@ -42,13 +89,48 @@ const useAuthStore = create<AuthStore>((set) => ({} else {set({auth: {- instance: instance || "https://cloud.linkwarden.app",+ instance: instance || cloudInstance,session: null,status: "unauthenticated",},});}},+ requestVerificationEmail,+ signUp: async ({ name, username, email, password, instance }) => {+ try {+ const res = await Promise.race([+ fetch(`${instance}/api/v1/users`, {+ method: "POST",+ body: JSON.stringify({+ name,+ username,+ email,+ password,+ acceptPromotionalEmails: false,+ }),+ headers: { "Content-Type": "application/json" },+ }),+ timeout(),+ ]);+ const data = await res.json().catch(() => null);++ if (res.ok) {+ return email ? await requestVerificationEmail(email, instance) : true;+ }++ Alert.alert("Error", data?.response || "Could not create account");+ return false;+ } catch (err: any) {+ Alert.alert(+ err?.message === "TIMEOUT" ? "Request timed out" : "Network error",+ err?.message === "TIMEOUT"+ ? "Unable to reach the server in time. Please check your network configuration and try again."+ : "Could not connect to the server. Please check your network configuration and try again."+ );+ return false;+ }+ },signIn: async (username, password, instance, token) => {if (process.env.EXPO_PUBLIC_SHOW_LOGS === "true")console.log("Signing into", instance);diff --git a/apps/web/lib/api/verifyByCredentials.ts b/apps/web/lib/api/verifyByCredentials.tsindex 5c05f538..d73ddd58 100644--- a/apps/web/lib/api/verifyByCredentials.ts+++ b/apps/web/lib/api/verifyByCredentials.ts@@ -41,6 +41,10 @@ export default async function verifyByCredentials({return null;}+ if (emailEnabled && !user.emailVerified) {+ return null;+ }+let passwordMatches: boolean = false;if (user?.password) {diff --git a/apps/web/pages/api/v1/auth/request-verification-email.ts b/apps/web/pages/api/v1/auth/request-verification-email.tsnew file mode 100644index 00000000..49e8c95c--- /dev/null+++ b/apps/web/pages/api/v1/auth/request-verification-email.ts@@ -0,0 +1,74 @@+import sendVerificationRequest from "@/lib/api/sendVerificationRequest";+import { prisma } from "@linkwarden/prisma";+import { createHash, randomBytes } from "crypto";+import type { NextApiRequest, NextApiResponse } from "next";++const emailEnabled =+ process.env.EMAIL_FROM && process.env.EMAIL_SERVER ? true : false;++export default async function requestVerificationEmail(+ req: NextApiRequest,+ res: NextApiResponse+) {+ if (req.method !== "POST")+ return res.status(405).json({ response: "Method not allowed." });++ if (+ !emailEnabled ||+ !process.env.NEXTAUTH_URL ||+ !process.env.NEXTAUTH_SECRET+ )+ return res.status(400).json({ response: "Email is not configured." });++ const email =+ typeof req.body.email === "string"+ ? req.body.email.toLowerCase().trim()+ : "";++ const user = await prisma.user.findUnique({ where: { email } });++ if (!user) return res.status(400).json({ response: "Invalid email." });++ if (user.emailVerified)+ return res.status(400).json({ response: "Email is already verified." });++ const recentVerificationRequestsCount = await prisma.verificationToken.count({+ where: {+ identifier: email,+ createdAt: {+ gt: new Date(new Date().getTime() - 1000 * 60 * 5),+ },+ },+ });++ if (recentVerificationRequestsCount >= 4)+ return res+ .status(429)+ .json({ response: "Too many requests. Please try again later." });++ const token = randomBytes(32).toString("hex");+ const expires = new Date(Date.now() + 1200 * 1000);+ const url = `${+ process.env.NEXTAUTH_URL+ }/callback/email?token=${token}&email=${encodeURIComponent(email)}`;++ await Promise.all([+ sendVerificationRequest({+ identifier: email,+ url,+ from: process.env.EMAIL_FROM as string,+ token,+ }),+ prisma.verificationToken.create({+ data: {+ identifier: email,+ token: createHash("sha256")+ .update(`${token}${process.env.NEXTAUTH_SECRET}`)+ .digest("hex"),+ expires,+ },+ }),+ ]);++ return res.status(200).json({ response: "Verification email sent." });+}diff --git a/packages/lib/schemaValidation.ts b/packages/lib/schemaValidation.tsindex b3be06b0..c0cb7b8a 100644--- a/packages/lib/schemaValidation.ts+++ b/packages/lib/schemaValidation.ts@@ -71,8 +71,8 @@ export const UpdateUserSchema = () => {.trim().toLowerCase().min(3)- .max(30)- .regex(/^[a-z0-9_-]{3,30}$/),+ .max(50)+ .regex(/^[a-z0-9_-]{3,50}$/),image: z.string().nullish(),password: z.string().min(8).max(2048).optional(),newPassword: z.string().min(8).max(2048).optional(),