|
| 1 | +import os from 'node:os' |
| 2 | +import {URL} from 'node:url' |
| 3 | +import {createHash} from 'node:crypto' |
| 4 | +import chalk from 'chalk' |
| 5 | +import fetch from 'node-fetch' |
| 6 | +import open from 'open' |
| 7 | +import {randomString, sleep} from './utils.js' |
| 8 | +import {confirm} from './prompt.js' |
| 9 | +import fs from 'node:fs' |
| 10 | +import {webpodLocalConfig} from './env.js' |
| 11 | + |
| 12 | +export async function login() { |
| 13 | + let baseUrl = 'https://app.webpod.dev' |
| 14 | + const localDev = createHash('sha1').update(process.env.WEBPOD_LOCAL_DEV ?? '').digest('hex') |
| 15 | + if (localDev == 'd4f57dba817bd3ddc1101e3498754ed234f08094') { |
| 16 | + baseUrl = 'http://0.0.0.0:8000' |
| 17 | + } |
| 18 | + const resp = await fetch(`${baseUrl}/api/user`, { |
| 19 | + headers: { |
| 20 | + Authorization: `Bearer ${process.env.WEBPOD_TOKEN}`, |
| 21 | + Accept: 'application/json', |
| 22 | + }, |
| 23 | + }) |
| 24 | + if (resp.status == 200) { |
| 25 | + const {id} = await resp.json() as { id: number } |
| 26 | + if (!Number.isFinite(id)) { |
| 27 | + throw new Error('Invalid user id') |
| 28 | + } |
| 29 | + return |
| 30 | + } |
| 31 | + |
| 32 | + const randomCode = [randomString(), randomString(), randomString()].join('-') |
| 33 | + const url = new URL(`${baseUrl}/api-token`) |
| 34 | + url.searchParams.set('code', randomCode) |
| 35 | + url.searchParams.set('hostname', os.hostname()) |
| 36 | + console.log(`Please visit ${chalk.underline(url.href)} to login.`) |
| 37 | + if (await confirm(`Open in browser?`)) { |
| 38 | + await open(url.href) |
| 39 | + } |
| 40 | + |
| 41 | + console.log(chalk.magenta('Waiting for login...')) |
| 42 | + console.log('Alternatively, you can:') |
| 43 | + console.log('- Create API Token: https://app.webpod.dev/user/api-tokens') |
| 44 | + console.log(`- Set the ${chalk.bold('WEBPOD_TOKEN')} environment variable to the token.`) |
| 45 | + |
| 46 | + while (true) { |
| 47 | + await sleep(3000) |
| 48 | + |
| 49 | + const resp = await fetch(`${baseUrl}/api-token/${randomCode}`, { |
| 50 | + headers: { |
| 51 | + Accept: 'application/json', |
| 52 | + }, |
| 53 | + }) |
| 54 | + if (resp.status != 200) { |
| 55 | + continue |
| 56 | + } |
| 57 | + |
| 58 | + const json = await resp.json() as { ok: number, token: string } |
| 59 | + if (!json.ok) { |
| 60 | + continue |
| 61 | + } |
| 62 | + |
| 63 | + fs.appendFileSync(webpodLocalConfig(), `\nglobal.WEBPOD_TOKEN = '${json.token}';\n`) |
| 64 | + process.env.WEBPOD_TOKEN = json.token |
| 65 | + console.log(chalk.green('Login successful!')) |
| 66 | + |
| 67 | + return |
| 68 | + } |
| 69 | +} |
0 commit comments