From 2a19b46d52c6a05a6274ab94492fab2aa6f37840 Mon Sep 17 00:00:00 2001 From: Thomas Basler Date: Wed, 23 Nov 2022 21:00:54 +0100 Subject: [PATCH] Add authentication to websocket --- src/WebApi_ws_live.cpp | 9 ++++++++- webapp/src/utils/authentication.ts | 12 ++++++++++++ webapp/src/views/HomeView.vue | 5 +++-- 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/WebApi_ws_live.cpp b/src/WebApi_ws_live.cpp index 166fdea6..0027c8f2 100644 --- a/src/WebApi_ws_live.cpp +++ b/src/WebApi_ws_live.cpp @@ -5,8 +5,8 @@ #include "WebApi_ws_live.h" #include "AsyncJson.h" #include "Configuration.h" -#include "defaults.h" #include "WebApi.h" +#include "defaults.h" WebApiWsLiveClass::WebApiWsLiveClass() : _ws("/livedata") @@ -66,6 +66,13 @@ void WebApiWsLiveClass::loop() String buffer; if (buffer) { serializeJson(root, buffer); + + if (Configuration.get().Security_AllowReadonly) { + _ws.setAuthentication("", ""); + } else { + _ws.setAuthentication(AUTH_USERNAME, Configuration.get().Security_Password); + } + _ws.textAll(buffer); } diff --git a/webapp/src/utils/authentication.ts b/webapp/src/utils/authentication.ts index 0bcb178e..53dda78f 100644 --- a/webapp/src/utils/authentication.ts +++ b/webapp/src/utils/authentication.ts @@ -16,6 +16,18 @@ export function authHeader(): Headers { return new Headers(headers); } +export function authUrl(): string { + let user = null; + try { + user = JSON.parse(localStorage.getItem('user') || ""); + } catch { } + + if (user && user.authdata) { + return encodeURIComponent(atob(user.authdata)).replace("%3A", ":") + '@'; + } + return ""; +} + export function logout() { // remove user from local storage to log user out localStorage.removeItem('user'); diff --git a/webapp/src/views/HomeView.vue b/webapp/src/views/HomeView.vue index 16c714bf..a8b12b1b 100644 --- a/webapp/src/views/HomeView.vue +++ b/webapp/src/views/HomeView.vue @@ -342,7 +342,7 @@ import type { EventlogItems } from '@/types/EventlogStatus'; import type { LiveData, Inverter } from '@/types/LiveDataStatus'; import type { LimitStatus } from '@/types/LimitStatus'; import type { LimitConfig } from '@/types/LimitConfig'; -import { isLoggedIn, handleResponse, authHeader } from '@/utils/authentication'; +import { isLoggedIn, handleResponse, authHeader, authUrl } from '@/utils/authentication'; import { formatNumber } from '@/utils'; export default defineComponent({ @@ -474,8 +474,9 @@ export default defineComponent({ console.log("Starting connection to WebSocket Server"); const { protocol, host } = location; + const authString = authUrl(); const webSocketUrl = `${protocol === "https:" ? "wss" : "ws" - }://${host}/livedata`; + }://${authString}${host}/livedata`; this.socket = new WebSocket(webSocketUrl);