UNPKG

3.09 kBJavaScriptView Raw
1'use strict';
2
3const BbPromise = require('bluebird');
4const path = require('path');
5const fse = require('fs-extra');
6
7class OpenWhiskConfigCredentials {
8 constructor(serverless, options) {
9 this.serverless = serverless;
10 this.options = options;
11 // Note: we're not setting the provider here as this plugin should also be
12 // run when the CWD is not an AWS service
13
14 // this will be merged with the core config commands
15 this.commands = {
16 config: {
17 commands: {
18 credentials: {
19 lifecycleEvents: [
20 'config',
21 ],
22 options: {
23 apihost: {
24 usage: 'OpenWhisk platform API hostname.',
25 shortcut: 'h',
26 required: true,
27 },
28 auth: {
29 usage: 'User authentication credentials for the provider',
30 shortcut: 'a',
31 required: true,
32 }
33 },
34 },
35 },
36 },
37 };
38
39 this.hooks = {
40 'config:credentials:config': () => BbPromise.bind(this)
41 .then(this.configureCredentials),
42 };
43 }
44
45 configureCredentials() {
46 // sanitize
47 this.options.provider = this.options.provider.toLowerCase();
48 this.options.profile = this.options.profile ? this.options.profile : 'default';
49
50 // resolve if provider option is not 'aws'
51 if (this.options.provider !== 'openwhisk') {
52 return BbPromise.resolve();
53 }
54
55 // validate
56 if (!this.options.apihost || !this.options.auth) {
57 throw new this.serverless.classes.Error('Please include --auth and --apihost options for Apache OpenwWhisk.');
58 }
59
60 this.serverless.cli.log('Setting up Apache OpenWhisk...');
61 this.serverless.cli.log('Saving your credentials in "~/.wskprops"...');
62
63 // locate home directory on user's machine
64 const env = process.env;
65 const home = env.HOME ||
66 env.USERPROFILE ||
67 (env.HOMEPATH ? ((env.HOMEDRIVE || 'C:/') + env.HOMEPATH) : null);
68
69 if (!home) {
70 throw new this.serverless.classes
71 .Error('Can\'t find home directory on your local file system.');
72 }
73
74 // check if ~/.wskprops exists
75 const credsPath = path.join(home, '.wskprops');
76
77 if (this.serverless.utils.fileExistsSync(credsPath)) {
78 // check if credentials files contains anything
79 const credsFile = this.serverless.utils.readFileSync(credsPath);
80
81 // if credentials file exists w/ auth, exit
82 if (credsFile.length && credsFile.indexOf(`AUTH`) > -1) {
83 this.serverless.cli.log(
84 `Failed! ~/.wskprops exists and already has credentials.`);
85 return BbPromise.resolve();
86 }
87 }
88
89 // write credentials file with 'default' profile
90 this.serverless.utils.writeFile(
91 credsPath,
92 `APIHOST=${this.options.apihost}
93AUTH=${this.options.auth}`);
94
95 this.serverless.cli.log(
96 'Success! Your Apache OpenWhisk credentials were stored in the configuration file (~/.wskprops).'
97 );
98
99 return BbPromise.resolve();
100 }
101}
102
103module.exports = OpenWhiskConfigCredentials;