Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: migrate to better auth #1951

Merged
merged 12 commits into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
feat: add better-auth
  • Loading branch information
DIYgod committed Dec 1, 2024
commit 46060924fbe7ccb6fd43452d4ab326c933b6d912
14 changes: 0 additions & 14 deletions apps/renderer/src/lib/auth.ts

This file was deleted.

4 changes: 2 additions & 2 deletions apps/renderer/src/modules/auth/LoginModalContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { FollowIcon } from "@follow/components/icons/follow.jsx"
import { MotionButtonBase } from "@follow/components/ui/button/index.js"
import { LoadingCircle } from "@follow/components/ui/loading/index.jsx"
import { authProvidersConfig } from "@follow/constants"
import type { LoginRuntime } from "@follow/shared/auth"
import { loginHandler } from "@follow/shared/auth"
import { stopPropagation } from "@follow/utils/dom"
import clsx from "clsx"
import { AnimatePresence, m } from "framer-motion"
Expand All @@ -10,8 +12,6 @@ import { useTranslation } from "react-i18next"

import { modalMontionConfig } from "~/components/ui/modal/stacked/constants"
import { useCurrentModal } from "~/components/ui/modal/stacked/hooks"
import type { LoginRuntime } from "~/lib/auth"
import { loginHandler } from "~/lib/auth"
import { useAuthProviders } from "~/queries/users"

interface LoginModalContentProps {
Expand Down
47 changes: 5 additions & 42 deletions apps/renderer/src/queries/auth.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
import type { Session } from "@auth/core/types"
import type { getSession as getSessionReact } from "@hono/auth-js/react"
import { authConfigManager } from "@hono/auth-js/react"
import { getSession } from "@follow/shared/auth"
import type { FetchError } from "ofetch"
import { ofetch } from "ofetch"

import { useAuthQuery } from "~/hooks/common"
import { defineQuery } from "~/lib/defineQuery"

type GetSessionParams = Parameters<typeof getSessionReact>[0]
export const auth = {
getSession: () => defineQuery(["auth", "session"], () => getSession()),
}
Expand All @@ -34,47 +30,14 @@ export const useSession = (options?: { enabled?: boolean }) => {
const fetchError = error as FetchError

return {
session: data,
session: data?.data,
...rest,
status: isLoading
? "loading"
: data
? "authenticated"
: fetchError?.statusCode === 401
? "unauthenticated"
: "error",
: fetchError
? "error"
: "unauthenticated",
}
}

/**
* Fetch session data, copy and patch code from @hono/auth-js/react
*/
async function fetchData<T = any>(
path: string,

req: any = {},
): Promise<T | null> {
const config = authConfigManager.getConfig()
const url = `${config.baseUrl}${config.basePath}/${path}`

const options: RequestInit = {
headers: {
"Content-Type": "application/json",
...(req?.headers?.cookie ? { cookie: req.headers.cookie } : {}),
},
credentials: config.credentials,
}

if (req?.body) {
options.body = JSON.stringify(req.body)
options.method = "POST"
}

const data = await ofetch(url, options)

return data as T
}

function getSession(params?: GetSessionParams) {
return fetchData<Session>("session", params)
}
5 changes: 2 additions & 3 deletions apps/renderer/src/queries/users.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { getProviders } from "@hono/auth-js/react"
import { useQuery } from "@tanstack/react-query"

import { apiClient } from "~/lib/api-fetch"
Expand All @@ -17,7 +16,7 @@ export const users = {
export const useAuthProviders = () => {
return useQuery({
queryKey: ["providers"],
queryFn: () => getProviders(),
queryFn: () => apiClient["auth-app"].providers.$get(),
placeholderData: {
google: {
id: "google",
Expand All @@ -27,6 +26,6 @@ export const useAuthProviders = () => {
id: "github",
name: "GitHub",
},
} as Awaited<ReturnType<typeof getProviders>>,
},
})
}
14 changes: 0 additions & 14 deletions apps/server/client/lib/auth.ts

This file was deleted.

8 changes: 3 additions & 5 deletions apps/server/client/pages/(login)/login.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { UserAvatar } from "@client/components/ui/user-avatar"
import { apiClient } from "@client/lib/api-fetch"
import { LOGIN_CALLBACK_URL, loginHandler } from "@client/lib/auth"
import { useAuthProviders } from "@client/query/users"
import { Logo } from "@follow/components/icons/logo.jsx"
import { Button } from "@follow/components/ui/button/index.js"
import { authProvidersConfig } from "@follow/constants"
import { loginHandler } from "@follow/shared/auth"
import { DEEPLINK_SCHEME } from "@follow/shared/constants"
import { cn } from "@follow/utils/utils"
import { SessionProvider, signIn, signOut, useSession } from "@hono/auth-js/react"
import { SessionProvider, signOut, useSession } from "@hono/auth-js/react"
import { useCallback, useEffect, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useLocation } from "react-router"
Expand Down Expand Up @@ -36,9 +36,7 @@ function Login() {

useEffect(() => {
if (provider && status === "unauthenticated") {
signIn(provider, {
callbackUrl: LOGIN_CALLBACK_URL,
})
loginHandler(provider)
setRedirecting(true)
}
}, [status])
Expand Down
5 changes: 2 additions & 3 deletions apps/server/client/query/users.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { apiClient } from "@client/lib/api-fetch"
import { getHydrateData } from "@client/lib/helper"
import { capitalizeFirstLetter, isBizId, parseUrl } from "@follow/utils/utils"
import { getProviders } from "@hono/auth-js/react"
import { useQuery } from "@tanstack/react-query"

export const useUserSubscriptionsQuery = (userId: string | undefined) => {
Expand Down Expand Up @@ -60,7 +59,7 @@ export const useUserQuery = (handleOrId: string | undefined) => {
export const useAuthProviders = () => {
return useQuery({
queryKey: ["providers"],
queryFn: () => getProviders(),
queryFn: () => apiClient["auth-app"].providers.$get(),
placeholderData: {
google: {
id: "google",
Expand All @@ -70,6 +69,6 @@ export const useAuthProviders = () => {
id: "github",
name: "GitHub",
},
} as Awaited<ReturnType<typeof getProviders>>,
},
})
}
1 change: 1 addition & 0 deletions packages/shared/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"@electron-toolkit/tsconfig": "^1.0.1",
"@hono/node-server": "^1.13.7",
"@t3-oss/env-core": "^0.11.1",
"better-auth": "1.0.7",
"drizzle-orm": "^0.36.4",
"electron": "^33.2.1",
"hono": "^4.6.11",
Expand Down
23 changes: 23 additions & 0 deletions packages/shared/src/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { env } from "@follow/shared/env"
import { createAuthClient } from "better-auth/react"

import { IN_ELECTRON, WEB_URL } from "./constants"

const authClient = createAuthClient({
baseURL: `${env.VITE_API_URL}/better-auth`,
})

export const { signIn, signOut, getSession } = authClient

export const LOGIN_CALLBACK_URL = `${WEB_URL}/login`
export type LoginRuntime = "browser" | "app"
export const loginHandler = (provider: string, runtime: LoginRuntime = "app") => {
if (IN_ELECTRON) {
window.open(`${WEB_URL}/login?provider=${provider}`)
} else {
signIn.social({
provider: provider as "google" | "github" | "apple",
callbackURL: runtime === "app" ? LOGIN_CALLBACK_URL : WEB_URL,
})
}
}
Loading