Coverage for portality/models/account.py: 77%

351 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-20 13:43 +0000

1import uuid 

2import hashlib 

3import hmac 

4import re 

5from flask_login import UserMixin 

6from datetime import timedelta 

7from werkzeug.security import generate_password_hash, check_password_hash 

8 

9from portality import constants 

10from portality.dao import DomainObject as DomainObject 

11from portality.core import app 

12from portality.authorise import Authorise 

13from portality.lib import dates 

14from portality.lib.dates import FMT_DATETIME_STD 

15 

16class Account(DomainObject, UserMixin): 

17 __type__ = 'account' 

18 

19 def __init__(self, **kwargs): 

20 from portality.forms.validate import ReservedUsernames 

21 ReservedUsernames().validate(kwargs.get('id', '')) 

22 super(Account, self).__init__(**kwargs) 

23 

24 @classmethod 

25 def make_account(cls, email, username=None, name=None, roles=None, associated_journal_ids=None, attributes:dict[str, list]=None): 

26 if roles is None: 

27 roles = [] 

28 

29 if associated_journal_ids is None: 

30 associated_journal_ids = [] 

31 

32 # If we have an existing account with these credentials, supply it 

33 a = cls.pull(username) or cls.pull_by_email(email) 

34 if a: 

35 return a 

36 

37 # Create a new account 

38 _id = username or cls.new_short_uuid() 

39 a = Account(id=_id) 

40 a.set_email(email) 

41 a.set_name(name) if name else None 

42 

43 for role in roles: 

44 a.add_role(role) 

45 

46 for jid in associated_journal_ids: 

47 a.add_journal(jid) 

48 

49 if attributes is not None: 

50 for attr_type, value in attributes.items(): 

51 if not isinstance(value, list): 

52 value = [value] 

53 for v in value: 

54 a.add_attribute(attr_type, v) 

55 

56 # New accounts don't have passwords set - create a reset token for password. 

57 reset_token = uuid.uuid4().hex 

58 # give them 14 days to create their first password if timeout not specified in config 

59 a.set_reset_token(reset_token, app.config.get("PASSWORD_CREATE_TIMEOUT", 

60 app.config.get('PASSWORD_RESET_TIMEOUT', 86400) * 14)) 

61 return a 

62 

63 @classmethod 

64 def pull_by_email(cls, email: str): 

65 if email is None: 

66 return None 

67 res = cls.query(q='email:"' + email + '"') 

68 if res.get('hits', {}).get('total', {}).get('value', 0) == 1: 

69 acc = cls(**res['hits']['hits'][0]['_source']) 

70 if acc.email.lower() == email.lower(): # allow case insensitive login 

71 return acc 

72 return None 

73 

74 @classmethod 

75 def email_in_use(cls, email: str): 

76 if email is None: 

77 return None 

78 res = cls.query(q='email:"' + email + '"') 

79 return res.get('hits', {}).get('total', {}).get('value', 0) > 0 

80 

81 @classmethod 

82 def get_by_reset_token(cls, reset_token, not_expired=True): 

83 res = cls.query(q='reset_token.exact:"' + reset_token + '"') 

84 obs = [hit.get("_source") for hit in res.get("hits", {}).get("hits", [])] 

85 if len(obs) == 0 or len(obs) > 1: 

86 return None 

87 expires = obs[0].get("reset_expires") 

88 if expires is None: 

89 return None 

90 if not_expired: 

91 try: 

92 ed = dates.parse(expires) 

93 if ed < dates.now(): 

94 return None 

95 except ValueError: 

96 return None 

97 return cls(**obs[0]) 

98 

99 # @classmethod 

100 # def autocomplete(cls, field, prefix, admin_only=False, size=5): 

101 # 

102 # return {"suggestions": super().autocomplete(field, prefix, filter_condition=filter_condition, size=size)} 

103 

104 @classmethod 

105 def admin_autocomplete(cls, field, prefix, size=5): 

106 """Autocomplete for admin users only.""" 

107 filter_condition = {"role.exact": "admin"} 

108 return cls.autocomplete(field, prefix, filter_condition=filter_condition, size=size) 

109 

110 @property 

111 def marketing_consent(self): 

112 return self.data.get("marketing_consent") 

113 

114 def set_marketing_consent(self, consent): 

115 self.data["marketing_consent"] = bool(consent) 

116 

117 @property 

118 def name(self): 

119 return self.data.get("name") 

120 

121 def set_name(self, name): 

122 self.data["name"] = name 

123 

124 @property 

125 def email(self): 

