def users_create_default(email, password, id_): """Create default user. This user has the administrator role and can retrieve other user information as well as create new users. """ reana_user_characteristics = { "id_": id_, "email": email, } try: user = User.query.filter_by(**reana_user_characteristics).first() if not user: reana_user_characteristics["access_token"] = secrets.token_urlsafe( 16) user = User(**reana_user_characteristics) create_user_workspace(user.get_user_workspace()) Session.add(user) Session.commit() # create invenio user, passing `confirmed_at` to mark it as confirmed register_user(email=email, password=password, confirmed_at=datetime.datetime.now()) click.echo(reana_user_characteristics["access_token"]) except Exception as e: click.echo("Something went wrong: {0}".format(e)) sys.exit(1)
def new_user(session, db): """Create new user.""" user = User(email="{}@reana.io".format(uuid4()), access_token="secretkey-{}".format(uuid4())) session.add(user) session.commit() return user
def default_user(app, session): """Create users. Scope: function This fixture creates an user with a default UUID ``00000000-0000-0000-0000-000000000000``, ``email`` `[email protected]` and ``access_token`` ``secretkey`` and returns it. .. code-block:: python def test_default_user_exists(default) with app.test_client() as client: res = client.post(url_for('api.get_users'), query_string={"user": default_user.id_}) assert res.status_code == 200 """ default_user_id = "00000000-0000-0000-0000-000000000000" user = User.query.filter_by(id_=default_user_id).first() if not user: with patch("reana_db.database.Session", return_value=session): user = User(id_=default_user_id, email="*****@*****.**", access_token="secretkey") session.add(user) session.commit() return user
def _create_and_associate_reana_user(sender, token=None, response=None, account_info=None): try: user_email = account_info['user']['email'] user_fullname = account_info['user']['profile']['full_name'] username = account_info['user']['profile']['username'] search_criteria = dict() search_criteria['email'] = user_email users = Session.query(User).filter_by(**search_criteria).all() if users: user = users[0] else: user_access_token = secrets.token_urlsafe(16) user_parameters = dict(access_token=user_access_token) user_parameters['email'] = user_email user_parameters['full_name'] = user_fullname user_parameters['username'] = username user = User(**user_parameters) Session.add(user) Session.commit() except (InvalidRequestError, IntegrityError): Session.rollback() raise ValueError('Could not create user, ' 'possible constraint violation') except Exception: raise ValueError('Could not create user') return user
def _create_and_associate_reana_user(sender, token=None, response=None, account_info=None): try: user_email = account_info["user"]["email"] user_fullname = account_info["user"]["profile"]["full_name"] username = account_info["user"]["profile"]["username"] search_criteria = dict() search_criteria["email"] = user_email users = Session.query(User).filter_by(**search_criteria).all() if users: user = users[0] else: user_parameters = dict(email=user_email, full_name=user_fullname, username=username) user = User(**user_parameters) Session.add(user) Session.commit() except (InvalidRequestError, IntegrityError): Session.rollback() raise ValueError("Could not create user, " "possible constraint violation") except Exception: raise ValueError("Could not create user") return user
def users_create_default(email, id_): """Create default user. This user has the administrator role and can retrieve other user information as well as create new users. """ user_characteristics = {"id_": id_, "email": email, } try: user = User.query.filter_by(**user_characteristics).first() if not user: user_characteristics['access_token'] = secrets.token_urlsafe() user = User(**user_characteristics) create_user_workspace(user.get_user_workspace()) Session.add(user) Session.commit() click.echo('Created 1st user with access_token: {}'. format(user_characteristics['access_token'])) except Exception as e: click.echo('Something went wrong: {0}'.format(e)) sys.exit(1)
def _import_users(admin_access_token, users_csv_file): """Import list of users to database. :param admin_access_token: Admin access token. :type admin_access_token: str :param users_csv_file: CSV file object containing a list of users. :type users_csv_file: _io.TextIOWrapper """ admin = User.query.filter_by(id_=ADMIN_USER_ID).one_or_none() if admin_access_token != admin.access_token: raise ValueError('Admin access token invalid.') csv_reader = csv.reader(users_csv_file) for row in csv_reader: user = User(id_=row[0], email=row[1], access_token=row[2]) Session.add(user) Session.commit() Session.remove()
def _create_user(email, user_access_token, admin_access_token): """Create user with provided credentials.""" try: admin = Session.query(User).filter_by(id_=ADMIN_USER_ID).one_or_none() if admin_access_token != admin.access_token: raise ValueError('Admin access token invalid.') if not user_access_token: user_access_token = secrets.token_urlsafe(16) user_parameters = dict(access_token=user_access_token) user_parameters['email'] = email user = User(**user_parameters) Session.add(user) Session.commit() except (InvalidRequestError, IntegrityError) as e: Session.rollback() raise ValueError('Could not create user, ' 'possible constraint violation') return user
def _create_and_associate_reana_user(email, fullname, username): try: search_criteria = dict() search_criteria["email"] = email users = Session.query(User).filter_by(**search_criteria).all() if users: user = users[0] else: user_parameters = dict(email=email, full_name=fullname, username=username) user = User(**user_parameters) Session.add(user) Session.commit() except (InvalidRequestError, IntegrityError): Session.rollback() raise ValueError( "Could not create user, possible constraint violation") except Exception: raise ValueError("Could not create user") return user
def test_grant_token(default_user, session): """Test grant access token.""" runner = CliRunner() # non-existing email user result = runner.invoke( reana_admin, [ "token-grant", "--admin-access-token", default_user.access_token, "-e", "*****@*****.**", ], ) assert "does not exist" in result.output # non-existing id user result = runner.invoke( reana_admin, [ "token-grant", "--admin-access-token", default_user.access_token, "--id", "fake_id", ], ) assert "does not exist" in result.output # non-requested-token user user = User(email="*****@*****.**") session.add(user) session.commit() result = runner.invoke( reana_admin, [ "token-grant", "--admin-access-token", default_user.access_token, "-e", user.email, ], ) assert "token status is None, do you want to proceed?" in result.output # abort grant result = runner.invoke( reana_admin, [ "token-grant", "--admin-access-token", default_user.access_token, "-e", user.email, ], input="\n", ) assert "Grant token aborted" in result.output # confirm grant result = runner.invoke( reana_admin, [ "token-grant", "--admin-access-token", default_user.access_token, "-e", user.email, ], input="y\n", ) assert f"Token for user {user.id_} ({user.email}) granted" in result.output assert user.access_token assert default_user.audit_logs[-1].action is AuditLogAction.grant_token # user with active token active_user = User(email="*****@*****.**", access_token="valid_token") session.add(active_user) session.commit() result = runner.invoke( reana_admin, [ "token-grant", "--admin-access-token", default_user.access_token, "--id", str(active_user.id_), ], ) assert "has already an active access token" in result.output # typical ui user workflow ui_user = User(email="*****@*****.**") session.add(ui_user) session.commit() ui_user.request_access_token() assert ui_user.access_token_status is UserTokenStatus.requested.name assert ui_user.access_token is None result = runner.invoke( reana_admin, [ "token-grant", "--admin-access-token", default_user.access_token, "--id", str(ui_user.id_), ], ) assert ui_user.access_token_status is UserTokenStatus.active.name assert ui_user.access_token assert default_user.audit_logs[-1].action is AuditLogAction.grant_token
def test_revoke_token(default_user, session): """Test revoke access token.""" runner = CliRunner() # non-active-token user user = User(email="*****@*****.**") session.add(user) session.commit() result = runner.invoke( reana_admin, [ "token-revoke", "--admin-access-token", default_user.access_token, "-e", user.email, ], ) assert "does not have an active access token" in result.output # user with requested token user.request_access_token() assert user.access_token_status == UserTokenStatus.requested.name result = runner.invoke( reana_admin, [ "token-revoke", "--admin-access-token", default_user.access_token, "-e", user.email, ], ) assert "does not have an active access token" in result.output # user with active token user.access_token = "active_token" session.commit() assert user.access_token result = runner.invoke( reana_admin, [ "token-revoke", "--admin-access-token", default_user.access_token, "--id", str(user.id_), ], ) assert "was successfully revoked" in result.output assert user.access_token_status == UserTokenStatus.revoked.name assert default_user.audit_logs[-1].action is AuditLogAction.revoke_token # try to revoke again result = runner.invoke( reana_admin, [ "token-revoke", "--admin-access-token", default_user.access_token, "--id", str(user.id_), ], ) assert "does not have an active access token" in result.output