Skip to content

Commit 4016636

Browse files
committed
changes from copilot review
1 parent 9d7cc9e commit 4016636

8 files changed

Lines changed: 62 additions & 49 deletions

File tree

packages/helpermodules/command.py

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -365,20 +365,27 @@ def removeChargepoint(self, connection_id: str, payload: dict) -> None:
365365
payload, connection_id,
366366
f'Die ID \'{cp_id}\' ist größer als die maximal vergebene '
367367
f'ID \'{self.max_id_hierarchy}\'.', MessageType.ERROR)
368-
cp_type = SubData.cp_data.get(f"cp{cp_id}", None).chargepoint.data.config.type
369-
cp_ip = (SubData.cp_data.get(f"cp{cp_id}", None).chargepoint.data.config.configuration.get("ip_address")
370-
if cp_type == "external_openwb" else "127.0.0.1" if cp_type == "internal_openwb" else None)
371-
if cp_type == "external_openwb" and cp_ip is not None:
372-
# check if ip is used in other chargepoints, if not remove display user
373-
for cp in SubData.cp_data.values():
374-
if (
375-
cp.chargepoint.data.config.configuration.get("ip_address", None) == cp_ip
376-
and cp.chargepoint.num != cp_id
377-
):
378-
log.info(f"IP {cp_ip} is still used by cp{cp.chargepoint.num}, not removing display user")
379-
break
380-
else:
381-
remove_display_user(cp_ip)
368+
return
369+
cp = SubData.cp_data.get(f"cp{cp_id}", None)
370+
if cp is None:
371+
pub_user_message(
372+
payload, connection_id,
373+
f'Ladepunkt mit ID \'{cp_id}\' existiert nicht.', MessageType.ERROR)
374+
return
375+
cp_type = cp.chargepoint.data.config.type
376+
if cp_type == "external_openwb":
377+
cp_ip = cp.chargepoint.data.config.configuration.get("ip_address")
378+
if cp_ip is not None:
379+
# check if ip is used in other charge points, if not remove display user
380+
for cp in SubData.cp_data.values():
381+
if (
382+
cp.chargepoint.data.config.configuration.get("ip_address", None) == cp_ip
383+
and cp.chargepoint.num != cp_id
384+
):
385+
log.info(f"IP {cp_ip} is still used by cp{cp.chargepoint.num}, not removing display user")
386+
break
387+
else:
388+
remove_display_user(cp_ip)
382389
remove_acl_role("chargepoint-<id>-access", cp_id)
383390
remove_acl_role("chargepoint-<id>-write-access", cp_id)
384391
ProcessBrokerBranch(f'chargepoint/{cp_id}/').remove_topics()

packages/helpermodules/mosquitto_dynsec/mosquitto_dynsec.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,32 +3,32 @@
33
import requests
44
from json import load as json_load, dump as json_dump
55
from pathlib import Path
6-
from typing import Optional
6+
from typing import Optional, Tuple
77
from datetime import datetime, timedelta
88
from passlib.hash import bcrypt
99
from secrets import token_hex
1010

1111
from helpermodules.subdata import SubData
1212
from helpermodules.utils.run_command import run_command
13-
from helpermodules.mosquitto_dynsec.role_handler import add_acl_role, update_acls
13+
from helpermodules.mosquitto_dynsec.role_handler import _get_base_path, add_acl_role, update_acls
1414
from helpermodules.mosquitto_dynsec.user_handler import create_display_user, user_exists
1515
from modules.common.component_type import special_to_general_type_mapping
1616

17-
TOKEN_DATA_PATH = Path(Path(__file__).resolve().parents[2]/"ramdisk"/"password_reset_tokens")
17+
TOKEN_DATA_PATH = Path(_get_base_path() / "ramdisk" / "password_reset_tokens")
1818

1919
log = logging.getLogger(__name__)
2020

2121

2222
def get_user_email(username: str) -> Optional[str]:
2323
email_regexp = r'(^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9]{2,7}$)'
2424
if user_exists(username):
25-
result = run_command(["/var/www/html/openWB/runs/dynsec_helper/get_user_mail.sh", username])
25+
result = run_command([f"{_get_base_path()}/runs/dynsec_helper/get_user_mail.sh", username])
2626
email = result.strip()
2727
return email if re.fullmatch(email_regexp, email) else None
2828
return None
2929

