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
Prev Previous commit
Next Next commit
feat: remove hono/auth-js
  • Loading branch information
DIYgod committed Dec 1, 2024
commit c94d718927cc02dfcb7f25a3fe7c9df9b3aa63ca
1 change: 0 additions & 1 deletion apps/renderer/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
"@follow/shared": "workspace:*",
"@fontsource/sn-pro": "5.1.0",
"@headlessui/react": "2.2.0",
"@hono/auth-js": "1.0.15",
"@hookform/resolvers": "3.9.1",
"@lottiefiles/dotlottie-react": "0.10.0",
"@microflash/remark-callout-directives": "4.3.2",
Expand Down
6 changes: 4 additions & 2 deletions apps/renderer/src/atoms/user.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import type { User } from "@auth/core/types"
import type { UserRole } from "@follow/constants"
import type { AuthSession } from "@follow/shared/hono"
import { atom } from "jotai"

import { createAtomHooks } from "~/lib/jotai"

export const [, , useWhoami, , whoami, setWhoami] = createAtomHooks(atom<Nullable<User>>(null))
export const [, , useWhoami, , whoami, setWhoami] = createAtomHooks(
atom<Nullable<NonNullable<AuthSession>["user"]>>(null),
)

export const [, , useLoginModalShow, useSetLoginModalShow, getLoginModalShow, setLoginModalShow] =
createAtomHooks(atom<boolean>(false))
Expand Down
9 changes: 3 additions & 6 deletions apps/renderer/src/hooks/biz/useSignOut.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { env } from "@follow/shared/env"
import { signOut } from "@follow/shared/auth"
import { clearStorage } from "@follow/utils/ns"
import { signOut } from "@hono/auth-js/react"
import { useCallback } from "react"

import { setWhoami } from "~/atoms/user"
import { isWebBuild, QUERY_PERSIST_KEY } from "~/constants"
import { QUERY_PERSIST_KEY } from "~/constants"
import { tipcClient } from "~/lib/client"
import { clearLocalPersistStoreData } from "~/store/utils/clear"

Expand All @@ -22,7 +21,5 @@ export const useSignOut = () =>
// clear local store data
await Promise.allSettled([clearLocalPersistStoreData(), tipcClient?.cleanAuthSessionToken()])
// Sign out
await signOut({
callbackUrl: isWebBuild ? env.VITE_WEB_URL : undefined,
})
await signOut()
}, [])
8 changes: 0 additions & 8 deletions apps/renderer/src/initialize/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { initializeDayjs } from "@follow/components/dayjs"
import { registerGlobalContext } from "@follow/shared/bridge"
import { IN_ELECTRON } from "@follow/shared/constants"
import { env } from "@follow/shared/env"
import { authConfigManager } from "@hono/auth-js/react"
import { repository } from "@pkg"
import { enableMapSet } from "immer"

