user.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. import { z } from "zod"
  2. import { and, eq, getTableColumns, inArray, isNull, or, sql } from "drizzle-orm"
  3. import { fn } from "./util/fn"
  4. import { Database } from "./drizzle"
  5. import { UserRole, UserTable } from "./schema/user.sql"
  6. import { Actor } from "./actor"
  7. import { Identifier } from "./identifier"
  8. import { render } from "@jsx-email/render"
  9. import { AWS } from "./aws"
  10. import { Account } from "./account"
  11. import { AccountTable } from "./schema/account.sql"
  12. import { Key } from "./key"
  13. import { KeyTable } from "./schema/key.sql"
  14. export namespace User {
  15. const assertAdmin = async () => {
  16. const actor = Actor.assert("user")
  17. const user = await User.fromID(actor.properties.userID)
  18. if (user?.role !== "admin") {
  19. throw new Error(`Expected admin user, got ${user?.role}`)
  20. }
  21. }
  22. const assertNotSelf = (id: string) => {
  23. const actor = Actor.assert("user")
  24. if (actor.properties.userID === id) {
  25. throw new Error(`Expected not self actor, got self actor`)
  26. }
  27. }
  28. export const list = fn(z.void(), () =>
  29. Database.use((tx) =>
  30. tx
  31. .select({
  32. ...getTableColumns(UserTable),
  33. accountEmail: AccountTable.email,
  34. })
  35. .from(UserTable)
  36. .leftJoin(AccountTable, eq(UserTable.accountID, AccountTable.id))
  37. .where(and(eq(UserTable.workspaceID, Actor.workspace()), isNull(UserTable.timeDeleted))),
  38. ),
  39. )
  40. export const fromID = fn(z.string(), (id) =>
  41. Database.use((tx) =>
  42. tx
  43. .select()
  44. .from(UserTable)
  45. .where(and(eq(UserTable.workspaceID, Actor.workspace()), eq(UserTable.id, id), isNull(UserTable.timeDeleted)))
  46. .then((rows) => rows[0]),
  47. ),
  48. )
  49. export const getAccountEmail = fn(z.string(), (id) =>
  50. Database.use((tx) =>
  51. tx
  52. .select({
  53. email: AccountTable.email,
  54. })
  55. .from(UserTable)
  56. .leftJoin(AccountTable, eq(UserTable.accountID, AccountTable.id))
  57. .where(and(eq(UserTable.workspaceID, Actor.workspace()), eq(UserTable.id, id)))
  58. .then((rows) => rows[0]?.email),
  59. ),
  60. )
  61. export const invite = fn(
  62. z.object({
  63. email: z.string(),
  64. role: z.enum(UserRole),
  65. }),
  66. async ({ email, role }) => {
  67. await assertAdmin()
  68. const workspaceID = Actor.workspace()
  69. // create user
  70. const account = await Account.fromEmail(email)
  71. await Database.use((tx) =>
  72. tx
  73. .insert(UserTable)
  74. .values({
  75. id: Identifier.create("user"),
  76. name: "",
  77. ...(account
  78. ? {
  79. accountID: account.id,
  80. }
  81. : {
  82. email,
  83. }),
  84. workspaceID,
  85. role,
  86. })
  87. .onDuplicateKeyUpdate({
  88. set: {
  89. role,
  90. timeDeleted: null,
  91. },
  92. }),
  93. )
  94. // create api key
  95. //if (account) {
  96. // const existing = await Database.use(tx => {
  97. // const key = tx.select().from(KeyTable).where(and(eq(KeyTable.workspaceID, workspaceID), eq(KeyTable, account.id))).then((rows) => rows[0])
  98. // return key
  99. // })
  100. //}
  101. // send email, ignore errors
  102. try {
  103. const { InviteEmail } = await import("@opencode/console-mail/InviteEmail.jsx")
  104. await AWS.sendEmail({
  105. to: email,
  106. subject: `You've been invited to join the ${workspaceID} workspace on OpenCode Zen`,
  107. body: render(
  108. // @ts-ignore
  109. InviteEmail({
  110. assetsUrl: `https://opencode.ai/email`,
  111. workspace: workspaceID,
  112. }),
  113. ),
  114. })
  115. } catch (e) {
  116. console.error(e)
  117. }
  118. },
  119. )
  120. export const joinInvitedWorkspaces = fn(z.void(), async () => {
  121. const account = Actor.assert("account")
  122. const invitations = await Database.use(async (tx) => {
  123. const invitations = await tx
  124. .select({
  125. id: UserTable.id,
  126. workspaceID: UserTable.workspaceID,
  127. })
  128. .from(UserTable)
  129. .where(eq(UserTable.email, account.properties.email))
  130. await tx
  131. .update(UserTable)
  132. .set({
  133. accountID: account.properties.accountID,
  134. email: null,
  135. })
  136. .where(eq(UserTable.email, account.properties.email))
  137. return invitations
  138. })
  139. await Promise.all(
  140. invitations.map((invite) =>
  141. Actor.provide(
  142. "user",
  143. {
  144. workspaceID: invite.workspaceID,
  145. userID: invite.id,
  146. },
  147. () => Key.create({ name: "Default API Key" }),
  148. ),
  149. ),
  150. )
  151. return invitations.length
  152. })
  153. export const updateRole = fn(
  154. z.object({
  155. id: z.string(),
  156. role: z.enum(UserRole),
  157. }),
  158. async ({ id, role }) => {
  159. await assertAdmin()
  160. if (role === "member") assertNotSelf(id)
  161. return await Database.use((tx) =>
  162. tx
  163. .update(UserTable)
  164. .set({ role })
  165. .where(and(eq(UserTable.id, id), eq(UserTable.workspaceID, Actor.workspace()))),
  166. )
  167. },
  168. )
  169. export const remove = fn(z.string(), async (id) => {
  170. await assertAdmin()
  171. assertNotSelf(id)
  172. return await Database.use((tx) =>
  173. tx
  174. .update(UserTable)
  175. .set({
  176. timeDeleted: sql`now()`,
  177. })
  178. .where(and(eq(UserTable.id, id), eq(UserTable.workspaceID, Actor.workspace()))),
  179. )
  180. })
  181. }