refactor: extract code related to logging into login function

This commit is contained in:
Levi Yan
2025-03-23 20:31:31 +08:00
parent a55ee0cf90
commit a858f80164
2 changed files with 52 additions and 55 deletions

View File

@@ -2,6 +2,7 @@ import * as vscode from 'vscode';
import * as path from 'path';
import * as os from 'os';
import * as fs from 'fs';
import DevstarAPIHandler from './devstar-api';
const {
generateKeyPairSync,
createHash
@@ -22,7 +23,7 @@ export default class User {
this.userToken = this.context.globalState.get(this.userTokenKey);
// 提取devstar domain的主域名用于本地ssh key的命名
let devstarDomainFromConfig: string|undefined;
let devstarDomainFromConfig: string | undefined;
let devstarDomainURL: string;
devstarDomainFromConfig = vscode.workspace.getConfiguration('devstar').get('devstarDomain')
// 如果没有配置devstar domain则默认domain为https://devstar.cn
@@ -31,6 +32,43 @@ export default class User {
this.devstarHostname = parsedUrl.hostname.replace(/\./g, '_'); //提取hostname并用下划线替换.
}
public async login(token: string, username: string): Promise<string> {
const devstarAPIHandler = new DevstarAPIHandler()
try {
const res = await devstarAPIHandler.verifyToken(token, username)
if (res !== 'ok') {
throw new Error('Token verification failed')
}
// token与用户名验证通过
// 插件登录存储token与用户名
this.setUserTokenToLocal(token)
this.setUsernameToLocal(username)
// 检查本地是否有用户所属公钥,没有则创建
if (!this.existUserPublicKey()) {
await this.createUserSSHKey()
// 上传公钥
const uploadResult = await devstarAPIHandler.uploadUserPublicKey(this)
if (uploadResult !== 'ok') {
throw new Error('Upload user public key failed')
}
}
return 'ok'
} catch (error) {
console.error(error)
return 'login failed'
}
}
public logout() {
this.setUserTokenToLocal("")
this.setUsernameToLocal("")
}
public isLogged() {
var existUsername = false;
var existUserToken = false;