-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathgeneric.js
328 lines (269 loc) · 10.4 KB
/
generic.js
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
const inquirer = require("inquirer");
const { Command } = require("commander");
const Client = require("../client");
const { sdkForConsole } = require("../sdks");
const { globalConfig, localConfig } = require("../config");
const { actionRunner, success, parseBool, commandDescriptions, error, parse, hint, log, drawTable, cliConfig } = require("../parser");
const ID = require("../id");
const { questionsLogin, questionsLogout, questionsListFactors, questionsMfaChallenge } = require("../questions");
const { accountUpdateMfaChallenge, accountCreateMfaChallenge, accountGet, accountCreateEmailPasswordSession, accountDeleteSession } = require("./account");
const DEFAULT_ENDPOINT = 'https://cloud.appwrite.io/v1';
const loginCommand = async ({ email, password, endpoint, mfa, code }) => {
const oldCurrent = globalConfig.getCurrentSession();
const configEndpoint = (endpoint ?? globalConfig.getEndpoint()) || DEFAULT_ENDPOINT;
if (globalConfig.getCurrentSession() !== '') {
log('You are currently signed in as ' + globalConfig.getEmail());
if (globalConfig.getSessions().length === 1) {
hint('You can sign in and manage multiple accounts with Appwrite CLI');
}
}
const answers = email && password ? { email, password } : await inquirer.prompt(questionsLogin);
if (!answers.method) {
answers.method = 'login';
}
if (answers.method === 'select') {
const accountId = answers.accountId;
if (!globalConfig.getSessionIds().includes(accountId)) {
throw Error('Session ID not found');
}
globalConfig.setCurrentSession(accountId);
success(`Current account is ${accountId}`);
return;
}
const id = ID.unique();
globalConfig.addSession(id, {});
globalConfig.setCurrentSession(id);
globalConfig.setEndpoint(configEndpoint);
globalConfig.setEmail(answers.email);
let client = await sdkForConsole(false);
let account;
try {
await accountCreateEmailPasswordSession({
email: answers.email,
password: answers.password,
parseOutput: false,
sdk: client
})
client.setCookie(globalConfig.getCookie());
account = await accountGet({
sdk: client,
parseOutput: false
});
} catch (error) {
if (error.response === 'user_more_factors_required') {
const { factor } = mfa ? { factor: mfa } : await inquirer.prompt(questionsListFactors);
const challenge = await accountCreateMfaChallenge({
factor,
parseOutput: false,
sdk: client
});
const { otp } = code ? { otp: code } : await inquirer.prompt(questionsMfaChallenge);
await accountUpdateMfaChallenge({
challengeId: challenge.$id,
otp,
parseOutput: false,
sdk: client
});
account = await accountGet({
sdk: client,
parseOutput: false
});
} else {
globalConfig.removeSession(id);
globalConfig.setCurrentSession(oldCurrent);
if (endpoint !== DEFAULT_ENDPOINT && error.response === 'user_invalid_credentials') {
log('Use the --endpoint option for self-hosted instances')
}
throw error;
}
}
success("Successfully signed in as " + account.email);
hint("Next you can create or link to your project using 'appwrite init project'");
};
const whoami = new Command("whoami")
.description(commandDescriptions['whoami'])
.action(actionRunner(async () => {
if (globalConfig.getEndpoint() === '' || globalConfig.getCookie() === '') {
error("No user is signed in. To sign in, run 'appwrite login'");
return;
}
let client = await sdkForConsole(false);
let account;
try {
account = await accountGet({
sdk: client,
parseOutput: false
});
} catch (error) {
error("No user is signed in. To sign in, run 'appwrite login'");
return;
}
const data = [
{
'ID': account.$id,
'Name': account.name,
'Email': account.email,
'MFA enabled': account.mfa ? 'Yes' : 'No',
'Endpoint': globalConfig.getEndpoint()
}
];
if (cliConfig.json) {
console.log(data);
return;
}
drawTable(data)
}));
const register = new Command("register")
.description(commandDescriptions['register'])
.action(actionRunner(async () => {
log('Visit https://cloud.appwrite.io/register to create an account')
}));
const login = new Command("login")
.description(commandDescriptions['login'])
.option(`--email [email]`, `User email`)
.option(`--password [password]`, `User password`)
.option(`--endpoint [endpoint]`, `Appwrite endpoint for self hosted instances`)
.option(`--mfa [factor]`, `Multi-factor authentication login factor: totp, email, phone or recoveryCode`)
.option(`--code [code]`, `Multi-factor code`)
.configureHelp({
helpWidth: process.stdout.columns || 80
})
.action(actionRunner(loginCommand));
const deleteSession = async (accountId) => {
try {
let client = await sdkForConsole();
await accountDeleteSession({
sessionId: 'current',
parseOutput: false,
sdk: client
})
globalConfig.removeSession(accountId);
} catch (e) {
error('Unable to log out, removing locally saved session information')
}
globalConfig.removeSession(accountId);
}
const logout = new Command("logout")
.description(commandDescriptions['logout'])
.configureHelp({
helpWidth: process.stdout.columns || 80
})
.action(actionRunner(async () => {
const sessions = globalConfig.getSessions();
const current = globalConfig.getCurrentSession();
if (current === '' || !sessions.length) {
log('No active sessions found.');
return;
}
if (sessions.length === 1) {
await deleteSession(current);
success("Logging out");
return;
}
const answers = await inquirer.prompt(questionsLogout);
if (answers.accounts) {
for (let accountId of answers.accounts) {
globalConfig.setCurrentSession(accountId);
await deleteSession(accountId);
}
}
const remainingSessions = globalConfig.getSessions();
if (remainingSessions.length > 0 && remainingSessions.filter(session => session.id === current).length !== 1) {
const accountId = remainingSessions [0].id;
globalConfig.setCurrentSession(accountId);
success(`Current account is ${accountId}`);
}
success("Logging out");
}));
const client = new Command("client")
.description(commandDescriptions['client'])
.configureHelp({
helpWidth: process.stdout.columns || 80
})
.option("-ss, --self-signed <value>", "Configure the CLI to use a self-signed certificate ( true or false )", parseBool)
.option("-e, --endpoint <endpoint>", "Set your Appwrite server endpoint")
.option("-p, --project-id <project-id>", "Set your Appwrite project ID")
.option("-k, --key <key>", "Set your Appwrite server's API key")
.option("-d, --debug", "Print CLI debug information")
.option("-r, --reset", "Reset the CLI configuration")
.action(actionRunner(async ({ selfSigned, endpoint, projectId, key, debug, reset }, command) => {
if (selfSigned == undefined && endpoint == undefined && projectId == undefined && key == undefined && debug == undefined && reset == undefined) {
command.help()
}
if (debug) {
let config = {
endpoint: globalConfig.getEndpoint(),
key: globalConfig.getKey(),
cookie: globalConfig.getCookie(),
selfSigned: globalConfig.getSelfSigned(),
project: localConfig.getProject()
}
parse(config)
}
if (endpoint !== undefined) {
try {
const id = ID.unique();
let url = new URL(endpoint);
if (url.protocol !== "http:" && url.protocol !== "https:") {
throw new Error();
}
let client = new Client().setEndpoint(endpoint);
client.setProject('console');
if (selfSigned || globalConfig.getSelfSigned()) {
client.setSelfSigned(true);
}
let response = await client.call('GET', '/health/version');
if (!response.version) {
throw new Error();
}
globalConfig.setCurrentSession(id);
globalConfig.addSession(id, {});
globalConfig.setEndpoint(endpoint);
} catch (_) {
throw new Error("Invalid endpoint or your Appwrite server is not running as expected.");
}
}
if (key !== undefined) {
globalConfig.setKey(key)
}
if (projectId !== undefined) {
localConfig.setProject(projectId, '');
}
if (selfSigned == true || selfSigned == false) {
globalConfig.setSelfSigned(selfSigned);
}
if (reset !== undefined) {
const sessions = globalConfig.getSessions();
for (let accountId of sessions.map(session => session.id)) {
globalConfig.setCurrentSession(accountId);
await deleteSession(accountId);
}
}
success("Setting client")
}));
const migrate = async () => {
if (!globalConfig.has('endpoint') || !globalConfig.has('cookie')) {
return;
}
const endpoint = globalConfig.get('endpoint');
const cookie = globalConfig.get('cookie');
const id = ID.unique();
const data = {
endpoint,
cookie,
email: 'legacy'
};
globalConfig.addSession(id, data);
globalConfig.setCurrentSession(id);
globalConfig.delete('endpoint');
globalConfig.delete('cookie');
}
module.exports = {
loginCommand,
whoami,
register,
login,
logout,
migrate,
client
};