Skip to content

⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.

feat(mobile): add google oauth

daniel31x131268bfa5372b
diff --git a/apps/mobile/.env.sample b/apps/mobile/.env.sample
index 03878a54..d8627759 100644
--- a/apps/mobile/.env.sample
+++ b/apps/mobile/.env.sample
@@ -1,2 +1,6 @@
-LINKWARDEN_URL=
-EXPO_PUBLIC_SHOW_LOGS=
\ No newline at end of file
+EXPO_PUBLIC_GOOGLE_WEB_CLIENT_ID=
+EXPO_PUBLIC_GOOGLE_IOS_URL_SCHEME=
+EXPO_PUBLIC_GOOGLE_IOS_CLIENT_ID=
+SENTRY_AUTH_TOKEN=
+EXPO_PUBLIC_SHOW_LOGS=
+# Expo: https://docs.expo.dev/more/expo-cli/#environment-variables
\ No newline at end of file
diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts
new file mode 100644
index 00000000..4d02ac59
--- /dev/null
+++ b/apps/mobile/app.config.ts
@@ -0,0 +1,131 @@
+import { ExpoConfig } from "expo/config";
+
+const config: ExpoConfig = {
+ name: "Linkwarden",
+ slug: "linkwarden",
+ version: "1.3.0",
+ orientation: "portrait",
+ icon: "./assets/images/icon.png",
+ scheme: "linkwarden",
+ userInterfaceStyle: "automatic",
+ ios: {
+ supportsTablet: true,
+ bundleIdentifier: "app.linkwarden",
+ entitlements: {
+ "com.apple.security.application-groups": ["group.app.linkwarden"],
+ },
+ infoPlist: {
+ ITSAppUsesNonExemptEncryption: false,
+ NSAppTransportSecurity: {
+ NSAllowsArbitraryLoads: true,
+ },
+ },
+ },
+ android: {
+ adaptiveIcon: {
+ foregroundImage: "./assets/images/maskable_logo.png",
+ backgroundColor: "#ffffff",
+ },
+ package: "app.linkwarden",
+ },
+ web: {
+ bundler: "metro",
+ output: "static",
+ favicon: "./assets/images/favicon.png",
+ },
+ plugins: [
+ "expo-router",
+ [
+ "expo-splash-screen",
+ {
+ image: "./assets/images/splash-icon.png",
+ imageWidth: 200,
+ resizeMode: "contain",
+ backgroundColor: "#FFFFFF",
+ dark: {
+ image: "./assets/images/splash-icon.png",
+ resizeMode: "contain",
+ backgroundColor: "#171717",
+ },
+ },
+ ],
+ [
+ "@react-native-google-signin/google-signin",
+ {
+ iosUrlScheme:
+ process.env.EXPO_PUBLIC_GOOGLE_IOS_URL_SCHEME ??
+ "com.googleusercontent.apps.1097450926817-o94t2bb30jt2me2u17ni2cc2qogd2v34",
+ },
+ ],
+ "expo-secure-store",
+ [
+ "expo-share-intent",
+ {
+ iosAppGroupIdentifier: "group.app.linkwarden",
+ iosActivationRules:
+ 'SUBQUERY (extensionItems, $extensionItem, SUBQUERY ($extensionItem.attachments, $attachment, (ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "public.url" OR ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "public.text" OR ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "public.plain-text")).@count > 0).@count > 0',
+ androidIntentFilters: ["text/*"],
+ },
+ ],
+ [
+ "expo-build-properties",
+ {
+ android: {
+ enableProguardInReleaseBuilds: true,
+ extraProguardRules: "-keep public class com.horcrux.svg.** {*;}",
+ allowBackup: false,
+ compileSdkVersion: 36,
+ targetSdkVersion: 36,
+ buildToolsVersion: "36.0.0",
+ usesCleartextTraffic: true,
+ },
+ },
+ ],
+ [
+ "react-native-edge-to-edge",
+ {
+ android: {
+ parentTheme: "Default",
+ enforceNavigationBarContrast: false,
+ },
+ },
+ ],
+ "./plugins/with-daynight-transparent-nav",
+ "expo-font",
+ "expo-web-browser",
+ "expo-apple-authentication",
+ [
+ "@sentry/react-native/expo",
+ {
+ url: "https://sentry.io/",
+ project: "react-native",
+ organization: "linkwarden",
+ },
+ ],
+ [
+ "expo-navigation-bar",
+ {
+ barStyle: "dark-content",
+ },
+ ],
+ ],
+ experiments: {
+ typedRoutes: true,
+ },
+ androidStatusBar: {
+ backgroundColor: "#ffffff",
+ barStyle: "dark-content",
+ translucent: false,
+ },
+ extra: {
+ router: {
+ origin: false,
+ },
+ eas: {
+ projectId: "34f82639-7a25-4ebe-81c8-2db521b612cf",
+ },
+ },
+ owner: "linkwarden",
+};
+
+export default config;
diff --git a/apps/mobile/app.json b/apps/mobile/app.json
deleted file mode 100644
index 90d7b132..00000000
--- a/apps/mobile/app.json
+++ /dev/null
@@ -1,120 +0,0 @@
-{
- "expo": {
- "name": "Linkwarden",
- "slug": "linkwarden",
- "version": "1.3.0",
- "orientation": "portrait",
- "icon": "./assets/images/icon.png",
- "scheme": "linkwarden",
- "userInterfaceStyle": "automatic",
- "ios": {
- "supportsTablet": true,
- "bundleIdentifier": "app.linkwarden",
- "entitlements": {
- "com.apple.security.application-groups": ["group.app.linkwarden"]
- },
- "infoPlist": {
- "ITSAppUsesNonExemptEncryption": false,
- "NSAppTransportSecurity": {
- "NSAllowsArbitraryLoads": true
- }
- }
- },
- "android": {
- "adaptiveIcon": {
- "foregroundImage": "./assets/images/maskable_logo.png",
- "backgroundColor": "#ffffff"
- },
- "package": "app.linkwarden"
- },
- "web": {
- "bundler": "metro",
- "output": "static",
- "favicon": "./assets/images/favicon.png"
- },
- "plugins": [
- "expo-router",
- [
- "expo-splash-screen",
- {
- "image": "./assets/images/splash-icon.png",
- "imageWidth": 200,
- "resizeMode": "contain",
- "backgroundColor": "#FFFFFF",
- "dark": {
- "image": "./assets/images/splash-icon.png",
- "resizeMode": "contain",
- "backgroundColor": "#171717"
- }
- }
- ],
- "expo-secure-store",
- [
- "expo-share-intent",
- {
- "iosAppGroupIdentifier": "group.app.linkwarden",
- "iosActivationRules": "SUBQUERY (extensionItems, $extensionItem, SUBQUERY ($extensionItem.attachments, $attachment, (ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO \"public.url\" OR ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO \"public.text\" OR ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO \"public.plain-text\")).@count > 0).@count > 0",
- "androidIntentFilters": ["text/*"]
- }
- ],
- [
- "expo-build-properties",
- {
- "android": {
- "enableProguardInReleaseBuilds": true,
- "extraProguardRules": "-keep public class com.horcrux.svg.** {*;}",
- "allowBackup": false,
- "compileSdkVersion": 36,
- "targetSdkVersion": 36,
- "buildToolsVersion": "36.0.0",
- "usesCleartextTraffic": true
- }
- }
- ],
- [
- "react-native-edge-to-edge",
- {
- "android": {
- "parentTheme": "Default",
- "enforceNavigationBarContrast": false
- }
- }
- ],
- "./plugins/with-daynight-transparent-nav",
- "expo-font",
- "expo-web-browser",
- "expo-apple-authentication",
- [
- "@sentry/react-native/expo",
- {
- "url": "https://sentry.io/",
- "project": "react-native",
- "organization": "linkwarden"
- }
- ],
- [
- "expo-navigation-bar",
- {
- "barStyle": "dark-content"
- }
- ]
- ],
- "experiments": {
- "typedRoutes": true
- },
- "androidStatusBar": {
- "backgroundColor": "#ffffff",
- "barStyle": "dark-content",
- "translucent": false
- },
- "extra": {
- "router": {
- "origin": false
- },
- "eas": {
- "projectId": "34f82639-7a25-4ebe-81c8-2db521b612cf"
- }
- },
- "owner": "linkwarden"
- }
-}
diff --git a/apps/mobile/app/login.tsx b/apps/mobile/app/login.tsx
index 3d31cd76..5e08a4c9 100644
--- a/apps/mobile/app/login.tsx
+++ b/apps/mobile/app/login.tsx
@@ -7,6 +7,7 @@ import {
type Config,
} from "@linkwarden/router/config";
import * as AppleAuthentication from "expo-apple-authentication";
+import { GoogleSigninButton } from "@react-native-google-signin/google-signin";
import { Redirect, router } from "expo-router";
import { useColorScheme } from "nativewind";
import { useEffect, useState } from "react";
@@ -28,14 +29,17 @@ import { SafeAreaView } from "react-native-safe-area-context";
const cloudInstance = "https://cloud.linkwarden.app";
export default function HomeScreen() {
- const { auth, signIn, signInWithApple } = useAuthStore();
+ const { auth, signIn, signInWithApple, signInWithGoogle } = useAuthStore();
const { colorScheme } = useColorScheme();
const [method, setMethod] = useState<"password" | "token">("password");
const [isLoading, setIsLoading] = useState(false);
const [appleEnabled, setAppleEnabled] = useState(
Platform.OS === "ios" && (auth.instance || cloudInstance) === cloudInstance
);
- const [isCheckingApple, setIsCheckingApple] = useState(false);
+ const [googleEnabled, setGoogleEnabled] = useState(
+ (auth.instance || cloudInstance) === cloudInstance
+ );
+ const [isCheckingOAuth, setIsCheckingOAuth] = useState(false);
const [form, setForm] = useState({
user: "",
@@ -71,13 +75,15 @@ export default function HomeScreen() {
}, [method]);
useEffect(() => {
- if (Platform.OS !== "ios" || !instance) {
+ if (!instance) {
setAppleEnabled(false);
+ setGoogleEnabled(false);
return;
}
- setAppleEnabled(instance === cloudInstance);
- setIsCheckingApple(true);
+ setAppleEnabled(Platform.OS === "ios" && instance === cloudInstance);
+ setGoogleEnabled(instance === cloudInstance);
+ setIsCheckingOAuth(true);
let active = true;
const timer = setTimeout(async () => {
try {
@@ -91,19 +97,26 @@ export default function HomeScreen() {
const config = ((await configRes.json())?.response ??
null) as Config | null;
const logins = await loginsRes.json().catch(() => null);
+ const versionOk = isAtLeastInstanceVersion(
+ config?.INSTANCE_VERSION,
+ "v2.15.0"
+ );
const hasApple =
logins?.buttonAuths?.some(
(b: { method?: string }) => b.method === "apple"
) === true;
+ const hasGoogle =
+ logins?.buttonAuths?.some(
+ (b: { method?: string }) => b.method === "google"
+ ) === true;
- if (active)
- setAppleEnabled(
- hasApple &&
- isAtLeastInstanceVersion(config?.INSTANCE_VERSION, "v2.15.0")
- );
+ if (active) {
+ setAppleEnabled(Platform.OS === "ios" && hasApple && versionOk);
+ setGoogleEnabled(hasGoogle && versionOk);
+ }
} catch {
} finally {
- if (active) setIsCheckingApple(false);
+ if (active) setIsCheckingOAuth(false);
}
}, 400);
@@ -257,11 +270,26 @@ export default function HomeScreen() {
cornerRadius={8}
style={{ width: "100%", height: 48 }}
onPress={() => {
- if (isCheckingApple) return;
+ if (isCheckingOAuth) return;
signInWithApple(instance);
}}
/>
)}
+ {googleEnabled && (
+ <GoogleSigninButton
+ size={GoogleSigninButton.Size.Wide}
+ color={
+ colorScheme === "dark"
+ ? GoogleSigninButton.Color.Light
+ : GoogleSigninButton.Color.Dark
+ }
+ style={{ width: "100%", height: 48 }}
+ onPress={() => {
+ if (isCheckingOAuth) return;
+ signInWithGoogle(instance);
+ }}
+ />
+ )}
<TouchableOpacity
className="w-fit mx-auto"
onPress={() => router.replace("/register")}
diff --git a/apps/mobile/app/register.tsx b/apps/mobile/app/register.tsx
index a1c79e18..db6c804e 100644
--- a/apps/mobile/app/register.tsx
+++ b/apps/mobile/app/register.tsx
@@ -7,6 +7,7 @@ import {
type Config,
} from "@linkwarden/router/config";
import * as AppleAuthentication from "expo-apple-authentication";
+import { GoogleSigninButton } from "@react-native-google-signin/google-signin";
import { Redirect, router } from "expo-router";
import { useColorScheme } from "nativewind";
import { useEffect, useState } from "react";
@@ -48,8 +49,13 @@ const timeout = () =>
);
export default function RegisterScreen() {
- const { auth, signUp, signInWithApple, requestVerificationEmail } =
- useAuthStore();
+ const {
+ auth,
+ signUp,
+ signInWithApple,
+ signInWithGoogle,
+ requestVerificationEmail,
+ } = useAuthStore();
const { colorScheme } = useColorScheme();
const [isLoading, setIsLoading] = useState(false);
const [isConfigLoading, setIsConfigLoading] = useState(false);
@@ -59,7 +65,10 @@ export default function RegisterScreen() {
const [appleEnabled, setAppleEnabled] = useState(
Platform.OS === "ios" && (auth.instance || cloudInstance) === cloudInstance
);
- const [isCheckingApple, setIsCheckingApple] = useState(false);
+ const [googleEnabled, setGoogleEnabled] = useState(
+ (auth.instance || cloudInstance) === cloudInstance
+ );
+ const [isCheckingOAuth, setIsCheckingOAuth] = useState(false);
const [sentTo, setSentTo] = useState<{
email: string;
instance: string;
@@ -171,13 +180,15 @@ export default function RegisterScreen() {
}, [instance]);
useEffect(() => {
- if (Platform.OS !== "ios" || !instance) {
+ if (!instance) {
setAppleEnabled(false);
+ setGoogleEnabled(false);
return;
}
- setAppleEnabled(instance === cloudInstance);
- setIsCheckingApple(true);
+ setAppleEnabled(Platform.OS === "ios" && instance === cloudInstance);
+ setGoogleEnabled(instance === cloudInstance);
+ setIsCheckingOAuth(true);
let active = true;
const timer = setTimeout(async () => {
try {
@@ -190,19 +201,26 @@ export default function RegisterScreen() {
const config = ((await configRes.json())?.response ?? null) as Config | null;
const logins = await loginsRes.json().catch(() => null);
+ const versionOk = isAtLeastInstanceVersion(
+ config?.INSTANCE_VERSION,
+ "v2.15.0"
+ );
const hasApple =
logins?.buttonAuths?.some(
(b: { method?: string }) => b.method === "apple"
) === true;
+ const hasGoogle =
+ logins?.buttonAuths?.some(
+ (b: { method?: string }) => b.method === "google"
+ ) === true;
- if (active)
- setAppleEnabled(
- hasApple &&
- isAtLeastInstanceVersion(config?.INSTANCE_VERSION, "v2.15.0")
- );
+ if (active) {
+ setAppleEnabled(Platform.OS === "ios" && hasApple && versionOk);
+ setGoogleEnabled(hasGoogle && versionOk);
+ }
} catch {
} finally {
- if (active) setIsCheckingApple(false);
+ if (active) setIsCheckingOAuth(false);
}
}, 400);
@@ -452,11 +470,26 @@ export default function RegisterScreen() {
cornerRadius={8}
style={{ width: "100%", height: 48 }}
onPress={() => {
- if (isCheckingApple) return;
+ if (isCheckingOAuth) return;
signInWithApple(instance);
}}
/>
)}
+ {googleEnabled && (
+ <GoogleSigninButton
+ size={GoogleSigninButton.Size.Wide}
+ color={
+ colorScheme === "dark"
+ ? GoogleSigninButton.Color.Light
+ : GoogleSigninButton.Color.Dark
+ }
+ style={{ width: "100%", height: 48 }}
+ onPress={() => {
+ if (isCheckingOAuth) return;
+ signInWithGoogle(instance);
+ }}
+ />
+ )}
<TouchableOpacity
className="w-fit mx-auto"
onPress={() => router.replace("/login")}
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index 619ae58f..2362d194 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -22,6 +22,7 @@
"@linkwarden/types": "*",
"@react-native-async-storage/async-storage": "2.2.0",
"@react-native-community/netinfo": "11.4.1",
+ "@react-native-google-signin/google-signin": "^15.0.0",
"@react-native-menu/menu": "2.0.0",
"@react-navigation/bottom-tabs": "^7.0.0",
"@react-navigation/native": "^7.0.0",
diff --git a/apps/mobile/store/auth.ts b/apps/mobile/store/auth.ts
index e97c5205..4ecc99fa 100644
--- a/apps/mobile/store/auth.ts
+++ b/apps/mobile/store/auth.ts
@@ -1,6 +1,10 @@
import { create } from "zustand";
import * as SecureStore from "expo-secure-store";
import * as AppleAuthentication from "expo-apple-authentication";
+import {
+ GoogleSignin,
+ statusCodes,
+} from "@react-native-google-signin/google-signin";
import { router } from "expo-router";
import { MobileAuth } from "@linkwarden/types/global";
import { Alert } from "react-native";
@@ -11,6 +15,17 @@ import useDataStore from "@/store/data";
import { useOfflineSyncStore } from "@/lib/offlineSync";
const cloudInstance = "https://cloud.linkwarden.app";
+const googleWebClientId =
+ process.env.EXPO_PUBLIC_GOOGLE_WEB_CLIENT_ID ??
+ "1097450926817-fb426eh4dkq46gmhiuoa00k6rv196g1s.apps.googleusercontent.com";
+const googleIosClientId =
+ process.env.EXPO_PUBLIC_GOOGLE_IOS_CLIENT_ID ??
+ "1097450926817-o94t2bb30jt2me2u17ni2cc2qogd2v34.apps.googleusercontent.com";
+
+GoogleSignin.configure({
+ webClientId: googleWebClientId,
+ iosClientId: googleIosClientId,
+});
type SignUpForm = {
name: string;
@@ -29,6 +44,7 @@ type AuthStore = {
token?: string
) => Promise<void>;
signInWithApple: (instance: string) => Promise<void>;
+ signInWithGoogle: (instance: string) => Promise<void>;
signUp: (form: SignUpForm) => Promise<boolean>;
requestVerificationEmail: (
email: string,
@@ -238,7 +254,10 @@ const useAuthStore = create<AuthStore>((set) => ({
return;
}
- const name = [credential.fullName?.givenName, credential.fullName?.familyName]
+ const name = [
+ credential.fullName?.givenName,
+ credential.fullName?.familyName,
+ ]
.filter(Boolean)
.join(" ")
.trim();
@@ -257,6 +276,71 @@ const useAuthStore = create<AuthStore>((set) => ({
]);
const data = await res.json().catch(() => null);
+ if (res.ok) {
+ const session = data.response.token;
+ await SecureStore.setItemAsync("TOKEN", session);
+ await SecureStore.setItemAsync("INSTANCE", instance);
+ set({ auth: { session, instance, status: "authenticated" } });
+ router.replace("/(tabs)/dashboard");
+ } else {
+ Alert.alert("Error", data?.response || "Could not sign in with Apple.");
+ }
+ } 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."
+ );
+ }
+ },
+ signInWithGoogle: async (instance) => {
+ let idToken: string | null = null;
+ let displayName = "";
+
+ try {
+ await GoogleSignin.hasPlayServices();
+ await GoogleSignin.signOut();
+ const response = await GoogleSignin.signIn();
+ idToken = response.data?.idToken ?? null;
+ displayName = response.data?.user?.name ?? "";
+ } catch (err: any) {
+ if (
+ err?.code === statusCodes.SIGN_IN_CANCELLED ||
+ err?.code === statusCodes.IN_PROGRESS
+ )
+ return;
+ console.log("Google sign-in error:", err?.code, err?.message, err);
+ Alert.alert(
+ "Error",
+ `Could not sign in with Google. ${err?.code ?? ""} ${
+ err?.message ?? ""
+ }`
+ );
+
+ Alert.alert("Error", "Could not sign in with Google.");
+ return;
+ }
+
+ if (!idToken) {
+ Alert.alert("Error", "Google did not return an identity token.");
+ return;
+ }
+
+ try {
+ const res = await Promise.race([
+ fetch(`${instance}/api/v1/auth/mobile/google`, {
+ method: "POST",
+ body: JSON.stringify({
+ identityToken: idToken,
+ name: displayName || undefined,
+ }),
+ headers: { "Content-Type": "application/json" },
+ }),
+ timeout(),
+ ]);
+ const data = await res.json().catch(() => null);
+
if (res.ok) {
const session = data.response.token;
await SecureStore.setItemAsync("TOKEN", session);
@@ -266,7 +350,7 @@ const useAuthStore = create<AuthStore>((set) => ({
} else {
Alert.alert(
"Error",
- data?.response || "Could not sign in with Apple."
+ data?.response || "Could not sign in with Google."
);
}
} catch (err: any) {
diff --git a/apps/web/lib/api/google.ts b/apps/web/lib/api/google.ts
new file mode 100644
index 00000000..14baca2a
--- /dev/null
+++ b/apps/web/lib/api/google.ts
@@ -0,0 +1,26 @@
+import { createRemoteJWKSet, jwtVerify } from "jose";
+
+const googleIssuers = ["https://accounts.google.com", "accounts.google.com"];
+const googleJwks = createRemoteJWKSet(
+ new URL("https://www.googleapis.com/oauth2/v3/certs")
+);
+
+export async function verifyGoogleIdentityToken(
+ identityToken: string,
+ audience: string
+) {
+ const { payload } = await jwtVerify(identityToken, googleJwks, {
+ issuer: googleIssuers,
+ audience,
+ });
+
+ if (!payload.sub)
+ throw Error("Google identity token is missing the subject.");
+
+ return payload as {
+ sub: string;
+ email?: string;
+ email_verified?: boolean | string;
+ name?: string;
+ };
+}
diff --git a/apps/web/pages/api/v1/auth/mobile/google.ts b/apps/web/pages/api/v1/auth/mobile/google.ts
new file mode 100644
index 00000000..2843c1fe
--- /dev/null
+++ b/apps/web/pages/api/v1/auth/mobile/google.ts
@@ -0,0 +1,113 @@
+import { verifyGoogleIdentityToken } from "@/lib/api/google";
+import createSession from "@/lib/api/controllers/session/createSession";
+import { prisma } from "@linkwarden/prisma";
+import type { NextApiRequest, NextApiResponse } from "next";
+
+const newSsoUsersDisabled = process.env.DISABLE_NEW_SSO_USERS === "true";
+
+export default async function googleMobileAuth(
+ req: NextApiRequest,
+ res: NextApiResponse
+) {
+ if (req.method !== "POST")
+ return res.status(405).json({ response: "Method not allowed." });
+
+ if (process.env.NEXT_PUBLIC_GOOGLE_ENABLED !== "true")
+ return res
+ .status(400)
+ .json({ response: "Google sign-in is not enabled on this instance." });
+
+ if (!process.env.GOOGLE_CLIENT_ID)
+ return res
+ .status(500)
+ .json({ response: "Google client ID is not configured." });
+
+ const { identityToken, name, sessionName } = req.body ?? {};
+
+ if (typeof identityToken !== "string" || !identityToken)
+ return res.status(400).json({ response: "Missing identity token." });
+
+ let claims;
+ try {
+ claims = await verifyGoogleIdentityToken(
+ identityToken,
+ process.env.GOOGLE_CLIENT_ID
+ );
+ } catch {
+ return res.status(401).json({ response: "Invalid Google identity token." });
+ }
+
+ const emailVerified =
+ claims.email_verified === true || claims.email_verified === "true";
+ const email = emailVerified ? claims.email?.toLowerCase() : undefined;
+
+ let account = await prisma.account.findFirst({
+ where: { provider: "google", providerAccountId: claims.sub },
+ include: { user: true },
+ });
+
+ let user = account?.user;
+
+ if (!user && email) {
+ const existingUser = await prisma.user.findUnique({
+ where: { email },
+ include: { accounts: true },
+ });
+
+ if (existingUser && existingUser.accounts.length > 0)
+ return res.status(409).json({
+ response:
+ "An account with this email is already linked to another sign-in method.",
+ });
+
+ if (existingUser) {
+ user = existingUser;
+ await prisma.account.create({
+ data: {
+ userId: user.id,
+ type: "oauth",
+ provider: "google",
+ providerAccountId: claims.sub,
+ },
+ });
+ }
+ }
+
+ if (!user) {
+ if (newSsoUsersDisabled)
+ return res.status(403).json({ response: "Sign ups are disabled." });
+
+ const fullName =
+ typeof name === "string" && name.trim()
+ ? name.trim()
+ : (claims.name?.trim() ?? "");
+
+ user = await prisma.user.create({
+ data: {
+ name: fullName,
+ email,
+ emailVerified: new Date(),
+ username: "user" + Math.round(Math.random() * 1000000000),
+ accounts: {
+ create: {
+ type: "oauth",
+ provider: "google",
+ providerAccountId: claims.sub,
+ },
+ },
+ dashboardSections: {
+ createMany: {
+ data: [
+ { order: 0, type: "STATS" },
+ { order: 1, type: "RECENT_LINKS" },
+ { order: 2, type: "PINNED_LINKS" },
+ ],
+ },
+ },
+ },
+ });
+ }
+
+ const token = await createSession(user.id, sessionName);
+ return res.status(token.status).json({ response: token.response });
+}
diff --git a/yarn.lock b/yarn.lock
index c6b711a0..eae71484 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -5244,6 +5244,7 @@ __metadata:
"@linkwarden/types": "npm:*"
"@react-native-async-storage/async-storage": "npm:2.2.0"
"@react-native-community/netinfo": "npm:11.4.1"
+ "@react-native-google-signin/google-signin": "npm:^15.0.0"
"@react-native-menu/menu": "npm:2.0.0"
"@react-navigation/bottom-tabs": "npm:^7.0.0"
"@react-navigation/native": "npm:^7.0.0"
@@ -7073,6 +7074,20 @@ __metadata:
languageName: node
linkType: hard
+"@react-native-google-signin/google-signin@npm:^15.0.0":
+ version: 15.0.0
+ resolution: "@react-native-google-signin/google-signin@npm:15.0.0"
+ peerDependencies:
+ expo: ">=52.0.40"
+ react: "*"
+ react-native: "*"
+ peerDependenciesMeta:
+ expo:
+ optional: true
+ checksum: 10c0/e0a2100bab0a59d795e352986cbc7bd3ba5fea85346ac628c8c5c7583af66ed3faed9873e2a53c422b86d44c8e21e2c8a1e3c96e85dc1ea559c28fbb3c35ee42
+ languageName: node
+ linkType: hard
+
"@react-native-menu/menu@npm:2.0.0":
version: 2.0.0
resolution: "@react-native-menu/menu@npm:2.0.0"