|
1 | 1 | import { consola } from 'consola' |
2 | 2 | import { colors } from 'consola/utils' |
3 | | -import { isCancel, select, text } from '@clack/prompts' |
| 3 | +import { isCancel, select, text, password } from '@clack/prompts' |
4 | 4 | import { joinURL } from 'ufo' |
5 | 5 | import { ofetch } from 'ofetch' |
6 | 6 | import { gitInfo } from './git.mjs' |
@@ -47,6 +47,54 @@ export async function selectTeam() { |
47 | 47 | } else { |
48 | 48 | team = teams[0] |
49 | 49 | } |
| 50 | + |
| 51 | + if (!team.cloudflareAccountId) { |
| 52 | + return await linkCloudflareAccount(team) |
| 53 | + } |
| 54 | + return team |
| 55 | +} |
| 56 | + |
| 57 | +export async function linkCloudflareAccount(team, retry = false) { |
| 58 | + if (!retry) { |
| 59 | + const tokenLink = joinURL(NUXT_HUB_URL, `cloudflare-token?name=NuxtHub+Team+${team.name}`) |
| 60 | + consola.info(`You need to link your Cloudflare account to the \`${team.name}\` team.`) |
| 61 | + consola.info(`Create a new Cloudflare API token by following this link:\n\`${encodeURI(tokenLink)}\``) |
| 62 | + } |
| 63 | + let apiToken = await password({ |
| 64 | + message: 'Cloudflare API token' |
| 65 | + }) |
| 66 | + if (isCancel(apiToken)) return null |
| 67 | + |
| 68 | + const cfAccounts = await $api('/cloudflare/accounts', { |
| 69 | + params: { apiToken } |
| 70 | + }).catch(() => { |
| 71 | + consola.error('Couldn\'t list Cloudflare accounts\nPlease check your API Token, make sure to have "Account Settings: Read" permission.') |
| 72 | + return null |
| 73 | + }) |
| 74 | + if (!cfAccounts) return linkCloudflareAccount(team, true) |
| 75 | + |
| 76 | + let accountId |
| 77 | + if (cfAccounts.length > 1) { |
| 78 | + accountId = await select({ |
| 79 | + message: 'Select a Cloudflare account', |
| 80 | + options: cfAccounts |
| 81 | + }) |
| 82 | + } else { |
| 83 | + accountId = cfAccounts[0].id |
| 84 | + } |
| 85 | + if (isCancel(accountId)) return null |
| 86 | + |
| 87 | + const account = await $api(`/teams/${team.slug}/accounts/cloudflare`, { |
| 88 | + method: 'PUT', |
| 89 | + body: { apiToken, accountId } |
| 90 | + }) |
| 91 | + .catch((err) => { |
| 92 | + consola.error(err.data?.message || err.message) |
| 93 | + return null |
| 94 | + }) |
| 95 | + if (!account) return linkCloudflareAccount(team, true) |
| 96 | + consola.success('Cloudflare account linked.') |
| 97 | + |
50 | 98 | return team |
51 | 99 | } |
52 | 100 |
|
|
0 commit comments