126 return self.data.get("email") 

127 

128 def set_email(self, email): 

129 self.data["email"] = email 

130 

131 def set_password(self, password): 

132 self.data['password'] = generate_password_hash(password) 

133 

134 def set_password_hash(self, hash): 

135 self.data['password'] = hash 

136 

137 def clear_password(self): 

138 if self.data.get('password'): 

139 del self.data['password'] 

140 

141 def check_password(self, password): 

142 """Check the provided password against the stored hash. 

143 

144 Handles legacy hashes removed in Werkzeug 3 (e.g. 'sha1$...' or raw 40-hex SHA1) by verifying once 

145 and upgrading them to a modern hash. This preserves behaviour for existing records while moving 

146 them forward to supported hash schemes. 

147 """ 

148 try: 

149 stored = self.data['password'] 

150 except KeyError: 

151 app.logger.error("Problem with user '{}' account: no password field".format(self.data['id'])) 

152 raise 

153 

154 # If the stored hash looks like a legacy SHA1 format, verify via compatibility shim first. 

155 if self._is_legacy_sha1_hash(stored): 

156 if self._verify_legacy_sha1(stored, password): 

157 # Upgrade path: replace legacy hash with a modern one and persist. 

158 # Note: This handles a breaking change in Werkzeug 3 (legacy verifiers removed). 

159 self.set_password(password) 

160 try: 

161 # DomainObject.save() is expected to exist; failure to save should not block login success. 

162 self.save() 

163 except Exception as e: 

164 app.logger.warning( 

165 "Password upgraded for user '%s' but save failed: %s", self.data.get('id'), str(e) 

166 ) 

167 return True 

168 return False 

169 

170 # Otherwise, use Werkzeug's checker. If Werkzeug raises due to an unsupported legacy format, 

171 # fall back to the legacy verifier as a last resort. 

172 try: 

173 return check_password_hash(stored, password) 

174 except ValueError: 

175 # Fallback for unsupported legacy formats encountered at runtime. 

176 if self._verify_legacy_sha1(stored, password): 

177 self.set_password(password) 

178 try: 

179 self.save() 

180 except Exception as e: 

181 app.logger.warning( 

182 "Password upgraded for user '%s' after ValueError but save failed: %s", 

183 self.data.get('id'), str(e) 

184 ) 

185 return True 

186 return False 

187 

188 # --- Legacy SHA1 compatibility (Werkzeug 3 removal) --- 

189 _SHA1_HEX_RE = re.compile(r"^[a-f0-9]{40}$", re.IGNORECASE) 

190 

191 @classmethod 

192 def _is_legacy_sha1_hash(cls, stored: str) -> bool: 

193 """Detect legacy SHA1 formats that Werkzeug 3 no longer supports. 

194 

195 Supported legacy patterns: 

196 - 'sha1$<salt>$<hexdigest>' (old Werkzeug simple salted SHA1) 

197 - '<40-hex>' (unsalted plain SHA1 of password) 

198 """ 

199 if not stored or not isinstance(stored, str): 

200 return False 

201 if stored.startswith('sha1$'): 

202 parts = stored.split('$') 

203 return len(parts) == 3 and bool(parts[1]) and bool(parts[2]) 

204 # plain 40 hex characters implies unsalted SHA1 

205 return bool(cls._SHA1_HEX_RE.fullmatch(stored)) 

206 

207 @classmethod 

208 def _verify_legacy_sha1(cls, stored: str, password: str) -> bool: 

209 """Verify a password against legacy SHA1 formats. 

210 

211 - 'sha1$<salt>$<hexdigest>' uses sha1(salt + password) 

212 - '<40-hex>' uses sha1(password) 

213 """ 

214 if not stored or password is None: 

215 return False 

216 try: 

217 if stored.startswith('sha1$'): 

218 # salted format: sha1$<salt>$<hexdigest> 

219 _, salt, hexdigest = stored.split('$', 2) 

220 digest = hashlib.sha1((salt + password).encode('utf-8')).hexdigest() 

221 return hmac.compare_digest(digest, hexdigest) 

222 # unsalted plain SHA1 hex 

223 if cls._SHA1_HEX_RE.fullmatch(stored): 

224 digest = hashlib.sha1(password.encode('utf-8')).hexdigest() 

225 return hmac.compare_digest(digest, stored.lower()) 

226 except Exception: 

227 # Any parsing/encoding issues -> treat as non-match 

228 return False 

229 return False 

230 

231 @property 

232 def journal(self): 

233 return self.data.get("journal") 

