diff options
Diffstat (limited to 'jimbrella/users.py')
-rw-r--r-- | jimbrella/users.py | 79 |
1 files changed, 32 insertions, 47 deletions
diff --git a/jimbrella/users.py b/jimbrella/users.py index 4a6348e..641e360 100644 --- a/jimbrella/users.py +++ b/jimbrella/users.py @@ -1,16 +1,14 @@ -from .csv_table import CsvTable +import sqlite3 from .exceptions import UsernameTakenError -class Users(CsvTable): +class Users: """A table of users, including admins. A user must register through the interface provided by JImbrella to be one of the users in this table. Those who borrow umbrellas via jForm are not stored here. - The file format is csv. Each user takes one row. - Columns: - username | identifier Unicode string. must be unique. - password | salted and hashed password. @@ -21,61 +19,48 @@ class Users(CsvTable): - id | (optional) student/faculty ID. - phone | (optional) phone number. - email | (optional) email address. + + Schema: + CREATE TABLE Users( + username TEXT PRIMARY KEY, + password TEXT, + role TEXT, + status TEXT, + language TEXT, + realname TEXT, + id TEXT, + phone TEXT, + email TEXT + ); """ def __init__(self, path): self.path = path - super().__init__( - path, - [ - {"name": col} - for col in [ - "username", - "password", - "role", - "status", - "language", - "realname", - "id", - "phone", - "email", - ] - ], - ) - - def read(self): - """Alias for `_read.`""" - return self._read() def register(self, username, password, language): """Create a new user. If username is already taken, raise UsernameTakenError. """ - users = self._read() - usernames = [user["username"] for user in users] - if username in usernames: + db = sqlite3.connect(self.path) + try: + db.execute( + "INSERT INTO Users (username, password, role, status, language) " + + "VALUES (?, ?, ?, ?, ?)", + (username, password, "user", "normal", "en-US"), + ) + except sqlite3.IntegrityError: raise UsernameTakenError(username) - user = { - "username": username, - "password": password, - "role": "user", - "status": "normal", - "language": language, - "realname": "", - "id": "", - "phone": "", - "email": "", - } - self._append(user) + db.commit() + db.close() def find(self, username) -> dict: - """Find a user and return it in its `dict` structure.""" - - users = self._read() - for user in users: - if user["username"] == username: - return user + """Find a user and return it in its `dict` structure. If user is not found, return None.""" + db = sqlite3.connect(self.path) + db.row_factory = sqlite3.Row - return None + user = db.execute( + "SELECT * FROM Users WHERE username = ?", (username,) + ).fetchone() + return user |