from fnmatch import fnmatch from . import Backend from accounts.models import Account def _match_filter(account, filters, wildcard): if filters is None: return True for key in filters: if not hasattr(account, key): return False if wildcard: if not fnmatch(getattr(account, key), filters[key]): return False else: if getattr(account, key) != filters[key]: return False return True class DummyBackend(Backend): """ This is a simple user backend that persists the users in a simple list. The users are stored only in memory and during initialization two dummy users (test and test2) are created. """ def __init__(self, app): super(DummyBackend, self).__init__(app) self._storage = { "test": { "uidNumber": 1, "mail": "test@accounts.spline.de", "password": "test" }, "test2": { "uidNumber": 2, "mail": "test2@accounts.spline.de", "password": "test2" }, "admin": { "uidNumber": 3, "mail": "admin@accounts.spline.de", "password": "admin" }, } self._next_uidNumber = 4 def _get_accounts(self): accounts = [] for uid, attrs in self._storage.items(): accounts.append( Account( uid, attrs["mail"], uidNumber=attrs["uidNumber"] ) ) return accounts def auth(self, username, password): """ Tries to authenticate a user with a given password. If the authentication is successful an Account object will be returned. """ acc = self.get_by_uid(username) if not self._verify_password(acc, password): raise self.InvalidPasswordError("Invalid password") acc.password = password return acc def find(self, filters=None, wildcard=False): """ Find accounts by a given filter. """ return [acc for acc in self._get_accounts() if _match_filter(acc, filters, wildcard)] def _store(self, account): self._storage[account.uid] = { "uidNumber": account.uidNumber, "mail": account.mail, "password": account.password } def _verify_password(self, account, password): return password == self._storage[account.uid]["password"] def _alter_password(self, account, password): self._storage[account.uid]["password"] = password def update(self, account, as_admin=False): """ Updates account information like passwords or email. """ stored_account = self.get_by_uid(account.uid) if not as_admin: if not self._verify_password(stored_account, account.password): raise self.InvalidPasswordError("Invalid password") if account.new_password_root: old, new = account.new_password_root if self._verify_password(stored_account, old): self._alter_password(stored_account, new) def delete(self, account, as_admin=False): """ Deletes an account permanently. """ stored_account = self.get_by_uid(account.uid) if not as_admin: if stored_account.password != account.password: raise self.InvalidPasswordError("Invalid password") self._storage = [acc for acc in self._storage if acc.uid != account.uid] def _get_next_uidNumber(self): value = self._next_uidNumber self._next_uidNumber += 1 return value