Skip to content

Commit

Permalink
feat: support authorization
Browse files Browse the repository at this point in the history
  • Loading branch information
hyj1991 committed Mar 14, 2018
1 parent b5e2251 commit 6642eaa
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
37 changes: 37 additions & 0 deletions lib/cnpm_config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
'use strict';
const path = require('path');
const fs = require('fs');
const config = {};

function createConfigs() {
let root;
if (process.platform === 'win32') {
root = process.env.USERPROFILE || process.env.APPDATA || process.env.TMP || process.env.TEMP;
} else {
root = process.env.HOME || process.env.TMPDIR || '/tmp';
}
let userConfig = path.join(root, '.cnpmrc');
if (!fs.existsSync(userConfig)) return;
let userConfigContent = fs.readFileSync(userConfig).toString();
let configs = typeof userConfigContent === 'string' && userConfigContent.split('\n');
configs.reduce((pre, next) => {
if (typeof next === 'string') {
let map = next.split('=');
let key = map[0];
let value = map[1];
if (value === 'true') value = true;
if (value === 'false') value = false;
pre[key] = value;
}
return pre;
}, config);

}

createConfigs();

module.exports = {
get(key) {
return config[key];
}
}
10 changes: 10 additions & 0 deletions lib/get.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ const destroy = require('destroy');
const HttpAgent = require('agentkeepalive');
const HttpsAgent = require('agentkeepalive').HttpsAgent;
const utils = require('./utils');
const cnpmConfig = require('./cnpm_config');
const urlParser = require('url');

module.exports = get;

Expand Down Expand Up @@ -41,6 +43,14 @@ function* get(url, options, globalOptions) {
debug('enableProxy: %s', options.proxy);
}
}
// need auth
const registryUrl = cnpmConfig.get('registry');
const registryUri = registryUrl.replace(urlParser.parse(registryUrl).protocol, '');
const authed = url.indexOf(registryUri) != -1;
if (authed || cnpmConfig.get(registryUri + ':always-auth') || cnpmConfig.get('always-auth')) {
const authToken = (`${cnpmConfig.get(registryUri + ':username')}:${Buffer.from(cnpmConfig.get(registryUri + ':_password'), 'base64').toString()}`);
options.headers['Authorization'] = `Basic ${Buffer.from(authToken).toString('base64')}`;
}
const retry = options.retry || options.retry === 0 ? options.retry : MAX_RETRY;
options.retry = undefined;
debug('GET %s with headers: %j', url, options.headers);
Expand Down

0 comments on commit 6642eaa

Please sign in to comment.