Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Add AuthenticationProvider implementing OAuth2 code flow #256

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
845 changes: 40 additions & 805 deletions client/package-lock.json

Large diffs are not rendered by default.

7 changes: 5 additions & 2 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
},
"license": "SEE LICENSE IN LICENSE",
"engines": {
"vscode": "^1.37.0"
"vscode": "^1.54.0"
},
"scripts": {
"test": "echo \"No tests in client yet!\""
Expand All @@ -21,9 +21,12 @@
"axios": "^0.21.1",
"copy-paste": "^1.3.0",
"lodash": "^4.17.20",
"vscode-languageclient": "6.0.0-next.1"
"uuid": "^8.3.2",
"vscode-languageclient": "6.0.0-next.1",
"yaml-js": "^0.2.3"
},
"devDependencies": {
"@types/uuid": "^8.3.0",
"@types/vscode": "^1.14.0"
}
}
149 changes: 149 additions & 0 deletions client/src/AuthenticationProvider/AuthenticationProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
import * as vscode from 'vscode';
import {
authentication,
AuthenticationProvider,
AuthenticationProviderAuthenticationSessionsChangeEvent,
AuthenticationSession,
Event,
EventEmitter
} from 'vscode'
import { v4 as uuid } from 'uuid';
import {
getHost,
PromiseAdapter,
promiseFromEvent
} from '../Utils/Utils';
import axios, { AxiosRequestConfig } from 'axios';

function parseQuery(uri: vscode.Uri) {
return uri.query.split('&').reduce((prev: any, current) => {
const queryString = current.split('=');
prev[queryString[0]] = queryString[1];
return prev;
}, {});
}


class UriEventHandler extends vscode.EventEmitter<vscode.Uri> implements vscode.UriHandler {
public handleUri(uri: vscode.Uri) {
this.fire(uri);
}
}

export const uriHandler = new UriEventHandler;

export class OHAuthenticationProvider implements AuthenticationProvider {
private _emitter = new EventEmitter<AuthenticationProviderAuthenticationSessionsChangeEvent>()
private context: vscode.ExtensionContext
private _pendingStates = new Map<string[], string[]>();

constructor(context: vscode.ExtensionContext) {
this.context = context
}

onDidChangeSessions: Event<AuthenticationProviderAuthenticationSessionsChangeEvent> = this._emitter.event

public async getSessions(scopes?: string[]): Promise<readonly AuthenticationSession[]> {
const refreshToken = await this.context.secrets.get('openhab.refreshToken')
const clientId = await this.context.secrets.get('openhab.clientId')
const host = getHost()
if (clientId && refreshToken) {
try {
const tokenUrl = `${host}/rest/auth/token`
let config: AxiosRequestConfig = {
url: host + '/rest/auth/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: `grant_type=refresh_token&client_id=${encodeURIComponent(clientId.replace('?', '%3F'))}&redirect_uri=${encodeURIComponent(clientId.replace('?', '%3F'))}&refresh_token=${refreshToken}`
}

const result = await axios(config)
console.info('Token refresh success!')

return Promise.resolve([{
id: host,
account: {
label: 'openHAB',
id: host
},
scopes: ['admin'],
accessToken: result.data.access_token
}])
} catch (err) {
console.warn('Error while refreshing the session: ' + err)
await this.context.secrets.delete('openhab.refreshToken')
await this.context.secrets.delete('openhab.clientId')
return Promise.resolve([])
}
} else {
return Promise.resolve([])
}
}

public async createSession(scopes: string[]): Promise<AuthenticationSession> {
const callbackUri = await vscode.env.asExternalUri(vscode.Uri.parse(`${vscode.env.uriScheme}://openhab.openhab/auth`))
const host = getHost()

const state = uuid();
const existingStates = this._pendingStates.get(scopes) || [];
this._pendingStates.set(scopes, [...existingStates, state]);

const uri = vscode.Uri.parse(`${host}/auth?response_type=code&client_id=${encodeURIComponent(callbackUri.toString())}&redirect_uri=${encodeURIComponent(callbackUri.toString())}&scope=admin&state=${state}`);
await vscode.env.openExternal(uri);

let codeExchangePromise = promiseFromEvent(uriHandler.event, this.exchangeCodeForToken(host, callbackUri.toString(), callbackUri.toString(), scopes))

return codeExchangePromise.promise.then((accessToken) => {
return Promise.resolve({
id: host,
account: {
label: 'openHAB',
id: host
},
scopes: ['admin'],
accessToken: accessToken
})
})
}

public async removeSession(sessionId: string): Promise<void> {
return Promise.all([
this.context.secrets.delete('openhab.refreshToken'),
this.context.secrets.delete('openhab.clientId')
]).then(() => Promise.resolve())
}

private exchangeCodeForToken: (host: string, clientId: string, callbackUri: string, scopes: string[]) => PromiseAdapter<vscode.Uri, string> =
(host, clientId, callbackUri, scopes) => async (uri, resolve, reject) => {
const query = parseQuery(uri)
const code = query.code
const acceptedStates = this._pendingStates.get(scopes) || []
if (!acceptedStates.includes(query.state)) {
reject('Received mismatched state')
return
}

try {
const tokenUrl = `${host}/rest/auth/token`
let config: AxiosRequestConfig = {
url: host + '/rest/auth/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: `grant_type=authorization_code&client_id=${encodeURIComponent(clientId.replace('?', '%3F'))}&redirect_uri=${encodeURIComponent(callbackUri.replace('?', '%3F'))}&code=${code}`
}
console.debug(`Exchanging token: calling token endpoint with ${config.data}`)
const result = await axios(config)
console.info('Token exchange success!')
console.info('Saving refresh_token in keychain')
this.context.secrets.store('openhab.refreshToken', result.data.refresh_token)
this.context.secrets.store('openhab.clientId', clientId)
resolve(result.data.access_token)
} catch (ex) {
reject(ex);
}
}
}
36 changes: 23 additions & 13 deletions client/src/ThingsExplorer/ThingsModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import * as _ from 'lodash'
import axios, { AxiosRequestConfig } from 'axios'
import { ConfigManager } from '../Utils/ConfigManager'
import { OH_CONFIG_PARAMETERS } from '../Utils/types'
import { authentication } from 'vscode'


/**
Expand Down Expand Up @@ -42,20 +43,29 @@ export class ThingsModel {
headers: {}
}

if(ConfigManager.tokenAuthAvailable()){
config.headers = {
'X-OPENHAB-TOKEN': ConfigManager.get(OH_CONFIG_PARAMETERS.connection.authToken)
}
}

return new Promise((resolve, reject) => {
axios(config)
.then(function (response) {
resolve(this.sort(transform(response.data as Thing[] | Thing)))
}.bind(this))
.catch(err => {
utils.appendToOutput(`Could not reload items for Things Explorer`)
utils.handleRequestError(err).then(err => resolve([]))
authentication.getSession('openhab', ['admin'])
.then((session) => {
if (session && session.accessToken) {
config.headers = {
'X-OPENHAB-TOKEN': session.accessToken
}
} else if (ConfigManager.tokenAuthAvailable()){
config.headers = {
'X-OPENHAB-TOKEN': ConfigManager.get(OH_CONFIG_PARAMETERS.connection.authToken)
}
}
return Promise.resolve()
})
.then(() => {
axios(config)
.then(function (response) {
resolve(this.sort(transform(response.data as Thing[] | Thing)))
}.bind(this))
.catch(err => {
utils.appendToOutput(`Could not reload items for Things Explorer`)
utils.handleRequestError(err).then(err => resolve([]))
})
})
})
}
Expand Down
Loading