askrobots / dbbasic-accounts
Public
Unix-style user accounts (passwd, groups, permissions) with a web-friendly Python API.
accounts.py · 7.8 KB · 280 lines
| 1 | """ |
| 2 | Web-friendly accounts API built on top of Unix-style PasswdDB |
| 3 | """ |
| 4 | |
| 5 | import os |
| 6 | from pathlib import Path |
| 7 | from typing import Optional |
| 8 | from .passwd import PasswdDB, User |
| 9 | |
| 10 | |
| 11 | class Accounts: |
| 12 | """ |
| 13 | Web-friendly accounts management with filesystem integration. |
| 14 | |
| 15 | Built on top of Unix PasswdDB, adds: |
| 16 | - Email-based registration/login |
| 17 | - Home directory creation |
| 18 | - Mailbox creation |
| 19 | - Convenience methods for web apps |
| 20 | """ |
| 21 | |
| 22 | def __init__(self, base_dir: str = ".", domain: str = "localhost"): |
| 23 | """ |
| 24 | Initialize Accounts system. |
| 25 | |
| 26 | Args: |
| 27 | base_dir: Base directory for the Unix-style filesystem |
| 28 | domain: Default domain for email addresses |
| 29 | """ |
| 30 | self.base_dir = Path(base_dir) |
| 31 | self.domain = domain |
| 32 | |
| 33 | # Initialize directory structure |
| 34 | self.etc_dir = self.base_dir / "etc" |
| 35 | self.home_dir = self.base_dir / "home" |
| 36 | self.var_dir = self.base_dir / "var" |
| 37 | self.mail_dir = self.var_dir / "mail" |
| 38 | |
| 39 | # Create directories |
| 40 | self.etc_dir.mkdir(parents=True, exist_ok=True) |
| 41 | self.home_dir.mkdir(parents=True, exist_ok=True) |
| 42 | self.var_dir.mkdir(parents=True, exist_ok=True) |
| 43 | self.mail_dir.mkdir(parents=True, exist_ok=True) |
| 44 | |
| 45 | # Initialize PasswdDB (Unix layer) |
| 46 | self.passwd = PasswdDB(str(self.etc_dir)) |
| 47 | |
| 48 | def _email_to_username(self, email: str) -> str: |
| 49 | """Extract username from email (john@example.com -> john)""" |
| 50 | return email.split('@')[0] |
| 51 | |
| 52 | def _create_home_directory(self, username: str) -> Path: |
| 53 | """Create home directory for user""" |
| 54 | user_home = self.home_dir / username |
| 55 | user_home.mkdir(parents=True, exist_ok=True) |
| 56 | |
| 57 | # Create common subdirectories |
| 58 | (user_home / "uploads").mkdir(exist_ok=True) |
| 59 | |
| 60 | return user_home |
| 61 | |
| 62 | def _create_mailbox(self, username: str) -> Path: |
| 63 | """Create mailbox file for user""" |
| 64 | mailbox = self.mail_dir / username |
| 65 | if not mailbox.exists(): |
| 66 | mailbox.touch() |
| 67 | return mailbox |
| 68 | |
| 69 | def register(self, email: str, password: str, name: str = '') -> User: |
| 70 | """ |
| 71 | Register new user (web-friendly). |
| 72 | |
| 73 | Args: |
| 74 | email: Email address (becomes username@domain) |
| 75 | password: Plain text password (will be hashed) |
| 76 | name: Display name |
| 77 | |
| 78 | Returns: |
| 79 | User object |
| 80 | |
| 81 | Raises: |
| 82 | ValueError: If user already exists |
| 83 | |
| 84 | Example: |
| 85 | user = accounts.register('john@example.com', 'secret123', name='John Doe') |
| 86 | # Creates: |
| 87 | # - etc/passwd.tsv: john entry |
| 88 | # - etc/shadow.tsv: john password |
| 89 | # - etc/group.tsv: adds john to users group |
| 90 | # - home/john/ directory |
| 91 | # - var/mail/john mailbox |
| 92 | """ |
| 93 | username = self._email_to_username(email) |
| 94 | |
| 95 | # Build fullname with email |
| 96 | fullname = f"{name} <{email}>" if name else email |
| 97 | |
| 98 | # Create user in passwd database |
| 99 | user = self.passwd.useradd( |
| 100 | username=username, |
| 101 | password=password, |
| 102 | fullname=fullname, |
| 103 | homedir=f"/home/{username}" |
| 104 | ) |
| 105 | |
| 106 | # Create filesystem structures |
| 107 | self._create_home_directory(username) |
| 108 | self._create_mailbox(username) |
| 109 | |
| 110 | return user |
| 111 | |
| 112 | def login(self, email: str, password: str) -> Optional[User]: |
| 113 | """ |
| 114 | Authenticate user (web-friendly). |
| 115 | |
| 116 | Args: |
| 117 | email: Email address |
| 118 | password: Plain text password |
| 119 | |
| 120 | Returns: |
| 121 | User object if valid, None otherwise |
| 122 | |
| 123 | Example: |
| 124 | user = accounts.login('john@example.com', 'secret123') |
| 125 | if user: |
| 126 | session['user_id'] = user.uid |
| 127 | session['username'] = user.username |
| 128 | """ |
| 129 | username = self._email_to_username(email) |
| 130 | return self.passwd.authenticate(username, password) |
| 131 | |
| 132 | def get_user(self, user_id: Optional[int] = None, |
| 133 | email: Optional[str] = None, |
| 134 | username: Optional[str] = None) -> Optional[User]: |
| 135 | """ |
| 136 | Get user by ID, email, or username. |
| 137 | |
| 138 | Args: |
| 139 | user_id: User ID (uid) |
| 140 | email: Email address |
| 141 | username: Username |
| 142 | |
| 143 | Returns: |
| 144 | User object or None |
| 145 | |
| 146 | Example: |
| 147 | user = accounts.get_user(user_id=1000) |
| 148 | user = accounts.get_user(email='john@example.com') |
| 149 | user = accounts.get_user(username='john') |
| 150 | """ |
| 151 | if username: |
| 152 | return self.passwd.getuser(username) |
| 153 | |
| 154 | if email: |
| 155 | username = self._email_to_username(email) |
| 156 | return self.passwd.getuser(username) |
| 157 | |
| 158 | if user_id is not None: |
| 159 | # Search by UID |
| 160 | for user in self.passwd.list_users(): |
| 161 | if user.uid == user_id: |
| 162 | return user |
| 163 | |
| 164 | return None |
| 165 | |
| 166 | def add_role(self, email: str, role: str) -> bool: |
| 167 | """ |
| 168 | Add role to user (convenience method for groups). |
| 169 | |
| 170 | Args: |
| 171 | email: Email address |
| 172 | role: Role name (becomes group) |
| 173 | |
| 174 | Returns: |
| 175 | True if added, False if user not found |
| 176 | |
| 177 | Example: |
| 178 | accounts.add_role('john@example.com', 'editor') |
| 179 | """ |
| 180 | username = self._email_to_username(email) |
| 181 | return self.passwd.usermod(username, add_groups=[role]) |
| 182 | |
| 183 | def remove_role(self, email: str, role: str) -> bool: |
| 184 | """ |
| 185 | Remove role from user. |
| 186 | |
| 187 | Args: |
| 188 | email: Email address |
| 189 | role: Role name (group) |
| 190 | |
| 191 | Returns: |
| 192 | True if removed, False if user not found |
| 193 | """ |
| 194 | username = self._email_to_username(email) |
| 195 | return self.passwd.usermod(username, remove_groups=[role]) |
| 196 | |
| 197 | def get_roles(self, email: str) -> list[str]: |
| 198 | """ |
| 199 | Get roles for user (groups). |
| 200 | |
| 201 | Args: |
| 202 | email: Email address |
| 203 | |
| 204 | Returns: |
| 205 | List of role names |
| 206 | |
| 207 | Example: |
| 208 | roles = accounts.get_roles('john@example.com') |
| 209 | # ['users', 'editors', 'admins'] |
| 210 | """ |
| 211 | username = self._email_to_username(email) |
| 212 | return self.passwd.groups(username) |
| 213 | |
| 214 | def change_password(self, email: str, new_password: str) -> bool: |
| 215 | """ |
| 216 | Change user password. |
| 217 | |
| 218 | Args: |
| 219 | email: Email address |
| 220 | new_password: New plain text password |
| 221 | |
| 222 | Returns: |
| 223 | True if changed, False if user not found |
| 224 | """ |
| 225 | username = self._email_to_username(email) |
| 226 | return self.passwd.passwd(username, new_password) |
| 227 | |
| 228 | def delete_user(self, email: str) -> bool: |
| 229 | """ |
| 230 | Delete user account. |
| 231 | |
| 232 | Args: |
| 233 | email: Email address |
| 234 | |
| 235 | Returns: |
| 236 | True if deleted, False if user not found |
| 237 | """ |
| 238 | username = self._email_to_username(email) |
| 239 | return self.passwd.userdel(username) |
| 240 | |
| 241 | def list_users(self) -> list[User]: |
| 242 | """ |
| 243 | List all users. |
| 244 | |
| 245 | Returns: |
| 246 | List of User objects |
| 247 | """ |
| 248 | return self.passwd.list_users() |
| 249 | |
| 250 | def get_home_directory(self, email: str) -> Optional[Path]: |
| 251 | """ |
| 252 | Get path to user's home directory. |
| 253 | |
| 254 | Args: |
| 255 | email: Email address |
| 256 | |
| 257 | Returns: |
| 258 | Path to home directory or None if user not found |
| 259 | """ |
| 260 | username = self._email_to_username(email) |
| 261 | user = self.passwd.getuser(username) |
| 262 | if not user: |
| 263 | return None |
| 264 | return self.home_dir / username |
| 265 | |
| 266 | def get_mailbox(self, email: str) -> Optional[Path]: |
| 267 | """ |
| 268 | Get path to user's mailbox. |
| 269 | |
| 270 | Args: |
| 271 | email: Email address |
| 272 | |
| 273 | Returns: |
| 274 | Path to mailbox file or None if user not found |
| 275 | """ |
| 276 | username = self._email_to_username(email) |
| 277 | user = self.passwd.getuser(username) |
| 278 | if not user: |
| 279 | return None |
| 280 | return self.mail_dir / username |