nancy/src/nancy/user.py
Jacob Hinkle f18368f1e0 Add Program, Environment, User, Machine, with auto insertion
Also removed freeze and thaw, and converted to record().
2022-09-21 20:51:57 -04:00

73 lines
1.7 KiB
Python

from . import machine, store
import getpass
import os
import pwd
from typing import NamedTuple
class User(NamedTuple):
id: int # if not None, this is `id` in the `machine` table
username: str
userid: int
fullname: str
machine: machine.Machine
@classmethod
def find_or_insert(cls, cur, user=None):
"""Given a DB cursor, find or create row in user table and fill"""
if user is None:
user = cls.detect()
m = machine.Machine.find_or_insert(cur)
user = user._replace(machine=m.id)
# insert or ignore, handle each case to set id
cur.execute('''
SELECT
id
FROM
user
WHERE
username = ? AND
userid = ? AND
fullname = ? AND
machine = ?
LIMIT 1
''',
user[1:],
)
res = cur.fetchone()
if res is None:
cur.execute('''
INSERT INTO user VALUES (?,?,?,?,?);
''',
user,
)
id = cur.lastrowid
cur.connection.commit()
else:
id = res[0]
return user._replace(id=id)
@classmethod
def detect(cls):
"""Detect values for user independent of the database.
Note that the machine entry will not have a valid id.
"""
# TODO: will this fail on Windows/OSX?
fullname = pwd.getpwuid(os.getuid()).pw_gecos
m = machine.Machine.detect()
return cls(
None,
getpass.getuser(),
os.getuid(),
fullname,
m.id,
)