3030

31-
def generate_password_reset_token(username: str) -> list[str, int]:
31+
def generate_password_reset_token(username: str) -> Tuple[str, int]:
3232
token = token_hex(16)
3333
token_hash = bcrypt.hash(token)
3434
expires_at = datetime.now() + timedelta(hours=1)
@@ -68,15 +68,15 @@ def send_password_reset_to_server(email: str, token: str, expires_at: int) -> No
6868
timeout=timeout,
6969
verify=True
7070
)
71-
print(f"{response.status_code}: {response.text}")
71+
log.debug(f"Password reset token request returned {response.status_code}: {response.text}")
7272
except requests.exceptions.Timeout:
7373
error = f"Error: request timed out after {timeout}s"
7474
except requests.exceptions.ConnectionError:
7575
error = f"Error: connection to {TOKEN_SERVER_URL} failed"
7676
except requests.RequestException as e:
7777
error = f"HTTP-Error: {e}"
7878
if error is not None or response.status_code != 200:
79-
print(f"Failed to send password reset email: {error or f'status {response.status_code}'}")
79+
log.error(f"Failed to send password reset email: {error or f'status {response.status_code}'}")
8080

8181

8282
def verify_password_reset_token(username: str, token: str) -> bool:

packages/helpermodules/mosquitto_dynsec/role_handler.py

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from typing import Tuple, TypedDict, Optional
44
from pathlib import Path
55
from json import load as json_load
6+
from copy import deepcopy
67

78
from helpermodules.utils.run_command import run_command
89

@@ -24,12 +25,12 @@ class MosquittoRole(TypedDict):
2425
acls: list[MosquittoAcl]
2526

2627

27-
def _get_packages_path() -> Path:
28+
def _get_base_path() -> Path:
2829
return Path(__file__).resolve().parents[3]
2930

3031

