opencode/packages/console/app/src/context/auth.ts

84 lines
2.4 KiB
TypeScript
Raw Normal View History

2025-08-21 04:52:43 +08:00
import { getRequestEvent } from "solid-js/web"
2025-10-05 09:33:39 +08:00
import { and, Database, eq, inArray, sql } from "@opencode-ai/console-core/drizzle/index.js"
import { UserTable } from "@opencode-ai/console-core/schema/user.sql.js"
2025-09-03 04:38:26 +08:00
import { redirect } from "@solidjs/router"
2025-10-05 09:33:39 +08:00
import { Actor } from "@opencode-ai/console-core/actor.js"
2025-08-21 04:52:43 +08:00
2025-08-29 23:58:17 +08:00
import { createClient } from "@openauthjs/openauth/client"
import { useAuthSession } from "./auth.session"
export const AuthClient = createClient({
clientID: "app",
issuer: import.meta.env.VITE_AUTH_URL,
})
2025-08-21 04:52:43 +08:00
2025-09-04 01:10:57 +08:00
export const getActor = async (workspace?: string): Promise<Actor.Info> => {
2025-08-21 04:52:43 +08:00
"use server"
const evt = getRequestEvent()
2025-08-30 13:19:03 +08:00
if (!evt) throw new Error("No request event")
2025-09-04 00:31:09 +08:00
if (evt.locals.actor) return evt.locals.actor
evt.locals.actor = (async () => {
const auth = await useAuthSession()
2025-09-04 01:10:57 +08:00
if (!workspace) {
2025-09-04 00:31:09 +08:00
const account = auth.data.account ?? {}
const current = account[auth.data.current ?? ""]
if (current) {
return {
type: "account",
properties: {
email: current.email,
accountID: current.id,
},
}
}
if (Object.keys(account).length > 0) {
const current = Object.values(account)[0]
await auth.update((val) => ({
...val,
current: current.id,
}))
return {
type: "account",
properties: {
email: current.email,
accountID: current.id,
},
}
2025-08-21 04:52:43 +08:00
}
return {
2025-09-04 00:31:09 +08:00
type: "public",
properties: {},
2025-08-21 04:52:43 +08:00
}
}
2025-09-04 00:31:09 +08:00
const accounts = Object.keys(auth.data.account ?? {})
if (accounts.length) {
2025-10-03 05:55:54 +08:00
const user = await Database.use((tx) =>
2025-10-02 07:34:37 +08:00
tx
2025-10-03 05:55:54 +08:00
.select()
.from(UserTable)
.where(and(eq(UserTable.workspaceID, workspace), inArray(UserTable.accountID, accounts)))
2025-09-04 00:31:09 +08:00
.limit(1)
.execute()
2025-10-02 07:34:37 +08:00
.then((x) => x[0]),
)
2025-10-03 05:55:54 +08:00
if (user) {
2025-10-02 07:34:37 +08:00
await Database.use((tx) =>
tx
.update(UserTable)
.set({ timeSeen: sql`now()` })
2025-10-03 05:55:54 +08:00
.where(and(eq(UserTable.workspaceID, workspace), eq(UserTable.id, user.id))),
2025-10-02 07:34:37 +08:00
)
2025-09-04 00:31:09 +08:00
return {
type: "user",
properties: {
2025-10-03 05:55:54 +08:00
userID: user.id,
workspaceID: user.workspaceID,
2025-09-04 00:31:09 +08:00
},
}
2025-09-03 04:38:26 +08:00
}
2025-08-21 04:52:43 +08:00
}
2025-09-04 00:31:09 +08:00
throw redirect("/auth/authorize")
})()
return evt.locals.actor
2025-09-03 04:38:26 +08:00
}