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
Prev Previous commit
Next Next commit
feat: web login returning
  • Loading branch information
DIYgod committed Dec 2, 2024
commit 9e52bd34f0662b1fc6f5fa0b4feff91af17576a1
2 changes: 1 addition & 1 deletion CONTRIBUTE.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ If you prefer to develop in Electron, follow these steps:
pnpm run dev
```

> **Tip:** If you encounter login issues, copy the `authjs.session-token` from your browser's cookies into the app.
> **Tip:** If you encounter login issues, copy the `better-auth.session_token` from your browser's cookies into the app.

## Contribution Guidelines

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ pnpm run dev
Since it is not very convenient to develop in Electron, the first way to develop and contribute is recommended at this stage.

> [!TIP]
> If you can't log in to the app, copy the `authjs.session-token` in the cookie from your browser into the app.
> If you can't log in to the app, copy the `better-auth.session_token` in the cookie from your browser into the app.

## 📝 License

Expand Down
13 changes: 7 additions & 6 deletions apps/main/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { updateProxy } from "./lib/proxy"
import { handleUrlRouting } from "./lib/router"
import { store } from "./lib/store"
import { registerAppTray } from "./lib/tray"
import { setAuthSessionToken, updateNotificationsToken } from "./lib/user"
import { setBetterAuthSessionCookie, updateNotificationsToken } from "./lib/user"
import { registerUpdater } from "./updater"
import { cleanupOldRender } from "./updater/hot-updater"
import {
Expand Down Expand Up @@ -189,15 +189,16 @@ function bootstrap() {
const urlObj = new URL(url)

if (urlObj.hostname === "auth" || urlObj.pathname === "//auth") {
const token = urlObj.searchParams.get("token")
const ck = urlObj.searchParams.get("ck")
const userId = urlObj.searchParams.get("userId")

if (token && apiURL) {
setAuthSessionToken(token)
if (ck && apiURL) {
setBetterAuthSessionCookie(ck)
const cookie = atob(ck)
mainWindow.webContents.session.cookies.set({
url: apiURL,
name: "authjs.session-token",
value: token,
name: cookie.split("=")[0],
value: cookie.split("=")[1],
secure: true,
httpOnly: true,
domain: new URL(apiURL).hostname,
Expand Down
10 changes: 5 additions & 5 deletions apps/main/src/lib/api-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { hc } from "hono/client"
import { ofetch } from "ofetch"

import { logger } from "../logger"
import { getAuthSessionToken, getUser } from "./user"
import { getBetterAuthSessionCookie, getUser } from "./user"

const abortController = new AbortController()
export const apiFetch = ofetch.create({
Expand All @@ -14,8 +14,8 @@ export const apiFetch = ofetch.create({
signal: abortController.signal,
retry: false,
onRequest({ request }) {
const authSessionToken = getAuthSessionToken()
if (!authSessionToken) {
const betterAuthSessionCookie = getBetterAuthSessionCookie()
if (!betterAuthSessionCookie) {
abortController.abort()
return
}
Expand All @@ -32,12 +32,12 @@ export const apiFetch = ofetch.create({
export const apiClient = hc<AppType>("", {
fetch: async (input, options = {}) => apiFetch(input.toString(), options),
headers() {
const authSessionToken = getAuthSessionToken()
const betterAuthSessionCookie = getBetterAuthSessionCookie()
const user = getUser()
return {
"X-App-Version": PKG.version,
"X-App-Dev": process.env.NODE_ENV === "development" ? "1" : "0",
Cookie: authSessionToken ? `authjs.session-token=${authSessionToken}` : "",
Cookie: betterAuthSessionCookie ? atob(betterAuthSessionCookie) : "",
"User-Agent": `Follow/${PKG.version}${user?.id ? ` uid: ${user.id}` : ""}`,
}
},
Expand Down
26 changes: 16 additions & 10 deletions apps/main/src/lib/user.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import type { User } from "@auth/core/types"
import type { Credentials } from "@eneris/push-receiver/dist/types"

import { logger } from "~/logger"

import { apiClient } from "./api-client"
import { store } from "./store"

const AuthKey = "authSessionToken"
export const setAuthSessionToken = (token: string) => store.set(AuthKey, token)
export const getAuthSessionToken = (): string | null => store.get(AuthKey)
export const cleanAuthSessionToken = () => store.set(AuthKey, null)
const BetterAuthKey = "betterAuthSessionCookie"
export const setBetterAuthSessionCookie = (cookie: string) => store.set(BetterAuthKey, cookie)
export const getBetterAuthSessionCookie = (): string | null => store.get(BetterAuthKey)
export const cleanBetterAuthSessionCookie = () => store.set(BetterAuthKey, null)

const UserKey = "user"
export const setUser = (user: User) => store.set(UserKey, JSON.stringify(user))
Expand All @@ -24,11 +26,15 @@ export const updateNotificationsToken = async (newCredentials?: Credentials) =>
}
const credentials = newCredentials || store.get("notifications-credentials")
if (credentials?.fcm?.token) {
await apiClient.messaging.$post({
json: {
token: credentials.fcm.token,
channel: "desktop",
},
})
try {
await apiClient.messaging.$post({
json: {
token: credentials.fcm.token,
channel: "desktop",
},
})
} catch (error) {
logger.error("updateNotificationsToken error: ", error)
}
}
}
6 changes: 3 additions & 3 deletions apps/main/src/tipc/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { cleanupOldRender, loadDynamicRenderEntry } from "~/updater/hot-updater"
import { isDev, isWindows11 } from "../env"
import { downloadFile } from "../lib/download"
import { i18n } from "../lib/i18n"
import { cleanAuthSessionToken, cleanUser } from "../lib/user"
import { cleanBetterAuthSessionCookie, cleanUser } from "../lib/user"
import type { RendererHandlers } from "../renderer-handlers"
import { quitAndInstall } from "../updater"
import { getMainWindow } from "../window"
Expand Down Expand Up @@ -167,8 +167,8 @@ export const appRoute = {
quitAndInstall()
}),

cleanAuthSessionToken: t.procedure.action(async () => {
cleanAuthSessionToken()
cleanBetterAuthSessionCookie: t.procedure.action(async () => {
cleanBetterAuthSessionCookie()
cleanUser()
}),
/// clipboard
Expand Down
5 changes: 4 additions & 1 deletion apps/renderer/src/hooks/biz/useSignOut.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ export const useSignOut = () =>
clearStorage()
window.analytics?.reset()
// clear local store data
await Promise.allSettled([clearLocalPersistStoreData(), tipcClient?.cleanAuthSessionToken()])
await Promise.allSettled([
clearLocalPersistStoreData(),
tipcClient?.cleanBetterAuthSessionCookie(),
])
// Sign out
await signOut()
}, [])
2 changes: 1 addition & 1 deletion apps/server/client/pages/(login)/login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ function Login() {
const { data } = await createSession()
if (!data) return null
return {
url: `${DEEPLINK_SCHEME}auth?token=${data.token}&userId=${data.userId}`,
url: `${DEEPLINK_SCHEME}auth?ck=${data.ck}&userId=${data.userId}`,
userId: data.userId,
}
}, [])
Expand Down
4 changes: 2 additions & 2 deletions apps/server/src/lib/api-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export const createApiClient = () => {
"X-App-Version": PKG.version,
"X-App-Dev": isDev ? "1" : "0",
"User-Agent": `Follow External Server Api Client/${PKG.version}`,
Cookie: authSessionToken ? `authjs.session-token=${authSessionToken}` : "",
Cookie: authSessionToken ? `better-auth.session_token=${authSessionToken}` : "",
}
},
})
Expand All @@ -72,7 +72,7 @@ export const getTokenFromCookie = (cookie: string) => {
},
{} as Record<string, string>,
)
return parsedCookieMap["authjs.session-token"]
return parsedCookieMap["better-auth.session_token"]
}

export type ApiClient = ReturnType<typeof createApiClient>
24 changes: 3 additions & 21 deletions packages/shared/src/hono.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,8 @@ declare const authPlugins: ({
}> | undefined)?]>(...ctx: C): Promise<C extends [{
asResponse: true;
}] ? Response : {
id: string;
ck: string;
userId: string;
createdAt: Date;
updatedAt: Date;
expiresAt: Date;
token: string;
ipAddress?: string | null | undefined;
userAgent?: string | null | undefined;
} | null>;
path: "/create-session";
options: {
Expand Down Expand Up @@ -6621,14 +6615,8 @@ declare const auth: {
}> | undefined)?]>(...ctx: C): Promise<C extends [{
asResponse: true;
}] ? Response : {
id: string;
ck: string;
userId: string;
createdAt: Date;
updatedAt: Date;
expiresAt: Date;
token: string;
ipAddress?: string | null | undefined;
userAgent?: string | null | undefined;
} | null>;
path: "/create-session";
options: {
Expand Down Expand Up @@ -9236,14 +9224,8 @@ declare const auth: {
}> | undefined)?]>(...ctx: C): Promise<C extends [{
asResponse: true;
}] ? Response : {
id: string;
ck: string;
userId: string;
createdAt: Date;
updatedAt: Date;
expiresAt: Date;
token: string;
ipAddress?: string | null | undefined;
userAgent?: string | null | undefined;
} | null>;
path: "/create-session";
options: {
Expand Down