# -*- coding: utf-8 -*- from __future__ import absolute_import from copy import deepcopy 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 = [ Account('test', 'test@accounts.spline.de', password='test'), Account('test2', 'test2@accounts.spline.de', password='test2'), ] 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 acc.password != password: raise self.InvalidPasswordError("Invalid password") return acc def find(self, filters=None, wildcard=False): """ Find accounts by a given filter. """ results = [] for acc in self._storage: if _match_filter(acc, filters, wildcard): results.append(deepcopy(acc)) return results def _store(self, account): self._storage.append(deepcopy(account)) 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 stored_account.password != account.password: raise self.InvalidPasswordError("Invalid password") if account.new_password_root: old, new = account.new_password_root if old == stored_account.password: account.password = new account.new_password_root = None self._storage = [acc for acc in self._storage if acc.uid != account.uid] self._storage.append(deepcopy(account)) 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]