This repository has been archived by the owner on Apr 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
login.ts
66 lines (56 loc) · 2.22 KB
/
login.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import fetch from 'node-fetch'
import open = require('open')
import sleep = require('sleep-promise')
import {BaseCommand} from '../lib'
import {getEnvironment} from '../lib/environments'
export default class Login extends BaseCommand {
static description = 'Login to Slash GraphQL. Calling this function will keep you logged in for 24 hours, and you will not need to pass access tokens for any backends that you own'
static examples = [
'$ slash-graphql login',
]
static flags = {
...BaseCommand.commonFlags,
}
async run() {
const opts = this.parse(Login)
const {apiServer, authFile} = getEnvironment(opts.flags.environment)
const deviceCodeResponse = await fetch(`${apiServer}/command-line/device-code`, {
method: 'POST',
headers: {'content-type': 'application/json'},
body: JSON.stringify({}),
})
if (deviceCodeResponse.status !== 200) {
this.error('Could not get device code from Auth0')
return
}
const deviceCode = await deviceCodeResponse.json()
open(deviceCode.verification_uri_complete)
this.log('You should see the following code in your browser:', deviceCode.user_code)
const token = await this.pollForToken(apiServer, deviceCode)
if (!token) {
this.error('Was not able to get confirmation in time. Please try logging in again')
return
}
this.writeAuthFile(authFile, token)
this.log('Logged In')
}
async pollForToken(apiServer: string, deviceCode: any): Promise<AuthConfig | undefined> {
// Poll until authorized
const pollTime = deviceCode.expires_in > 300 ? 300 : deviceCode.expires_in
const pollUntil = new Date(new Date().getTime() + (pollTime * 1000))
while (new Date() < pollUntil) {
// eslint-disable-next-line no-await-in-loop
const res = await fetch(`${apiServer}/command-line/access-token`, {
method: 'POST',
headers: {'content-type': 'application/json'},
body: JSON.stringify({deviceCode: deviceCode.device_code}),
})
if (res.status === 200) {
// eslint-disable-next-line no-await-in-loop
return await res.json() as AuthConfig
}
// eslint-disable-next-line no-await-in-loop
await sleep(deviceCode.interval * 1000)
}
}
}