feat: upload user's ssh public key

This commit is contained in:
Levi Yan
2025-03-03 13:20:44 +08:00
parent ef3629c5c4
commit e7bac7991f

60
src/devstar-api.ts Normal file
View File

@@ -0,0 +1,60 @@
import * as os from 'os';
import User from "./user";
import * as utils from './utils';
export default class DevstarAPIHandler {
private user: User;
private devstarDomain: string;
constructor(user: User) {
this.user = user
// 获取domain
const devstarDomainFromUserConfig = utils.getDevstarDomain()
if (undefined == devstarDomainFromUserConfig || "" == devstarDomainFromUserConfig) {
this.devstarDomain = "https://devstar.cn";
} else {
this.devstarDomain = devstarDomainFromUserConfig.endsWith('/') ? devstarDomainFromUserConfig.slice(0, -1) : devstarDomainFromUserConfig;
}
}
// 上传公钥
public async uploadUserPublicKey() {
// 获取机器名称
const machineName = os.hostname();
// 组成公钥名称
const timestamp = Date.now();
const keyTitle = `${this.user.getUsernameFromLocal()}-${machineName}-${timestamp}`
const postData = {
"key": this.user.getUserPublicKey(),
"title": keyTitle
}
const uploadUrl = this.devstarDomain + `/api/v1/user/keys`
// 上传公钥
fetch(uploadUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'token ' + this.user.getUserTokenFromLocal()
},
body: JSON.stringify(postData)
})
.then(response => {
response.json().then(data => {
if (response.ok) {
console.log("Successfully upload new created public key.\n", data)
} else {
throw new Error(`Failed to upload new created public key!\nError: ${data.message}`)
}
})
})
.catch(error => {
console.error(error);
});
}
}