def add_client(values): """Registers a new client. To register a new client the request must be autheticated by providing the username and password of the existing user. The function will return a dictionary with the client_id and client_secret which will than be used to request authorization for a certain service endpoint.""" username = values["username"] password = values["password"] with get_storage() as storage: try: user = storage.session.query(User).filter( User.name == username).one() if verify_password(password, user.password): user_id = user.id else: raise AuthError("User can not be authorized.") except: raise AuthError("User can not be authorized.") client = Client() client.name = values['name'] client.client_id = generate_password(40) client.client_secret = generate_password(50) client._redirect_uris = None # values['redirect_uris'] client._default_scopes = None # values['scopes'] client.user_id = user_id with get_storage() as storage: storage.create(client) client_id = client.client_id client_secret = client.client_secret return dict(client_id=client_id, client_secret=client_secret)
def test_notfound_error(): from tedega_view import NotFound from tedega_storage.rdbms import get_storage from tedega_storage.rdbms.crud import read, update, delete with pytest.raises(NotFound): with get_storage() as storage: read(storage, Dummy, 12) with pytest.raises(NotFound): with get_storage() as storage: update(storage, Dummy, 12, {}) with pytest.raises(NotFound): with get_storage() as storage: delete(storage, Dummy, 12)
def search(limit=100, offset=0, search="", sort="", fields=""): """Loads all users. .. seealso:: Methods :func:`tedega_core.api.crud.search` :limit: Limit number of result to N entries. :offset: Return entries with an offset of N. :search: Return entries with an offset of N. :sort: Define sort and ordering. :fields: Only return defined fields. :returns: List of dictionary with values of the user >>> import tedega_core.api.user >>> users = tedega_core.api.user.search() >>> isinstance(users, list) True """ if fields != "": fields = fields.split("|") else: fields = None with get_storage() as storage: users = _search(storage, User, limit, offset, search, sort) users = [user.get_values(fields) for user in users] return users
def reset_password(item_id, password=None): """Will reset the password of the user. .. seealso:: Methods :func:`tedega_core.model.user.reset_password` :item_id: ID of the user to update :password: Unencrypted password :returns: Unencrypted password >>> import tedega_core.api.user >>> # First create a new user. >>> newuser = tedega_core.api.user.create(name="foo5", password="******") >>> oldpass = newuser.password >>> # Set custom password. >>> result = tedega_core.api.user.reset_password(item_id = newuser.id, password = "******") >>> result == "newpass" True >>> # Set random password. >>> result = tedega_core.api.user.reset_password(item_id = newuser.id) >>> result != "newpass" True """ with get_storage() as storage: user = _read(storage, User, item_id) new_password = user.reset_password(password) return new_password
def test_crud(): from tedega_storage.rdbms import get_storage from tedega_storage.rdbms.crud import create, read, update, delete with get_storage() as storage: item = create(storage, Dummy, {}) read(storage, Dummy, item.id) item = update(storage, Dummy, item.id, {'id': 2}) delete(storage, Dummy, 2)
def ping(): data = {} log = get_logger() with get_storage() as storage: factory = Ping.get_factory(storage) item = factory.create() storage.create(item) items = storage.read(Ping) data["total"] = len(items) data["data"] = [item.get_values() for item in items] log.info("Let's log something") return data
def login(values): client_id = values["client_id"] client_secret = values["client_secret"] with get_storage() as storage: try: query = storage.session.query(Client) query = query.filter(Client.client_id == client_id, Client.client_secret == client_secret) query.one() except: raise AuthError("Client can not be authenticated") encoded = jwt.encode({'some': 'payload'}, 'secret', algorithm='HS256') return encoded.decode('utf-8')
def build_app(servicename): # Define things we want to happen of application creation. We want: # 1. Initialise out fluent logger. # 2. Initialise the storage. # 3. Start the monitoring of out service to the "outside". # 4. Start the monitoring of the system every 10sec (CPU, RAM,DISK). run_on_init = [(init_logger, servicename), (init_storage, None), (monitor_connectivity, [("www.google.com", 80)]), (monitor_system, 10)] application = create_application(servicename, run_on_init=run_on_init) log = get_logger() with get_storage() as storage: user = _create(storage, tedega_auth.model.user.User, dict(name="admin", password="******")) storage.create(user) log.info("Create default user 'admin' with password 'secret'") return application
def create(name, password): """Creates a new user with the given `name` and `password`. .. seealso:: Methods :func:`tedega_core.api.crud.create` :name: Name of the new user :password: Password (unencrypted) of the new user :returns: Dictionary with values of the user >>> import tedega_core.api.user >>> user = tedega_core.api.user.create(name="foo1", password="******") >>> user['name'] 'foo1' """ with get_storage() as storage: user = _create(storage, User, dict(name=name, password=password)) user = user.get_values() return user
def ping(): data = {} log = get_logger() with get_storage() as storage: # Create a new "Ping" and store it in the storage. factory = Ping.get_factory(storage) item = factory.create() storage.create(item) # Read all previous pings from storage and populate the data # object. items = storage.read(Ping) data["total"] = len(items) data["data"] = [item.get_values() for item in items] log.info("Let's log something") return data
def delete(item_id): """Deletes a user from the database. .. seealso:: Methods :func:`tedega_core.api.crud.delete` :item_id: ID of the user to update >>> import tedega_core.api.user >>> # First create a new user. >>> newuser = tedega_core.api.user.create(name="foo4", password="******") >>> # Now delete the user >>> tedega_core.api.user.delete(item_id = newuser.id) >>> # Check that the user was actually deleted. >>> loaduser = tedega_core.api.user.read(item_id = newuser.id) Traceback (most recent call last): ... sqlalchemy.orm.exc.NoResultFound: No row was found for one() """ with get_storage() as storage: return _delete(storage, User, item_id)
def read(item_id): """Read (load) a existing user from the database. .. seealso:: Methods :func:`tedega_core.api.crud.read` :item_id: ID of the user to load. :returns: Dictionary with values of the user >>> import tedega_core.api.user >>> # First create a new user. >>> newuser = tedega_core.api.user.create(name="foo2", password="******") >>> # Now load the user >>> loaduser = tedega_core.api.user.read(item_id = newuser.id) >>> loaduser['name'] 'foo2' """ with get_storage() as storage: user = _read(storage, User, item_id) user = user.get_values() return user
def update(item_id, values): """Update a user with the given values in the database. .. seealso:: Methods :func:`tedega_core.api.crud.update` :item_id: ID of the user to update :values: Dictionary of values :returns: Dictionary with values of the user >>> import tedega_core.api.user >>> # First create a new user. >>> newuser = tedega_core.api.user.create(name="foo3", password="******") >>> # Now load the user >>> values = {"name": "baz"} >>> updateduser = tedega_core.api.user.update(item_id = newuser.id, values=values) >>> updateduser['name'] 'baz' """ with get_storage() as storage: user = _update(storage, User, item_id, values) user = user.get_values() return user
def test_storage_crud(): new_id = None with get_storage() as storage: new = DummyModel() new.dummy_string = "Foo" new.dummy_date = datetime.date.today() new_id = storage.create(new) assert new.dummy_string == "Foo" assert new.id is not None assert new_id == new.id assert new_id is not None with pytest.raises(Exception): with get_storage() as storage: new = DummyModel() new.dummy_string = "Foo" new.dummy_date = "XXX" new_id = storage.create(new) with get_storage() as storage: loaded = storage.read(DummyModel, new_id) assert loaded.dummy_string == "Foo" loaded.dummy_string = "Foo2" storage.update(loaded) with get_storage() as storage: loaded = storage.read(DummyModel, new_id) assert loaded.dummy_string == "Foo2" with get_storage() as storage: loaded = storage.read(DummyModel, new_id) storage.delete(loaded) with pytest.raises(Exception): with get_storage() as storage: loaded = storage.read(DummyModel, new_id) # DetachedInstanceError with pytest.raises(Exception): assert new_id == new.id
def test_search(): from tedega_storage.rdbms import get_storage from tedega_storage.rdbms.crud import search from tedega_view import ClientError # Search with get_storage() as storage: search(storage, Dummy, search="id::1") with pytest.raises(ClientError): with get_storage() as storage: search(storage, Dummy, search="xxx::1") with pytest.raises(ClientError): with get_storage() as storage: search(storage, Dummy, search="id:1") # Sort with get_storage() as storage: search(storage, Dummy, sort="-id") with get_storage() as storage: search(storage, Dummy, sort="id") with pytest.raises(ClientError): with get_storage() as storage: search(storage, Dummy, sort="-xxx")
def test_storage_without_scope(): storage = get_storage()
def storage(request, dbmodel): return get_storage()
def test_storage(): with get_storage() as storage: assert storage is not None assert storage.engine is not None