Debian Codegraph @

src/calibre/srv/users.py

raw
1 #!/usr/bin/env python
2 # License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
3
4 import json
5 import os
6 import re
7 from functools import lru_cache
8 from threading import RLock
9
10 import apsw
11
12 from calibre import as_unicode
13 from calibre.constants import config_dir
14 from calibre.utils.config import from_json, to_json
15 from calibre.utils.localization import _
16
17
18 def as_json(data):
19 return json.dumps(data, ensure_ascii=False, default=to_json)
20
21
22 def load_json(raw):
23 try:
24 return json.loads(raw, object_hook=from_json)
25 except Exception:
26 return {}
27
28
29 @lru_cache(maxsize=1024)
30 def parse_restriction(raw):
31 r = load_json(raw)
32 if not isinstance(r, dict):
33 r = {}
34 lr = r.get('library_restrictions', {})
35 if not isinstance(lr, dict):
36 lr = {}
37 r['allowed_library_names'] = frozenset(x.lower() for x in r.get('allowed_library_names', ()))
38 r['blocked_library_names'] = frozenset(x.lower() for x in r.get('blocked_library_names', ()))
39 r['library_restrictions'] = {k.lower(): v or '' for k, v in lr.items()}
40 return r
41
42
43 def serialize_restriction(r):
44 ans = {}
45 for x in 'allowed_library_names blocked_library_names'.split():
46 v = r.get(x)
47 if v:
48 ans[x] = list(v)
49 ans['library_restrictions'] = {l.lower(): v or '' for l, v in r.get('library_restrictions', {}).items()}
50 return json.dumps(ans)
51
52
53 def validate_username(username):
54 if re.sub(r'[-a-zA-Z_0-9 ]', '', username):
55 return _('For maximum compatibility you should use only the letters A-Z, the numbers 0-9, spaces, underscores and hyphens in the username')
56
57
58 def validate_password(pw):
59 if not pw:
60 return _('Empty passwords are not allowed')
61 try:
62 pw = pw.encode('ascii', 'strict')
63 except ValueError:
64 return _('The password must contain only ASCII (English) characters and symbols')
65
66
67 def create_user_data(pw, readonly=False, restriction=None, misc_data='{}'):
68 misc_data = json.loads(misc_data)
69 return {
70 'pw': pw,
71 'restriction': parse_restriction(restriction or '{}').copy(),
72 'readonly': readonly,
73 'allow_change_password_via_http': bool(misc_data.get('allow_change_password_via_http', True)),
74 }
75
76
77 def connect(path, exc_class=ValueError):
78 try:
79 return apsw.Connection(path)
80 except apsw.CantOpenError as e:
81 pdir = os.path.dirname(path)
82 if os.path.isdir(pdir):
83 raise exc_class(f'Failed to open userdb database at {path} with error: {as_unicode(e)}')
84 try:
85 os.makedirs(pdir)
86 except OSError as e:
87 raise exc_class(f'Failed to make directory for userdb database at {pdir} with error: {as_unicode(e)}')
88 try:
89 return apsw.Connection(path)
90 except apsw.CantOpenError as e:
91 raise exc_class(f'Failed to open userdb database at {path} with error: {as_unicode(e)}')
92
93
94 class UserManager:
95 lock = RLock()
96
97 @property
98 def conn(self):
99 with self.lock:
100 if self._conn is None:
101 self._conn = connect(self.path)
102 with self._conn:
103 c = self._conn.cursor()
104 uv = next(c.execute('PRAGMA user_version'))[0]
105 if uv == 0:
106 # We have to store the unhashed password, since the digest
107 # auth scheme requires it. (Technically, one can store
108 # a MD5 hash of the username+realm+password, but it has to be
109 # without salt so it is trivially brute-forceable, anyway)
110 # timestamp stores the ISO 8601 creation timestamp in UTC.
111 c.execute('''
112 CREATE TABLE users (
113 id INTEGER PRIMARY KEY,
114 name TEXT NOT NULL,
115 pw TEXT NOT NULL,
116 timestamp TEXT DEFAULT CURRENT_TIMESTAMP,
117 session_data TEXT NOT NULL DEFAULT "{}",
118 restriction TEXT NOT NULL DEFAULT "{}",
119 readonly TEXT NOT NULL DEFAULT "n",
120 misc_data TEXT NOT NULL DEFAULT "{}",
121 UNIQUE(name)
122 );
123
124 PRAGMA user_version=1;
125 ''')
126 c.close()
127 return self._conn
128
129 def __init__(self, path=None):
130 self.path = os.path.join(config_dir, 'server-users.sqlite') if path is None else path
131 self._conn = None
132
133 def get_session_data(self, username):
134 with self.lock:
135 for (data,) in self.conn.cursor().execute('SELECT session_data FROM users WHERE name=?', (username,)):
136 return load_json(data)
137 return {}
138
139 def set_session_data(self, username, data):
140 with self.lock:
141 conn = self.conn
142 c = conn.cursor()
143 data = as_json(data)
144 if isinstance(data, bytes):
145 data = data.decode('utf-8')
146 c.execute('UPDATE users SET session_data=? WHERE name=?', (data, username))
147
148 def get(self, username):
149 "Get password for user, or None if user does not exist"
150 with self.lock:
151 for (pw,) in self.conn.cursor().execute('SELECT pw FROM users WHERE name=?', (username,)):
152 return pw
153
154 def has_user(self, username):
155 return self.get(username) is not None
156
157 def validate_username(self, username):
158 if self.has_user(username):
159 return _('The username %s already exists') % username
160 return validate_username(username)
161
162 def validate_password(self, pw):
163 return validate_password(pw)
164
165 def add_user(self, username, pw, restriction=None, readonly=False, allow_change_password_via_http=True):
166 with self.lock:
167 msg = self.validate_username(username) or self.validate_password(pw)
168 if msg is not None:
169 raise ValueError(msg)
170 restriction = restriction or {}
171 misc_data = {'allow_change_password_via_http': allow_change_password_via_http}
172 self.conn.cursor().execute(
173 'INSERT INTO users (name, pw, restriction, readonly, misc_data) VALUES (?, ?, ?, ?, ?)',
174 (username, pw, serialize_restriction(restriction), ('y' if readonly else 'n'), json.dumps(misc_data)),
175 )
176
177 def remove_user(self, username):
178 with self.lock:
179 self.conn.cursor().execute('DELETE FROM users WHERE name=?', (username,))
180 return self.conn.changes() > 0
181
182 @property
183 def all_user_names(self):
184 with self.lock:
185 return {x for (x,) in self.conn.cursor().execute('SELECT name FROM users')}
186
187 @property
188 def user_data(self):
189 with self.lock:
190 ans = {}
191 for name, pw, restriction, readonly, misc_data in self.conn.cursor().execute('SELECT name,pw,restriction,readonly,misc_data FROM users'):
192 ans[name] = create_user_data(pw, readonly.lower() == 'y', restriction, misc_data)
193 return ans
194
195 @user_data.setter
196 def user_data(self, users):
197 with self.lock, self.conn:
198 c = self.conn.cursor()
199 remove = self.all_user_names - set(users)
200 if remove:
201 c.executemany('DELETE FROM users WHERE name=?', [(n,) for n in remove])
202 for name, data in users.items():
203 res = serialize_restriction(data['restriction'])
204 misc_data = json.dumps({'allow_change_password_via_http': bool(data.get('allow_change_password_via_http', True))})
205 r = 'y' if data['readonly'] else 'n'
206 c.execute(
207 'INSERT INTO USERS (name, pw, restriction, readonly, misc_data) VALUES (?, ?, ?, ?, ?) '
208 'ON CONFLICT DO UPDATE SET pw=?, restriction=?, readonly=?, misc_data=?',
209 (name, data['pw'], res, r, misc_data, data['pw'], res, r, misc_data),
210 )
211 self.refresh()
212
213 def refresh(self):
214 pass # legacy compat
215
216 def is_readonly(self, username):
217 with self.lock:
218 for (readonly,) in self.conn.cursor().execute('SELECT readonly FROM users WHERE name=?', (username,)):
219 return readonly == 'y'
220 return False
221
222 def set_readonly(self, username, value):
223 with self.lock:
224 self.conn.cursor().execute('UPDATE users SET readonly=? WHERE name=?', ('y' if value else 'n', username))
225
226 def change_password(self, username, pw):
227 with self.lock:
228 msg = self.validate_password(pw)
229 if msg is not None:
230 raise ValueError(msg)
231 self.conn.cursor().execute('UPDATE users SET pw=? WHERE name=?', (pw, username))
232
233 def restrictions(self, username):
234 with self.lock:
235 for (restriction,) in self.conn.cursor().execute('SELECT restriction FROM users WHERE name=?', (username,)):
236 return parse_restriction(restriction).copy()
237
238 def allowed_library_names(self, username, all_library_names):
239 "Get allowed library names for specified user from set of all library names"
240 r = self.restrictions(username)
241 if r is None:
242 return set()
243 inc = r['allowed_library_names']
244 exc = r['blocked_library_names']
245
246 def check(n):
247 n = n.lower()
248 return (not inc or n in inc) and n not in exc
249
250 return {n for n in all_library_names if check(n)}
251
252 def update_user_restrictions(self, username, restrictions):
253 if not isinstance(restrictions, dict):
254 raise TypeError('restrictions must be a dict')
255 with self.lock:
256 self.conn.cursor().execute('UPDATE users SET restriction=? WHERE name=?', (serialize_restriction(restrictions), username))
257
258 def library_restriction(self, username, library_path):
259 r = self.restrictions(username)
260 if r is None:
261 return ''
262 library_name = os.path.basename(library_path).lower()
263 return r['library_restrictions'].get(library_name) or ''
264
265 def misc_data(self, username):
266 with self.lock:
267 for (misc_data,) in self.conn.cursor().execute('SELECT misc_data FROM users WHERE name=?', (username,)):
268 return json.loads(misc_data)
269 return {}
270
271 def is_allowed_to_change_password_via_http(self, username: str) -> bool:
272 return bool(self.misc_data(username).get('allow_change_password_via_http', True))
273
274 def set_allowed_to_change_password_via_http(self, username: str, allow: bool = True) -> None:
275 with self.lock:
276 md = self.misc_data(username)
277 md['allow_change_password_via_http'] = allow
278 self.conn.cursor().execute('UPDATE users SET misc_data=? WHERE name=?', (json.dumps(md), username))