def setUp(self): from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--no-default-browser-check') chrome_options.add_argument('--no-first-run') chrome_options.add_argument('--disable-default-apps') chrome_options.add_argument('--remote-debugging-port=9222') chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') """Setup the test driver and create test users""" self.driver = webdriver.Chrome(chrome_options=chrome_options) self.driver.get(self.get_server_url()) email_admin = test_admin_email db.session.commit() db.drop_all() db.create_all() user_datastore.create_user(email=test_admin_email, username=test_admin_username, password=test_admin_password) user_datastore.create_user(email=test_user_final_email, username=test_user_final_username, password=test_user_final_password) user_datastore.find_or_create_role(name='admin', description='Administrator') user_datastore.find_or_create_role(name='end-user', description='End user') user_datastore.add_role_to_user(email_admin, 'admin') db.session.commit()
def create_admin_user_to_db(): print(db.session.query(User).count()) user = User.query.filter(User.email == "admin").first() user_role = Role.query.filter(Role.name == "user").first() super_user_role = Role.query.filter(Role.name == "superuser").first() if not user_role: user_role = Role(name="user") db.session.add(user_role) db.session.commit() if not super_user_role: super_user_role = Role(name="superuser") db.session.add(super_user_role) db.session.commit() if not user: now = datetime.now() user_datastore.create_user(email='admin', password=encrypt_password('8Lapis6Luna'), connect_date=now, roles=[user_role, super_user_role]) db.session.commit() print("admin user created")
def register(): if request.method == 'POST': name = request.form['name'] email = request.form['email'] phone = request.form['phone'] username = request.form['username'] password = utils.encrypt_password(request.form['password']) active = True user_datastore.create_user(name=name, email=email, phone=phone, username=username, password=password, active=active) db.session.commit() flash('Вітаємо! Ви зареєстровані!') return redirect(url_for('security.login')) name_form = 'user' title = 'Реєстрація користувача' form = RegistrationForm() return render_template('create_form.html', form=form, form_type=name_form, title=title)
def before_first_request(): # Create any database tables that don't exist yet. db.create_all() # 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(app.config['ADMIN_PASS']) if not user_datastore.get_user(app.config['ADMIN_EMAIL']): user_datastore.create_user(email=app.config['ADMIN_EMAIL'], password=encrypted_password, username=app.config['ADMIN_USERNAME'], name=app.config['ADMIN_NAME']) for specie in ALL_SPECIES: # Commit any database changes; the User and Roles must exist before # we can add a Role to the User specie_to_add = Specie(name=specie) if not db.session.query(Specie)\ .filter(Specie.name == specie_to_add.name).count() > 0: db.session.add(specie_to_add) db.session.commit()
def run(self): email = input("Email: ") name = input("Name: ") password = get_pw() roles = Role.query.all() selected_roles = [] if len(roles) > 0: role_select = None while role_select not in [r.id for r in roles]: print(role_select, [r.id for r in roles]) print("Select a role") role_select = int( input("".join([ "[{}] - {} : {}\n".format(role.id, role.name, role.description) for role in roles ]))) selected_roles.append(Role.query.get(role_select).name) with app.app_context(): try: user_datastore.create_user(email=email, password=hash_password(password), name=name, roles=selected_roles) db.session.commit() print("User with email {} has been created".format(email)) except IntegrityError as e: print(e)
def before_first_request(): """ runs before the first request, adds an user account and sets it as 'admin' role. """ # create admin and normal user roles user_datastore.find_or_create_role(name='admin', description='Administrator') user_datastore.find_or_create_role(name='user', description='End user') # create an admin user and add to database encrypted_password = hash_password('password') if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user(email='*****@*****.**', password=encrypted_password) try: db_init.session.commit() except SQLAlchemyError: raise InvalidUsage(status_code=500) # make [email protected] the admin user user_datastore.add_role_to_user('*****@*****.**', 'admin') try: db_init.session.commit() except SQLAlchemyError: raise InvalidUsage(status_code=500)
def setUp(self): from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-setuid-sandbox") """Setup the test driver and create test users""" self.driver = webdriver.Chrome(chrome_options=chrome_options) self.driver.get(self.get_server_url()) email_admin = test_admin_email db.session.commit() db.drop_all() db.create_all() user_datastore.create_user(email=test_admin_email, username=test_admin_username, password=test_admin_password) user_datastore.create_user(email=test_user_final_email, username=test_user_final_username, password=test_user_final_password) user_datastore.find_or_create_role(name='admin', description='Administrator') user_datastore.find_or_create_role(name='end-user', description='End user') user_datastore.add_role_to_user(email_admin, 'admin') db.session.commit()
def createadmin(): username = prompt(Fore.BLUE + "Username") query_username = db.session.query(FinalUser).filter_by( username=username).first() email = prompt(Fore.BLUE + "Write Email") if re.match( '^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', email) == None: print(Fore.RED + "Invalid email format") return query_email = db.session.query(FinalUser).filter_by(email=email).first() if query_username is None and query_email is None: password = prompt(Fore.BLUE + "Write password") repeat_password = prompt(Fore.BLUE + "Repeat password") if password == repeat_password: encrypted_password = utils.encrypt_password(password) user_datastore.create_user(username=username, password=encrypted_password, email=email) db.session.commit() user_datastore.add_role_to_user(email, 'admin') db.session.commit() print(Fore.GREEN + "Admin created") else: print(Fore.RED + "The password does not match") return else: print(Fore.RED + "The username or email are in use") return
def setUp(self): super().setUp() # Create user user_datastore.create_user(email='*****@*****.**', password='******', name='Foo Bar') # Log in with the user we just created self.client.post(url_for('security.login'), data={ 'email': '*****@*****.**', 'password': '******' }, follow_redirects=True)
def register(): form = forms.RegistrationForm() if form.validate_on_submit(): user_datastore.create_user(email=form.email.data, password=form.password.data) db.session.commit() return '', 200 for field, errors in form.errors.items(): for error in errors: print(error) return '', 403
def test_add_user(self): """ Create a user and find it (test_user_model.UserModel) """ user_datastore.create_user(email='*****@*****.**', password='******', username='******', active=True) self.assertTrue(True) user = user_datastore.get_user('*****@*****.**') self.assertIn('Test', str(user))
def setUp(self): print("Setting up test environment") configuration = config.TestConfig() app.config.from_object(configuration) self.app = app.test_client() db.create_all() user_datastore.create_user(email='*****@*****.**', password='******') db.session.commit()
def test_register_fail(self): user_datastore.create_user(email='*****@*****.**', name='test', password='******') db.session.commit() response = self.client.post( '/api/users', headers={'Content-Type': 'application/json'}, data=json.dumps({ 'email': '*****@*****.**', 'name': 'test', 'password': '******' })) self.assertEqual(response.status_code, 409)
def init(): db.drop_all() db.create_all() # Create roles user_datastore.create_role(name='admin', description='System administrator') user_datastore.create_role(name='user', description='Conference user') admin = user_datastore.create_user(username='******', password=utils.encrypt_password('admin')) user = user_datastore.create_user(username='******', password=utils.encrypt_password('user')) user_datastore.add_role_to_user(admin, 'admin') user_datastore.add_role_to_user(user, 'user') contacts = [ ('1010', gettext('John Smith')), ('1020', gettext('Sam Brown')), ] for c in contacts: rec = Contact(phone=c[0], name=c[1], user=admin) db.session.add(rec) guest_user_profile = ParticipantProfile(name=gettext('Guest'), startmuted=True) db.session.add(guest_user_profile) marked_user_profile = ParticipantProfile(name=gettext('Marker'),marked=True) db.session.add(marked_user_profile) admin_user_profile = ParticipantProfile(name=gettext('Administrator'), admin=True) db.session.add(admin_user_profile) conf_profile = ConferenceProfile(name=gettext('Default')) db.session.add(conf_profile) conf = Conference(number=100, name=gettext('Test Conference'), conference_profile=conf_profile, public_participant_profile=guest_user_profile, is_public=True, user=admin, ) db.session.add(conf) p1 = Participant(conference=conf, profile=admin_user_profile, phone='1001', user=admin) p2 = Participant(conference=conf, profile=guest_user_profile, phone='1002', user=admin) p3 = Participant(conference=conf, profile=marked_user_profile, phone='1003', user=admin) db.session.add(p1) db.session.add(p2) db.session.add(p3) db.session.commit()
def test_login_success(self): user_datastore.create_user(email='*****@*****.**', name='test', password=hash_password('123456')) db.session.commit() response = self.client.post( '/api/sessions', headers={'Content-Type': 'application/json'}, data=json.dumps({ 'email': '*****@*****.**', 'password': '******', })) self.assertEqual(response.status_code, 200) json_response = json.loads(response.get_data(as_text=True)) self.assertEqual(json_response['name'], 'test')
def registration(): if request.method == 'POST': if not User.query.filter( User.email == request.form.get('email')).first(): user_datastore.create_user(email=request.form.get('email'), password=hash_password( request.form.get('password'))) db.session.commit() user = User.query.filter( User.email == request.form.get('email')).first() login_user(user) return redirect('/') return render_template('registration.html')
def create_user(): db.create_all() with app.app_context(): password = encrypt_password('admin') user_datastore.create_role(name='admin', description='Administrator') user_datastore.create_role(name='user', description='Simple user') user_datastore.create_user(email='*****@*****.**', password=password) user = User.query.first() role = Role.query.first() user_datastore.add_role_to_user(user, role) db.session.commit()
def create_user(): print("Let's create a new user ... ") email = get_and_validate('email') password = get_and_validate('password') active = get_and_validate('active (True/False)', is_bool=True) admin = get_and_validate('admin (True/False)', is_bool=True) if not user_datastore.get_user(email): user_datastore.create_user(email=email, password=password, active=active) else: print('User by email {} already exists.'.format(email)) if admin: user_datastore.add_role_to_user(email, 'admin') db.session.commit()
def create_admin_admin(): user_datastore.create_role(name='admin', description='System administrator') user_datastore.create_role(name='user', description='Conference user') admin = user_datastore.create_user(username='******', password=utils.encrypt_password('admin')) user_datastore.add_role_to_user(admin, 'admin') db.session.commit()
def create_admin_admin(): user_datastore.create_role(name='admin', description='System administrator') user_datastore.create_role(name='user', description='Conference user') admin = user_datastore.create_user( username='******', password=utils.encrypt_password('admin')) user_datastore.add_role_to_user(admin, 'admin') db.session.commit()
def setUp(self): database.clean() self.client = application.test_client() self.user1 = user_datastore.create_user(email="*****@*****.**", password="******") self.user2 = user_datastore.create_user(email="*****@*****.**", password="******") db.session.commit() with self.client.session_transaction() as sess: sess["user_id"] = self.user1.get_id() sess["_fresh"] = True self.project1 = Project(name="Foos project") self.project2 = Project(name="Bars project") self.user1.add_project(self.project1, ProjectsUsers.ROLE_ADMIN) self.user2.add_project(self.project2, ProjectsUsers.ROLE_ADMIN) self.project1.save() self.project2.save()
def post(self): parser = request.get_json() email = parser.get('email') password = parser.get('password') if email is None or password is None: abort(400) # missing arguments user = user_datastore.create_user(email=email,password=utils.encrypt_password(password)) login_user(user, remember = True) return 201
def create(email, password, do_hash=True, **kwargs): from app import user_datastore if do_hash: password = hash_password(password) return user_datastore.create_user(email=email, password=password, **kwargs)
def build(): db.create_all() user_role = user_datastore.create_role(name="user") admin_role = user_datastore.create_role(name="admin") admin_user = user_datastore.create_user(email="*****@*****.**", password="******") user_datastore.add_role_to_user(admin_user, admin_role) test_user1 = user_datastore.create_user(email="*****@*****.**", password="******") test_user2 = user_datastore.create_user(email="*****@*****.**", password="******") user_datastore.add_role_to_user(test_user1, user_role) user_datastore.add_role_to_user(test_user2, user_role) db.session.add(admin_user) db.session.add(test_user1) db.session.add(test_user2) db.session.commit()
def createadmin(): email = prompt(Fore.BLUE + "Email") query_email = db.session.query(FinalUser).filter_by(email=email).first() if query_email is None: password = prompt(Fore.BLUE + "Write password") repeat_password = prompt(Fore.BLUE + "Repeat password") if password == repeat_password: encrypted_password = utils.encrypt_password(password) user_datastore.create_user(email=email, password=encrypted_password) db.session.commit() user_datastore.add_role_to_user(email, 'admin') db.session.commit() print(Fore.GREEN + "Admin created") else: print(Fore.RED + "The password does not match") return else: print(Fore.RED + "The username or email are in use") return
def setUp(self): """Clear the database for the next unit test. """ self.client = application.test_client() database.clean() self.user = user_datastore.create_user(email="*****@*****.**", password="******") db.session.commit() with self.client.session_transaction() as sess: sess["user_id"] = self.user.id sess["_fresh"] = True
def add_admin(email): """ Creates an admin user and adds it to the database """ pwd = getpass.getpass("Password for " + email + ": ") verify = getpass.getpass("Verify password for " + email + ": ") if pwd != verify: print("Passwords don't match") return salt = binascii.hexlify(os.urandom(32)) encrypted_pwd = flask_security.utils.encrypt_password(password=pwd) admin = user_datastore.create_user(email=email, password=encrypted_pwd) user_datastore.add_role_to_user(admin, 'Admin') user_datastore.commit()
def build_sample_db(): """ Populate a small db with some example entries. """ 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'] last_names = ['Brown', 'Smith', 'Patel'] 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 registration(): if request.method == 'POST': try: user = user_datastore.create_user( email=request.form['email'], password=request.form['password']) role = Role.query[1] user_datastore.add_role_to_user(user, role) db.session.commit() except: print('Please try again.') return redirect(url_for('security.login')) form = Registration() return render_template('security/register.html', form=form)
def setUp(self): database.clean() self.client = application.test_client() self.user1 = user_datastore.create_user(email="*****@*****.**", password="******") self.user2 = user_datastore.create_user(email="*****@*****.**", password="******") db.session.commit() with self.client.session_transaction() as sess: sess["user_id"] = self.user1.get_id() sess["_fresh"] = True self.project = Project(name="Bars project", user=self.user2) self.project.save() file_handle, file_path = tempfile.mkstemp() file_handle = os.fdopen(file_handle, "r+") file_handle.write("foobar") self.file_path = os.path.join(file_path) self.document_file = DocumentFile(projects=[self.project], path=self.file_path) self.document_file.save()
def setUp(self): """Clear the database for the next unit test. """ self.client = application.test_client() database.clean() self.user = user_datastore.create_user(email="*****@*****.**", password="******") db.session.add(self.user) db.session.commit() with self.client.session_transaction() as sess: db.session.add(self.user) sess["user_id"] = self.user.id sess["_fresh"] = True
def setUp(self): database.clean() self.client = application.test_client() self.user1 = user_datastore.create_user(email="*****@*****.**", password="******") self.user2 = user_datastore.create_user(email="*****@*****.**", password="******") db.session.commit() with self.client.session_transaction() as sess: sess["user_id"] = self.user1.get_id() sess["_fresh"] = True self.project = Project(name="Bars project") self.user2.add_project(self.project, role=ProjectsUsers.ROLE_ADMIN) file_handle, file_path = tempfile.mkstemp() file_handle = os.fdopen(file_handle, "r+") file_handle.write("foobar") self.file_path = os.path.join(file_path) self.document_file = DocumentFile(projects=[self.project], path=self.file_path) self.document_file.save()
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 post(self): """ register """ args = user_args.parse_args() password_hash = hash_password(args['password']) try: user = user_datastore.create_user(name=args['name'], email=args['email'], password=password_hash) db.session.commit() return user except Exception as e: db.session.rollback() raise Conflict
def db_create(): with app.app_context(): db.create_all() db.session.commit() admin_role = user_datastore.find_or_create_role(name="admin", description="Administrator") user_role = user_datastore.find_or_create_role(name="user", description="User") admin = user_datastore.create_user(email="*****@*****.**", password=encrypt_password("password"), cc_login="******") user_datastore.add_role_to_user(admin, admin_role) user_datastore.add_role_to_user(admin, user_role) admin = user_datastore.create_user(email="*****@*****.**", password=encrypt_password("password"), cc_login="******") user_datastore.add_role_to_user(admin, admin_role) user_datastore.add_role_to_user(admin, user_role) admin = user_datastore.create_user(email="*****@*****.**", password=encrypt_password("password"), cc_login="******") user_datastore.add_role_to_user(admin, admin_role) user_datastore.add_role_to_user(admin, user_role) db.session.commit()
def create_superuser(): if Role.query.filter_by(name='admin').first(): return password_raw = os.getenv("FLASK_USER_PASSWORD") or '123456' password_hash = hash_password(password_raw) try: role = user_datastore.create_role(name='admin') user = user_datastore.create_user(name=os.getenv("FLASK_USER") or "admin", email=os.getenv("FLASK_USER_EMAIL") or "*****@*****.**", password=password_hash) user_datastore.add_role_to_user(user, role) db.session.commit() except Exception as e: print(e) pass
def add_to_db(pk, db_type): if db_type == 'Unf Questions': unf_obj = UnfQuestions.query.filter(UnfQuestions.id == int(pk)).first() total = len(Users.query.all()) + 1 # psy_id=int(random.randrange(start=1,stop=total)) #getting the latest entry in database prev_psy_id = get_last_record_psy_id() #finding the next valid psy_id for this question pre_psy_id = (prev_psy_id + 1) % total '''here we will assume that first 3 ids are admins in user table (another perfect work around is to check each time whether that psy_id is psycologist or not)''' if pre_psy_id >= 0 and pre_psy_id <= 3: pre_psy_id = 4 f_obj = FilQuestions(q_title=unf_obj.q_title, q_desc=unf_obj.q_desc, psy_id=pre_psy_id, no_upvotes=0) db.session.add(f_obj) db.session.commit() db.session.delete(unf_obj) db.session.commit() else: psy = Psycologists.query.filter(Psycologists.id == pk).first() user = user_datastore.create_user(email=psy.email, password=psy.password) db.session.add(user) db.session.commit() role = Roles.query.filter(Roles.id == 2).first() re = user_datastore.add_role_to_user(user, role) db.session.commit() #setting up their profile also ----------------some bug about unique constraint psy_id = Users.query.filter(Users.email == psy.email).first().id pr = Profile(psy_id=psy_id, id=psy_id) db.session.add(pr) db.session.commit() if re: db.session.delete(psy) db.session.commit() return 'Data has been moved' else: return 'unsuccessful' return redirect(url_for('conf'))
def add_user(credentials): """ Adds user to the database """ if check_email(credentials["email"]) == None: last_id = db.session.query(func.max(User.id)).first() id = 1 if not (last_id[0] == None): id = last_id[0] + 1 encrypted_pass = encrypt_password(credentials["password"]) user = user_datastore.create_user(id=id, email=credentials["email"], password=encrypted_pass, name=credentials["name"], surname=credentials["surname"], lastName=credentials["lastName"]), student_role = user_datastore.find_role("Student") user_datastore.add_role_to_user(user[0], student_role) db.session.commit() return (True, "OK") else: return (False, "User already exists")
def build_sample_db(): """ Populate a small db with some example entries. """ db.drop_all() db.create_all() with app.app_context(): super_user_role = Role(name='superuser') db.session.add(super_user_role) db.session.commit() test_user = user_datastore.create_user( name='superuser', email='*****@*****.**', password=encrypt_password('123456'), roles=[super_user_role]) db.session.commit() return
def run(): init_db() user_datastore.create_user(email='*****@*****.**', password='******') db.session.commit()
# coding=utf-8 from app import db, Role, User, roles_users, app, user_datastore from datetime import date, datetime from flask_security.utils import encrypt_password import string import random print "Enter password:"******"Admin", email="admin", password=encrypt_password(admin_pw), roles=[user_role, super_user_role] ) db.session.commit()
from app import db db.create_all() from app import user_datastore from config import ADMIN_PASSWORD try: user_datastore.create_role(name="admin", description="Site Administrators.") user_datastore.create_user(email="*****@*****.**", password=ADMIN_PASSWORD) user_datastore.add_role_to_user("*****@*****.**", "admin") db.session.commit() except Exception: pass # Import your application as: # from app import application # Example: from app import app # Import CherryPy import cherrypy if __name__ == '__main__': # Mount the application cherrypy.tree.graft(app, "/") # Unsubscribe the default server