1 | 'use strict'
|
2 |
|
3 | let cli = require('heroku-cli-util')
|
4 | let co = require('co')
|
5 | let fs = require('fs')
|
6 |
|
7 | function open (url) {
|
8 | cli.log(`Opening ${cli.color.cyan(url)}...`)
|
9 | return cli.open(url)
|
10 | }
|
11 |
|
12 | const ssoPath = '/tmp/heroku-sso.html'
|
13 |
|
14 | function writeSudoTemplate (ctx, sso, path) {
|
15 | return new Promise(function (resolve, reject) {
|
16 | let html = `<!DOCTYPE HTML>
|
17 | <html>
|
18 | <head>
|
19 | <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
20 | <title>Heroku Add-ons SSO</title>
|
21 | <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
|
22 | </head>
|
23 |
|
24 | <body>
|
25 | <h3>Opening ${ctx.args.addon}${ctx.app ? ` on ${ctx.app}` : ''}...</h3>
|
26 | <form method="POST" action="${sso.action}">
|
27 | </form>
|
28 |
|
29 | <script type="text/javascript">
|
30 | var params = ${JSON.stringify(sso.params)}
|
31 | var form = document.forms[0]
|
32 | $(document).ready(function() {
|
33 | $.each(params, function(key, value) {
|
34 | $('<input>').attr({ type: 'hidden', name: key, value: value })
|
35 | .appendTo(form)
|
36 | })
|
37 | form.submit()
|
38 | })
|
39 | </script>
|
40 | </body>
|
41 | </html>`
|
42 | fs.writeFile(path, html, function (err) {
|
43 | if (err) reject(err)
|
44 | else resolve()
|
45 | })
|
46 | })
|
47 | }
|
48 |
|
49 | let sudo = co.wrap(function * (ctx, api) {
|
50 | let sso = yield api.request({
|
51 | method: 'GET',
|
52 | path: `/apps/${ctx.app}/addons/${ctx.args.addon}/sso`,
|
53 | headers: {Accept: 'application/json'}
|
54 | })
|
55 | if (sso.method === 'get') {
|
56 | yield open(sso.action)
|
57 | } else {
|
58 | yield writeSudoTemplate(ctx, sso, ssoPath)
|
59 | yield open(`file://${ssoPath}`)
|
60 | }
|
61 | })
|
62 |
|
63 | function * run (ctx, api) {
|
64 | const resolve = require('../../lib/resolve')
|
65 |
|
66 | if (process.env.HEROKU_SUDO) return sudo(ctx, api)
|
67 |
|
68 | let attachment = yield resolve.attachment(api, ctx.app, ctx.args.addon)
|
69 | .catch(function (err) {
|
70 | if (err.statusCode !== 404) throw err
|
71 | })
|
72 |
|
73 | let webUrl
|
74 | if (attachment) {
|
75 | webUrl = attachment.web_url
|
76 | } else {
|
77 | let addon = yield resolve.addon(api, ctx.app, ctx.args.addon)
|
78 | webUrl = addon.web_url
|
79 | }
|
80 |
|
81 | if (ctx.flags['show-url']) {
|
82 | cli.log(webUrl)
|
83 | } else {
|
84 | yield open(webUrl)
|
85 | }
|
86 | }
|
87 |
|
88 | module.exports = {
|
89 | topic: 'addons',
|
90 | command: 'open',
|
91 | wantsApp: true,
|
92 | needsAuth: true,
|
93 | args: [{name: 'addon'}],
|
94 | flags: [{name: 'show-url', description: 'show URL, do not open browser'}],
|
95 | run: cli.command({preauth: true}, co.wrap(run)),
|
96 | description: "open an add-on's dashboard in your browser"
|
97 | }
|