Expand Down Expand Up @@ -63,12 +61,6 @@ export const initializeApp = async () => {
window.version = APP_VERSION

const now = Date.now()
// Initialize the auth config first
authConfigManager.setConfig({
baseUrl: env.VITE_API_URL,
basePath: "/auth",
credentials: "include",
})
initializeDayjs()
registerHistoryStack()

Expand Down
18 changes: 2 additions & 16 deletions apps/renderer/src/lib/api-fetch.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { env } from "@follow/shared/env"
import type { AppType } from "@follow/shared/hono"
import { getCsrfToken } from "@hono/auth-js/react"
import PKG from "@pkg"
import { hc } from "hono/client"
import { FetchError, ofetch } from "ofetch"
Expand All @@ -13,27 +12,15 @@ import { isDev } from "~/constants"
import { NeedActivationToast } from "~/modules/activation/NeedActivationToast"
import { DebugRegistry } from "~/modules/debug/registry"

let csrfTokenPromise: Promise<string> | null = null

const getPromisedCsrfToken = async () => {
if (!csrfTokenPromise) {
csrfTokenPromise = getCsrfToken()
}

return await csrfTokenPromise
}
export const apiFetch = ofetch.create({
baseURL: env.VITE_API_URL,
credentials: "include",
retry: false,
onRequest: async ({ options }) => {
const csrfToken = await getPromisedCsrfToken()

onRequest: ({ options }) => {
const header = new Headers(options.headers)

header.set("x-app-version", PKG.version)
header.set("X-App-Dev", process.env.NODE_ENV === "development" ? "1" : "0")
header.set("X-Csrf-Token", csrfToken)
options.headers = header
},
onResponse() {
Expand Down Expand Up @@ -92,11 +79,10 @@ export const apiClient = hc<AppType>(env.VITE_API_URL, {
}
throw err
}),
async headers() {
headers() {
return {
"X-App-Version": PKG.version,
"X-App-Dev": process.env.NODE_ENV === "development" ? "1" : "0",
"X-Csrf-Token": await getPromisedCsrfToken(),
}
},
})
Expand Down
3 changes: 2 additions & 1 deletion apps/renderer/src/queries/auth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { getSession } from "@follow/shared/auth"
import type { AuthSession } from "@follow/shared/hono"
import type { FetchError } from "ofetch"

import { useAuthQuery } from "~/hooks/common"
Expand Down Expand Up @@ -30,7 +31,7 @@ export const useSession = (options?: { enabled?: boolean }) => {
const fetchError = error as FetchError

return {
session: data?.data,
session: data?.data as AuthSession,
...rest,
status: isLoading
? "loading"
Expand Down
8 changes: 0 additions & 8 deletions apps/server/client/initialize/index.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,10 @@
import { initI18n } from "@client/i18n"
import { initializeDayjs } from "@follow/components/dayjs"
import { env } from "@follow/shared/env"
import { authConfigManager } from "@hono/auth-js/react"

import { initAnalytics } from "./analytics"
import { initSentry } from "./sentry"

export const initialize = () => {
authConfigManager.setConfig({
baseUrl: env.VITE_API_URL,
basePath: "/auth",
credentials: "include",
})

initializeDayjs()
initI18n()
initAnalytics()
Expand Down
11 changes: 1 addition & 10 deletions apps/server/client/lib/api-fetch.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,15 @@
import { env } from "@follow/shared/env"
import type { AppType } from "@follow/shared/hono"
import { getCsrfToken } from "@hono/auth-js/react"
import { hc } from "hono/client"
import { ofetch } from "ofetch"

let csrfTokenPromise: Promise<string> | null = null
const apiFetch = ofetch.create({
credentials: "include",
retry: false,
onRequest: async ({ options }) => {
if (!csrfTokenPromise) {
csrfTokenPromise = getCsrfToken()
}

const csrfToken = await csrfTokenPromise

onRequest: ({ options }) => {
const header = new Headers(options.headers)

header.set("x-app-version", "Web External")
header.set("X-Csrf-Token", csrfToken)
options.headers = header
},
})
Expand Down
10 changes: 3 additions & 7 deletions apps/server/client/pages/(login)/login.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,19 @@
import { UserAvatar } from "@client/components/ui/user-avatar"
import { apiClient } from "@client/lib/api-fetch"
import { useSession } from "@client/query/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 { loginHandler, signOut } from "@follow/shared/auth"
import { DEEPLINK_SCHEME } from "@follow/shared/constants"
import { cn } from "@follow/utils/utils"
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"

export function Component() {
return (
<SessionProvider>
<Login />
</SessionProvider>
)
return <Login />
}

function Login() {
Expand Down
38 changes: 1 addition & 37 deletions apps/server/client/query/auth.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import type { Session } from "@auth/core/types"
import type { GetSessionParams } from "@hono/auth-js/react"
import { authConfigManager } from "@hono/auth-js/react"
import { getSession } from "@follow/shared/auth"
import { useQuery } from "@tanstack/react-query"
import type { FetchError } from "ofetch"
import { ofetch } from "ofetch"

export const useSession = (options?: { enabled?: boolean }) => {
const { data, isLoading, ...rest } = useQuery({
Expand Down Expand Up @@ -38,36 +35,3 @@ export const useSession = (options?: { enabled?: boolean }) => {
: "error",
}
}

/**
* 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)
}
1 change: 0 additions & 1 deletion apps/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
"@fastify/middie": "9.0.2",
"@fastify/request-context": "6.0.1",
"@fontsource/sn-pro": "5.1.0",
"@hono/auth-js": "1.0.15",
"@openpanel/web": "1.0.1",
"@resvg/resvg-js": "2.6.2",
"@sentry/react": "8.40.0",
Expand Down
Loading