234 

235 def add_journal(self, jid): 

236 if jid in self.data.get("journal", []): 

237 return 

238 if "journal" not in self.data: 

239 self.data["journal"] = [] 

240 if jid not in self.data["journal"]: 

241 self.data["journal"].append(jid) 

242 

243 def remove_journal(self, jid): 

244 if "journal" not in self.data: 

245 return 

246 self.data["journal"].remove(jid) 

247 

248 @property 

249 def reset_token(self): 

250 return self.data.get('reset_token') 

251 

252 def set_reset_token(self, token, timeout): 

253 expires = dates.now() + timedelta(0, timeout) 

254 self.data["reset_token"] = token 

255 self.data["reset_expires"] = expires.strftime(FMT_DATETIME_STD) 

256 

257 def remove_reset_token(self): 

258 if "reset_token" in self.data: 

259 del self.data["reset_token"] 

260 if "reset_expires" in self.data: 

261 del self.data["reset_expires"] 

262 

263 @property 

264 def reset_expires(self): 

265 return self.data.get("reset_expires") 

266 

267 @property 

268 def reset_expires_timestamp(self): 

269 expires = self.reset_expires 

270 if expires is None: 

271 return None 

272 return dates.parse(expires) 

273 

274 def is_reset_expired(self): 

275 expires = self.reset_expires_timestamp 

276 if expires is None: 

277 return True 

278 return expires < dates.now() 

279 

280 @property 

281 def is_super(self): 

282 # return not self.is_anonymous and self.id in app.config['SUPER_USER'] 

283 return Authorise.has_role(app.config["SUPER_USER_ROLE"], self.data.get("role", [])) 

284 

285 def has_role(self, role): 

286 return Authorise.has_role(role, self.data.get("role", [])) 

287 

288 @classmethod 

289 def all_top_level_roles(cls): 

290 return Authorise.top_level_roles() 

291 

292 def add_role(self, role): 

293 if "role" not in self.data: 

294 self.data["role"] = [] 

295 if role not in self.data["role"]: 

296 self.data["role"].append(role) 

297 # If we're adding the API role, ensure we also have a key to validate 

298 if role == 'api' and not self.data.get('api_key', None): 

299 self.generate_api_key() 

300 

301 def remove_role(self, role): 

302 if "role" not in self.data: 

303 return 

304 if role in self.data["role"]: 

305 self.data["role"].remove(role) 

306 

307 @property 

308 def role(self): 

309 return self.data.get("role", []) 

310 

311 def set_role(self, role): 

312 if not isinstance(role, list): 

313 role = [role] 

314 self.data["role"] = role 

315 

316 ############################### 

317 ## user attributes 

318 

319 @property 

320 def attributes(self): 

321 return self.data.get("attributes") 

322 

323 @attributes.deleter 

324 def attributes(self): 

325 if "attributes" in self.data: 

326 del self.data["attributes"] 

327 

328 @property 

329 def attribute_workflow(self): 

330 return self.data.get("attributes", {}).get(constants.USER_ATTR__WORKFLOW, []) 

331 

332 @property 

333 def attribute_language(self): 

334 return self.data.get("attributes", {}).get(constants.USER_ATTR__LANGUAGE, []) 

335 

336 @property 

337 def attribute_country(self): 

338 return self.data.get("attributes", {}).get(constants.USER_ATTR__COUNTRY, []) 

339 

340 @property 

341 def attribute_tag(self): 

342 return self.data.get("attributes", {}).get(constants.USER_ATTR__TAG, []) 

343 

344 def add_attribute(self, attribute_type, value): 

345 if attribute_type not in constants.USER_ATTR__ALL: 

346 raise ValueError("Unknown user attribute type: {}".format(attribute_type)) 

347 if "attributes" not in self.data: 

348 self.data["attributes"] = {} 

349 if attribute_type not in self.data["attributes"]: 

350 self.data["attributes"][attribute_type] = [] 

351 if value not in self.data["attributes"][attribute_type]: 

352 self.data["attributes"][attribute_type].append(value) 

353 

354 def has_attribute(self, attribute_type, value): 

355 if attribute_type not in constants.USER_ATTR__ALL: 

356 raise ValueError("Unknown user attribute type: {}".format(attribute_type)) 

357 return value in self.data.get("attributes", {}).get(attribute_type, []) 

358 

359 def get_attributes(self, attribute_type): 

360 if attribute_type not in constants.USER_ATTR__ALL: 

361 raise ValueError("Unknown user attribute type: {}".format(attribute_type)) 

