setup-node/src/authutil.ts
Danny McCormick 78148dae50
Add auth support (#21)
* Updates

* Update

* Update

* Update

* Update

* Yarn sometimes prefers npmrc, so use same token

* Description

* Update readme

* Feedback

* Add type

* new toolkit and scoped registries

* npmrc in RUNNER_TEMP

* Dont always auth

* Try exporting blank token

* Get auth working for now pending runner changes

* Fix string interpolation for auth token.

* Don't export both userconfigs

* Update authutil.js

* Add single quotes for authString

* Fix the registry string.

* Use userconfig and append trailing slash

* Keep in root of repo

* Try just adding auth token

* Remove auth token

* Try changes again

* Add tests

* Npm and GPR samples

* Add types
2019-08-06 18:26:04 -04:00

51 lines
1.7 KiB
TypeScript

import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as core from '@actions/core';
import * as github from '@actions/github';
export function configAuthentication(registryUrl: string) {
const npmrc: string = path.resolve(
process.env['RUNNER_TEMP'] || process.cwd(),
'.npmrc'
);
if (!registryUrl.endsWith('/')) {
registryUrl += '/';
}
writeRegistryToFile(registryUrl, npmrc);
}
function writeRegistryToFile(registryUrl: string, fileLocation: string) {
let scope: string = core.getInput('scope');
if (!scope && registryUrl.indexOf('npm.pkg.github.com') > -1) {
scope = github.context.repo.owner;
}
if (scope && scope[0] != '@') {
scope = '@' + scope;
}
core.debug(`Setting auth in ${fileLocation}`);
let newContents: string = '';
if (fs.existsSync(fileLocation)) {
const curContents: string = fs.readFileSync(fileLocation, 'utf8');
curContents.split(os.EOL).forEach((line: string) => {
// Add current contents unless they are setting the registry
if (!line.toLowerCase().startsWith('registry')) {
newContents += line + os.EOL;
}
});
}
// Remove http: or https: from front of registry.
const authString: string =
registryUrl.replace(/(^\w+:|^)/, '') + ':_authToken=${NODE_AUTH_TOKEN}';
const registryString: string = scope
? `${scope}:registry=${registryUrl}`
: `registry=${registryUrl}`;
newContents += `${authString}${os.EOL}${registryString}`;
fs.writeFileSync(fileLocation, newContents);
core.exportVariable('NPM_CONFIG_USERCONFIG', fileLocation);
// Export empty node_auth_token so npm doesn't complain about not being able to find it
core.exportVariable('NODE_AUTH_TOKEN', 'XXXXX-XXXXX-XXXXX-XXXXX');
}