selfprivacy-rest-api/selfprivacy_api/utils.py

59 lines
1.6 KiB
Python
Raw Normal View History

2021-11-11 18:31:28 +00:00
#!/usr/bin/env python3
2021-11-16 16:14:01 +00:00
"""Various utility functions"""
2021-11-22 16:50:50 +00:00
import json
import portalocker
2021-11-16 16:14:01 +00:00
2021-11-11 18:31:28 +00:00
USERDATA_FILE = "/etc/nixos/userdata/userdata.json"
2021-11-30 21:53:39 +00:00
2021-11-11 18:31:28 +00:00
def get_domain():
2021-11-16 16:14:01 +00:00
"""Get domain from /var/domain without trailing new line"""
with open("/var/domain", "r", encoding="utf-8") as domain_file:
domain = domain_file.readline().rstrip()
2021-11-11 18:31:28 +00:00
return domain
2021-11-22 16:50:50 +00:00
class WriteUserData(object):
"""Write userdata.json with lock"""
def __init__(self):
2021-11-30 21:53:39 +00:00
self.userdata_file = open(USERDATA_FILE, "r+", encoding="utf-8")
2021-11-22 16:50:50 +00:00
portalocker.lock(self.userdata_file, portalocker.LOCK_EX)
self.data = json.load(self.userdata_file)
def __enter__(self):
return self.data
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is None:
self.userdata_file.seek(0)
json.dump(self.data, self.userdata_file, indent=4)
self.userdata_file.truncate()
portalocker.unlock(self.userdata_file)
self.userdata_file.close()
class ReadUserData(object):
"""Read userdata.json with lock"""
def __init__(self):
2021-11-30 21:53:39 +00:00
self.userdata_file = open(USERDATA_FILE, "r", encoding="utf-8")
2021-11-22 16:50:50 +00:00
portalocker.lock(self.userdata_file, portalocker.LOCK_SH)
self.data = json.load(self.userdata_file)
def __enter__(self):
return self.data
def __exit__(self, *args):
portalocker.unlock(self.userdata_file)
self.userdata_file.close()
2021-11-23 18:32:51 +00:00
def validate_ssh_public_key(key):
"""Validate SSH public key. It may be ssh-ed25519 or ssh-rsa."""
if not key.startswith("ssh-ed25519"):
if not key.startswith("ssh-rsa"):
return False
return True