auth.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import { getRequestEvent } from "solid-js/web"
  2. import { and, Database, eq, inArray, isNull, sql } from "@opencode-ai/console-core/drizzle/index.js"
  3. import { UserTable } from "@opencode-ai/console-core/schema/user.sql.js"
  4. import { redirect } from "@solidjs/router"
  5. import { Actor } from "@opencode-ai/console-core/actor.js"
  6. import { createClient } from "@openauthjs/openauth/client"
  7. import { useAuthSession } from "./auth.session"
  8. export const AuthClient = createClient({
  9. clientID: "app",
  10. issuer: import.meta.env.VITE_AUTH_URL,
  11. })
  12. export const getActor = async (workspace?: string): Promise<Actor.Info> => {
  13. "use server"
  14. const evt = getRequestEvent()
  15. if (!evt) throw new Error("No request event")
  16. if (evt.locals.actor) return evt.locals.actor
  17. evt.locals.actor = (async () => {
  18. const auth = await useAuthSession()
  19. if (!workspace) {
  20. const account = auth.data.account ?? {}
  21. const current = account[auth.data.current ?? ""]
  22. if (current) {
  23. return {
  24. type: "account",
  25. properties: {
  26. email: current.email,
  27. accountID: current.id,
  28. },
  29. }
  30. }
  31. if (Object.keys(account).length > 0) {
  32. const current = Object.values(account)[0]
  33. await auth.update((val) => ({
  34. ...val,
  35. current: current.id,
  36. }))
  37. return {
  38. type: "account",
  39. properties: {
  40. email: current.email,
  41. accountID: current.id,
  42. },
  43. }
  44. }
  45. return {
  46. type: "public",
  47. properties: {},
  48. }
  49. }
  50. const accounts = Object.keys(auth.data.account ?? {})
  51. if (accounts.length) {
  52. const user = await Database.use((tx) =>
  53. tx
  54. .select()
  55. .from(UserTable)
  56. .where(
  57. and(
  58. eq(UserTable.workspaceID, workspace),
  59. isNull(UserTable.timeDeleted),
  60. inArray(UserTable.accountID, accounts),
  61. ),
  62. )
  63. .limit(1)
  64. .execute()
  65. .then((x) => x[0]),
  66. )
  67. if (user) {
  68. await Database.use((tx) =>
  69. tx
  70. .update(UserTable)
  71. .set({ timeSeen: sql`now()` })
  72. .where(and(eq(UserTable.workspaceID, workspace), eq(UserTable.id, user.id))),
  73. )
  74. return {
  75. type: "user",
  76. properties: {
  77. userID: user.id,
  78. workspaceID: user.workspaceID,
  79. accountID: user.accountID,
  80. role: user.role,
  81. },
  82. }
  83. }
  84. }
  85. throw redirect("/auth/authorize")
  86. })()
  87. return evt.locals.actor
  88. }