Skip to content
This repository was archived by the owner on May 6, 2025. It is now read-only.

Commit 54f8b4a

Browse files
committed
optimize cli auth process and use new local store method
1 parent 979fdef commit 54f8b4a

32 files changed

Lines changed: 466 additions & 364 deletions

lib/commands/functions/index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ function getFunctionContext(name, envId, configPath) {
3333
const cloudBaseConfig = yield utils_1.resolveCloudBaseConfig(configPath);
3434
const assignEnvId = envId || cloudBaseConfig.envId;
3535
if (!assignEnvId) {
36-
throw new error_1.CloudBaseError('未识别到有效的环境 Id 变量,请在项目根目录进行操作或通过 envId 参数指定环境 Id');
36+
throw new error_1.CloudBaseError('未识别到有效的环境 Id 变量,请在项目根目录进行操作或通过 -e 参数指定环境 Id');
3737
}
3838
let { functions = [] } = cloudBaseConfig;
3939
const ctx = {

lib/commands/gateway/create.js

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
88
step((generator = generator.apply(thisArg, _arguments || [])).next());
99
});
1010
};
11+
var __importDefault = (this && this.__importDefault) || function (mod) {
12+
return (mod && mod.__esModule) ? mod : { "default": mod };
13+
};
1114
Object.defineProperty(exports, "__esModule", { value: true });
15+
const chalk_1 = __importDefault(require("chalk"));
1216
const error_1 = require("../../error");
1317
const gateway_1 = require("../../gateway");
1418
const function_1 = require("../../function");
@@ -17,12 +21,12 @@ function createGw(ctx, servicePath, commandOptions) {
1721
return __awaiter(this, void 0, void 0, function* () {
1822
const { envId } = ctx;
1923
if (!servicePath) {
20-
throw new error_1.CloudBaseError('请指定需要创建的HTTP service路径!');
24+
throw new error_1.CloudBaseError('请指定需要创建的 HTTP service 路径!');
2125
}
2226
const { function: functionName } = commandOptions;
2327
if (functionName) {
2428
const loading = utils_1.loadingFactory();
25-
loading.start(`[${functionName}] 云函数HTTP service创建中...`);
29+
loading.start(`[${functionName}] 云函数 HTTP service 创建中...`);
2630
try {
2731
const functionList = yield function_1.listFunction({
2832
envId,
@@ -37,15 +41,16 @@ function createGw(ctx, servicePath, commandOptions) {
3741
path: servicePath,
3842
functionName
3943
});
40-
loading.succeed(`云函数HTTP service [path: ${envId}.service.tcloudbase.com${servicePath}] [id: ${res.APIId}] 创建成功!`);
44+
const endpoint = `https://${envId}.service.tcloudbase.com${servicePath}`;
45+
loading.succeed(`云函数 HTTP service 创建成功!\n${chalk_1.default.bold.underline(endpoint)}`);
4146
}
4247
catch (e) {
4348
loading.stop();
4449
throw e;
4550
}
4651
return;
4752
}
48-
throw new error_1.CloudBaseError('请指定需要创建的HTTP service类型!');
53+
throw new error_1.CloudBaseError('请指定需要创建的 HTTP service 类型!');
4954
});
5055
}
5156
exports.createGw = createGw;

lib/commands/gateway/delete.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,10 @@ function deleteGw(ctx, commandOptions) {
1717
const { envId } = ctx;
1818
const { servicePath, serviceId } = commandOptions;
1919
if (!servicePath && !serviceId) {
20-
throw new error_1.CloudBaseError('请指定需要删除的HTTP Service路径或ID!');
20+
throw new error_1.CloudBaseError('请指定需要删除的 HTTP Service 路径或 ID!');
2121
}
2222
const loading = utils_1.loadingFactory();
23-
loading.start(`[${servicePath || serviceId}] HTTP Service删除中...`);
23+
loading.start(`[${servicePath || serviceId}] HTTP Service 删除中...`);
2424
try {
2525
yield gateway_1.deleteGateway({
2626
envId,

lib/commands/gateway/index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ function getGatewayContext(envId, configPath) {
2626
const cloudBaseConfig = yield utils_1.resolveCloudBaseConfig(configPath);
2727
const assignEnvId = envId || cloudBaseConfig.envId;
2828
if (!assignEnvId) {
29-
throw new error_1.CloudBaseError('未识别到有效的环境 Id 变量,请在项目根目录进行操作或通过 envId 参数指定环境 Id');
29+
throw new error_1.CloudBaseError('未识别到有效的环境 Id 变量,请在项目根目录进行操作或通过 -e 参数指定环境 Id');
3030
}
3131
const ctx = {
3232
envId: assignEnvId,

lib/utils/auth.js

Lines changed: 47 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
1313
};
1414
Object.defineProperty(exports, "__esModule", { value: true });
1515
const os_1 = __importDefault(require("os"));
16+
const fs_1 = __importDefault(require("fs"));
17+
const path_1 = __importDefault(require("path"));
1618
const http_1 = __importDefault(require("http"));
1719
const crypto_1 = __importDefault(require("crypto"));
1820
const portfinder_1 = __importDefault(require("portfinder"));
@@ -26,7 +28,9 @@ const constant_1 = require("../constant");
2628
const logger_1 = __importDefault(require("../logger"));
2729
const utils_1 = require("../utils");
2830
const error_1 = require("../error");
31+
const cloud_api_request_1 = require("./cloud-api-request");
2932
const logger = new logger_1.default('Auth');
33+
const tcbService = new cloud_api_request_1.CloudApiService('tcb');
3034
const defaultPort = 9012;
3135
const CliAuthBaseUrl = 'https://console.cloud.tencent.com/tcb/auth';
3236
const refreshTokenUrl = 'https://iaas.cloud.tencent.com/tcb_refresh';
@@ -136,6 +140,30 @@ function createLocalServer() {
136140
});
137141
});
138142
}
143+
function respondWithFile(req, res, statusCode, filename) {
144+
return new Promise(function (resolve, reject) {
145+
fs_1.default.readFile(path_1.default.join(__dirname, '../../templates', filename), function (err, response) {
146+
if (err) {
147+
return reject(err);
148+
}
149+
res.writeHead(statusCode, {
150+
'Content-Length': response.length,
151+
'Content-Type': 'text/html'
152+
});
153+
res.end(response);
154+
req.socket.destroy();
155+
return resolve();
156+
});
157+
});
158+
}
159+
function checkAuth(credential) {
160+
return __awaiter(this, void 0, void 0, function* () {
161+
const { tmpSecretId, tmpSecretKey, tmpToken } = credential;
162+
tcbService.setCredential(tmpSecretId, tmpSecretKey, tmpToken);
163+
return tcbService.request('DescribeEnvs');
164+
});
165+
}
166+
exports.checkAuth = checkAuth;
139167
function getAuthTokenFromWeb(options) {
140168
return __awaiter(this, void 0, void 0, function* () {
141169
const { getAuthUrl } = options;
@@ -161,16 +189,32 @@ function getAuthTokenFromWeb(options) {
161189
loading.succeed('已打开云开发 CLI 授权页面,请在云开发 CLI 授权页面同意授权!');
162190
return new Promise(resolve => {
163191
server.on('request', (req, res) => {
164-
var _a;
192+
var _a, _b;
165193
const { url } = req;
166194
const { query } = query_string_1.default.parseUrl(url);
195+
if ((_a = query) === null || _a === void 0 ? void 0 : _a.html) {
196+
return checkAuth(query)
197+
.then(() => {
198+
return respondWithFile(req, res, 200, 'html/loginSuccess.html');
199+
})
200+
.then(() => {
201+
server.close();
202+
resolve(query);
203+
})
204+
.catch(e => {
205+
server.close();
206+
return respondWithFile(req, res, 502, 'html/loginFail.html');
207+
});
208+
}
167209
res.writeHead(200, {
168210
'Access-Control-Allow-Origin': '*',
211+
'Access-Control-Allow-Methods': '*',
212+
'Access-Control-Allow-Headers': '*',
169213
'Content-Type': 'text/plain',
170214
Connection: 'close'
171215
});
172-
res.end('ok');
173-
if ((_a = query) === null || _a === void 0 ? void 0 : _a.tmpToken) {
216+
res.end();
217+
if ((_b = query) === null || _b === void 0 ? void 0 : _b.tmpToken) {
174218
server.close();
175219
}
176220
resolve(query);

lib/utils/check-auth.js

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
1212
const auth_1 = require("./auth");
1313
const store_1 = require("./store");
1414
const constant_1 = require("../constant");
15-
const cloud_api_request_1 = require("./cloud-api-request");
16-
const tcbService = new cloud_api_request_1.CloudApiService('tcb');
17-
function checkAuth(secretId, secretKey, token) {
18-
return __awaiter(this, void 0, void 0, function* () {
19-
tcbService.setCredential(secretId, secretKey, token);
20-
return tcbService.request('DescribeEnvs');
21-
});
22-
}
2315
function checkAndGetCredential() {
2416
return __awaiter(this, void 0, void 0, function* () {
2517
const credential = auth_1.getCredentialData();
@@ -28,7 +20,10 @@ function checkAndGetCredential() {
2820
}
2921
if (credential.secretId && credential.secretKey) {
3022
const { secretId, secretKey } = credential;
31-
yield checkAuth(secretId, secretKey);
23+
yield auth_1.checkAuth({
24+
tmpSecretId: secretId,
25+
tmpSecretKey: secretKey
26+
});
3227
return {
3328
secretId,
3429
secretKey
@@ -37,7 +32,7 @@ function checkAndGetCredential() {
3732
if (credential.refreshToken) {
3833
if (Date.now() < Number(credential.tmpExpired)) {
3934
const { tmpSecretId, tmpSecretKey, tmpToken } = credential;
40-
yield checkAuth(tmpSecretId, tmpSecretKey, tmpToken);
35+
yield auth_1.checkAuth(credential);
4136
return {
4237
secretId: tmpSecretId,
4338
secretKey: tmpSecretKey,
@@ -59,7 +54,7 @@ function checkAndGetCredential() {
5954
}
6055
store_1.authStore.set(constant_1.ConfigItems.credentail, refreshCredential || {});
6156
const { tmpSecretId, tmpSecretKey, tmpToken } = refreshCredential;
62-
yield checkAuth(tmpSecretId, tmpSecretKey, tmpToken);
57+
yield auth_1.checkAuth(refreshCredential);
6358
return {
6459
secretId: tmpSecretId,
6560
secretKey: tmpSecretKey,

lib/utils/cloud-api-request.js

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -82,19 +82,19 @@ class CloudApiService {
8282
}
8383
}
8484
request(action, data = {}, method = 'POST') {
85+
var _a;
8586
return __awaiter(this, void 0, void 0, function* () {
8687
this.action = action;
8788
this.data = deepRemoveVoid(Object.assign(Object.assign({}, data), this.baseParams));
8889
this.method = method;
8990
this.url = this.baseUrl;
90-
const credential = yield auth_1.getCredentialWithoutCheck();
91-
if (!credential) {
92-
throw new error_1.CloudBaseError('无有效身份信息,请使用 cloudbase login 登录');
91+
if (!((_a = this.credential) === null || _a === void 0 ? void 0 : _a.secretId)) {
92+
const credential = yield auth_1.getCredentialWithoutCheck();
93+
if (!credential) {
94+
throw new error_1.CloudBaseError('无有效身份信息,请使用 cloudbase login 登录');
95+
}
96+
this.credential = credential;
9397
}
94-
const { secretId, secretKey, token } = credential;
95-
this.secretId = secretId;
96-
this.secretKey = secretKey;
97-
this.token = token;
9898
try {
9999
const data = yield this.requestWithSign();
100100
if (data.Response.Error) {
@@ -117,6 +117,7 @@ class CloudApiService {
117117
});
118118
}
119119
requestWithSign() {
120+
var _a, _b;
120121
return __awaiter(this, void 0, void 0, function* () {
121122
const timestamp = Math.floor(Date.now() / 1000);
122123
const { method, timeout, data = {} } = this;
@@ -137,8 +138,8 @@ class CloudApiService {
137138
'X-TC-Version': this.version
138139
}
139140
};
140-
if (this.token) {
141-
config.headers['X-TC-Token'] = this.token;
141+
if ((_a = this.credential) === null || _a === void 0 ? void 0 : _a.token) {
142+
config.headers['X-TC-Token'] = (_b = this.credential) === null || _b === void 0 ? void 0 : _b.token;
142143
}
143144
if (method === 'GET') {
144145
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
@@ -153,7 +154,8 @@ class CloudApiService {
153154
});
154155
}
155156
getRequestSign(timestamp) {
156-
const { method = 'POST', url, service, secretId, secretKey } = this;
157+
const { method = 'POST', url, service } = this;
158+
const { secretId, secretKey } = this.credential;
157159
const urlObj = new url_1.URL(url);
158160
let headers = '';
159161
const signedHeaders = 'content-type;host';
@@ -177,9 +179,11 @@ class CloudApiService {
177179
return `TC3-HMAC-SHA256 Credential=${secretId}/${date}/${service}/tc3_request, SignedHeaders=${signedHeaders}, Signature=${signature}`;
178180
}
179181
setCredential(secretId, secretKey, token) {
180-
this.secretId = secretId;
181-
this.secretKey = secretKey;
182-
this.token = token;
182+
this.credential = {
183+
secretId,
184+
secretKey,
185+
token
186+
};
183187
}
184188
}
185189
exports.CloudApiService = CloudApiService;

lib/utils/cloudbase-config.js

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ var __importStar = (this && this.__importStar) || function (mod) {
2121
Object.defineProperty(exports, "__esModule", { value: true });
2222
const fs_1 = __importDefault(require("fs"));
2323
const path_1 = __importDefault(require("path"));
24-
const store_1 = require("./store");
2524
const error_1 = require("../error");
2625
const DefaultFunctionDeployOptions = {
2726
config: {
@@ -34,10 +33,6 @@ const DefaultCloudBaseConfig = {
3433
functionRoot: './functions',
3534
functions: []
3635
};
37-
function getCloudBaseConfig() {
38-
return store_1.authStore.all();
39-
}
40-
exports.getCloudBaseConfig = getCloudBaseConfig;
4136
function resolveCloudBaseConfig(configPath = '') {
4237
return __awaiter(this, void 0, void 0, function* () {
4338
const tcbrcPath = path_1.default.resolve('tcbrc.json');
@@ -72,7 +67,7 @@ function getEnvId(envId, configPath) {
7267
const cloudbaseConfig = yield resolveCloudBaseConfig(configPath);
7368
const assignEnvId = envId || cloudbaseConfig.envId;
7469
if (!assignEnvId) {
75-
throw new error_1.CloudBaseError('未识别到有效的环境 Id 变量,请在项目根目录进行操作或通过 envId 参数指定环境 Id');
70+
throw new error_1.CloudBaseError('未识别到有效的环境 Id 变量,请在项目根目录进行操作或通过 -e 参数指定环境 Id');
7671
}
7772
return assignEnvId;
7873
});

lib/utils/store/db.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
"use strict";
2+
var __importDefault = (this && this.__importDefault) || function (mod) {
3+
return (mod && mod.__esModule) ? mod : { "default": mod };
4+
};
5+
Object.defineProperty(exports, "__esModule", { value: true });
6+
const os_1 = __importDefault(require("os"));
7+
const lowdb_1 = __importDefault(require("lowdb"));
8+
const path_1 = __importDefault(require("path"));
9+
const FileSync_1 = __importDefault(require("lowdb/adapters/FileSync"));
10+
const xdg_basedir_1 = __importDefault(require("xdg-basedir"));
11+
const configDir = xdg_basedir_1.default.config || path_1.default.join(os_1.default.tmpdir(), '.config');
12+
const cloudbaseConfigDir = path_1.default.join(configDir, '.cloudbase');
13+
function getAuthDB() {
14+
const dbPath = path_1.default.join(cloudbaseConfigDir, 'auth.json');
15+
const adapter = new FileSync_1.default(dbPath);
16+
const db = lowdb_1.default(adapter);
17+
return db;
18+
}
19+
exports.getAuthDB = getAuthDB;

lib/utils/store/index.js

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,30 +6,33 @@ Object.defineProperty(exports, "__esModule", { value: true });
66
const os_1 = __importDefault(require("os"));
77
const fs_1 = __importDefault(require("fs"));
88
const path_1 = __importDefault(require("path"));
9-
const local_store_1 = require("./local-store");
9+
const db_1 = require("./db");
1010
const constant_1 = require("../../constant");
11-
const ConfigDefaultItems = [constant_1.ConfigItems.credentail];
12-
class AuthStore extends local_store_1.LocalStore {
13-
constructor(name, defaults) {
14-
super(name, defaults);
11+
class AuthStore {
12+
constructor(defaults) {
13+
this.defaults = defaults;
14+
this.db = db_1.getAuthDB();
15+
this.db.defaults(defaults);
1516
this.moveOldConfig();
1617
}
1718
get(item) {
18-
if (ConfigDefaultItems.includes(item)) {
19-
return super.get(item) || {};
20-
}
21-
else {
22-
return super.get(item);
23-
}
19+
const defaultValue = this.defaults[item];
20+
return this.db.get(item).value() || defaultValue;
21+
}
22+
set(item, value) {
23+
this.db.set(item, value).write();
24+
}
25+
delete(item) {
26+
this.db.unset(item).write();
2427
}
2528
moveOldConfig() {
2629
const oldConfigPath = path_1.default.resolve(os_1.default.homedir(), '.config', 'configstore', '@cloudbase', 'cli.json');
2730
if (fs_1.default.existsSync(oldConfigPath)) {
2831
try {
2932
const content = JSON.parse(fs_1.default.readFileSync(oldConfigPath, 'utf8'));
3033
const { credential, ssh } = content;
31-
this.set(constant_1.ConfigItems.credentail, credential);
32-
this.set(constant_1.ConfigItems.ssh, ssh);
34+
this.db.set(constant_1.ConfigItems.credentail, credential).write();
35+
this.db.set(constant_1.ConfigItems.ssh, ssh).write();
3336
fs_1.default.unlinkSync(oldConfigPath);
3437
}
3538
catch (e) {
@@ -38,7 +41,7 @@ class AuthStore extends local_store_1.LocalStore {
3841
}
3942
}
4043
}
41-
exports.authStore = new AuthStore('auth', {
44+
exports.authStore = new AuthStore({
4245
_: '这是您的 CloudBase 身份凭据文件,请不要分享给他人!',
4346
[constant_1.ConfigItems.credentail]: {},
4447
[constant_1.ConfigItems.ssh]: {}

0 commit comments

Comments
 (0)