-
Notifications
You must be signed in to change notification settings - Fork 6
/
SSHCredentialGuard.ts
83 lines (70 loc) · 2.09 KB
/
SSHCredentialGuard.ts
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
import Helper from "./Helper";
import { credential } from "./types";
import { config, hpcConfigMap } from "../configs/config";
const NodeSSH = require("node-ssh");
const redis = require("redis");
const { promisify } = require("util");
class CredentialManager {
private redis = {
getValue: null,
setValue: null,
delValue: null,
};
private isConnected = false;
async add(key: string, cred: credential) {
await this.connect();
await this.redis.setValue(key, JSON.stringify(cred));
}
async get(key: string): Promise<credential> {
await this.connect();
return JSON.parse(await this.redis.getValue(key));
}
private async connect() {
if (this.isConnected) return;
var client = new redis.createClient({
host: config.redis.host,
port: config.redis.port,
});
if (config.redis.password != null && config.redis.password != undefined) {
var redisAuth = promisify(client.auth).bind(client);
await redisAuth(config.redis.password);
}
this.redis.getValue = promisify(client.get).bind(client);
this.redis.setValue = promisify(client.set).bind(client);
this.redis.delValue = promisify(client.del).bind(client);
this.isConnected = true;
}
}
class SSHCredentialGuard {
private credentialManager = new CredentialManager();
private ssh = new NodeSSH();
async validatePrivateAccount(
hpcName: string,
user: string,
password: string
): Promise<void> {
const hpc = hpcConfigMap[hpcName];
try {
await this.ssh.connect({
host: hpc.ip,
port: hpc.port,
user: user,
password: password,
});
await this.ssh.dispose();
} catch (e) {
throw new Error(`unable to check credentials with ${hpcName}`);
}
}
async registerCredential(user: string, password: string): Promise<string> {
const credentialId = Helper.generateId();
this.credentialManager.add(credentialId, {
id: credentialId,
user: user,
password: password,
});
return credentialId;
}
}
export default SSHCredentialGuard;
export { CredentialManager, SSHCredentialGuard };