-
Notifications
You must be signed in to change notification settings - Fork 837
Expand file tree
/
Copy pathauth.ts
More file actions
93 lines (82 loc) · 2.53 KB
/
auth.ts
File metadata and controls
93 lines (82 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { Command } from "interactive-commander";
import Ora from "ora";
import express from "express";
import cors from "cors";
import open from "open";
import readline from "readline/promises";
import { getSettings, saveSettings } from "../utils/settings";
import { createAuthenticator } from "../utils/auth";
export default new Command()
.command("auth")
.description("Authenticate with Lingo.dev API")
.helpOption("-h, --help", "Show help")
.option("--logout", "Delete existing authentication and clear your saved API key.")
.option("--login", "Authenticate with Lingo.dev API.")
.action(async (options) => {
try {
let settings = await getSettings(undefined);
if (options.logout) {
settings.auth.apiKey = "";
await saveSettings(settings);
}
if (options.login) {
const apiKey = await login(settings.auth.webUrl);
settings.auth.apiKey = apiKey;
await saveSettings(settings);
settings = await getSettings(undefined);
}
const authenticator = createAuthenticator({
apiUrl: settings.auth.apiUrl,
apiKey: settings.auth.apiKey!,
});
const auth = await authenticator.whoami();
if (!auth) {
Ora().warn("Not authenticated");
} else {
Ora().succeed(`Authenticated as ${auth.email}`);
}
} catch (error: any) {
Ora().fail(error.message);
process.exit(1);
}
});
export async function login(webAppUrl: string) {
await readline
.createInterface({
input: process.stdin,
output: process.stdout,
})
.question(
`
Press Enter to open the browser for authentication.
---
Having issues? Put LINGODOTDEV_API_KEY in your .env file instead.
`.trim() + "\n",
);
const spinner = Ora().start("Waiting for the API key");
const apiKey = await waitForApiKey(async (port) => {
await open(`${webAppUrl}/app/cli?port=${port}`, { wait: false });
});
spinner.succeed("API key received");
return apiKey;
}
async function waitForApiKey(cb: (port: string) => void): Promise<string> {
// start a sever on an ephemeral port and return the port number
// from the function
const app = express();
app.use(express.json());
app.use(cors());
return new Promise((resolve) => {
const server = app.listen(0, async () => {
const port = (server.address() as any).port;
cb(port.toString());
});
app.post("/", (req, res) => {
const apiKey = req.body.apiKey;
res.end();
server.close(() => {
resolve(apiKey);
});
});
});
}