| 103 | }), |
| 104 | subjects, |
| 105 | async success(ctx, response) { |
| 106 | console.log(response) |
| 107 | |
| 108 | let subject: string | undefined |
| 109 | let email: string | undefined |
| 110 | |
| 111 | if (response.provider === "github") { |
| 112 | const emails = (await fetch("https://api.github.com/user/emails", { |
| 113 | headers: { |
| 114 | Authorization: `Bearer ${response.tokenset.access}`, |
| 115 | "User-Agent": "opencode", |
| 116 | Accept: "application/vnd.github+json", |
| 117 | }, |
| 118 | }).then((x) => x.json())) as any |
| 119 | const user = (await fetch("https://api.github.com/user", { |
| 120 | headers: { |
| 121 | Authorization: `Bearer ${response.tokenset.access}`, |
| 122 | "User-Agent": "opencode", |
| 123 | Accept: "application/vnd.github+json", |
| 124 | }, |
| 125 | }).then((x) => x.json())) as any |
| 126 | subject = user.id.toString() |
| 127 | |
| 128 | const primaryEmail = emails.find((x: any) => x.primary) |
| 129 | if (!primaryEmail) throw new Error("No primary email found for GitHub user") |
| 130 | if (!primaryEmail.verified) throw new Error("Primary email for GitHub user not verified") |
| 131 | email = primaryEmail.email |
| 132 | } else if (response.provider === "google") { |
| 133 | if (!response.id.email_verified) throw new Error("Google email not verified") |
| 134 | subject = response.id.sub as string |
| 135 | email = response.id.email as string |
| 136 | } else throw new Error("Unsupported provider") |
| 137 | |
| 138 | if (!email) throw new Error("No email found") |
| 139 | if (!subject) throw new Error("No subject found") |
| 140 | |
| 141 | if (Resource.App.stage !== "production" && !email.endsWith("@anoma.ly")) { |
| 142 | throw new Error("Invalid email") |
| 143 | } |
| 144 | |
| 145 | // Get account |
| 146 | let newAccount = false |
| 147 | const accountID = await (async () => { |
| 148 | const matches = await Database.use(async (tx) => |
| 149 | tx |
| 150 | .select({ |
| 151 | provider: AuthTable.provider, |
| 152 | accountID: AuthTable.accountID, |
| 153 | }) |
| 154 | .from(AuthTable) |
| 155 | .where( |
| 156 | or( |
| 157 | and(eq(AuthTable.provider, response.provider), eq(AuthTable.subject, subject)), |
| 158 | and(eq(AuthTable.provider, "email"), eq(AuthTable.subject, email)), |
| 159 | ), |
| 160 | ), |
| 161 | ) |
| 162 | const idByProvider = matches.find((x) => x.provider === response.provider)?.accountID |