def first_data(app, user_datastore): with app.app_context(): db.create_all() user_datastore.create_role( name='admin', description="administration user" ) user_datastore.create_role( name='user', description="general user" ) admin = user_datastore.create_user( email='*****@*****.**', username='******', active=True, password=hash_password('password') ) user = user_datastore.create_user( email='*****@*****.**', username='******', active=True, password=hash_password('password') ) user_datastore.add_role_to_user(admin, 'user') user_datastore.add_role_to_user(user, 'user') user_datastore.add_role_to_user(admin, 'admin') db.session.commit()
def init_users(): """Sample users, not to be used in production.""" ds = current_app.extensions['invenio-accounts'].datastore superuser = Role.query.filter_by(name='superuser').one() cataloger = Role.query.filter_by(name='cataloger').one() hermes_curator = Role.query.filter_by(name='hermescurator').one() hermes_collections = Role.query.filter_by(name='hermescoll').one() with db.session.begin_nested(): ds.create_user( email='*****@*****.**', password=hash_password("123456"), active=True, roles=[superuser] ) ds.create_user( email='*****@*****.**', password=hash_password("123456"), active=True, roles=[cataloger] ) ds.create_user( email='*****@*****.**', password=hash_password("123456"), active=True, roles=[hermes_curator, hermes_collections] ) ds.create_user( email='*****@*****.**', password=hash_password("123456"), active=True ) db.session.commit()
def test_admin_createuser(app, admin_view): """Test flask-admin user creation""" with app.test_client() as client: # Test empty mail form res = client.post( url_for('user.create_view'), data={'email': ''}, follow_redirects=True ) assert b'This field is required.' in res.data # Reproduces the workflow described in #154 res = client.post( url_for('user.create_view'), data={'email': '*****@*****.**'}, follow_redirects=True ) assert _datastore.get_user('*****@*****.**') is not None res = client.post( url_for('user.create_view'), data={'email': '*****@*****.**', 'active': 'true'}, follow_redirects=True ) user = _datastore.get_user('*****@*****.**') assert user is not None assert user.active is True res = client.post( url_for('user.create_view'), data={'email': '*****@*****.**', 'active': 'false'}, follow_redirects=True ) user = _datastore.get_user('*****@*****.**') assert user is not None assert user.active is False user_data = dict(email='*****@*****.**', active=False, password=hash_password('123456')) _datastore.create_user(**user_data) user_data = dict(email='*****@*****.**', active=True, password=hash_password('123456')) _datastore.create_user(**user_data) user_data = dict(email='*****@*****.**', active=False, password=hash_password('123456')) _datastore.create_user(**user_data) _datastore.commit() assert _datastore.get_user('*****@*****.**') is not None user = _datastore.get_user('*****@*****.**') assert user is not None assert user.active is True user = _datastore.get_user('*****@*****.**') assert user is not None assert user.active is False
def set_pass(user, passw): """ Regenerate an user's password hash. """ user.password = hash_password(passw) db.session.commit() return True
def _create_user_for_api_registration(self, api_user_id): api_registration = ApiRegistrations.query.filter_by(id=api_user_id).one() password = os.urandom(5).encode('hex') kwargs = dict(email=api_registration.email, password=password, active='y') form = ConfirmRegisterForm(MultiDict(kwargs), csrf_enabled=False) u = None # Role with id 4 is an API user r = Role.query.filter_by(id=4).one() if form.validate(): kwargs['password'] = hash_password(kwargs['password']) kwargs['active'] = True u = _datastore.create_user(**kwargs) if _datastore.add_role_to_user(u, r): msg = TemplatedMessage(template_html='scoap3_api/email.html', subject='SCOAP3 - API registration confirmation', sender=current_app.config.get('MAIL_DEFAULT_SENDER'), recipients=[api_registration.email], ctx={'email': api_registration.email, 'password': password, 'recipient': api_registration.name }) current_app.extensions['mail'].send(msg) else: flash('Error creating user. %s' % form.errors, 'error')
def create_default_user_tenant_and_roles(admin_username, admin_password, amqp_manager, authorization_file_path): """ Create the bootstrap admin, the default tenant and the security roles, as well as a RabbitMQ vhost and user corresponding to the default tenant :return: The default tenant """ admin_role = _create_roles(authorization_file_path) default_tenant = _create_default_tenant() amqp_manager.create_tenant_vhost_and_user(tenant=default_tenant) admin_user = user_datastore.create_user( id=constants.BOOTSTRAP_ADMIN_ID, username=admin_username, password=hash_password(admin_password), roles=[admin_role] ) # User role assigned to admin user as a member of default tenant # This is the default role when adding a user is added to a tenant. # Anyway, `sys_admin` will be the effective role since is the system role. user_role = user_datastore.find_role(constants.DEFAULT_TENANT_ROLE) user_tenant_association = UserTenantAssoc( user=admin_user, tenant=default_tenant, role=user_role, ) admin_user.tenant_associations.append(user_tenant_association) user_datastore.commit() return default_tenant
def _create_new_record_version(app): """Create a new version of a record existing before the upgrade.""" from invenio_accounts.models import User from flask_security import url_for_security from flask_security.utils import hash_password from flask import url_for from invenio_oauth2server.models import Token user = User.query.filter(User.email=='*****@*****.**').one() user.password = hash_password('123') token = Token.create_personal( 'other_token', user.id, scopes=[] ) headers = [ ('Authorization', 'Bearer {}'.format(token.access_token)), ('Content-type', 'application/json') ] db.session.commit() with app.test_request_context(): login_url = url_for_security('login') with app.test_client() as client: res = client.post(login_url, data={ 'email': '*****@*****.**', 'password': '******' }) assert res.status_code == 302 url = url_for('b2share_records_rest.b2rec_list', version_of='1033083fedf4408fb5611f23527a926d') res = client.post(url, headers=headers) assert res.status_code == 201
def users(app): """Create user fixtures.""" hashed_password = hash_password('123456') user = User( email='*****@*****.**', password=hashed_password, active=True ) user_allowed = User( email='*****@*****.**', password=hashed_password, active=True ) db.session.add_all([user, user_allowed]) db.session.commit() author_admin = ActionUsers( action='admin-holdingpen-authors', user_id=user_allowed.id ) db.session.add(author_admin) db.session.commit() yield ActionUsers.query.filter_by(action='admin-holdingpen-authors').delete() User.query.filter_by(email='*****@*****.**').delete() User.query.filter_by(email='*****@*****.**').delete() db.session.commit()
def create_user(username, email, password): user = User() user.username = username user.email = email user.password = hash_password(password) user.roles.append(get_role()) db.session.add(user) db.session.commit()
def test_context(app): """Test passlib password context.""" with app.app_context(): ctx = flask.current_app.extensions['security'].pwd_context hashval = hash_password("test") assert hashval != "test" assert verify_password("test", hashval) assert not ctx.needs_update(hashval) assert ctx.hash("test") != ctx.hash("test")
def change_password(): if request.method == 'POST': user = User.query.get(session.get('user_id')) oldpass = request.form.get("oldpass") if not verify_password(oldpass, user.password): flash('Wrong password entered.') else: password = request.form.get('password') if password != '': user.password = hash_password(password) user.save() flash ('Password changed successfully. ') return render_template('change-password.html')
def test_client_authenticated(app): """Test for testutils.py:client_authenticated(client). We want to verify that it doesn't return True when the client isn't authenticated/logged in. """ ds = app.extensions['security'].datastore email = '*****@*****.**' password = '******' with app.app_context(): change_password_url = url_for_security('change_password') login_url = url_for_security('login') with app.test_client() as client: # At this point we should not be authenticated/logged in as a user # assert flask_login.current_user.is_anonymous assert not testutils.client_authenticated( client, test_url=change_password_url) # Test HTTP status code of view when not logged in. response = client.get(change_password_url) assert response.status_code == 302 assert change_password_url not in response.location assert login_url in response.location # Once more, following redirects. response = client.get(change_password_url, follow_redirects=True) assert response.status_code == 200 assert response.location is None # Create a user manually directly in the datastore ds.create_user(email=email, password=hash_password(password)) db.session.commit() # Manual login via view response = client.post(login_url, data={'email': email, 'password': password}, environ_base={'REMOTE_ADDR': '127.0.0.1'}) # Client gets redirected after logging in assert response.status_code == 302 assert testutils.client_authenticated(client) assert flask_login.current_user.is_authenticated # `is_authenticated` returns True as long as the user object # isn't anonymous, i.e. it's an actual user. response = client.get(change_password_url) assert response.status_code == 200 response = client.get(change_password_url, follow_redirects=True) assert response.status_code == 200
def users(app): """Create users needed in this test module.""" scientist = User( email='*****@*****.**', password=hash_password('scientist'), active=True, ) db.session.add(scientist) db.session.commit() yield User.query.filter_by(email='*****@*****.**').delete() db.session.commit()
def users_create(email, password, active): """Create a user.""" kwargs = dict(email=email, password=password, active='y' if active else '') form = ConfirmRegisterForm(MultiDict(kwargs), csrf_enabled=False) if form.validate(): kwargs['password'] = hash_password(kwargs['password']) kwargs['active'] = active _datastore.create_user(**kwargs) click.secho('User created successfully.', fg='green') kwargs['password'] = '******' click.echo(kwargs) else: raise click.UsageError('Error creating user. %s' % form.errors)
def upgrade(): ### commands auto generated by Alembic - please adjust! ### import flask_security.utils as security_utils role_table = op.create_table('role', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('name', sa.String(length=80), nullable=True), sa.Column('description', sa.String(length=255), nullable=True), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('name') ) op.bulk_insert(role_table, [ {'id': 1, 'name': 'admin', 'description': 'admin role'}, ], multiinsert=False) from sqlalchemy.sql import text op.get_bind().execute(text("ALTER SEQUENCE role_id_seq RESTART WITH 2;")) user_table = op.create_table('user', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('login', sa.String(length=64), nullable=False, unique=True), sa.Column('display', sa.String(length=255), nullable=False), sa.Column('email', sa.String(length=255), nullable=True), sa.Column('password', sa.String(length=255), nullable=True), sa.Column('active', sa.Boolean(), nullable=True), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('email') ) hashed_password = security_utils.hash_password('password') op.bulk_insert(user_table, [ {'id': 1, 'login': '******', 'display': 'Administrator', 'email': '*****@*****.**', 'password': hashed_password, 'active': True}, ], multiinsert=False) op.get_bind().execute(text("ALTER SEQUENCE user_id_seq RESTART WITH 2;")) roles_users_table = op.create_table('roles_users', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('role_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['role_id'], ['role.id'], ), sa.ForeignKeyConstraint(['user_id'], ['user.id'], ), sa.PrimaryKeyConstraint('id'), ) op.bulk_insert(roles_users_table, [ {'id': 1, 'user_id': 1, 'role_id': 1}, ], multiinsert=False) op.get_bind().execute(text("ALTER SEQUENCE roles_users_id_seq RESTART WITH 2;"))
def create_test_user(email, password='******', **kwargs): """Create a user in the datastore, bypassing the registration process. Accesses the application's datastore. An error is thrown if called from outside of an application context. Returns the created user model object instance, with the plaintext password as `user.password_plaintext`. :param email: The user email. :param password: The user password. (Default: ``123456``) :returns: A :class:`invenio_accounts.models.User` instance. """ assert flask.current_app.testing hashed_password = hash_password(password) user = _datastore.create_user(email=email, password=hashed_password, **kwargs) _datastore.commit() user.password_plaintext = password return user
def test_admin(app, admin_view): """Test flask-admin interace.""" # Test activation and deactivation with app.app_context(): # create user and save url for testing request_url = url_for("user.action_view") kwargs = dict(email="*****@*****.**", active=False, password=hash_password('aafaf4as5fa')) _datastore.create_user(**kwargs) _datastore.commit() inserted_id = _datastore.get_user('*****@*****.**').id with app.test_client() as client: res = client.post( request_url, data={'rowid': inserted_id, 'action': 'activate'}, follow_redirects=True ) assert res.status_code == 200 res = client.post( request_url, data={'rowid': inserted_id, 'action': 'inactivate'}, follow_redirects=True ) assert res.status_code == 200 pytest.raises( ValueError, client.post, request_url, data={'rowid': -42, 'action': 'inactivate'}, follow_redirects=True ) pytest.raises( ValueError, client.post, request_url, data={'rowid': -42, 'action': 'activate'}, follow_redirects=True )
def create_user(name, roles=None, permissions=None, admin_communities=None, member_communities=None): """Create a user. Args: name (str): user's name. roles (list): roles assigned to this new user. Returns: (UserInfo) created user's information. """ users_password = '******' accounts = current_app.extensions['invenio-accounts'] security = current_app.extensions['security'] email = '{}@example.org'.format(name) with db.session.begin_nested(): user = accounts.datastore.create_user( email=email, password=hash_password(users_password), active=True, ) db.session.add(user) if roles is not None: for role in roles: security.datastore.add_role_to_user(user, role) if permissions is not None: for permission in permissions: # permissions of the form [('action name', 'argument'), (...)] if len(permission) == 2: permission = ParameterizedActionNeed(permission[0], permission[1]) db.session.add(ActionUsers.allow(permission, user=user)) return UserInfo(email=email, password=users_password, id=user.id)
def create(self, username, password, completename=None): """ Init the user model, and save it in DB """ if User.query.filter_by(nickname=username).count() != 0: return False password = hash_password(password) user_datastore.create_user(nickname=username, password=password, completename=completename, active=False) myuser = User.query.filter_by(nickname=username).first() myuser.theme = "default" myuser.api_key = self.generate_api_key(username, password) # the first user is active and admin if User.query.count() == 1: self.manage_admin_role(myuser.id) user_datastore.activate_user(myuser) db.session.commit() return True
def loaduser(user_data): """Load a single user to Zenodo from JSON fixture.""" kwargs = { 'email': user_data['email'], 'password': hash_password(user_data['password']), 'active': user_data.get('active', True) } datastore = current_app.extensions['security'].datastore datastore.create_user(**kwargs) db.session.commit() user = User.query.filter_by(email=user_data['email']).one() actions = current_app.extensions['invenio-access'].actions actionusers_f = { 'allow': ActionUsers.allow, 'deny': ActionUsers.deny, } # e.g. [('allow', 'admin-access'), ] for action_type, action_name in user_data.get('access', []): action = actions[action_name] db.session.add( actionusers_f[action_type](action, user_id=user.id) ) db.session.commit()
def add_customer(self, data): data['password'] = hash_password(data.get('password')) customer = Customer(**data) customer.save() return customer
def register(): if request.method=='POST': user_datastore.create_user(email=request.form.get('email'),password=hash_password(request.form.get('password'))) db.session.commit() return redirect(url_for('profile')) return render_template('register.html')
def set_password(self, password: str) -> None: """Stores new password in database.""" self.password = hash_password(password)
def seeddb(): """ Seeds the database with the values in the setup.ini file """ # Load the setup.ini config file config_path = os.path.join(HOME_DIR, 'etc', 'setup.ini') if not os.path.exists(config_path): raise FileNotFoundError('Unable to locate setup.ini at: {}'.format(config_path)) config = configparser.ConfigParser(allow_no_value=True) config.optionxform = str # This preserves case-sensitivity for the values config.read(config_path) # Admin role if not models.Role.query.filter_by(name='admin').first(): admin_role = models.Role(name='admin') db.session.add(admin_role) db.session.commit() app.logger.info('SETUP: Created user role: admin') # Analyst role if not models.Role.query.filter_by(name='analyst').first(): analyst_role = models.Role(name='analyst') db.session.add(analyst_role) db.session.commit() app.logger.info('SETUP: Created user role: analyst') # Create the indicator confidences for value in config['indicator_confidence']: if not models.IndicatorConfidence.query.filter_by(value=value).first(): db.session.add(models.IndicatorConfidence(value=value)) db.session.commit() app.logger.info('SETUP: Created indicator confidence: {}'.format(value)) # Create the indicator impacts for value in config['indicator_impact']: if not models.IndicatorImpact.query.filter_by(value=value).first(): db.session.add(models.IndicatorImpact(value=value)) db.session.commit() app.logger.info('SETUP: Created indicator impact: {}'.format(value)) # Create the indicator statuses for value in config['indicator_status']: if not models.IndicatorStatus.query.filter_by(value=value).first(): db.session.add(models.IndicatorStatus(value=value)) db.session.commit() app.logger.info('SETUP: Created indicator status: {}'.format(value)) # Create the indicator types for value in config['indicator_type']: if not models.IndicatorType.query.filter_by(value=value).first(): db.session.add(models.IndicatorType(value=value)) db.session.commit() app.logger.info('SETUP: Created indicator type: {}'.format(value)) # Create the intel sources for value in config['intel_source']: if not models.IntelSource.query.filter_by(value=value).first(): db.session.add(models.IntelSource(value=value)) db.session.commit() app.logger.info('SETUP: Created intel source: {}'.format(value)) # Admin user if not models.User.query.filter_by(username='******').first(): user_datastore = SQLAlchemyUserDatastore(db, models.User, models.Role) password = ''.join(random.choice(string.ascii_letters + string.punctuation + string.digits) for x in range(20)) admin_role = models.Role.query.filter_by(name='admin').first() user_datastore.create_user(email='admin@localhost', password=hash_password(password), username='******', first_name='Admin', last_name='Admin', roles=[admin_role, analyst_role]) db.session.commit() admin = models.User.query.filter_by(username='******').first() app.logger.info('SETUP: Created admin user with password: {}'.format(password)) app.logger.info('SETUP: Created admin user with API key: {}'.format(admin.apikey))
def app(request): """Flask application fixture.""" # Set temporary instance path for sqlite instance_path = tempfile.mkdtemp() app = Flask('testapp', instance_path=instance_path) app.config.update(SQLALCHEMY_DATABASE_URI=os.environ.get( 'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'), TESTING=True, SECRET_KEY='SECRET_KEY', SQLALCHEMY_TRACK_MODIFICATIONS=False, JSONSCHEMAS_ENDPOINT='/schema', JSONSCHEMAS_HOST='ils.test.rero.ch', RECORDS_UI_ENDPOINTS={ "doc": { "pid_type": "doc", "route": "/documents/<pid_value>", "template": "reroils_data/detailed_view_documents_items.html" } }) InvenioDB(app) InvenioPIDStore(app) InvenioRecords(app) InvenioAccounts(app) REROILSDATA(app) InvenioAccess(app) InvenioJSONSchemas(app) InvenioRecordsUI(app) Menu(app) Babel(app) app.register_blueprint(item_blueprint) @app.route('/test/login') def login(): from flask_security import login_user from flask import request as flask_request role = flask_request.args.get('role') if role: datastore.create_role(name=role) datastore.add_role_to_user(user, role) datastore.commit() login_user(user) return "Logged In" @app.route('/test/login') def logout(): from flask_security import logout_user logout_user() return "Logged Out" from invenio_db import db as db_ with app.app_context(): if not database_exists(str(db_.engine.url)): create_database(str(db_.engine.url)) db_.create_all() security = LocalProxy(lambda: app.extensions['security']) datastore = LocalProxy(lambda: security.datastore) user = datastore.create_user(email='*****@*****.**', active=True, password=hash_password('aafaf4as5fa')) yield app # Teardown instance path. db_.session.remove() db_.drop_all() shutil.rmtree(instance_path)
def on_model_change(self, form, model, is_created): # If the password field isn't blank... if len(model.password2): # ... then encrypt the new password prior to storing it in the database. If the password field is blank, # the existing password in the database will be retained. model.password = utils.hash_password(model.password2)
def on_model_change(self, form, User, is_created): """Hash password when saving.""" if form.password.data is not None: User.password = hash_password(form.password.data)
def edit_user(user_id): """ Handles GET and POST requests to edit a user. GET request sends info on user. POST request submits changes. In case of failure, any change is rolled-back. @param user_id: the database ID of the user to edit. @type user_id: int @return: JSON with the current user data or HTTP 500 in case of error @rtype: JSON """ if request.method == 'GET': # user_id = request.args['user_id'] session = db.session() try: u = session.query(users).filter(users.id == user_id).first() if u is None: abort(404, description="User not found.") #r = session.query(roles_users).filter(roles_users.user_id == user_id) return jsonify({'id': u.id, 'username': u.username, 'email': u.email, 'password': '', 'first_name': u.first_name, 'last_name': u.last_name, 'active': u.active, 'is_superuser': u.is_superuser, 'roles': [{'id': role.id, 'name': role.name} for role in u.roles]}) except Exception: app.logger.exception("{} {}: Exception occurred while trying to delete category:".format(__file__, __name__)) return ("An error occured.", 500) pass finally: session.close() elif request.method == 'POST': session = db.session() try: if not 'input-email' in request.form or not isinstance(request.form['input-email'], str): raise ValueError("No email provided for adding a user.") email = request.form['input-email'] # handle special case for the admin user. It is the only user allowed without email username = email.split('@')[0] if request.form['input-username-hidden'] != 'admin' else 'admin' if len(username) < 2: app.logger.exception("{} {}: Username must be at least two characters long. Make sure to specify a valid email.".format(__file__, __name__)) return ("Could not edit user.", 500) firstname = request.form['input-firstname'] if 'input-firstname' in request.form else '' lastname = request.form['input-lastname'] if 'input-lastname' in request.form else '' password = hash_password(request.form['input-password']) if 'input-password' in request.form else '' roles = request.form.getlist('edit-select-roles') if 'edit-select-roles' in request.form else [] active = 1 if 'input-active' in request.form else 0 deleteRolesUsersByUser(session, user_id) update_data = { 'username': username, 'email': email, 'first_name': firstname, 'last_name': lastname, 'active': active } if password != '': update_data['password'] = password session.query(users).filter(users.id == user_id).update(update_data) for role_id in roles: addRolesUsers(session, user_id=user_id, role_id=role_id ) session.commit() app.logger.info("{} {}: Successfully edited user ({})".format(__file__, __name__, user_id)) return jsonify({ 'msg': 'User edited successfully.', 'user': {'username': username, 'email': email, 'firstname': firstname, 'lastname': lastname, 'active': active} }) except Exception: app.logger.exception("{} {}: Exception occurred while trying to edit user: {}".format(__file__, __name__, user_id)) session.rollback() return ("Could not edit user.", 500) finally: session.close()
def login_as_admin(self): user = user_datastore.create_user(email='*****@*****.**', name='test', password=hash_password('123456')) role = user_datastore.create_role(name='admin') user_datastore.add_role_to_user(user, role) db.session.commit() response = self.client.post( '/api/sessions', headers={'Content-Type': 'application/json'}, data=json.dumps({ 'email': '*****@*****.**', 'password': '******', })) json_response = json.loads(response.get_data(as_text=True)) return json_response
def accounts(): """ Register an account The method is available to apps with a token obtained via the client credentials grant. It creates a user and account records, as well as an access token for the app that initiated the request. The method returns the access token, which the app should save for later. --- tags: - Accounts definitions: Token: type: object properties: access_token: type: string token_type: type: string scope: type: string created_at: type: integer responses: 200: description: Returns Token schema: $ref: '#/definitions/Token' """ if not current_app.config["REGISTRATION_ENABLED"]: abort(403) errors = {} # Get the bearer token bearer = None if "Authorization" in request.headers: b = request.headers.get("Authorization") b = b.strip().split(" ") if len(b) == 2: bearer = b[1] else: errors["bearer"] = ["API Bearer Authorization format issue"] else: current_app.logger.info( "/api/v1/accounts: no Authorization bearer given") if not request.json: abort(400) if "nickname" not in request.json: errors["nickname"] = ["nickname is missing"] if "email" not in request.json: errors["email"] = ["email is missing"] if "fullname" not in request.json: errors["fullname"] = ["fullname is missing"] if "password" not in request.json: errors["password"] = ["password is missing"] if "confirm" not in request.json: errors["confirm"] = ["password confirm is missing"] if "agreement" not in request.json: errors["agreement"] = ["agreement is missing"] if len(errors) > 0: return jsonify({"error": str(errors)}), 400 if forbidden_username(request.json["nickname"]): return jsonify( {"error": str({"nickname": ["this username cannot be used"]})}), 400 if request.json["password"] != request.json["confirm"]: return jsonify( {"error": str({"confirm": ["passwords doesn't match"]})}), 400 if "agreement" not in request.json: return jsonify({ "error": str({"agreement": ["you need to accept the terms and conditions"]}) }), 400 # Check if user already exists by local user username user = User.query.filter(User.name == request.json["username"]).first() if user: return jsonify({"error": str({"ap_id": ["has already been taken"]})}), 400 # Check if user already exists by old local user (Actors) user = Actor.query.filter( Actor.preferred_username == request.json["username"]).first() if user: return jsonify({"error": str({"ap_id": ["has already been taken"]})}), 400 # Check if user already exists by email user = User.query.filter(User.email == request.json["email"]).first() if user: return jsonify({"error": str({"email": ["has already been taken"]})}), 400 # Check username is valid # /^[a-zA-Z\d]+$/ if not username_is_legal.match(request.json["username"]): return jsonify({ "error": str({"ap_id": ["should contains only letters and numbers"]}) }), 400 # Proceed to register the user role = Role.query.filter(Role.name == "user").first() if not role: return jsonify({"error": "server error"}), 500 u = user_datastore.create_user( name=request.json["username"], email=request.json["email"], display_name=request.json["fullname"], password=hash_password(request.json["password"]), roles=[role], ) actor = create_actor(u) actor.user = u actor.user_id = u.id if "bio" in request.json: actor.summary = request.json["bio"] db.session.add(actor) db.session.commit() if FSConfirmable.requires_confirmation(u): FSConfirmable.send_confirmation_instructions(u) # get the matching item from the given bearer bearer_item = OAuth2Token.query.filter( OAuth2Token.access_token == bearer).first() if not bearer_item: abort(400) client_item = OAuth2Client.query.filter( OAuth2Client.client_id == bearer_item.client_id).first() if not client_item: abort(400) # https://github.com/lepture/authlib/blob/master/authlib/oauth2/rfc6749/grants/base.py#L51 token = authorization.generate_token(client_item.client_id, "client_credentials", user=u, scope=client_item.scope, expires_in=None) tok = OAuth2Token() tok.user_id = u.id tok.client_id = client_item.client_id # the frontend should request an app every time it doesn't have one in local storage # and this app should allow delivering a somewhat non usuable Token # token which gets sent to this endpoint and gets used to get back the right client_id # to associate in the database... tok.token_type = token["token_type"] tok.access_token = token["access_token"] tok.refresh_token = None tok.scope = token["scope"] tok.revoked = False tok.expires_in = token["expires_in"] db.session.add(tok) db.session.commit() return jsonify({**token, "created_at": tok.issued_at}), 200
def on_model_change(self, form, User, is_created): """Hash password when saving.""" if form.password.data is not None: pwd_ctx = current_app.extensions['security'].pwd_context if pwd_ctx.identify(form.password.data) is None: User.password = hash_password(form.password.data)
def new_potential_user(): user = User(email='*****@*****.**', password=hash_password('test123')) return user
def test_authorized_signup_valid_user(app, example_globus): """Test authorized callback with sign-up.""" with app.test_client() as c: # User login with email 'info' ioc = app.extensions['oauthlib.client'] # Ensure remote apps have been loaded (due to before first request) resp = c.get(url_for('invenio_oauthclient.login', remote_app='globus')) assert resp.status_code == 302 example_info, example_token, example_account_id = example_globus mock_response(app.extensions['oauthlib.client'], 'globus', example_token) example_info.update(example_account_id) oauth_resp = OAuthResponse(resp=None, content=json.dumps(example_info), content_type='application/json') mock_remote_get(ioc, 'globus', oauth_resp) # User authorized the requests and is redirect back resp = c.get( url_for('invenio_oauthclient.authorized', remote_app='globus', code='test', state=_get_state())) assert resp.status_code == 302 assert resp.location == ('http://localhost/account/settings/' + 'linkedaccounts/') # Assert database state (Sign-up complete) user = User.query.filter_by(email='*****@*****.**').one() remote = RemoteAccount.query.filter_by(user_id=user.id).one() RemoteToken.query.filter_by(id_remote_account=remote.id).one() assert user.active # Disconnect link # should not work, because it's the user's only means of login resp = c.get( url_for('invenio_oauthclient.disconnect', remote_app='globus')) assert resp.status_code == 400 user = User.query.filter_by(email='*****@*****.**').one() assert 1 == UserIdentity.query.filter_by( method='globus', id_user=user.id, ).count() # set a password for the user user.password = hash_password("1234") db.session.commit() # Disconnect again resp = c.get( url_for('invenio_oauthclient.disconnect', remote_app='globus')) assert resp.status_code == 302 # User exists user = User.query.filter_by(email='*****@*****.**').one() assert 0 == UserIdentity.query.filter_by( method='globus', id_user=user.id, ).count() assert RemoteAccount.query.filter_by(user_id=user.id).count() == 0 assert RemoteToken.query.count() == 0 # User authorized the requests and is redirect back resp = c.get( url_for('invenio_oauthclient.authorized', remote_app='globus', code='test', state=_get_state())) assert resp.status_code == 302 assert resp.location == ('http://localhost/' + 'account/settings/linkedaccounts/') # check that exist only one account user = User.query.filter_by(email='*****@*****.**').one() assert User.query.count() == 1
def test_authorized_signup(app_with_userprofiles, example_orcid, orcid_bio): """Test authorized callback with sign-up.""" app = app_with_userprofiles example_data, example_account_info = example_orcid example_email = '*****@*****.**' with app.test_client() as c: # Ensure remote apps have been loaded (due to before first # request) c.get(url_for('invenio_oauthclient.login', remote_app='orcid')) mock_response(app.extensions['oauthlib.client'], 'orcid', example_data) # User authorized the requests and is redirect back resp = c.get( url_for('invenio_oauthclient.authorized', remote_app='orcid', code='test', state=get_state('orcid'))) assert resp.status_code == 302 assert resp.location == ( 'http://localhost' + url_for('invenio_oauthclient.signup', remote_app='orcid')) # User load sign-up page. resp = c.get(url_for('invenio_oauthclient.signup', remote_app='orcid')) assert resp.status_code == 200 account_info = session[token_session_key('orcid') + '_account_info'] data = { 'email': example_email, 'password': '******', 'profile.username': '******', 'profile.full_name': account_info['user']['profile']['full_name'], } # Mock request to ORCID to get user bio. httpretty.enable() httpretty.register_uri( httpretty.GET, 'http://orcid.org/{0}/orcid-bio'.format(example_data['orcid']), body=orcid_bio, content_type='application/orcid+json; qs=2;charset=UTF-8', ) # User fills form to register resp = c.post( url_for('invenio_oauthclient.signup', remote_app='orcid'), data=data, ) assert resp.status_code == 302 httpretty.disable() # Assert database state (Sign-up complete) user = User.query.filter_by(email=example_email).one() UserIdentity.query.filter_by(method='orcid', id_user=user.id, id=example_data['orcid']).one() # FIXME see contrib/orcid.py line 167 assert user.profile.full_name == 'Josiah Carberry' # assert user.given_names == 'Josiah' # assert user.family_name == 'Carberry' # check that the user's email is not yet validated assert user.active # check that the validation email has been sent # assert hasattr(locmem, 'outbox') and len(locmem.outbox) == 1 # Disconnect link # should not work, because it's the user's only means of login resp = c.get( url_for('invenio_oauthclient.disconnect', remote_app='orcid')) assert resp.status_code == 400 user = User.query.filter_by(email=example_email).one() assert 1 == UserIdentity.query.filter_by( method='orcid', id_user=user.id, id=example_data['orcid']).count() # set a password for the user user.password = hash_password("1234") db.session.commit() # Disconnect again resp = c.get( url_for('invenio_oauthclient.disconnect', remote_app='orcid')) assert resp.status_code == 302 # User exists user = User.query.filter_by(email=example_email).one() # UserIdentity removed. assert 0 == UserIdentity.query.filter_by( method='orcid', id_user=user.id, id=example_data['orcid']).count() assert RemoteAccount.query.filter_by(user_id=user.id).count() == 0 assert RemoteToken.query.count() == 0
def change_password(self, user_name, password): user = self.find_user(email=user_name) user.password = hash_password(password) self.put(user)
def _adjust_kwargs(cls, **kwargs): if 'password' in kwargs: # Password is stored hashed kwargs['password'] = hash_password(kwargs['password']) return kwargs
def set_password(self, password): self.password = hash_password(password)
def post(self): if check_member_role(["admin"], current_user.email) == False: return { "message": 'Missing authorization to retrieve content', }, 401 if "application/json" in request.headers["Content-Type"]: email = request.json["email"] print('\n\n\n\n', email, '\n\n\n\n') password = request.json["password"] username = request.json.get("username") current_login_ip = request.remote_addr company = request.json.get("company") contact = request.json.get("contact") address = request.json.get("address") roles = request.json.get("role") ####### NEED TO UPDATE TO DYNAMICALLY SEARCH AND INDEX INPUT FROM CLIENT ###### try: suppliers = request.json["suppliers"] except: # suppliers_list = Supplier.query.order_by(Supplier.email).all() # data = [supplier.as_dict() for supplier in suppliers_list] suppliers = [] pass # suppliers_list = Supplier.query.order_by(Supplier.email).all() # data = [supplier.as_dict() for supplier in suppliers_list] if user_datastore.get_user(email): return { "version": api_version, "message": "User {} exist. Please login".format(email), "data": {} }, 422 elif not re.match(r"[^@]+@[^@]+\.[^@]+", email): return { "version": api_version, "message": "Please check your email format.", "data": {} }, 422 elif len(password) < 6 or not password: return { "version": api_version, "message": "Password must be at least 6 characters long.", "data": {} }, 422 # create user and add user role as default user_datastore.create_user(email=email, password=hash_password(password), username=username, current_login_ip=current_login_ip, suppliers=str(suppliers), company=company, contact=contact, address=address) db_session.commit() if roles and Role.query.filter_by(name=roles).first(): user_datastore.add_role_to_user(email, roles) else: user_datastore.add_role_to_user(email, "user") db_session.commit() roles = user_datastore.find_user(email=email).roles user = User.query.filter_by(email=email).first() return { "version": api_version, "message": "User {} created.".format(email), "data": { "id": user.id, "email": user.email, "roles": list(map(lambda x: x.name, roles)), "suppliers": ast.literal_eval(user.suppliers), "company": user.company, "contact": user.contact, "address": user.address, "active": user.active } }, 200
def reset_password(self, password: Optional[str] = None) -> str: new_password = password or genword() self.password = hash_password(new_password) return new_password
def reset_password(self, password: Optional[str] = None) -> str: new_password = password or genword() self.password = hash_password(new_password) return new_password
def post(self, args): """Create user""" user = User(**args) user.password = hash_password(user.password) user.save() return user
def import_crits_indicators(): """ Imports CRITS indicators from the exported MongoDB JSON """ # Make sure the indicators.json file exists. if not os.path.exists('./import/indicators.json'): current_app.logger.error('Could not locate indicators.json for CRITS import') return # Validate the indicators JSON. crits_create_schema = { 'type': 'object', 'properties': { 'bucket_list': { 'type': 'array', 'items': {'type': 'string', 'maxLength': 255} }, 'campaign': { 'type': 'array', 'items': { 'type': 'object', 'properties': { 'name': {'type': 'string', 'maxLength': 255} } } }, 'confidence': { 'type': 'object', 'properties': { 'rating': {'type': 'string', 'minLength': 1, 'maxLength': 255} } }, 'created': { 'type': 'object', 'properties': { '$date': {'type': 'string', 'minLength': 24, 'maxLength': 24} } }, 'impact': { 'type': 'object', 'properties': { 'rating': {'type': 'string', 'minLength': 1, 'maxLength': 255} } }, 'modified': { 'type': 'object', 'properties': { '$date': {'type': 'string', 'minLength': 24, 'maxLength': 24} } }, 'source': { 'type': 'array', 'items': { 'type': 'object', 'properties': { 'instances': { 'type': 'array', 'items': { 'type': 'object', 'properties': { 'analyst': {'type': 'string', 'minLength': 1, 'maxLength': 255}, 'reference': {'type': 'string', 'maxLength': 512} } } }, 'name': {'type': 'string', 'minLength': 1, 'maxLength': 255} } } }, 'status': {'type': 'string', 'minLength': 1, 'maxLength': 255}, 'type': {'type': 'string', 'minLength': 1, 'maxLength': 255}, 'value': {'type': 'string', 'minLength': 1} }, 'required': ['confidence', 'created', 'impact', 'modified', 'source', 'status', 'type', 'value'] } start = time.time() # Connect to the database engine to issue faster select statements. with db.engine.connect() as conn: # Get the existing values from the database that indicators depend upon. existing_campaigns = dict() for x in models.Campaign.query.all(): existing_campaigns[x.name] = x existing_indicator_confidence = dict() for x in models.IndicatorConfidence.query.all(): existing_indicator_confidence[x.value] = x existing_indicator_impact = dict() for x in models.IndicatorImpact.query.all(): existing_indicator_impact[x.value] = x existing_indicator_status = dict() for x in models.IndicatorStatus.query.all(): existing_indicator_status[x.value] = x existing_indicator_type = dict() for x in models.IndicatorType.query.all(): existing_indicator_type[x.value] = x existing_intel_reference = dict() # source: reference: object for x in models.IntelReference.query.all(): if x.source.value not in existing_intel_reference: existing_intel_reference[x.source.value] = dict() existing_intel_reference[x.source.value][x.reference] = x existing_intel_source = dict() for x in models.IntelSource.query.all(): existing_intel_source[x.value] = x existing_tags = dict() for x in models.Tag.query.all(): existing_tags[x.value] = x existing_users = dict() for x in models.User.query.all(): existing_users[x.username] = x num_new_indicators = 0 unique_indicators = dict() # type: value line_count = 0 with open('./import/indicators.json') as f: for line in f: indicator = json.loads(line) jsonschema.validate(indicator, crits_create_schema) line_count += 1 # Skip this indicator if it is a duplicate. if indicator['type'] not in unique_indicators: unique_indicators[indicator['type']] = [] if indicator['value'] in unique_indicators[indicator['type']]: current_app.logger.warning('CRITS IMPORT: Skipping duplicate indicator: {}'.format(indicator['_id']['$oid'])) continue else: unique_indicators[indicator['type']].append(indicator['value']) # Check if the indicator confidence must be created. if indicator['confidence']['rating'] in existing_indicator_confidence: indicator_confidence = existing_indicator_confidence[indicator['confidence']['rating']] else: new_indicator_confidence = models.IndicatorConfidence(value=indicator['confidence']['rating']) existing_indicator_confidence[new_indicator_confidence.value] = new_indicator_confidence indicator_confidence = new_indicator_confidence db.session.add(new_indicator_confidence) db.session.flush() # Check if the indicator impact must be created. if indicator['impact']['rating'] in existing_indicator_impact: indicator_impact = existing_indicator_impact[indicator['impact']['rating']] else: new_indicator_impact = models.IndicatorImpact(value=indicator['impact']['rating']) existing_indicator_impact[new_indicator_impact.value] = new_indicator_impact indicator_impact = new_indicator_impact db.session.add(new_indicator_impact) db.session.flush() # Check if the indicator status must be created. if indicator['status'] in existing_indicator_status: indicator_status = existing_indicator_status[indicator['status']] else: new_indicator_status = models.IndicatorStatus(value=indicator['status']) existing_indicator_status[new_indicator_status.value] = new_indicator_status indicator_status = new_indicator_status db.session.add(new_indicator_status) db.session.flush() # Check if the indicator type must be created. if indicator['type'] in existing_indicator_type: indicator_type = existing_indicator_type[indicator['type']] else: new_indicator_type = models.IndicatorType(value=indicator['type']) existing_indicator_type[new_indicator_type.value] = new_indicator_type indicator_type = new_indicator_type db.session.add(new_indicator_type) db.session.flush() # Check if the user must be created. username = indicator['source'][0]['instances'][0]['analyst'] if username in existing_users: user = existing_users[username] else: password = ''.join(random.choice(string.ascii_letters + string.punctuation + string.digits) for x in range(20)) new_user = models.User(active=False, email='{}@unknown'.format(username), first_name=username, last_name='Unknown', password=hash_password(password), roles=[], username=username) existing_users[username] = new_user user = new_user db.session.add(new_user) db.session.flush() # Create the campaigns list. campaigns = set() if 'campaign' in indicator and indicator['campaign']: for campaign in indicator['campaign']: campaigns.add(existing_campaigns[campaign['name']]) # Create the intel references list. references = set() for s in indicator['source']: # Check if the source must be created. if s['name'] in existing_intel_source: source = existing_intel_source[s['name']] else: source = models.IntelSource(value=s['name']) existing_intel_source[s['name']] = source db.session.add(source) db.session.flush() # Make sure the source exists in the intel reference dictionary. if source.value not in existing_intel_reference: existing_intel_reference[source.value] = dict() for instance in s['instances']: # Check if the reference must be created. if 'reference' in instance and source.value in existing_intel_reference and instance['reference'] in existing_intel_reference[source.value]: references.add(existing_intel_reference[source.value][instance['reference']]) elif 'reference' in instance and instance['reference']: new_reference = models.IntelReference(reference=instance['reference'], source=source, user=user) existing_intel_reference[source.value][instance['reference']] = new_reference references.add(new_reference) db.session.add(new_reference) db.session.flush() # Create the tags list. tags = [] if 'bucket_list' in indicator and indicator['bucket_list']: for tag in indicator['bucket_list']: # Check if the tag must be created. if tag in existing_tags: tags.append(existing_tags[tag]) else: new_tag = models.Tag(value=tag) existing_tags[tag] = new_tag tags.append(new_tag) db.session.add(new_tag) db.session.flush() # Create the new indicator. try: new_indicator = models.Indicator(campaigns=list(campaigns), case_sensitive=False, confidence=indicator_confidence, created_time=parse(indicator['created']['$date']), impact=indicator_impact, modified_time=parse(indicator['modified']['$date']), references=list(references), status=indicator_status, substring=False, tags=tags, type=indicator_type, user=user, value=indicator['value']) db.session.add(new_indicator) num_new_indicators += 1 except Exception as e: current_app.logger.exception("CRITS IMPORT: unable to import indicator {}: {}".format(indicator, e)) #db.session.rollback() # Save any database changes. db.session.commit() current_app.logger.info('CRITS IMPORT: Imported {}/{} indicators in {}'.format(num_new_indicators, line_count, time.time() - start))
def set_password(self, pwd): self.password = hash_password(pwd) db.session.commit()
logs_repository=logs_repository, current_user=current_user, orchestation_interactor=orchestation_interactor, get_time_line_events=get_time_line_events, user_messaging=user_messaging, users_privileges=users_privileges, get_workers_load_model_status=get_workers_load_model) app.register_blueprint(dashboard.get_blueprint()) api_dashboard = ApiDashboard(create_ml_model=create_ml_model, token_verification=token_verification, worker_repository=worker_repository) app.register_blueprint(api_dashboard.get_blueprint()) # This snippet of code is user with password create example if CREATE_ADMIN_USER and not len(user_datastore.user_model.objects()): logging.info("Creating default admin user.") with app.app_context(): admin_role = user_datastore.find_or_create_role('admin') user_datastore.create_user(email='admin', password=utils.hash_password('admin'), name='admin', username='******', roles=[admin_role]) if __name__ == '__main__': # Start app app.run(debug=True, host='0.0.0.0', port=int(SERVICE_PORT))
def on_model_change(self, form, model, is_created): if form.password.data: model.password = hash_password(form.password.data)
def users(): form = UserForm() dform = DeleteForm() form.roles.choices = [ (r.name, r.description) for r in models.Role.query.order_by(models.Role.name.asc()).all() ] if current_app.config['AJAX_CALL_ENABLED']: form.associate_group_id.choices = [] associate_group_id = current_user.associate_group_id if associate_group_id and is_region_role(): form.associate_group_id.choices = [ (ag.id, ag.name) for ag in models.AssociateGroup.query.filter_by( id=associate_group_id).all() ] return render_template('admin/user.html', form=form, dform=dform) else: province_id = current_user.province_id if province_id and is_region_role(): us = models.User.query.filter_by(province_id=province_id).all() form.province_id.choices = [ (p.province_id, p.type + " " + p.name) for p in models.Province.query.filter_by( province_id=province_id).all() ] else: us = models.User.query.all() form.province_id.choices = [] # form create or edit submit if request.method == 'POST' and form.data['submit']: if not check_role(crud_role): return redirect(url_for(request.endpoint)) form.province_id.choices = [(form.province_id.data, form.province_id.label.text)] # edit user if form.id.data: # remove required validator in fields pass and confirm # when form is edit form setattr(form.password, 'validators', [match_pass]) setattr(form.confirm, 'validators', []) if form.validate_on_submit(): edit_user = user_datastore.find_user(id=form.id.data) if form.old_password.data: if not security_utils.verify_and_update_password( form.old_password.data, edit_user): flash(str(__('Old password is wrong!')), 'error') # TODO: fix return to keep current state of form return redirect(url_for(request.endpoint)) else: edit_user.password = security_utils.hash_password( form.password.data) temp_user = sqla.session.query(models.User) \ .filter_by(email=form.email.data).all() if not check_user_email(temp_user, edit_user.email): form.email.errors.append(__('The email was existed!')) flash(str(__('The email was existed!')), 'error') else: edit_user.email = form.email.data edit_user.fullname = form.fullname.data if form.province_id.data != edit_user.province_id: edit_user.province = models.Province.query \ .filter_by(province_id=form.province_id.data) \ .one() for new_role in form.roles.data: role_is_added = False for r in edit_user.roles: if new_role == r.name: role_is_added = True break if not role_is_added: user_datastore.add_role_to_user( edit_user.email, new_role) temp_roles = list(edit_user.roles) for old_role in temp_roles: if old_role.name not in form.roles.data: user_datastore.remove_role_from_user( edit_user.email, old_role.name) user_datastore.put(edit_user) for user in us: if user.id == edit_user.id: us.remove(user) us.append(edit_user) flash(str(__('Update user success!')), 'success') return redirect(url_for(request.endpoint)) else: flash(str(__('The form is not validated!')), 'error') # add user else: setattr(form.password, 'validators', [data_required, match_pass]) setattr(form.confirm, 'validators', [data_required]) form.id.data = str(uuid.uuid4()) if form.validate_on_submit(): if not user_datastore.find_user(email=form.email.data): province = models.Province.query.filter_by( province_id=form.province_id.data).one() user_datastore.create_user( id=form.id.data, email=form.email.data, fullname=form.fullname.data, province=province, password=security_utils.hash_password( form.password.data)) sqla.session.commit() for role in form.roles.data: user_datastore.add_role_to_user( form.email.data, role) sqla.session.commit() flash(str(__('Add user success!')), 'success') return redirect(url_for(request.endpoint)) else: form.email.errors.append(__('The email was existed!')) flash(str(__('The email was existed!')), 'error') else: flash(str(__('The form is not validated!')), 'error') # form delete submit if request.method == 'POST' and dform.data['submit_del']: if not check_role(crud_role): return redirect(url_for(request.endpoint)) elif dform.validate_on_submit(): del_user = user_datastore.find_user(id=dform.id.data) user_datastore.delete_user(del_user) sqla.session.commit() flash(str(__('Delete user success!')), 'success') return redirect(url_for(request.endpoint)) return render_template('admin/user.html', us=us, form=form, dform=dform)
def populate_test_data(): print("Populating test data into the database...") from .models import User, RolesUsers, Challenge, Solve a_user = User( username=contestant["username"], email=contestant["email"], password=utils.hash_password(contestant["password"]), active=True ) abc_user = User( username=admin["username"], email=admin["email"], password=utils.hash_password(admin["password"]), active=True) db.session.add(a_user) db.session.add(abc_user) db.session.commit() a_contestant = RolesUsers( user_id=a_user.id, role_id=2) abc_admin = RolesUsers( user_id=abc_user.id, role_id=1) db.session.add(a_contestant) db.session.add(abc_admin) db.session.commit() first_challenge = Challenge( title=challenges[0]["title"], category=challenges[0]["category"], author=challenges[0]["author"], body=challenges[0]["body"], solution=challenges[0]["solution"]) second_challenge = Challenge( title=challenges[1]["title"], category=challenges[1]["category"], author=challenges[1]["author"], body=challenges[1]["body"], solution=challenges[1]["solution"]) db.session.add(first_challenge) db.session.add(second_challenge) db.session.commit() third_challenge = Challenge( title=challenges[2]["title"], category=challenges[2]["category"], author=challenges[2]["author"], body=challenges[2]["body"], solution=challenges[2]["solution"], previous_challenge_id=second_challenge.id) db.session.add(third_challenge) db.session.commit() for user in (a_user, abc_user): for challenge in (first_challenge, second_challenge, third_challenge): solve = Solve( user_id=user.id, challenge_id=challenge.id, solved=False, ) db.session.add(solve) db.session.commit()
def hash_backup_codes(codes): return [hash_password(clean_random_code(c)) for c in codes]
def test_admin_createuser(app, admin_view): """Test flask-admin user creation""" with app.test_client() as client: # Test empty mail form res = client.post(url_for("user.create_view"), data={"email": ""}, follow_redirects=True) assert b"This field is required." in res.data # Reproduces the workflow described in #154 res = client.post( url_for("user.create_view"), data={"email": "*****@*****.**"}, follow_redirects=True, ) assert _datastore.get_user("*****@*****.**") is not None res = client.post( url_for("user.create_view"), data={ "email": "*****@*****.**", "active": "true" }, follow_redirects=True, ) user = _datastore.get_user("*****@*****.**") assert user is not None assert user.active is True res = client.post( url_for("user.create_view"), data={ "email": "*****@*****.**", "active": "false" }, follow_redirects=True, ) user = _datastore.get_user("*****@*****.**") assert user is not None assert user.active is False user_data = dict(email="*****@*****.**", active=False, password=hash_password("123456")) _datastore.create_user(**user_data) user_data = dict(email="*****@*****.**", active=True, password=hash_password("123456")) _datastore.create_user(**user_data) user_data = dict(email="*****@*****.**", active=False, password=hash_password("123456")) _datastore.create_user(**user_data) _datastore.commit() assert _datastore.get_user("*****@*****.**") is not None user = _datastore.get_user("*****@*****.**") assert user is not None assert user.active is True user = _datastore.get_user("*****@*****.**") assert user is not None assert user.active is False
from flask_security import utils sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from app import create_app from models import Page, db, Role, User app = create_app() with app.app_context(): admin_role = Role() admin_role.name = 'admin' db.session.add(admin_role) db.session.commit() root = User() root.email = '*****@*****.**' root.password = utils.hash_password("123456") root.active = True root.roles.append(admin_role) db.session.add(root) db.session.commit() page = Page() page.title = "Home Page" page.content = "<h1><b>Hello from flask - docker!<b></h1>" page.is_homepage = True db.session.add(page) db.session.commit()
def password_str(self, value: str): if value: self.password = hash_password(value)
def register_user(self, data): user = self.user_datastore.create_user(email=data.get("email"), password=hash_password( data.get("password"))) self.db.session.commit() return user
def on_model_change(self, form, model, is_created): model.password = hash_password(model.password2)