3132
def _get_default_roles() -> list[MosquittoRole]:
32-
with open(_get_packages_path() /
33+
with open(_get_base_path() /
3334
"data" / "config" / "mosquitto" / "public" / "default-dynamic-security.json", 'r',
3435
encoding='utf-8') as file:
3536
dynsec_config = json_load(file)
@@ -38,7 +39,7 @@ def _get_default_roles() -> list[MosquittoRole]:
3839

3940

4041
def _get_role_templates() -> list[MosquittoRole]:
41-
with open(_get_packages_path() /
42+
with open(_get_base_path() /
4243
"data" / "config" / "mosquitto" / "public" / "role-templates.json", 'r', encoding='utf-8') as file:
4344
roles: list[MosquittoRole] = json_load(file)
4445
return roles if roles else []
@@ -51,21 +52,22 @@ def extract_id_from_role_name(role_name: str) -> Optional[int]:
5152
return None
5253

5354

54-
def get_acl_role_data(role_template: str, id: int) -> MosquittoRole:
55-
roles = _get_role_templates()
56-
role_data = None
57-
for role in roles:
58-
if role["rolename"] == role_template:
59-
role_data = role
60-
break
61-
if role_data is None:
62-
raise ValueError(f"Kein passendes Rollen-Template für '{role_template}' gefunden.")
63-
role_data["rolename"] = role_data["rolename"].replace("<id>", str(id))
64-
role_data["textname"] = role_data["textname"].replace("<id>", str(id))
65-
role_data["textdescription"] = role_data["textdescription"].replace("<id>", str(id))
66-
for acl in role_data["acls"]:
67-
acl["topic"] = acl["topic"].replace("<id>", str(id))
68-
return role_data
55+
def get_acl_role_data(role_template_name: str, id: int) -> MosquittoRole:
56+
template_roles = _get_role_templates()
57+
for template_role in template_roles:
58+
if template_role["rolename"] == role_template_name:
59+
role_data: MosquittoRole = {
60+
"rolename": template_role["rolename"].replace("<id>", str(id)),
61+
"textname": template_role["textname"].replace("<id>", str(id)),
62+
"textdescription": template_role["textdescription"].replace("<id>", str(id)),
63+
"acls": []
64+
}
65+
for acl in template_role["acls"]:
66+
new_acl = deepcopy(acl)
67+
new_acl["topic"] = new_acl["topic"].replace("<id>", str(id))
68+
role_data["acls"].append(new_acl)
69+
return role_data
70+
raise ValueError(f"Kein passendes Rollen-Template für '{role_template_name}' gefunden.")
6971

7072

7173
def get_configured_role_data(role_name: str) -> Optional[MosquittoRole]:

packages/helpermodules/mosquitto_dynsec/user_handler.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33
from typing import Optional, Tuple
44
from json import dump as json_dump
55

6-
from helpermodules.mosquitto_dynsec.role_handler import _get_packages_path
6+
from helpermodules.mosquitto_dynsec.role_handler import _get_base_path
77
from helpermodules.utils.run_command import run_command
88

9-
USER_CREDENTIALS_PATH = _get_packages_path() / "data" / "clients"
9+
USER_CREDENTIALS_PATH = _get_base_path() / "data" / "clients"
1010
log = logging.getLogger(__name__)
1111

1212

@@ -58,7 +58,7 @@ def remove_display_user(ip_address: str) -> bool:
5858
return False
5959

6060

61-
def user_exists(username: str) -> Optional[dict]:
61+
def user_exists(username: str) -> bool:
6262
result = run_command(["mosquitto_ctrl", "dynsec", "getClient", username], process_exception=True)
6363
if username in result:
6464
return True

packages/modules/display_themes/cards/source/src/App.vue

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -159,12 +159,15 @@ export default {
159159
createConnection() {
160160
const { protocol, host, port, path, ...options } = this.connection;
161161
const connectUrl = `${protocol}://${host}:${port}${path}`;
162-
const [user, pass] = this.$cookies.get("mqtt")?.split(":") || [null, null];
162+
const [user, pass] = this.$cookies
163+
.get("mqtt")
164+
?.match(/^([^:]+):(.+)$/)
165+
?.slice(1) || [null, null];
163166
if (!(user && pass)) {
164167
console.debug("Anonymous mqtt connection (no cookie set)");
165168
}
166169
if ((this.nodeEnv !== "production" || protocol == "wss") && user && pass) {
167-
console.debug("Using mqtt credentials from cookie:", user, "/", pass);
170+
console.debug(`Using mqtt credentials from cookie: "${user}" / "${pass.charAt(0)}..."`);
168171
options.username = user;
169172
options.password = pass;
170173
if (user === "admin" && pass === "openwb") {

packages/modules/display_themes/cards/source/src/components/UserIndicator.vue

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,14 @@ import { library } from "@fortawesome/fontawesome-svg-core";
44
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
55
import {
66
faCircleUser as fasCircleUser,
7+
faLock as fasLock,
78
faArrowRightToBracket as fasArrowRightToBracket,
89
faArrowRightFromBracket as fasArrowRightFromBracket,
910
faEye as fasEye,
1011
faEyeSlash as fasEyeSlash,
1112
} from "@fortawesome/free-solid-svg-icons";
1213
/* add icons to the library */
13-
library.add(fasCircleUser, fasArrowRightToBracket, fasArrowRightFromBracket, fasEye, fasEyeSlash);
14+
library.add(fasCircleUser, fasLock, fasArrowRightToBracket, fasArrowRightFromBracket, fasEye, fasEyeSlash);
1415
import { useMqttStore } from "@/stores/mqtt.js";
1516
1617
export default {

packages/modules/web_themes/koala/source/src/stores/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ declare module 'pinia' {
1111
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
1212
export interface PiniaCustomProperties {
1313
// add your custom properties here, if any
14-
readonly router: Router;
14+
readonly router: Router | null;
1515
}
1616
}
1717

packages/modules/web_themes/koala/source/src/stores/mqtt-store.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,9 @@ export const useMqttStore = defineStore('mqtt', () => {
3434
let mqttUser = null;
3535
let mqttPass = null;
3636
if ($q.cookies.has('mqtt')) {
37-
[mqttUser, mqttPass] = decodeURIComponent($q.cookies.get('mqtt')).split(
38-
':',
39-
) || [null, null];
37+
[mqttUser, mqttPass] = decodeURIComponent($q.cookies.get('mqtt'))
38+
?.match(/^([^:]+):(.+)$/)
39+
?.slice(1) || [null, null];
4040
}
4141

4242
// local variables

0 commit comments

Comments
 (0)