use token if returned in session payload.

This commit is contained in:
Miroslav Šedivý 2021-04-24 20:57:14 +02:00
parent 6312ae2cd2
commit bf7a3b9163
3 changed files with 27 additions and 6 deletions

View File

@ -3,13 +3,15 @@ import * as Api from '../api'
export class NekoApi {
api_configuration = new Api.Configuration({
basePath: location.href.replace(/\/+$/, ''),
baseOptions: { withCredentials: true },
})
public setUrl(url: string) {
this.api_configuration = new Api.Configuration({
basePath: url.replace(/\/+$/, ''),
baseOptions: { withCredentials: true },
})
this.api_configuration.basePath = url.replace(/\/+$/, '')
}
public setToken(token: string) {
this.api_configuration.accessToken = token
}
get url(): string {

View File

@ -17,6 +17,7 @@ export class NekoWebSocket extends EventEmitter<NekoWebSocketEvents> {
private _connTimer?: NodeJS.Timeout
private _log: Logger
private _url: string
private _token: string
// reconnection
private _reconTimer?: NodeJS.Timeout
@ -28,6 +29,7 @@ export class NekoWebSocket extends EventEmitter<NekoWebSocketEvents> {
this._log = new Logger('websocket')
this._url = ''
this._token = ''
this.setUrl(location.href)
}
@ -35,6 +37,10 @@ export class NekoWebSocket extends EventEmitter<NekoWebSocketEvents> {
this._url = url.replace(/^http/, 'ws').replace(/\/+$/, '') + '/api/ws'
}
public setToken(token: string) {
this._token = token
}
get supported() {
return typeof WebSocket !== 'undefined' && WebSocket.OPEN === 1
}
@ -55,7 +61,12 @@ export class NekoWebSocket extends EventEmitter<NekoWebSocketEvents> {
this.emit('connecting')
this._ws = new WebSocket(this._url)
let url = this._url
if (this._token) {
url += '?token=' + encodeURIComponent(this._token)
}
this._ws = new WebSocket(url)
this._log.info(`connecting`)
this._ws.onopen = this.onConnected.bind(this)

View File

@ -206,7 +206,12 @@
throw new Error('client already authenticated')
}
await this.api.session.login({ username, password })
const res = await this.api.session.login({ username, password })
if (res.data.token) {
this.api.setToken(res.data.token)
this.websocket.setToken(res.data.token)
}
Vue.set(this.state.connection, 'authenticated', true)
this.websocket.connect()
}
@ -223,6 +228,9 @@
try {
await this.api.session.logout()
} finally {
this.api.setToken('')
this.websocket.setToken('')
Vue.set(this.state.connection, 'authenticated', false)
}
}