add upsert and other options in genpw

This commit is contained in:
Wolfgang Hottgenroth 2023-03-21 15:05:42 +01:00
parent 588d9270f9
commit 61bc3f8dfc

View File

@ -18,18 +18,23 @@ parser.add_argument('--password', '-p',
required=False)
parser.add_argument('--username', '-u',
help='Username',
required=True)
required=False)
parser.add_argument('--topic', '-t',
help='Initially granted topic',
required=True)
required=False)
parser.add_argument('--acl', '-a',
help='ACL value for topic, Bit0=read, Bit1=write, Bit2=subscribe',
required=True)
required=False)
parser.add_argument('--printonly', '-p',
help='Just print the password hash, do not write to database',
action='store_true')
args = parser.parse_args()
length = args.length
password = args.password
print_only = args.printonly
alphabet = string.ascii_letters + string.digits
iterations = 100000
@ -47,28 +52,37 @@ pw = f"PBKDF2$sha512${iterations}${salt_b64}${hash}"
print(f"{password=}")
print(f"hash={pw}")
if not print_only:
login = args.username
if (not login):
raise Exception("For writing to database a username must be given")
topic = args.topic
acl = int(args.acl)
login = args.username
topic = args.topic
acl = int(args.acl)
conn = psycopg2.connect()
conn.autocommit = False
conn = psycopg2.connect()
conn.autocommit = False
try:
with conn:
with conn.cursor() as cur:
cur.execute('insert into users_t (username, pw) values(%(username)s, %(pw)s) returning id',
{ 'username': login, 'pw': pw })
res = cur.fetchone()
if res is None:
raise Exception("Unable to add user to database")
id = res[0]
print("User added to database")
with conn.cursor() as cur:
cur.execute('insert into acls_t ("user", topic, rw) values(%(user)s, %(topic)s, %(rw)s)',
{ 'user': id, 'topic': topic, 'rw': acl })
print("ACL added to database")
finally:
if conn:
conn.close()
try:
with conn:
with conn.cursor() as cur:
cur.execute("""
insert into users_t (username, pw)
values(%(username)s, %(pw)s)
on conflict do update
set pw = %(pw)s
returning id
""",
{ 'username': login, 'pw': pw })
res = cur.fetchone()
if res is None:
raise Exception("Unable to add user to database")
id = res[0]
print("User added to database")
if (topic and acl):
with conn.cursor() as cur:
cur.execute('insert into acls_t ("user", topic, rw) values(%(user)s, %(topic)s, %(rw)s)',
{ 'user': id, 'topic': topic, 'rw': acl })
print("ACL added to database")
finally:
if conn:
conn.close()