99 lines
2.8 KiB
TypeScript
99 lines
2.8 KiB
TypeScript
import { program, Command } from '@/program.ts';
|
||
import { getConfig } from '@/module/get-config.ts';
|
||
import inquirer from 'inquirer';
|
||
import { loginInCommand } from '@/module/login/login-by-web.ts';
|
||
import { queryLogin, storage } from '@/module/query.ts';
|
||
|
||
/**
|
||
* 定义login命令,支持 `-u` 和 `-p` 参数来输入用户名和密码
|
||
*/
|
||
const loginCommand = new Command('login')
|
||
.description('Login to the application')
|
||
.option('-u, --username <username>', 'Specify username')
|
||
.option('-p, --password <password>', 'Specify password')
|
||
.option('-f, --force', 'Force login')
|
||
.option('-w, --web', 'Login on the web')
|
||
.action(async (options) => {
|
||
let { username, password } = options;
|
||
if (options.web) {
|
||
await loginInCommand();
|
||
return;
|
||
}
|
||
// 如果没有传递参数,则通过交互式输入
|
||
if (!username || !password) {
|
||
const answers = await inquirer.prompt([
|
||
{
|
||
type: 'input',
|
||
name: 'username',
|
||
message: 'Enter your username:',
|
||
when: () => !username, // 当 username 为空时,提示用户输入
|
||
},
|
||
{
|
||
type: 'password',
|
||
name: 'password',
|
||
message: 'Enter your password:',
|
||
mask: '*', // 隐藏输入的字符
|
||
when: () => !password, // 当 password 为空时,提示用户输入
|
||
},
|
||
]);
|
||
username = answers.username || username;
|
||
password = answers.password || password;
|
||
}
|
||
const token = storage.getItem('token');
|
||
if (token) {
|
||
const res = await showMe(false);
|
||
if (res.code === 200) {
|
||
const data = res.data;
|
||
if (data.username === username) {
|
||
console.log('Already Login For', data.username);
|
||
return;
|
||
}
|
||
}
|
||
}
|
||
|
||
const res = await queryLogin.login({
|
||
username,
|
||
password,
|
||
});
|
||
if (res.code === 200) {
|
||
console.log('welcome', username);
|
||
} else {
|
||
console.log('登录失败', res.message || '');
|
||
}
|
||
});
|
||
|
||
program.addCommand(loginCommand);
|
||
|
||
const showMe = async (show = true) => {
|
||
let me = await queryLogin.getMe();
|
||
if (me.code === 401) {
|
||
me = await queryLogin.getMe();
|
||
}
|
||
if (show) {
|
||
console.log('Me', me.data);
|
||
}
|
||
return me;
|
||
};
|
||
|
||
const switchOrgCommand = new Command('switch').argument('<username>', 'Switch to another organization or username').action(async (username) => {
|
||
const res = await queryLogin.switchUser(username);
|
||
if (res.code === 200) {
|
||
console.log('success switch to', username);
|
||
} else {
|
||
console.log('switch to', username, 'failed', res.message || '');
|
||
}
|
||
});
|
||
|
||
program.addCommand(switchOrgCommand);
|
||
|
||
const command = new Command('me').description('').action(async () => {
|
||
try {
|
||
const res = await showMe(false);
|
||
console.log('me', res?.data);
|
||
} catch (error) {
|
||
console.log('me error', error);
|
||
}
|
||
});
|
||
|
||
program.addCommand(command);
|