def create_admin(email, password): try: admin = Users() admin.email = email admin.password = encrypt_password(password) admin.active = True admin.confirmed_at = datetime.now(tzlocal()) db.session.add(admin) db.session.commit() except IntegrityError: db.session.rollback() admin = db.session.query(Users).filter(Users.email == email).one() admin.password = encrypt_password(password) admin.confirmed_at = datetime.now(tzlocal()) db.session.commit() print('Password reset for {0}'.format(email)) try: administrator = Roles() administrator.name = 'administrator' administrator.description = 'administrator' db.session.add(administrator) db.session.commit() except IntegrityError: db.session.rollback() administrator = (db.session.query(Roles) .filter(Roles.name == 'administrator').one()) admin.roles.append(administrator) db.session.commit()
def create_or_edit_user(user_id=None): if user_id: user = peewee_flask_utils.get_object_or_404(User, User.id==user_id) else: user = None # Create a new user form = user_form(user)(request.form) if form.validate_on_submit(): ds = current_app.extensions['security'].datastore if user: if form.password1.data: user.password=encrypt_password(form.password1.data) form.populate_obj(user) user.save() else: user = ds.create_user( email=form.email.data, password=encrypt_password(form.password1.data), active=form.active.data) for r in Role.select(): if getattr(form.roles.form, r.name).data: ds.add_role_to_user(user, r.name) else: ds.remove_role_from_user(user, r.name) flash('User {} was updated.'.format(user.email), "success") return redirect(url_for('.index'), code=303) return render_template('useradmin/create_or_edit_user.html', form=form, user=user)
def build_sample_db(): db.drop_all() db.create_all() with app.app_context(): user_role = Role(name='user') super_user_role = Role(name='superuser') blocked_user_role= Role(name='blocked') db.session.add(user_role) db.session.add(super_user_role) db.session.add(blocked_user_role) db.session.commit() test_user = user_datastore.create_user( name='Admin', email='admin', password=encrypt_password('admin'), roles=[user_role, super_user_role], confirmed_at=datetime.datetime.utcnow() ) user_datastore.create_user( name='test_user', email='*****@*****.**', password=encrypt_password('123456'), roles=[user_role, ], confirmed_at=datetime.datetime.utcnow() ) db.session.commit() return
def build_sample_db(): """ Populate a small db with some example entries. """ import string #db.drop_all() db.create_all() with app.app_context(): read_role = Role(name='read') user_role = Role(name='user') super_user_role = Role(name='adminrole') db.session.add(user_role) db.session.add(super_user_role) db.session.add(Role(name='create')) db.session.add(Role(name='supervisor')) db.session.add(Role(name='delete')) db.session.add(Role(name='export')) db.session.add(read_role) db.session.commit() test_user = user_datastore.create_user( first_name='Admin', email='admin', password=encrypt_password('admin'), roles=[user_role, super_user_role] ) #set user / pass in creden.py uname=app.config['USER1'] user1a = user_datastore.create_user( first_name=uname, email=uname, password=encrypt_password(app.config['PASS1']), roles=[user_role, super_user_role] ) first_names = [ 'read', ] last_names = [ 'Brown', ] for i in range(len(first_names)): tmp_email = first_names[i].lower() # initialize the users with simple password... 'a' tmp_pass = app.config['PASS1'] user_datastore.create_user( first_name=first_names[i], last_name=last_names[i], email=tmp_email, password=encrypt_password(tmp_pass), roles=[read_role ] ) db.session.commit() return
def create_test_models(): user_datastore.create_user(email='test', password=encrypt_password('test')) user_datastore.create_user(email='test2', password=encrypt_password('test2')) stuff = SomeStuff(data1=2, data2='toto', user_id=1) db.session.add(stuff) stuff = SomeStuff(data1=5, data2='titi', user_id=1) db.session.add(stuff) db.session.commit()
def build_sample_db(): """ Populate a small db with some example entries. """ import string #db.drop_all() db.create_all() with app.app_context(): read_role = Role(name='read') user_role = Role(name='user') super_user_role = Role(name='adminrole') db.session.add(user_role) db.session.add(super_user_role) db.session.add(Role(name='read')) db.session.add(Role(name='create')) db.session.add(Role(name='supervisor')) db.session.add(Role(name='delete')) db.session.add(Role(name='export')) db.session.commit() test_user = user_datastore.create_user( first_name='Admin', email='admin', password=encrypt_password('admin'), roles=[user_role, super_user_role] ) first_names = [ 'read', 'create', 'user', 'suser', 'delete', 'Charlie', 'Sophie', 'Mia', ] last_names = [ 'Brown', 'Smith', 'Patel', 'Jones', 'Williams', 'Johnson', 'Taylor', 'Thomas', ] roles1 = [ 'read', 'create', 'user', 'supervisor', 'delete', 'read', 'read', 'read', ] for i in range(len(first_names)): tmp_email = first_names[i].lower() # initialize the users with simple password... 'a' tmp_pass = '******' user_datastore.create_user( first_name=first_names[i], last_name=last_names[i], email=tmp_email, password=encrypt_password(tmp_pass), roles=[read_role, ] ) db.session.commit() return
def add_user(email, password, roles, admin_first_run=False): """ Add a new user. :param email: email of the new user :type email: str :param password: password of the new user :type password: str :param roles: site roles the new user should have :type roles: list or tuple :param admin_first_run: if first run, automatically set the user "confirmed_at" field :type admin_first_run: bool """ email_test = _DummyEmailField(email) email_validator = Email() try: email_validator(None, email_test) except ValidationError: print("Email is invalid") sys.exit(2) with current_app.app_context(): if User.query.filter_by(email=email).first(): print("User already exists") sys.exit(2) fullname = email.split("@")[0] if admin_first_run: user_datastore.create_user(email=email, password=encrypt_password(password), fullname=fullname, confirmed_at=datetime.now()) else: user_datastore.create_user(email=email, password=encrypt_password(password), fullname=fullname) try: db.session.commit() except exc.IntegrityError: db.session.rollback() raise AddUserError("User already exists") for role in roles: role_obj = user_datastore.find_role(role) if role_obj: user_datastore.add_role_to_user(email, role_obj) try: db.session.commit() except exc.IntegrityError: db.session.rollback() raise AddUserError("User roles not added correctly")
def build_sample_db(): """ Populate a small db with some example entries. """ import string import random db.drop_all() db.create_all() # Setup Flask-Security user_datastore = SQLAlchemyUserDatastore(db, User, Role) security = Security(app, user_datastore) with app.app_context(): user_role = Role(name='user') super_user_role = Role(name='superuser') db.session.add(user_role) db.session.add(super_user_role) db.session.commit() test_user = user_datastore.create_user( first_name='Admin', email='admin', password=encrypt_password('admin'), roles=[user_role, super_user_role] ) first_names = [ 'Harry', 'Amelia', 'Oliver', 'Jack', 'Isabella', 'Charlie', 'Sophie', 'Mia', 'Jacob', 'Thomas', 'Emily', 'Lily', 'Ava', 'Isla', 'Alfie', 'Olivia', 'Jessica', 'Riley', 'William', 'James', 'Geoffrey', 'Lisa', 'Benjamin', 'Stacey', 'Lucy' ] last_names = [ 'Brown', 'Smith', 'Patel', 'Jones', 'Williams', 'Johnson', 'Taylor', 'Thomas', 'Roberts', 'Khan', 'Lewis', 'Jackson', 'Clarke', 'James', 'Phillips', 'Wilson', 'Ali', 'Mason', 'Mitchell', 'Rose', 'Davis', 'Davies', 'Rodriguez', 'Cox', 'Alexander' ] for i in range(len(first_names)): tmp_email = first_names[i].lower() + "." + last_names[i].lower() + "@example.com" tmp_pass = ''.join(random.choice(string.ascii_lowercase + string.digits) for i in range(10)) user_datastore.create_user( first_name=first_names[i], last_name=last_names[i], email=tmp_email, password=encrypt_password(tmp_pass), roles=[user_role, ] ) db.session.commit() return
def test_user_teams(self): # create stub m = Mox() m.StubOutWithMock(utils, "encrypt_password") m.StubOutWithMock(utils, "verify_password") m.StubOutWithMock(base64, "b64encode") m.StubOutWithMock(os, "urandom") # start recording utils.encrypt_password("test") utils.verify_password("test", None).AndReturn(True) utils.verify_password("asdfasdf", None).AndReturn(False) # mock the urandom return for the salt, and make sure that gets base-64 encoded into something different os.urandom(128).AndReturn("she sells sea shells by the sea shore") base64.b64encode("she sells sea shells by the sea shore").AndReturn("Salt-n-Pepa") m.ReplayAll() # Create user and teams user1 = self.user_access.create_user(self.__get_user_dict()) team1 = self.user_access.create_team(self.__get_team_dict()) team2 = self.user_access.create_team(self.__get_team_dict()) # Add user to teams team_ids = [team1["id"], team2["id"]] self.user_access.update_user(user1["id"], {"team_ids": team_ids}) user_teams = self.user_access.find_user_teams({"user_id": user1["id"]}) team_id_list = [user_team["team_id"] for user_team in user_teams] self.assertEqual(team_id_list, team_ids) # Making team generalist should make all members generalists self.assertEqual(self.user_access.get_user(user1["id"])["is_generalist"], False) self.assertEqual(self.user_access.get_team(team1["id"])["is_generalist"], False) self.user_access.update_team(team1["id"], {"is_generalist": True}) self.assertEqual(self.user_access.get_user(user1["id"])["is_generalist"], True) self.assertEqual(self.user_access.get_team(team1["id"])["is_generalist"], True) # Making team not generalist should not affect members in another generalist team self.user_access.update_team(team2["id"], {"is_generalist": True}) self.user_access.update_team(team1["id"], {"is_generalist": False}) self.assertEqual(self.user_access.get_user(user1["id"])["is_generalist"], True) self.assertEqual(self.user_access.get_team(team1["id"])["is_generalist"], False) self.assertEqual(self.user_access.get_team(team2["id"])["is_generalist"], True) # Making team not generalist should update all affected users self.user_access.update_team(team2["id"], {"is_generalist": False}) self.assertEqual(self.user_access.get_user(user1["id"])["is_generalist"], False) self.assertEqual(self.user_access.get_team(team2["id"])["is_generalist"], False)
def users(app): """Create user fixtures.""" encrypted_password = encrypt_password('123456') user = User( email='*****@*****.**', password=encrypted_password, active=True ) user_allowed = User( email='*****@*****.**', password=encrypted_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 user(): """Create circulation admin user.""" from werkzeug.local import LocalProxy from flask_security.utils import encrypt_password from invenio_db import db from invenio_oauth2server.models import Token _datastore = LocalProxy(lambda: app.extensions['security'].datastore) kwargs = dict( email='*****@*****.**', password='******', active=True ) kwargs['password'] = encrypt_password(kwargs['password']) user = _datastore.create_user(**kwargs) Token.create_personal( 'test-personal-{0}'.format(user.id), user.id, scopes=['webhooks:event'], is_internal=True, ).access_token db.session.commit()
def configure_security(): # Create the Roles "admin" and "end-user" -- unless they already exist user_datastore.find_or_create_role(name='admin', description='Administrator') user_datastore.find_or_create_role(name='end-user', description='End user') user_datastore.find_or_create_role(name='blogger', description='Blogger') # Create two Users for testing purposes -- unless they already exists. # In each case, use Flask-Security utility function to encrypt the password. pw = encrypt_password('password') # pw = 'password' if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user(email='*****@*****.**', password=pw) if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user(email='*****@*****.**', password=pw) # Give one User has the "end-user" role, while the other has the "admin" role. #(This will have no effect if the # Users already have these Roles.) Again, commit any database changes. user_datastore.add_role_to_user('*****@*****.**', 'end-user') user_datastore.add_role_to_user('*****@*****.**', 'blogger') user_datastore.add_role_to_user('*****@*****.**', 'admin') user_datastore.add_role_to_user('*****@*****.**', 'blogger') db.session.commit()
def registerUser(): form = UserRegisterForm(request.form) if form.validate_on_submit(): user = User( name = form.name.data, surname = form.surname.data, email = form.email.data, password = utils.encrypt_password(form.password.data), birth_date = form.birth_date.data, #country = form.country.data, il_id = form.il.data if form.il.data > 0 else None, ilce_id = form.ilce.data if form.ilce.data > 0 else None, semt_id = form.semt.data if form.semt.data > 0 else None, confirmed = False, active = True ) for i in form.interests.data: #dao.addObject(interests_users(interest_id=i, user_id=user.id)) user.interests.append(dao.getObject(i, InterestArea)) dao.addObject(user) dao.commit() login_user(user) flash(u'Kayıt oldunuz', 'info') return redirect(url_for('index')) return render_template('register_user.html', form=form)
def test_verify_password_bcrypt(app, sqlalchemy_datastore): init_app_with_options(app, sqlalchemy_datastore, **{ 'SECURITY_PASSWORD_HASH': 'bcrypt', 'SECURITY_PASSWORD_SALT': 'salty' }) with app.app_context(): assert verify_password('pass', encrypt_password('pass'))
def createDB(): db.create_all() if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user(email='*****@*****.**', password=utils.encrypt_password('password'), name="Userguy", surname="Userson", confirmed=True) if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user(email='*****@*****.**', password=utils.encrypt_password('password'), name="Editorman", surname="Editson", confirmed=True) if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user(email='*****@*****.**', password=utils.encrypt_password('password'), name="Admin", surname="Adminson", confirmed=True) user_datastore.find_or_create_role(name='admin', description='Administrator') user_datastore.find_or_create_role(name='user', description='User') user_datastore.find_or_create_role(name='editor', description='Editor') db.session.commit() user_datastore.add_role_to_user('*****@*****.**', 'user') user_datastore.add_role_to_user('*****@*****.**', 'editor') user_datastore.add_role_to_user('*****@*****.**', 'admin') db.session.commit()
def build_sample_db(): """ Populate a small db with some example entries. """ import string import random #db.drop_all() db.create_all() with app.app_context(): user_role = Role(name='user') super_user_role = Role(name='superuser') db.session.add(user_role) db.session.add(super_user_role) db.session.commit() test_user = user_datastore.create_user( first_name='Admin', email='admin', password=encrypt_password('admin'), roles=[user_role, super_user_role] ) db.session.commit() return
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 = encrypt_password(password) user_datastore.create_user(nickname=username, password=password, completename=completename, active=False) myuser = User.query.filter_by(nickname=username).first() # TODO : manage API key with flask-login apikey_seed = str(random.randint(0, 0xFFFFFFFFFFFFFFFF)) apikey_seed = apikey_seed + str(int(time.time())) apikey_seed = apikey_seed + sha256(username).hexdigest() apikey_seed = apikey_seed + sha256(password).hexdigest() apikey_seed = ''.join(random.sample(apikey_seed, len(apikey_seed))) myuser.api_key = sha256(apikey_seed).hexdigest() myuser.theme = "default" # the first user is active and admin if User.query.count() == 1: role = user_datastore.find_or_create_role("admin", description="Administrator") if role is not None: user_datastore.add_role_to_user(myuser, role) else: app.logger.error("Cannot find and affect admin role to user") user_datastore.activate_user(myuser) db.session.commit() return True
def update_model(self, form, model): original_password = model.password model.update(**form.data) if form.data["password"] != original_password: model.password = encrypt_password(form.data["password"]) model.save() return flask.redirect(flask.url_for("user.index_view"))
def create_user(): if not models.User.query.first(): models.user_datastore.create_user( id='1', email='*****@*****.**', password=encrypt_password('gfhjkm')) db.session.commit() if not models.Role.query.first(): models.user_datastore.create_role( id=1, name='admin', description='admin') models.user_datastore.create_role( id=2, name='manager', description='Менеджер' ) models.user_datastore.create_role( id=3, name='logist', description='Логист' ) models.user_datastore.add_role_to_user( user='******', role='admin') db.session.commit()
def db_auth(): """ What to do if the main auth object has no rows """ missing_role = not Role.query.first() logger.debug("Missing role") if missing_role: udstore.create_role(name=config.ROLE_ADMIN, description='King') udstore.create_role(name=config.ROLE_USER, description='Citizen') logger.debug("Created roles") missing_user = not User.query.first() logger.debug("Missing user") if missing_user: import datetime now = datetime.datetime.utcnow() from flask_security.utils import encrypt_password udstore.create_user(first_name='TheOnlyUser', last_name='IAm', email=config.USER, confirmed_at=now, password=encrypt_password(config.PWD)) udstore.add_role_to_user(config.USER, config.ROLE_ADMIN) logger.debug("Created user") if missing_user or missing_role: db.session.commit() logger.info("Database init with user/roles from conf")
def add_tapadmin(email='*****@*****.**',firstname='Testy',lastname='Test',password='******'): """Add a TAP admin user to your database_string""" # add_tapadmin [email protected] --firstname=Doug --lastname=Goodwin --password= print "got email=%s,firstname=%s,lastname=%s,password=%s" %(email,firstname,lastname,password) epass = encrypt_password(email) print "pass set to: %s" %(epass) # set up the tapadmin role if necessary try: tapadmin_role = Role(name='tapadmin',description='TAP Administrator') db.session.add(tapadmin_role) db.session.commit() except: tapadmin_role = Role.query.filter(name=='tapadmin').first() # add this user unless s/he already exists try: tapadmin = User(email=email, firstname=firstname, lastname=lastname, password=epass, active=True, roles=[tapadmin_role], ) db.session.add(tapadmin) db.session.commit() except: tapadmin = User.query.filter(email==email).first()
def __init__(self, name): self.email = '{}@invenio-software.org'.format(name) self.user = accounts.datastore.create_user( email=self.email, password=encrypt_password(password), active=True, )
def change_passwd(): password = request.json.get('password') password_repeat = request.json.get('password_repeat') if not password or not password_repeat: # Request body is not complete. return error_response(errors.AUTH_RESET_MISSING, 400) if password != password_repeat: # Password do not match. return error_response(errors.AUTH_PASSWD_MATCH, 400) if current_user.is_authenticated: # No need to check password hash object or email. user = current_user else: email = request.json.get('email') hashstr = request.json.get('hashstr') if not email or not hashstr: # Request body is not complete for not authenticated # request, ie, uses password reset hash. return error_response(errors.AUTH_RESET_MISSING, 400) reset = db.session.query(PasswdReset).join(User).\ filter(User.email == email, PasswdReset.active == True).\ filter(PasswdReset.hashstr == hashstr).\ first() if not reset: return error_response(errors.AUTH_RESET_HASH, 404) db.session.add(reset) reset.active = False user = reset.user user.password = encrypt_password(password) db.session.add(user) db.session.commit() return jsonify({})
def create_admin(): user_datastore = current_app.extensions['security'].datastore admin = User.query.join(User.roles).filter(Role.name == u'superadmin').first() if not admin: admin_email = u'admin@localhost' admin_pwd = u'admin31!' admin = User( email=admin_email, active=True, ) for role_name in [u'superadmin', u'reviewer', u'publisher']: role = user_datastore.find_role(role_name) user_datastore.add_role_to_user(admin, role) admin.password = encrypt_password(admin_pwd) db.session.add(admin) db.session.commit() print("Admin user %(email)s (password: %(pwd)s) created successfully." % { 'email': admin.email, 'pwd': admin_pwd, }) else: print("Admin user %(email)s already exists!" % { 'email': admin.email, })
def init_users_and_permissions(): ds = current_app.extensions['invenio-accounts'].datastore with db.session.begin_nested(): superuser_role = ds.create_role( name='superuser', description='admin with no restrictions' ) cataloger_role = ds.create_role( name='cataloger', description='users with editing capabilities' ) ds.create_user( email='*****@*****.**', password=encrypt_password("123456"), active=True, roles=[superuser_role] ) db.session.add(ActionRoles( action='superuser-access', role=superuser_role )) db.session.add(ActionRoles( action='admin-access', role=superuser_role) ) db.session.add(ActionRoles( action='workflows-ui-admin-access', role=cataloger_role) ) db.session.commit()
def setup(config: dict): if not get_runtime_config_private_dict()['setup_needed']: error_abort('Setup already performed', code=requests.codes.conflict) unified_config = _DEFAULTS.copy() unified_config.update({key: value for key, value in config.items() if key in _DEFAULTS}) unified_config['setup_needed'] = False #known preferences for key, value in unified_config.items(): db.session.execute(''' INSERT INTO app_config (key, value) VALUES (:key, :value) ON CONFLICT(key) DO NOTHING ''', {'key': key, 'value': json.dumps(value)}) db.session.commit() # admin user admin_user_email = config.get('admin_user_email') admin_user_password = config.get('admin_user_password') if admin_user_email and admin_user_password and not db.session.query(models.roles_users).count(): try: user = user_datastore.create_user( active=True, password=encrypt_password(admin_user_password), email=admin_user_email, ) user_datastore.add_role_to_user(user, 'admin') db.session.commit() except IntegrityError: _logger.debug('User already exists. Skipping admin user creation')
def init_database(self): db.create_all() encrypted_password = utils.encrypt_password('password') user_datastore.create_user(email='*****@*****.**', password=encrypted_password, name="Userguy", surname="Userson") user_datastore.create_user(email='*****@*****.**', password=encrypted_password, name="Editorman", surname="Editson") user_datastore.create_user(email='*****@*****.**', password=encrypted_password, name="Admin", surname="Adminson") user_datastore.find_or_create_role(name='admin', description='Administrator') user_datastore.find_or_create_role(name='user', description='User') user_datastore.find_or_create_role(name='editor', description='Editor') tolstoy = Author(id=1, name="L.", surname="Tolstoy") tolkien = Author(id=2, name="J.R.R", surname="Tolkien") rowling = Author(id=3, name="J.K.", surname="Rowling") bloomsbury = Publisher(name="Bloomsbury") db.session.add(tolstoy) db.session.add(tolkien) db.session.add(rowling) db.session.add(bloomsbury) db.session.commit() user_datastore.add_role_to_user('*****@*****.**', 'user') user_datastore.add_role_to_user('*****@*****.**', 'editor') user_datastore.add_role_to_user('*****@*****.**', 'admin') db.session.add(Book(name="War and Peace", author=tolstoy, page_amount=1225)) db.session.add(Book(name="Hobbit", author=tolkien, page_amount=300)) db.session.add(Book(name="Harry Potter and the Philosopher's Stone", author=rowling, publisher=bloomsbury, publication_year=1997, publication_place="UK", isbn="0-7475-3269-9", page_amount=223)) db.session.add(Book(name="Harry Potter and the Chamber of Secrets", author=rowling, publisher=bloomsbury, publication_year=1998, publication_place="UK", isbn="0-7475-3849-2", page_amount=251)) db.session.commit()
def validate_user(data): new_data = dict() email_filter = re.compile( "^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9]" "(?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9]" "(?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$" ) if ('newPassword' in data and data['newPassword'] != "" and 'confirmPassword' in data and data['confirmPassword'] != ""): if data['newPassword'] == data['confirmPassword']: new_data['password'] = encrypt_password(data['newPassword']) else: raise Exception(_("Passwords do not match.")) if 'email' in data and data['email'] != "": if email_filter.match(data['email']): new_data['email'] = data['email'] else: raise Exception(_("Invalid email address.")) if 'role' in data and data['role'] != "": new_data['roles'] = int(data['role']) if 'active' in data and data['active'] != "": new_data['active'] = data['active'] return new_data
def users(app): # Create test users encrypted_password = encrypt_password('123456') user = User( email='*****@*****.**', password=encrypted_password, active=True ) user_partially_allowed = User( email='*****@*****.**', password=encrypted_password, active=True, ) user_allowed = User( email='*****@*****.**', password=encrypted_password, active=True, ) db.session.add_all( [user, user_partially_allowed, user_allowed] ) db.session.commit() # Create actions for the allowed user restricted_collection_action = ActionUsers( action='view-restricted-collection', argument='Restricted Collection', user_id=user_allowed.id ) another_restricted_collection_action = ActionUsers( action='view-restricted-collection', argument='Another Restricted Collection', user_id=user_allowed.id ) # Create actions for the partially allowed user partial_restricted_collection_action = ActionUsers( action='view-restricted-collection', argument='Restricted Collection', user_id=user_partially_allowed.id ) db.session.add_all( [ restricted_collection_action, another_restricted_collection_action, partial_restricted_collection_action ] ) db.session.commit() yield SessionActivity.query.delete() ActionUsers.query.filter_by(action='view-restricted-collection').delete() User.query.filter_by(email='*****@*****.**').delete() User.query.filter_by(email='*****@*****.**').delete() User.query.filter_by(email='*****@*****.**').delete() db.session.commit()
def register(): form = forms.RegisterForm(request.form) if request.method == "POST" and form.validate(): user_datastore.create_user( sid=r.get('sid'), first_name=form.first_name.data.title().strip(), last_name=form.last_name.data.title().strip(), login=form.login.data.lower().strip(), email=form.email.data.lower().strip(), password=encrypt_password(form.password.data.strip())) r.incr('sid') user = models.Users.objects.filter(login=form.login.data.lower()).first() user_datastore.add_role_to_user(user=user, role=user_datastore.find_role('user')) login_user(user) r.hset(config.REDIS_SIDS_LOGINS, user.sid, user.login) # for Tornado # send email for check token = generate_confirmation_token(user.email) confirm_url = url_for('.confirm_email', token=token, _external=True) send_email(subject="Dater: you was registered!", recipients=[user.email], sender=config.MAIL_DEFAULT_SENDER, name_template='email/email_confirmation', first_name=user.first_name, confirm_url=confirm_url) return redirect(url_for('.profile')) return render_template('register.html', form=form)
def __init__(self, **kwargs): self.__dict__.update(kwargs) self.password = utils.encrypt_password(self.password)
def RestoreDBFull(UseExistingDatabase=False): print("Configuration is Database:", app.config['DB_DATABASE']) print("Login: "******"/", app.config['DB_PASSWORD']) print("Host: ", app.config['DB_HOST']) print("Current directory: ", os.getcwd()) if not os.path.exists("ecotaxadb.zip"): print("File ecotaxadb.zip must be in the current directory") return print("Connect Database") if UseExistingDatabase: conn = psycopg2.connect(user=app.config['DB_USER'], password=app.config['DB_PASSWORD'], host=app.config['DB_HOST'], database=app.config['DB_DATABASE']) else: # On se loggue en postgres pour dropper/creer les bases qui doit être déclaré trust dans hba_conf conn = psycopg2.connect(user='******', host=app.config['DB_HOST']) cur = conn.cursor() print("Open ZipFile") if os.path.exists("DBFullRestore"): shutil.rmtree("DBFullRestore") os.mkdir("DBFullRestore") os.chdir("DBFullRestore") zfile = ZipFile("../ecotaxadb.zip", 'r', allowZip64=True) print("Extract schema") zfile.extract('schema.sql') conn.set_session(autocommit=True) if UseExistingDatabase: print("Drop the existing public schema") sql = "DROP SCHEMA public cascade" cur.execute(sql) # print("Create the public schema") # inutile fait par l'import du schema, ça evite une erreur dans le log # sql = "create schema public AUTHORIZATION " + app.config['DB_USER'] # cur.execute(sql) else: print("Drop the existing database") sql = "DROP DATABASE IF EXISTS " + app.config['DB_DATABASE'] cur.execute(sql) print("Create the new database") sql = "create DATABASE " + app.config[ 'DB_DATABASE'] + " WITH ENCODING='LATIN1' OWNER=" + app.config[ 'DB_USER'] + " TEMPLATE=template0 LC_CTYPE='C' LC_COLLATE='C' CONNECTION LIMIT=-1 " cur.execute(sql) toolsdir = GetDBToolsDir() os.environ["PGPASSWORD"] = app.config['DB_PASSWORD'] cmd = os.path.join(toolsdir, "psql") cmd += " -h " + app.config[ 'DB_HOST'] + " -U " + app.config['DB_USER'] + " -p " + app.config.get( 'DB_PORT', '5432') + " --file=schema.sql " + app.config[ 'DB_DATABASE'] + " >createschemaout.txt" print("Import Schema : %s", cmd) os.system(cmd) conn.close() conn = psycopg2.connect(user=app.config['DB_USER'], password=app.config['DB_PASSWORD'], host=app.config['DB_HOST'], database=app.config['DB_DATABASE']) cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) print("Encoding = ", conn.encoding) print("Restore data") for t in table_list: ColList = GetColsForTable('public', t) print("Restore table %s " % (t, )) try: zfile.extract(t + ".copy") with open(t + ".copy", "r", encoding='latin_1') as f: cur.copy_from(f, 'public' + "." + t, columns=ColList) cur.connection.commit() except: print("Error while data restoration %s", str(sys.exc_info())) cur.execute("update public.users set password=%s where email='admin'", (encrypt_password('ecotaxa'), )) cur.connection.commit() import manage manage.ResetDBSequence(cur) # Copie des Images print("Restore Images") cur.execute("select images.* from images ") # vaultroot=Path("../vault") vaultroot = Path( os.path.normpath( os.path.join(os.path.dirname(os.path.realpath(__file__)), R"../../vault"))) for r in cur: if r['file_name']: zipimagefile = "images/%s.img" % r['imgid'] zfile.extract(zipimagefile) VaultFolder = "%04d" % (r['imgid'] // 10000) #creation du repertoire contenant les images si necessaire if not vaultroot.joinpath(VaultFolder).exists(): vaultroot.joinpath(VaultFolder).mkdir() shutil.move(zipimagefile, vaultroot.joinpath(r['file_name']).as_posix()) if r['thumb_file_name']: zipimagefile = "images/%s.thumb" % r['imgid'] zfile.extract(zipimagefile) shutil.move( zipimagefile, vaultroot.joinpath(r['thumb_file_name']).as_posix()) # Clean Up du repertoire os.chdir("..") shutil.rmtree("DBFullRestore")
db.create_all() # add roles and admin to the db, this is only done once from frontend.models import Role, User user_role_exist = db.session.query( exists().where(Role.name == "user")).scalar() super_role_exist = db.session.query( exists().where(Role.name == "superuser")).scalar() admin_exist = db.session.query( exists().where(User.first_name == app.config['ADMIN_NAME'])).scalar() if not user_role_exist: user_role = Role(name='user') db.session.add(user_role) db.session.commit() if not super_role_exist: super_user_role = Role(name='superuser') db.session.add(super_user_role) db.session.commit() if not admin_exist: user_role = Role(name='user') super_user_role = Role(name='superuser') admin_user = user_datastore.create_user( first_name=app.config['ADMIN_NAME'], email=app.config['ADMIN_EMAIL'], password=encrypt_password(app.config['ADMIN_PASSWORD']), confirmed_at=datetime.datetime.now(), roles=[user_role, super_user_role]) db.session.commit()
def on_model_change(self, form, model, is_created): if len(model.password2): model.password = utils.encrypt_password(model.password2)
def password_set(self, password_clear): self.password = encrypt_password(password_clear) return self.password
def upgrade(): # ### commands auto generated by Alembic - please adjust! ### if get_version() != -1: return email, password = user_info() op.create_table('version', sa.Column('name', sa.String(length=32), nullable=False), sa.Column('value', sa.Integer(), nullable=False), sa.PrimaryKeyConstraint('name')) op.create_table( 'user', sa.Column('id', sa.Integer(), nullable=False), sa.Column('email', sa.String(length=256), nullable=False), sa.Column('password', sa.String(length=256), nullable=True), sa.Column('active', sa.Boolean(), nullable=False), sa.Column('confirmed_at', sa.DateTime(), nullable=True), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('email')) op.create_table( 'role', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=128), nullable=False), sa.Column('description', sa.String(length=256), nullable=False), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('name')) op.create_table( 'setting', sa.Column('user_id', sa.Integer(), nullable=False), sa.Column('setting', sa.String(length=256), nullable=False), sa.Column('value', sa.String(length=1024), nullable=True), sa.ForeignKeyConstraint( ['user_id'], ['user.id'], ), sa.PrimaryKeyConstraint('user_id', 'setting')) op.create_table('roles_users', 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'], )) op.create_table('servergroup', sa.Column('id', sa.Integer(), nullable=False), sa.Column('user_id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=128), nullable=False), sa.ForeignKeyConstraint( ['user_id'], ['user.id'], ), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('user_id', 'name')) op.create_table( 'server', sa.Column('id', sa.Integer(), nullable=False), sa.Column('user_id', sa.Integer(), nullable=False), sa.Column('servergroup_id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=128), nullable=False), sa.Column('host', sa.String(length=128), nullable=False), sa.Column('port', sa.Integer(), nullable=False), sa.Column('maintenance_db', sa.String(length=64), nullable=False), sa.Column('username', sa.String(length=64), nullable=False), sa.Column('ssl_mode', sa.String(length=16), nullable=False), sa.ForeignKeyConstraint( ['servergroup_id'], ['servergroup.id'], ), sa.ForeignKeyConstraint( ['user_id'], ['user.id'], ), sa.PrimaryKeyConstraint('id')) db.engine.execute(""" INSERT INTO "role" VALUES(1, 'Administrators', 'pgAdmin Administrators Role') """) db.engine.execute(""" INSERT INTO "roles_users" VALUES(1, 1); """) db.engine.execute(""" INSERT INTO "servergroup" VALUES(1, 1, 'Servers') """) current_salt = getattr(config, 'SECURITY_PASSWORD_SALT', base64.urlsafe_b64encode(os.urandom(32)).decode()) if current_app.extensions.get('security') is None: current_app.config['SECURITY_PASSWORD_SALT'] = current_salt user_datastore = SQLAlchemyUserDatastore(db, User, Role) Security(current_app, user_datastore, register_blueprint=False) else: current_app.config['SECURITY_PASSWORD_SALT'] = current_salt setattr(config, 'SECURITY_PASSWORD_SALT', current_salt) password = encrypt_password(password) db.engine.execute(""" INSERT INTO "user" VALUES(1, '%s', '%s', 1, NULL) """ % (email, password)) db.engine.execute(""" INSERT INTO "version" VALUES('ConfigDB', 2); """)
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.encrypt_password(model.password2)
def add_test_data(verbose=False): """Add some test data.""" if verbose: logger = logging.getLogger("peewee") if logger: logger.setLevel(logging.DEBUG) logger.addHandler(logging.StreamHandler()) fake = Faker() fake.seed(42) for (c, n) in [('Z4M4Q0', fake.company()), ('B4J4L6', fake.company()), ('Y9P9S3', fake.company()), ('V9A5K4', fake.company()), ('Y0U5B3', fake.company()), ('T3N2Y6', fake.company()), ('Q6U3Y9', fake.company()), ('W9J2M9', fake.company()), ('Y3Z9T9', fake.company()), ('R2H4P5', fake.company())]: Company.get_or_create(code=c, name=n) # Create all roles: emp = user_datastore.find_role("emp") approver = user_datastore.find_role("approver") admin = user_datastore.find_role("admin") # Test Users with app.app_context(): test_password = encrypt_password('12345') for id, (username, email, first_name, last_name) in enumerate( (('user0', fake.email(), fake.first_name(), fake.last_name()), ('user1', fake.email(), fake.first_name(), fake.last_name()), ('user2', fake.email(), fake.first_name(), fake.last_name()), ('approver0', fake.email(), fake.first_name(), fake.last_name()), ('approver1', fake.email(), fake.first_name(), fake.last_name()), ('approver2', fake.email(), fake.first_name(), fake.last_name()), ('admin0', fake.email(), fake.first_name(), fake.last_name()), ('admin1', fake.email(), fake.first_name(), fake.last_name()), ('admin2', fake.email(), fake.first_name(), fake.last_name())), 1): user = user_datastore.create_user( username=username, #code=username.upper(), email=email, password=test_password, first_name=first_name, last_name=last_name, workplace=Company.get(id=id)) user.save() if "user" in username: user.roles = [emp] else: user.approves_for = [ Company.get(id=company_id) for company_id in range(id, id + 2) ] user.roles.add(approver) if "admin" in username: user.roles.add(admin) user.save() # Timesheet entires week_dates = list(week_day_dates()) for no, (user, day) in enumerate(product(User.select(), week_dates)): entry = Entry(date=day, user=user, started_at=time(7, no * 10 % 60, 0), finished_at=time(16, no * 7 % 60, 0), break_for=Break.get(id=no % 20 + 1)) entry.save()
def validate(self): """Validate LDAP logins against AD.""" if not super(LDAPLoginForm, self).validate(): return False if self.email.data.strip() == "": self.email.errors.append(get_message("USERID_NOT_PROVIDED")[0]) return False if self.password.data.strip() == "": self.password.errors.append(get_message("PASSWORD_NOT_PROVIDED")[0]) return False try: admin_user = _datastore.get_user(1) if self.email.data == admin_user.username: current_app.artemis_logger.info("Super-user login") return self._try_local_auth() # first we try authenticating against ldap user_dn, ldap_data = _datastore.query_ldap_user(self.email.data) if not _datastore.verify_password(user_dn, self.password.data): self.password.errors.append(get_message("INVALID_PASSWORD")[0]) return False ldap_email = ldap_data[config_value("LDAP_EMAIL_FIELDNAME")].value password = encrypt_password(self.password.data) self.user = _datastore.find_user(email=ldap_email) if self.user: # note that this is being stored per user login self.user.password = password else: self.user = _datastore.create_user( username=ldap_email, email=ldap_email, password=password, active=True, ) # need to somehow decide what role they are groups = config_value("LDAP_ADMIN_GROUPS") field = ldap_data[config_value("LDAP_ADMIN_GROUPS_FIELDNAME")].values if ( isinstance(field, str) and any([group == field for group in groups]) ) or ( isinstance(field, list) and any([group in field for group in groups]) ): add_role = _datastore.find_role("admin") remove_role = _datastore.find_role("user") else: add_role = _datastore.find_role("user") remove_role = _datastore.find_role("admin") _datastore.add_role_to_user(self.user, add_role) _datastore.remove_role_from_user(self.user, remove_role) _datastore.commit() except LDAPKeyError: current_app.artemis_logger.exception("") self.email.errors.append("LDAP Key failure") if self.user: add_role = _datastore.find_role("user") remove_role = _datastore.find_role("admin") _datastore.add_role_to_user(self.user, add_role) _datastore.remove_role_from_user(self.user, remove_role) _datastore.commit() return True return False except LDAPSocketOpenError: current_app.artemis_logger.info("LDAP offline.. Trying local auth") self.email.errors.append("LDAP Server offline") return self._try_local_auth() except LDAPExceptionError: current_app.artemis_logger.exception("") self.email.errors.append("LDAP Auth failed") return False return True
def set_password(self, password): try: self.password = encrypt_password(password) except RuntimeError: # :-/ with app.app_context(): self.password = encrypt_password(password)
def populate_from_form(self, form): self.email = form.email.data self.displayname = form.displayname.data if form.password.data: self.password = encrypt_password(form.password.data)
def create_sample_db(db_sql, user_datastore): """ It removes any database that currently exists and create a new one. :param db_sql: SQLAlchemy instance :param user_datastore: SQLAlchemyUserDatastore instance """ db_sql.drop_all() db_sql.create_all() ocup_alumno = Ocupacion(nombre='Alumno', descripcion='Alumno perteneciente al CUCEA') db_sql.session.add(ocup_alumno) l_cucea = Lugar(nombre='CUCEA', coordenadas='POLYGON((-103.383085727692 \ 20.7399807434582, \ -103.378794193268 \ 20.7391780551767, \ -103.377120494843 \ 20.7447967837201, \ -103.3789229393 \ 20.7447967837201, \ -103.379480838776 \ 20.7445559853482, \ -103.381283283234 \ 20.7448770497589, \ -103.383085727692 \ 20.7399807434582))') l_cici = Lugar(nombre='CICI', coordenadas='POLYGON((-103.378770053387 \ 20.7441044873678, \ -103.378748595715 \ 20.7439991376452, \ -103.378555476665 \ 20.7440242209191, \ -103.378555476665 \ 20.7441245539733, \ -103.378770053387 \ 20.7441044873678))', lugar_padre=l_cucea) db_sql.session.add(l_cici) db_sql.session.commit() computadora1 = Computadora(nombre='dev01', id_lugar=l_cici.id) db_sql.session.add(computadora1) computadora2 = Computadora(nombre='dev02', id_lugar=l_cici.id) db_sql.session.add(computadora2) db_sql.session.commit() # Create the Roles "admin" and "end-user" -- unless they already exist user_datastore.find_or_create_role(name='admin', description='Administrator') user_datastore.find_or_create_role(name='end-user', description='End user') # Create two Users for testing purposes -- unless they already exists. # In each case, use Flask-Security utility # function to encrypt the password. encrypted_password = utils.encrypt_password('password') if not user_datastore.get_user('alan'): user_datastore.create_user( email='alan', password=encrypted_password, id_ocupacion=ocup_alumno.id, codigo='208696345', nip='1111', apellido_paterno='Sánchez', apellido_materno='Castro', nombres='Alan Andrés', lugares=[l_cici], token='ABCDEF', ) if not user_datastore.get_user('andres'): user_datastore.create_user( email='andres', password=encrypted_password, id_ocupacion=ocup_alumno.id, codigo='1234', nip='1111', apellido_paterno='Sánchez', apellido_materno='Castro', nombres='Alan Andrés', token='GHIJKL', lugares=[l_cici, l_cucea], ) if not user_datastore.get_user('admin'): user_datastore.create_user(email='admin', password=encrypted_password) # Commit any database changes; # the User and Roles must exist before we can add a Role to the User db_sql.session.commit() # Give one User has the "end-user" role, while the other # has the "admin" role. (This will have no effect if the # Users already have these Roles.) Again, commit any database changes. user_datastore.add_role_to_user('alan', 'end-user') user_datastore.add_role_to_user('andres', 'end-user') user_datastore.add_role_to_user('admin', 'admin') user_datastore.add_role_to_user('admin', 'end-user') db_sql.session.commit() alan = user_datastore.get_user('alan') andres = user_datastore.get_user('andres') entrada1 = Registro(id_usuario=alan.id, id_lugar=l_cici.id, fecha_hora_entrada=datetime.utcnow() - timedelta(minutes=10)) db_sql.session.add(entrada1) db_sql.session.commit() toma1 = Detalle_registro( id_computadora=computadora1.id, id_registro_entrada=entrada1.id, id_registro_salida=entrada1.id, fecha_hora_toma=datetime.utcnow() - timedelta(minutes=8), fecha_hora_entrega=datetime.utcnow() - timedelta(minutes=6)) db_sql.session.add(toma1) db_sql.session.commit() toma2 = Detalle_registro( id_computadora=computadora2.id, id_registro_entrada=entrada1.id, id_registro_salida=entrada1.id, fecha_hora_toma=datetime.utcnow() - timedelta(minutes=5), ) db_sql.session.add(toma2) db_sql.session.commit() entrada1.fecha_hora_salida = datetime.utcnow() - timedelta(minutes=2) db_sql.session.commit() entrada2 = Registro(id_usuario=andres.id, id_lugar=l_cici.id, fecha_hora_entrada=datetime.utcnow() - timedelta(minutes=60)) db_sql.session.add(entrada2) db_sql.session.commit() entrada3 = Registro(id_usuario=alan.id, id_lugar=l_cici.id, fecha_hora_entrada=datetime.utcnow() - timedelta(minutes=70)) db_sql.session.add(entrada3) db_sql.session.commit() toma2.id_registro_salida = entrada3.id toma2.fecha_hora_entrega = datetime.utcnow() - timedelta(minutes=4) toma3 = Detalle_registro( id_computadora=computadora1.id, id_registro_entrada=entrada3.id, id_registro_salida=entrada3.id, fecha_hora_toma=datetime.utcnow() - timedelta(minutes=65), ) db_sql.session.add(toma3) db_sql.session.commit() entrada3.fecha_hora_salida = datetime.utcnow() - timedelta(minutes=60) db_sql.session.commit()
def before_first_request(): # Create any database tables that don't exist yet. db.create_all() db.session.commit() # Create the Roles "admin" and "end-user" -- unless they already exist user_datastore.find_or_create_role(name='admin', description='Administrator') user_datastore.find_or_create_role(name='end-user', description='End user') user_datastore.find_or_create_role(name='manager', description='Manager') encrypted_password = utils.encrypt_password('pwd') # Create the Services if not Services.query.filter_by(id=1).first(): service = Services(name='Deposit Account', id=1) db.session.add(service) db.session.commit() if not Services.query.filter_by(id=2).first(): service = Services(name='Credit Card', id=2) db.session.add(service) db.session.commit() if not Services.query.filter_by(id=3).first(): service = Services(name='Other', id=3) db.session.add(service) db.session.commit() if not Services.query.filter_by(id=4).first(): service = Services(name='Mortgage - new', id=4) db.session.add(service) db.session.commit() if not Services.query.filter_by(id=5).first(): service = Services(name='Mortgage - refinance', id=5) db.session.add(service) db.session.commit() # Create the Markets if not Market.query.filter_by(id=1).first(): market = Market(name="Guam", id=1) db.session.add(market) db.session.commit() if not Market.query.filter_by(id=2).first(): market = Market(name="Oahu", id=2) db.session.add(market) db.session.commit() # Create the Branches if not Branch.query.filter_by(id=1).first(): branch = Branch(name="Garapan", market_id=1, time_zone="Pacific/Saipan", address="Spring Plaza, Chalan Pale Arnold, 96950", id=1) db.session.add(branch) db.session.commit() if not Branch.query.filter_by(id=2).first(): branch = Branch(name="Kailua", market_id=2, time_zone="Pacific/Honolulu", address="636 KAILUA RD, 96734", id=2) db.session.add(branch) db.session.commit() if not Branch.query.filter_by(id=3).first(): branch = Branch(name="Kaneohe", market_id=2, time_zone="Pacific/Honolulu", address="45-1001 KAMEHAMEHA HWY, 96744", id=3) db.session.add(branch) db.session.commit() if not Branch.query.filter_by(id=4).first(): branch = Branch(name="Waikiki", market_id=2, time_zone="Pacific/Honolulu", address="2155 KALAKAUA AVE STE 104, 96815", id=4) db.session.add(branch) db.session.commit() # Create the Users # First an admin and a branch manager if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user(email='*****@*****.**', password=encrypted_password, name="Admin User") user_datastore.add_role_to_user('*****@*****.**', 'admin') if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user(email='*****@*****.**', password=encrypted_password, name="Wikiki Manager", branch_id=4) user_datastore.add_role_to_user('*****@*****.**', 'manager') # Then regular employees if not user_datastore.get_user("*****@*****.**"): user_datastore.create_user( email="*****@*****.**", password=encrypted_password, name="John Garapan", branch_id=1, services=Services.query.filter((Services.id == 1) | (Services.id == 2) | (Services.id == 3)).all()) add_tbd_appointments( user_datastore.get_user("*****@*****.**").id) user_datastore.add_role_to_user("*****@*****.**", "end-user") if not user_datastore.get_user("*****@*****.**"): user_datastore.create_user( email="*****@*****.**", password=encrypted_password, name="John Kailua", branch_id=2, services=Services.query.filter((Services.id == 1) | (Services.id == 2) | (Services.id == 3)).all()) add_tbd_appointments( user_datastore.get_user("*****@*****.**").id) user_datastore.add_role_to_user("*****@*****.**", "end-user") if not user_datastore.get_user("*****@*****.**"): user_datastore.create_user( email="*****@*****.**", password=encrypted_password, name="John Kailua II", branch_id=2, services=Services.query.filter((Services.id == 4) | (Services.id == 5)).all()) add_tbd_appointments( user_datastore.get_user("*****@*****.**").id) user_datastore.add_role_to_user("*****@*****.**", "end-user") if not user_datastore.get_user("*****@*****.**"): user_datastore.create_user( email="*****@*****.**", password=encrypted_password, name="John kaneohe", branch_id=3, services=Services.query.filter((Services.id == 1) | (Services.id == 2) | (Services.id == 3)).all()) add_tbd_appointments( user_datastore.get_user("*****@*****.**").id) user_datastore.add_role_to_user("*****@*****.**", "end-user") if not user_datastore.get_user("*****@*****.**"): user_datastore.create_user( email="*****@*****.**", password=encrypted_password, name="John waikiki", branch_id=4, services=Services.query.filter((Services.id == 1) | (Services.id == 2) | (Services.id == 3)).all()) add_tbd_appointments( user_datastore.get_user("*****@*****.**").id) user_datastore.add_role_to_user("*****@*****.**", "end-user") db.session.commit()
# Create an admin profile. Useful for setting up the first admin when deployed # on Heroku. from flask_security.utils import encrypt_password from flask_security import SQLAlchemyUserDatastore from app import app from app import db from app.models import Role, User user_datastore = SQLAlchemyUserDatastore(db, User, Role) with app.app_context(): super_user_role = Role(name='superuser') user_role = Role(name='user') db.session.add(super_user_role) db.session.add(user_role) db.session.commit() first_admin = user_datastore.create_user( email='admin', password=encrypt_password('admin'), roles=[user_role, super_user_role]) db.session.add(first_admin) db.session.commit()
from app.utils.toolbox import FileDownloader from flask_security.utils import encrypt_password from colorama import init import logging from logging.handlers import RotatingFileHandler import os.path init() handler = RotatingFileHandler(LOG_FILE_NAME, maxBytes=10000, backupCount=1) handler.setLevel(logging.INFO) app.logger.addHandler(handler) app.logger.info("About to call db.create_all().") db.create_all() #create a default user user_datastore.create_user(email='*****@*****.**', password=encrypt_password('password')) db.session.commit() app.logger.info("db.create_all() completed.") if not os.path.exists(SQLALCHEMY_MIGRATE_REPO): api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository') api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO) app.logger.info("Creating database... {0}".format(SQLALCHEMY_DATABASE_URI)) app.logger.info("Importing word lists...") app.logger.info("Downloading wordlist from {0}".format(WORD_FILE_URL)) c = 0 d = FileDownloader(WORD_FILE_URL) d.DownloadUrl(WORD_FILE) app.logger.info("Wordlist downloaded and saved to {0}".format(WORD_FILE)) if os.path.isfile(WORD_FILE): with open(WORD_FILE) as f: for line in f:
def set_password(self, password): self.password = encrypt_password(password)
def rand_alphabet(): return encrypt_password(''.join( random.choice(ALPHABET) for i in range(16)))
def user_register(): content = request.get_json(force=True) if content is None: return bad_request(web_utils.INVALID_JSON) params, err_response = get_json_params(content, ["email", "password", "first_name", "last_name", "mobile_number", "address", "photo", "photo_type"]) if err_response: return err_response email, password, first_name, last_name, mobile_number, address, photo, photo_type = params if not utils.is_email(email): return bad_request(web_utils.INVALID_EMAIL) email = email.lower() if not password: return bad_request(web_utils.EMPTY_PASSWORD) if photo and len(photo) > 50000: return bad_request(web_utils.PHOTO_DATA_LARGE) req = UserCreateRequest(first_name, last_name, email, mobile_number, address, photo, photo_type, encrypt_password(password)) user = User.from_email(db.session, email) if user: time.sleep(5) return bad_request(web_utils.USER_EXISTS) utils.email_user_create_request(logger, req, req.MINUTES_EXPIRY) db.session.add(req) db.session.commit() return 'ok'
def reset_user_password(user_id): user = User.query.get_or_404(int(user_id)) user.password = encrypt_password(request.form["password"]) db.session.add(user) return jsonify(dict(success=True))
def build_sample_db(): """ Populate a small db with some example entries. """ import string import random db.drop_all() db.create_all() with app.app_context(): user_role = Role(name='user') super_user_role = Role(name='superuser') db.session.add(user_role) db.session.add(super_user_role) db.session.commit() test_user = user_datastore.create_user( first_name='Admin', email='admin', password=encrypt_password('admin'), roles=[user_role, super_user_role] ) first_names = [ 'Harry', 'Amelia', 'Oliver', 'Jack', 'Isabella', 'Charlie', 'Sophie', 'Mia', 'Jacob', 'Thomas', 'Emily', 'Lily', 'Ava', 'Isla', 'Alfie', 'Olivia', 'Jessica', 'Riley', 'William', 'James', 'Geoffrey', 'Lisa', 'Benjamin', 'Stacey', 'Lucy' ] last_names = [ 'Brown', 'Smith', 'Patel', 'Jones', 'Williams', 'Johnson', 'Taylor', 'Thomas', 'Roberts', 'Khan', 'Lewis', 'Jackson', 'Clarke', 'James', 'Phillips', 'Wilson', 'Ali', 'Mason', 'Mitchell', 'Rose', 'Davis', 'Davies', 'Rodriguez', 'Cox', 'Alexander' ] for i in range(len(first_names)): tmp_email = first_names[i].lower() + "." + last_names[i].lower() + "@example.com" tmp_pass = ''.join(random.choice(string.ascii_lowercase + string.digits) for i in range(10)) user_datastore.create_user( first_name=first_names[i], last_name=last_names[i], email=tmp_email, password=encrypt_password(tmp_pass), roles=[user_role, ] ) db.session.commit() product_names = ['coca', 'coca_cola_light_05', 'avocado', 'banana_bundle', 'banana_single', 'kiwi', 'pear', 'carrot', 'cucumber', 'lettuce', 'roma_vine_tomatoes', 'zucchini'] product_price = [2.5, 2.5, 2, 2, 0.5, 0.99, 1, 1.5, 0.5, 2.5, 3, 0.8] product_discount = [1]*12 for i, product_name in enumerate(product_names): product = Product(product_name = product_name, product_unit_price = product_price[i], product_discount = product_discount[i], product_code = i+1) db.session.add(product) db.session.commit() return
def _set_password(self, plaintext): self._password = utils.encrypt_password(plaintext)
# -*- coding: utf-8 -*- __author__ = 'Дмитрий' from application import app, db, user_datastore from flask_security.utils import encrypt_password from application.domain import models db.init_app(app) # admin = models.Role(name="Admin") # user = models.Role(name="User") # guest = models.Role(name="Guest") # root = models.User(email="superuser", password="") with app.app_context(): admin_role = user_datastore.create_role(name="Admin") user_datastore.create_role(name="User") user_datastore.create_role(name="Guest") created_user = user_datastore.create_user(email='superuser', password=encrypt_password('')) user_datastore.add_role_to_user(created_user, admin_role) # root.roles = [admin] # db.session.add(root) db.session.commit()
def do_setup(app): """Create a new settings database from scratch""" if config.SERVER_MODE is False: print(u"NOTE: Configuring authentication for DESKTOP mode.") email = config.DESKTOP_USER p1 = ''.join([ random.choice(string.ascii_letters + string.digits) for n in range(32) ]) else: print(u"NOTE: Configuring authentication for SERVER mode.\n") if all(value in os.environ for value in ['PGADMIN_SETUP_EMAIL', 'PGADMIN_SETUP_PASSWORD']): email = '' p1 = '' if os.environ['PGADMIN_SETUP_EMAIL'] and os.environ[ 'PGADMIN_SETUP_PASSWORD']: email = os.environ['PGADMIN_SETUP_EMAIL'] p1 = os.environ['PGADMIN_SETUP_PASSWORD'] else: # Prompt the user for their default username and password. print( u"Enter the email address and password to use for the initial " u"pgAdmin user account:\n") email_filter = re.compile( "^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9]" "(?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9]" "(?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$") email = input("Email address: ") while email == '' or not email_filter.match(email): print(u'Invalid email address. Please try again.') email = input("Email address: ") def pprompt(): return getpass.getpass(), getpass.getpass('Retype password:'******'Passwords do not match. Please try again.') else: print( u'Password must be at least 6 characters. Please try again.' ) p1, p2 = pprompt() # Setup Flask-Security user_datastore = SQLAlchemyUserDatastore(db, User, Role) Security(app, user_datastore) with app.app_context(): password = encrypt_password(p1) db.create_all() user_datastore.create_role(name='Administrator', description='pgAdmin Administrator Role') user_datastore.create_role(name='User', description='pgAdmin User Role') user_datastore.create_user(email=email, password=password) db.session.flush() user_datastore.add_role_to_user(email, 'Administrator') # Get the user's ID and create the default server group user = User.query.filter_by(email=email).first() server_group = ServerGroup(user_id=user.id, name="Servers") db.session.merge(server_group) # Set the schema version version = Version(name='ConfigDB', value=config.SETTINGS_SCHEMA_VERSION) db.session.merge(version) db.session.commit() # Create the keys key = Keys(name='CSRF_SESSION_KEY', value=config.CSRF_SESSION_KEY) db.session.merge(key) key = Keys(name='SECRET_KEY', value=config.SECRET_KEY) db.session.merge(key) key = Keys(name='SECURITY_PASSWORD_SALT', value=config.SECURITY_PASSWORD_SALT) db.session.merge(key) db.session.commit() # Done! print(u"") print(u"The configuration database has been created at {0}".format( config.SQLITE_PATH))
def load_user_from_request(request): if request.method == 'POST' and "/outputs/" not in request.base_url: username = request.form.get('email') password = request.form.get('password') if LOGIN_METHOD != "None": try: result = User.try_login(username, password) if not result: do_flash(*get_message('INVALID_PASSWORD')) return None except ldap.INVALID_CREDENTIALS, e: do_flash(*get_message('INVALID_PASSWORD')) return None user = User.query.filter_by(username=result['uid'][0]).first() if not user: encrypted_password = utils.encrypt_password(password) if not user_datastore.get_user(result['mail'][0]): user = user_datastore.create_user( email=result['mail'][0], password=encrypted_password, username=result['uid'][0], name=result['cn'][0], gid=result['gidNumber'][0], homedir=result['homeDirectory'][0]) db.session.commit() user = User.query.filter_by(username=result['uid'][0]).first() else: user = User.query.filter_by(username=LOGIN_USERNAME).first() if username != LOGIN_USERNAME or LOGIN_PASSWORD != password: do_flash(*get_message('INVALID_PASSWORD')) return None if not user: encrypted_password_config = utils.encrypt_password( LOGIN_PASSWORD) if not user_datastore.get_user(LOGIN_EMAIL): user = user_datastore.create_user( email=LOGIN_EMAIL, password=encrypted_password_config, username=LOGIN_USERNAME, name=LOGIN_USERNAME, gid=LOGIN_GID, homedir=LOGIN_HOMEDIR) db.session.commit() if not os.path.exists(os.path.join(LOGIN_HOMEDIR, "jobs")): os.makedirs(os.path.join(LOGIN_HOMEDIR, "jobs")) user = User.query.filter_by(username=LOGIN_USERNAME).first() login_user(user) return user
def upgrade(): conn = op.get_bind() for u in conn.execute(user_table.select()): conn.execute('UPDATE "user" set password=\'{}\' where id = {}'.format( encrypt_password(u[1]), u[0]))
def generate_hash(password): """ Utility to help with API """ return utils.encrypt_password(password)
def test_permission(app): """Test permission control to records.""" app.config.update( WTF_CSRF_ENABLED=False, SECRET_KEY='CHANGEME', SECURITY_PASSWORD_SALT='CHANGEME', # conftest switches off permission checking, so re-enable it for this # app. RECORDS_UI_DEFAULT_PERMISSION_FACTORY='invenio_records.permissions' ':read_permission_factory') Menu(app) InvenioRecordsUI(app) accounts = InvenioAccounts(app) app.register_blueprint(accounts_blueprint) InvenioAccess(app) setup_record_fixture(app) # Create admin with app.app_context(): admin = accounts.datastore.create_user( email='*****@*****.**', password=encrypt_password('123456'), active=True, ) reader = accounts.datastore.create_user( email='*****@*****.**', password=encrypt_password('123456'), active=True, ) # Get record 1 r = Resolver(pid_type='recid', object_type='rec', getter=Record.get_record) dummy_pid, record = r.resolve('1') # Setup permissions for record 1 (grant 'admin', deny 'reader') db.session.add( ActionUsers(action=records_read_all.value, argument=str(record.id), user=admin)) db.session.add( ActionUsers(action=records_read_all.value, argument=str(record.id), user=reader, exclude=True)) db.session.commit() with app.test_request_context(): login_url = url_for('security.login') record_url = url_for('invenio_records_ui.recid', pid_value='1') # Access record 1 as admin with app.test_client() as client: res = client.get(record_url) assert res.status_code == 302 res = client.post(login_url, data={ 'email': '*****@*****.**', 'password': '******' }) assert res.status_code == 302 res = client.get(record_url) res.status_code == 200 # Access record 1 as reader with app.test_client() as client: res = client.post(login_url, data={ 'email': '*****@*****.**', 'password': '******' }) assert res.status_code == 302 res = client.get(record_url) res.status_code == 403
def on_model_change(self, form, model, is_created): if model.password2: model.password = encrypt_password(model.password2)
def create_app(config_name): global user_datastore app = Flask(__name__) app.config.from_object(app_config[config_name]) csrf = CSRFProtect() csrf.init_app(app) assets = Environment(app) create_assets(assets) via = Via() via.init_app(app) # Ipload in several models - - - - from app.user import user_photo from app.restaurant import restaurant_photo from app.food import food_photo configure_uploads(app, (restaurant_photo, food_photo, user_photo)) engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI']) if not database_exists(engine.url): create_database(engine.url) security = Security(app, user_datastore, register_form=SecurityRegisterForm) create_security_admin(app=app, path=os.path.join(os.path.dirname(__file__))) with app.app_context(): db.init_app(app) #Conditionally create admin/end_user db.create_all() user_datastore.find_or_create_role(name='admin', description='Administrator') db.session.commit() user_datastore.find_or_create_role(name='end-user', description='End user') db.session.commit() # Create two Users for testing purposes -- unless they already exists. # In each case, use Flask-Security utility function to encrypt the password. encrypted_password = utils.encrypt_password('password') if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user(email='*****@*****.**', password=encrypted_password) if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user(email='*****@*****.**', password=encrypted_password) # Commit any database changes; the User and Roles must exist before we can add a Role to the User db.session.commit() # Give one User has the "end-user" role, while the other has the "admin" role. (This will have no effect if the # Users already have these Roles.) Again, commit any database changes. user_datastore.add_role_to_user('*****@*****.**', 'end-user') user_datastore.add_role_to_user('*****@*****.**', 'admin') db.session.commit() @app.route('/', methods=['GET']) @app.route('/home', methods=['GET']) def index(): return render_template('index.html') @app.errorhandler(403) def forbidden(error): return render_template('error/403.html', title='Forbidden'), 403 @app.errorhandler(404) def page_not_found(error): return render_template('error/404.html', title='Page Not Found'), 404 @app.errorhandler(500) def internal_server_error(error): db.session.rollback() return render_template('error/500.html', title='Server Error'), 500 return app
def run(self, user_data_file, **kwargs): from models.models import Role, User, Course, Assignment, CourseAssignment, AssignmentGroup, AssignmentGroupMembership print("Adding Admin") admin = User(first_name='Cory', last_name='Bart', password=encrypt_password('password'), confirmed_at=datetime.datetime.now(), active=True, email='*****@*****.**', gender='Male') db.session.add(admin) db.session.flush() db.session.add(Role(name='instructor', user_id=admin.id)) db.session.add(Role(name='admin', user_id=admin.id)) print("Adding some students for color") for student in ('Dan Tilden', 'Anamary Leal', 'Ellie Cayford'): first, last = student.split() email = '{}{}@vt.edu'.format(first[0].lower(), last.lower()) user = User(first_name=first, last_name=last, email=email) db.session.add(user) print("Adding default course") default_course = Course(name="Computational Thinking", owner_id=admin.id, service="native") db.session.add(default_course) db.session.flush() print("Adding public course") public_course = Course(name="Public Course", owner_id=admin.id, service="native", visibility='public') db.session.add(public_course) db.session.flush() db.session.add( Role(name='instructor', course_id=public_course.id, user_id=admin.id)) print("Adding local Canvas course") canvas_course = Course( name="Computational Thinking - Dev", owner_id=admin.id, service='canvas', visibility='private', external_id='cbdd860576c6c08ccb998b93009305c318bd269b') db.session.add(canvas_course) db.session.flush() print("Adding CS1 course") cs1_course = Course(name="CS 1", owner_id=user.id, service='canvas', visibility='private') db.session.add(cs1_course) db.session.flush() print("Adding some assignments") assignment1 = Assignment(name="Assignment #1", body="a=b+c", course_id=default_course.id, owner_id=admin.id) db.session.add(assignment1) assignment2 = Assignment(name="Assignment #2", body="Figure it out!", course_id=default_course.id, owner_id=admin.id) db.session.add(assignment2) assignment3 = Assignment(name="Assignment #3", body="Clue", course_id=default_course.id, owner_id=admin.id) db.session.add(assignment3) ca1 = CourseAssignment(course_id=public_course.id, assignment_id=assignment1.id) db.session.add(ca1) ca2 = CourseAssignment(course_id=public_course.id, assignment_id=assignment2.id) db.session.add(ca2) ag1 = AssignmentGroup(name="Day 1 - Decision", course_id=default_course.id) db.session.add(ag1) ag2 = AssignmentGroup(name="Day 2 - Iteration", course_id=default_course.id) db.session.add(ag2) db.session.commit() db.session.add( AssignmentGroupMembership(assignment_group_id=ag1.id, assignment_id=assignment1.id)) db.session.add( AssignmentGroupMembership(assignment_group_id=ag1.id, assignment_id=assignment2.id)) db.session.add( AssignmentGroupMembership(assignment_group_id=ag2.id, assignment_id=assignment3.id)) db.session.commit() print("Complete")