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