73 lines
1.7 KiB
Python
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,
|
|
)
|
|
|