-
Notifications
You must be signed in to change notification settings - Fork 0
/
AuthCommand.ts
65 lines (55 loc) · 2.21 KB
/
AuthCommand.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
import { Command } from '@oclif/core'
import axios from 'axios'
import createDebug from 'debug'
import { CodeGenieConfig, getCodeGenieConfig, updateCodeGenieConfig } from './config'
import { getOpenIdClient } from './openid-client'
const API_ENDPOINT = process.env.API_ENDPOINT || 'https://api.codegenie.codes'
axios.defaults.baseURL = API_ENDPOINT
const debug = createDebug('codegenie:AuthCommand')
debug('API_ENDPOINT %s', API_ENDPOINT)
export abstract class AuthCommand extends Command {
// @ts-expect-error CLI errors out if there's no current config
public codeGenieConfig: CodeGenieConfig
public async init(): Promise<void> {
await super.init()
await this.refreshToken()
axios.defaults.headers.common.Authorization = `Bearer ${this.codeGenieConfig.tokens.idToken}`
debug('Authorization header: %s', axios.defaults.headers.common.Authorization)
}
async refreshToken() {
const debug = createDebug('codegenie:AuthCommand:refreshToken')
const codeGenieConfig = await this.getCurrentConfig()
debug('codeGenieConfig: %O', codeGenieConfig)
const inOneMinute = Date.now() - 60_000
const tokenExpiresInLessThanOneMinute = codeGenieConfig.tokens.expiresAt < inOneMinute
debug({
expiresAt: codeGenieConfig.tokens.expiresAt,
inOneMinute,
tokenExpiresInLessThanOneMinute,
})
if (tokenExpiresInLessThanOneMinute) {
debug('refreshing')
const openIdClient = await getOpenIdClient()
const tokenSet = await openIdClient.refresh(codeGenieConfig.tokens.refreshToken)
codeGenieConfig.tokens = {
...codeGenieConfig.tokens,
idToken: tokenSet.id_token!,
accessToken: tokenSet.access_token!,
expiresAt: tokenSet.expires_at!,
}
debug('codeGenieConfig: %O', codeGenieConfig)
updateCodeGenieConfig(codeGenieConfig)
}
this.codeGenieConfig = codeGenieConfig
}
async getCurrentConfig() {
const codeGenieConfig = getCodeGenieConfig()
if (!codeGenieConfig) {
this.error('Not logged in', {
code: 'NOT_LOGGED_IN',
suggestions: ['Run `npx @codegenie/cli login`', "If you don't have an account yet, first register at https://app.codegenie.codes"],
})
}
return codeGenieConfig
}
}