362 return self.data.get("attributes", {}).get(attribute_type, []) 

363 

364 ####################### 

365 

366 def prep(self): 

367 self.data['last_updated'] = dates.now_str() 

368 

369 @property 

370 def api_key(self): 

371 if self.has_role('api'): 

372 return self.data.get('api_key', None) 

373 else: 

374 return None 

375 

376 def generate_api_key(self): 

377 k = uuid.uuid4().hex 

378 self.data['api_key'] = k 

379 return k 

380 

381 @property 

382 def is_premium(self): 

383 return (self.has_role(constants.ROLE_PREMIUM) or 

384 self.has_role(constants.ROLE_PREMIUM_OAI) or 

385 self.has_role(constants.ROLE_PREMIUM_PDD) or 

386 self.has_role(constants.ROLE_PREMIUM_CSV)) 

387 

388 @classmethod 

389 def pull_by_api_key(cls, key): 

390 """Find a user by their API key - only succeed if they currently have API access.""" 

391 res = cls.query(q='api_key.exact:"' + key + '"') 

392 if res.get('hits', {}).get('total', {}).get('value', 0) == 1: 

393 usr = cls(**res['hits']['hits'][0]['_source']) 

394 if usr.has_role('api'): 

395 return usr 

396 return None 

397 

398 @classmethod 

399 def new_short_uuid(cls): 

400 """ Generate a short UUID and check it's unique in this type """ 

401 trunc_uuid = str(uuid.uuid4())[:8] 

402 if cls.pull(trunc_uuid) is None: 

403 return trunc_uuid 

404 else: 

405 return cls.new_short_uuid() 

406 

407 @classmethod 

408 def get_name_safe(cls, account_id) -> str: 

409 if account_id: 

410 author = Account.pull(account_id) 

411 if author is not None and author.name: 

412 return author.name 

413 return '' 

414 

415 @classmethod 

416 def is_enable_publisher_email(cls) -> bool: 

417 # TODO: in the long run this needs to move out to the user's email preferences but for now it 

418 # is here to replicate the behaviour in the code it replaces 

419 return app.config.get("ENABLE_PUBLISHER_EMAIL", False) 

420 

421 @property 

422 def login_code(self): 

423 return self.data.get('login_code') 

424 

425 @property 

426 def login_code_expires(self): 

427 return self.data.get('login_code_expires') 

428 

429 def set_login_code(self, code, timeout=600): # default 10 minutes 

430 if code: 

431 expires = dates.now() + timedelta(seconds=timeout) 

432 self.data["login_code"] = code 

433 self.data["login_code_expires"] = expires.strftime(FMT_DATETIME_STD) 

434 

435 def remove_login_code(self): 

436 if "login_code" in self.data: 

437 del self.data["login_code"] 

438 if "login_code_expires" in self.data: 

439 del self.data["login_code_expires"] 

440 

441 def is_login_code_valid(self, code): 

442 if code is None: 

443 return False 

444 if not self.login_code or not self.login_code_expires: 

445 return False 

446 if self.login_code != code: 

447 return False 

448 expires = dates.parse(self.login_code_expires) 

449 return expires > dates.now() 

450 

451 @classmethod 

452 def pull_by_login_code(cls, code): 

453 if code is None: 

454 return None 

455 q = LoginCodeQuery(code) 

456 res = cls.object_query(q.query()) 

457 if len(res) > 0: 

458 return res[0] 

459 return None 

460 

461class LoginCodeQuery: 

462 def __init__(self, code): 

463 self.code = code 

464 

465 def query(self): 

466 return { 

467 "query": { 

468 "term": { 

469 "login_code.exact": self.code 

470 } 

471 } 

472 } 

473 

474 @classmethod 

475 def find_by_attributes(cls, attribute_types_and_values:list[tuple[str, str]], limit=1000): 

476 q = AttributesQuery(attribute_types_and_values, limit) 

477 return cls.object_query(q.query()) 

478 

479 

480class AttributesQuery: 

481 def __init__(self, attribute_types_and_values, page_size): 

482 self._tup = attribute_types_and_values 

483 self._size = page_size 

484 

485 def query(self): 

486 musts = [] 

487 for t, v in self._tup.items(): 

488 if not isinstance(v, list): 

489 v = [v] 

490 f = {"terms": {f"attribute.{t}.exact": v}} 

491 musts.append(f) 

492 

493 q = { 

494 "query": { 

495 "bool": { 

496 "must": musts 

497 } 

498 }, 

499 "size": self._size 

500 } 

501 return q