def test_admin_createuser(app, admin_view): """Test flask-admin user creation""" with app.test_client() as client: # Test empty mail form res = client.post(url_for('user.create_view'), data={'email': ''}, follow_redirects=True) assert b'This field is required.' in res.data # Reproduces the workflow described in #154 res = client.post(url_for('user.create_view'), data={'email': '*****@*****.**'}, follow_redirects=True) assert _datastore.get_user('*****@*****.**') is not None res = client.post(url_for('user.create_view'), data={ 'email': '*****@*****.**', 'active': 'true' }, follow_redirects=True) user = _datastore.get_user('*****@*****.**') assert user is not None assert user.active is True res = client.post(url_for('user.create_view'), data={ 'email': '*****@*****.**', 'active': 'false' }, follow_redirects=True) user = _datastore.get_user('*****@*****.**') assert user is not None assert user.active is False user_data = dict(email='*****@*****.**', active=False, password=encrypt_password('123456')) _datastore.create_user(**user_data) user_data = dict(email='*****@*****.**', active=True, password=encrypt_password('123456')) _datastore.create_user(**user_data) user_data = dict(email='*****@*****.**', active=False, password=encrypt_password('123456')) _datastore.create_user(**user_data) _datastore.commit() assert _datastore.get_user('*****@*****.**') is not None user = _datastore.get_user('*****@*****.**') assert user is not None assert user.active is True user = _datastore.get_user('*****@*****.**') assert user is not None assert user.active is False
def add_users(services): staff_role = Role.query.filter_by(name='Staff').first() patient_role = Role.query.filter_by(name='Patient').first() for service in services: user = AppUser( email=service.name.lower().replace(' ', '_') + '*****@*****.**', password=encrypt_password('password'), service_id=service.id, full_name=fake.name(), phone_number=formatted_phone_number() ) db.session.add(user) user.roles.append(staff_role) patient_user = AppUser( email='*****@*****.**', password=encrypt_password('password'), full_name=fake.name(), phone_number=formatted_phone_number() ) db.session.add(patient_user) patient_user.roles.append(patient_role) db.session.commit() app_users = AppUser.query.all() print "Added users" return app_users
def add_test_users(): print 'Init users...' with app.test_client() as c: # send a fake request, so `current_app` can be the app rv = c.get('/') role_admin = user_datastore.find_or_create_role('admin', desc='Site Admin') role_editor = user_datastore.find_or_create_role('editor', desc='Content Editor') for i in range(1, 3): u = user_datastore.create_user(email='test%s@localhost' % i, password=encrypt_password('test')) u = user_datastore.create_user(email='admin@localhost', password=encrypt_password('test')) user_datastore.add_role_to_user(u, role_admin) u = user_datastore.create_user(email='editor@localhost', password=encrypt_password('test')) user_datastore.add_role_to_user(u, role_editor) db.session.commit() print 'Done.' print
def before_first_request(): logging.info( "-------------------- initializing everything ---------------------") db.create_all() user_datastore.find_or_create_role(name='admin', description='Administrator') user_datastore.find_or_create_role(name='end-user', description='End user') encrypted_password = utils.encrypt_password('123123') if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user(email='*****@*****.**', password=encrypted_password, active=True, confirmed_at=datetime.datetime.now()) encrypted_password = utils.encrypt_password('123123') if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user(email='*****@*****.**', password=encrypted_password, active=True, confirmed_at=datetime.datetime.now()) db.session.commit() user_datastore.add_role_to_user('*****@*****.**', 'admin') user_datastore.add_role_to_user('*****@*****.**', 'end-user') db.session.commit()
def add_users(services): staff_role = Role.query.filter_by(name='Staff').first() patient_role = Role.query.filter_by(name='Patient').first() for service in services: user = AppUser(email=service.name.lower().replace(' ', '_') + '*****@*****.**', password=encrypt_password('password'), service_id=service.id, full_name=fake.name(), phone_number=formatted_phone_number()) db.session.add(user) user.roles.append(staff_role) patient_user = AppUser(email='*****@*****.**', password=encrypt_password('password'), full_name=fake.name(), phone_number=formatted_phone_number()) db.session.add(patient_user) patient_user.roles.append(patient_role) db.session.commit() app_users = AppUser.query.all() print "Added users" return app_users
def test_admin_createuser(app, admin_view): """Test flask-admin user creation""" with app.test_client() as client: # Test empty mail form res = client.post( url_for('user.create_view'), data={'email': ''}, follow_redirects=True ) assert b'This field is required.' in res.data # Reproduces the workflow described in #154 res = client.post( url_for('user.create_view'), data={'email': '*****@*****.**'}, follow_redirects=True ) assert _datastore.get_user('*****@*****.**') is not None res = client.post( url_for('user.create_view'), data={'email': '*****@*****.**', 'active': 'true'}, follow_redirects=True ) user = _datastore.get_user('*****@*****.**') assert user is not None assert user.active is True res = client.post( url_for('user.create_view'), data={'email': '*****@*****.**', 'active': 'false'}, follow_redirects=True ) user = _datastore.get_user('*****@*****.**') assert user is not None assert user.active is False user_data = dict(email='*****@*****.**', active=False, password=encrypt_password('123456')) _datastore.create_user(**user_data) user_data = dict(email='*****@*****.**', active=True, password=encrypt_password('123456')) _datastore.create_user(**user_data) user_data = dict(email='*****@*****.**', active=False, password=encrypt_password('123456')) _datastore.create_user(**user_data) _datastore.commit() assert _datastore.get_user('*****@*****.**') is not None user = _datastore.get_user('*****@*****.**') assert user is not None assert user.active is True user = _datastore.get_user('*****@*****.**') assert user is not None assert user.active is False
def create_users(): user_datastore.create_user(email="admin", active=True, password=encrypt_password("admin"), roles=['admin']) user_datastore.create_user(email="user", active=True, password=encrypt_password("user"), roles=['reader']) db.session.commit()
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 create_test_models(): user_datastore.create_user(email='test', password=encrypt_password('test')) user_datastore.create_user(email='test2', password=encrypt_password('test2')) stuff = Contact(street='abc',city='def',state='NB',zipcode=12345) db.session.add(stuff) stuff = Contact(street='2 abc',city='dddef',state='XB',zipcode=12345) db.session.add(stuff) db.session.commit()
def add_users(self): l= User(email='*****@*****.**', password=encrypt_password('password'), username='******', paid_through=datetime.datetime.utcnow() + datetime.timedelta(weeks=52), confirmed_at=datetime.datetime.utcnow(), active=True) t= User(email='*****@*****.**', password=encrypt_password('password'), username='******', confirmed_at=datetime.datetime.utcnow(), active=True) db.session.add(t) db.session.add(l) db.session.commit() return l,t
def setup(): role = Role.first(name='user') #Get the 'user' role or create it if not role: role = Role.create(name='user', description='provides basic system access', bitmask=2) if not User.first(email="*****@*****.**"): mixer.blend('app.models.users.User', email="*****@*****.**", password=encrypt_password('hello'), confirmed_at=datetime.now(), roles=[role]) if not User.first(email="*****@*****.**"): mixer.blend('app.models.users.User', email="*****@*****.**", password=encrypt_password('world'), roles=[role])
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 create_user(): """ This is executed the first time the app runs, adds a default user and admins, sets and creates the roles too """ # 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='operator', description='Operator') # 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('admin') if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user(email='*****@*****.**', password=encrypted_password, username="******", first_name="a", last_name="b") encrypted_password = utils.encrypt_password('123456') if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user(email='*****@*****.**', password=encrypted_password, username="******", first_name="b", last_name="c") user_datastore.add_role_to_user('*****@*****.**', 'admin') user_datastore.add_role_to_user('*****@*****.**', 'operator') if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user(email='*****@*****.**', password=encrypted_password, username="******", first_name="Misael", last_name="Zapata") user_datastore.add_role_to_user('*****@*****.**', 'admin') if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user(email='*****@*****.**', password=encrypted_password, username="******", first_name="Matias", last_name="Bastos") user_datastore.add_role_to_user('*****@*****.**', 'operator') if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user(email='*****@*****.**', password=encrypted_password, username="******", first_name="Federico", last_name="Apenhanz") user_datastore.add_role_to_user('*****@*****.**', 'operator')
def novo(): nucleos = [(c.id, c.descricao) for c in Nucleo.query.order_by(Nucleo.descricao).all()] form = AgenteFormInserir() form.id_nucleo.choices = nucleos form.id_nucleo.choices.insert(0, (0, "Selecione...")) if request.method == "POST" and form.validate_on_submit(): agente = Agente() form.populate_obj(agente) agente.active = True agente.coordenador_nucleo = False agente.coordenador_pastoral = False agente.password = encrypt_password(agente.password) try: db.session.add(agente) db.session.commit() flash("Agente adicionado com sucesso!", "success") return redirect("/agente/") except Exception: db.session.rollback() flash(u'ERRO: E-mail já utilizado!', "warning") return render_template("agente/form.html", form = form, menu='agente')
def run(self): email = prompt('Email') password = prompt_pass('Password') password_confirm = prompt_pass('Confirm Password') first_name = prompt('First name') last_name = prompt('Last name') data = MultiDict(dict(email=email, password=password, password_confirm=password_confirm, first_name=first_name, last_name=last_name)) form = RegisterForm(data, csrf_enabled=False) if form.validate(): user = _datastore.create_user(email=email, password=encrypt_password(password), first_name=first_name, last_name=last_name, active=True, confirmed_at=datetime.datetime.utcnow()) get_or_create_role = _datastore.find_or_create_role("ADMIN") _datastore.add_role_to_user(user, get_or_create_role) _datastore.commit() print('\nUser created successfully') print('User(id=%s email=%s)' % (user.id, user.email)) return print('\nError creating user:'******'\n'.join(errors))
def demo_init(): with app.app_context(): from sqlalchemy.exc import OperationalError from flask.ext.security.utils import encrypt_password from unifispot.models import User from unifispot.superadmin.models import Account from unifispot.admin.models import Admin from unifispot.client.models import Client try: account = Account.query.filter_by(id=1).first() except : app.logger.debug( "No Account table Entry found,could be running migration ") else: if not account: #create default admin user enc_pass = encrypt_password('password') account = Account() db.session.add(account) admin_user = Admin(email='*****@*****.**',password=enc_pass,displayname= "Admin User1",active=1) admin_user2 = Admin(email='*****@*****.**',password=enc_pass,displayname= "Admin User2",active=1) admin_user3 = Admin(email='*****@*****.**',password=enc_pass,displayname= "Admin User3",active=1) admin_user.account = account admin_user2.account = account admin_user3.account = account db.session.add(admin_user) db.session.add(admin_user2) db.session.add(admin_user3) db.session.commit()
def init_db(): import string import random from flask.ext.security.utils import encrypt_password from model.create_db import db from model.security import User, Role import model.blog from controllers.security import user_datastore, security app.config['SQLALCHEMY_ECHO'] = True db.init_app(app) security.init_app(app) db.drop_all() db.create_all() 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() user_datastore.create_user(first_name='Admin', email='admin', password=encrypt_password('admin'), roles=[user_role, super_user_role]) db.session.commit()
def run(self): email = prompt('Email') password = prompt_pass('Password') password_confirm = prompt_pass('Confirm Password') first_name = prompt('First name') last_name = prompt('Last name') data = MultiDict( dict(email=email, password=password, password_confirm=password_confirm, first_name=first_name, last_name=last_name)) form = RegisterForm(data, csrf_enabled=False) if form.validate(): user = _datastore.create_user( email=email, password=encrypt_password(password), first_name=first_name, last_name=last_name, active=True, confirmed_at=datetime.datetime.utcnow()) get_or_create_role = _datastore.find_or_create_role("ADMIN") _datastore.add_role_to_user(user, get_or_create_role) _datastore.commit() print('\nUser created successfully') print('User(id=%s email=%s)' % (user.id, user.email)) return print('\nError creating user:'******'\n'.join(errors))
def run(self, name=None, email=None, password=None, role=None): if not name: name = prompt("Full Name") if not email: email = prompt("A valid email address") if not password: password = prompt_pass("Password") if not role: roles = [r.name for r in Role.objects] role_name = prompt_choices("Role", choices=roles, no_choice=('none', '')) if role_name: role, created = Role.objects.get_or_create(name=role_name) else: role = None else: role, created = Role.objects.get_or_create(name=role) if all([name, email, password]): user = User.objects.create( name=name, email=email, password=encrypt_password(password), active=True, roles=[role] ) else: user = u"Cant create the supersuser" print user
def user(email, password, roles): """Create a new user to access the app with""" with app.app_context(): user = User.query.filter_by(email=email).count() if user: print("A user already exists with email: {}".format(email)) exit(1) user = current_app.user_datastore.create_user( email=email, password=encrypt_password(password) ) current_app.db.session.add(user) if roles: for role in roles.split(','): db_role = Role.query.filter_by(name=role).first() if not db_role: db_role = Role(name=role, description=None) current_app.db.session.add(db_role) user.roles.append(db_role) current_app.db.session.commit()
def create(username, email, role_names, first_name=None, last_name=None): new_password = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(12)) new_password_hash = utils.encrypt_password(new_password) user = model.user_datastore.create_user(first_name=first_name, last_name=last_name, email=email, username=username, password=new_password_hash) user.roles = [UserRoles.get(role_name) for role_name in role_names] model.db.session.commit() return user
def run(self, user_data_file, **kwargs): from models.models import Role, User, Course, Assignment 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()) db.session.add(User(first_name=first, last_name=last, email=email)) print("Adding default course") default_course = Course(name="Default Course", owner_id=admin.id, service="blockpy") db.session.add(default_course) db.session.flush() print("Adding some assignments") assignment1 = Assignment(name="Example #1", body="a=b+c", course_id=default_course.id, owner_id=admin.id) db.session.add(assignment1) db.session.commit() print("Complete")
def run(self, id, pw): if '@' in id: u = User.objects.get(email=id) else: u = User.objects.get(id=id) u.password = encrypt_password(pw) u.save()
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 get_or_create_user(email, password, role, **kwargs): u = user_datastore.get_user(email) if not u: u = user_datastore.create_user(email=email, password=encrypt_password(password), **kwargs) user_datastore.add_role_to_user(u, role) db.session.commit() return u
def initdb(): """Reset and init database.""" # Prevent from accidental droping DB. # TODO: Implement "silent" flag for this. if raw_input('Do you really want to make initial DB (y/n)?') != 'y': return db.drop_all() db.create_all() user_defaults = { 'username': '******', 'email': '*****@*****.**', 'password': '******', } input_msg = 'Enter %s [%s]: ' for key, value in user_defaults.iteritems(): user_defaults[key] = raw_input(input_msg % (key, value)) or value user_defaults['password'] = utils.encrypt_password( user_defaults['password']) user = models.User(**user_defaults) db.session.add(user) db.session.commit()
def db_create(): """ Create a new database Add some default roles Create an initial admin user """ db.drop_all() db.create_all() roles = [('user', 'Generic user role'), ('admin', 'Regular Admin'), ('super', 'Super secret admin'), ] print 'making roles' for role_name, role_desc in roles: role = user_datastore.create_role(name=role_name, description=role_desc) db.session.commit() user = user_datastore.find_role('user') superAdmin = user_datastore.find_role('super') print 'creating first admin user, login information:' print '\tname: admin' print '\temail: %s' % app.config['ADMINS'][0] print '\tpassword: password' admin = user_datastore.create_user( email=app.config['ADMINS'][0], name='admin', password=encrypt_password('password') ) print 'adding roles to user' user_datastore.add_role_to_user(admin, superAdmin) user.created_at = datetime.utcnow() admin.created_at = datetime.utcnow() print 'finishing up' db.session.commit()
def run(self, name=None, email=None, password=None, role=None): if not name: name = prompt("Full Name") if not email: email = prompt("A valid email address") if not password: password = prompt_pass("Password") if not role: roles = [r.name for r in Role.objects] role_name = prompt_choices("Role", choices=roles, no_choice=('none', '')) if role_name: role, created = Role.objects.get_or_create(name=role_name) else: role = None else: role, created = Role.objects.get_or_create(name=role) if all([name, email, password]): user = User.objects.create( name=name, email=email, password=encrypt_password(password), active=True, roles=[role] ) else: user = "******" print(user)
def init_db(): import string import random from flask.ext.security.utils import encrypt_password from model.create_db import db from model.security import User, Role import model.blog from controllers.security import user_datastore, security app.config["SQLALCHEMY_ECHO"] = True db.init_app(app) security.init_app(app) db.drop_all() db.create_all() 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() user_datastore.create_user( first_name="Admin", email="admin", password=encrypt_password("admin"), roles=[user_role, super_user_role] ) db.session.commit()
def init_data(): with app.app_context(): from sqlalchemy.exc import OperationalError from flask.ext.security.utils import encrypt_password from unifispot.models import User from unifispot.superadmin.models import Account from unifispot.admin.models import Admin try: account = Account.query.filter_by(id=1).first() except: app.logger.debug( "No Account table Entry found,could be running migration ") else: if not account: #create default admin user enc_pass = encrypt_password('password') account = Account() db.session.add(account) admin_user = Admin(email='*****@*****.**', password=enc_pass, displayname="Admin User", active=1) admin_user.account = account db.session.add(admin_user) 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 run(self, **kwargs): # handle confirmed if re.sub(r'\s', '', str(kwargs.pop('confirmed'))).lower() in [ '', 'y', 'yes', '1', 'active' ]: kwargs['confirmed_at'] = datetime.datetime.now() # sanitize active input ai = re.sub(r'\s', '', str(kwargs['active'])) kwargs['active'] = ai.lower() in ['', 'y', 'yes', '1', 'active'] from flask_security.forms import ConfirmRegisterForm from werkzeug.datastructures import MultiDict form = ConfirmRegisterForm(MultiDict(kwargs), csrf_enabled=False) if form.validate(): kwargs['password'] = encrypt_password(kwargs['password']) user_datastore.create_user(**kwargs) print('User created successfully.') kwargs['password'] = '******' pprint(kwargs) else: print('Error creating user') pprint(form.errors)
def home(): password_form = Password_Change_Form(request.form) if request.method == 'POST': if verify_password(password_form.current_password.data, current_user.password): db.session.query(User).filter(User.id == current_user.id).update({ "password": encrypt_password(password_form.new_password.data) }) db.session.commit() return redirect(url_for('home')) regional_leads = db.session.query(User).join( User.roles).filter(Role.name == 'regional').all() team_leads = db.session.query(User).join( User.roles).filter(Role.name == 'teamlead').all() if current_user.temp_pass == current_user.password: password_reset = True else: password_reset = False if current_user.roles[0] == "teamlead": return redirect(url_for('team_confirmation')) return render_template('index.html', password_form=password_form, regional_leads=regional_leads, password_reset=password_reset, team_leads=team_leads)
def main(): app = create_app() with app.app_context(): db.metadata.create_all(db.engine) services = Service.query.all() staff_role = Role.query.filter_by(name='Staff').first() print 'Enter full name: ' full_name = raw_input() print 'Enter email address: ' email = raw_input() print 'Enter phone number: ' phone_number = raw_input() print 'Current organizations:' for service in services: print '%d %s' % (service.id, service.name) print 'Enter the id of the organization to associate with this user: '******'Is this a staff user? Enter y or n: ' staff_user_yn = raw_input() password = getpass() assert password == getpass('Password (again):') user = AppUser( email=email, password=encrypt_password(password), service_id=service_id, full_name=full_name, phone_number=phone_number ) db.session.add(user) if staff_user_yn == 'y': user.roles.append(staff_role) db.session.commit() print 'User added.'
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 before_first_request(): # Create the Roles user_datastore.find_or_create_role(name='admin', description='Administrator') user_datastore.find_or_create_role(name='marine-operator', description='Marine Operator') user_datastore.find_or_create_role(name='science-user', description='Science User') user_datastore.find_or_create_role(name='redis', description='Redis User') encrypted_password = utils.encrypt_password('password') toemail = app.config['TOEMAIL'] if not user_datastore.get_user(toemail): user_datastore.create_user(email=toemail, _password='******', user_name=toemail, user_id=toemail, email_opt_in=True, organization_id=1, first_name='The', last_name='Admin') # Commit db.session.commit() # Add the default Roles user_datastore.add_role_to_user('*****@*****.**', 'admin') user_datastore.add_role_to_user('*****@*****.**', 'redis') # Commit db.session.commit()
def _create_new_account(self, user_data, source=''): try: email = user_data['email'] user_data['stripped_email'] = self._strip_email(email) user_data['password'] = encrypt_password( '%s%s%s' % (email, source, Ivysaur.Config.PASSWORD_PLACEHOLDER) ) user_data['source'] = source user_data['confirmed_at'] = arrow.utcnow().timestamp user_data['silver_points'] = 1000 user = self.user_datastore.create_user(**user_data) if email.endswith("@harvard.edu"): user.tier = "harvard" self.db.session.commit() self.user_datastore.add_role_to_user(email, 'user') self.db.session.commit() user = self.user_repo.set_default_username(user) return user except IntegrityError: raise exceptions.AccountExists() except: raise
def register(cls, name, email, password, confirmed=False, roles=None): """ Create a new user account. :param name: the name of the account :type name: string :param email: the email address used to identify the account :type email: string :param password: the plaintext password for the account :type password: string :param confirmed: whether to confirm the account immediately :type confirmed: boolean :param roles: a list containing the names of the Roles for this User :type roles: list(string) """ from .. import security new_user = security.Security.user_datastore.create_user( name=name, email=email, password=encrypt_password(password) ) db.session.commit() if confirmed: new_user.confirm() if roles: for role_name in roles: new_user.add_role(role_name) flask.current_app.logger.debug("Created user {0}".format(email)) return new_user
def db_create(): """ Create a new database Add some default roles Create an initial admin user """ db.drop_all() db.create_all() roles = [ ('user', 'Generic user role'), ('admin', 'Regular Admin'), ('super', 'Super secret admin'), ] print 'making roles' for role_name, role_desc in roles: role = user_datastore.create_role(name=role_name, description=role_desc) db.session.commit() user = user_datastore.find_role('user') superAdmin = user_datastore.find_role('super') print 'creating first admin user, login information:' print '\tname: admin' print '\temail: %s' % app.config['ADMINS'][0] print '\tpassword: password' admin = user_datastore.create_user(email=app.config['ADMINS'][0], name='admin', password=encrypt_password('password')) print 'adding roles to user' user_datastore.add_role_to_user(admin, superAdmin) user.created_at = datetime.utcnow() admin.created_at = datetime.utcnow() print 'finishing up' db.session.commit()
def main(): app = create_app() with app.app_context(): db.metadata.create_all(db.engine) services = Service.query.all() staff_role = Role.query.filter_by(name='Staff').first() print 'Enter full name: ' full_name = raw_input() print 'Enter email address: ' email = raw_input() print 'Enter phone number: ' phone_number = raw_input() print 'Current organizations:' for service in services: print '%d %s' % (service.id, service.name) print 'Enter the id of the organization to associate with this user: '******'Is this a staff user? Enter y or n: ' staff_user_yn = raw_input() password = getpass() assert password == getpass('Password (again):') user = AppUser(email=email, password=encrypt_password(password), service_id=service_id, full_name=full_name, phone_number=phone_number) db.session.add(user) if staff_user_yn == 'y': user.roles.append(staff_role) db.session.commit() print 'User added.'
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('pw1') 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()
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('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()
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 initial_setup(): """Sets up roles and creates an initial account to use for authentication. """ # Set up roles for r in (('admin', 'Admin'), ('reviewer', 'Application reviewer'), ('student', 'Student')): user_datastore.find_or_create_role(name=r[0], description=r[1]) # Create default user email = app.config.get('ADMIN_USER') password = app.config.get('ADMIN_PASSWORD') roles = ['admin', 'reviewer'] existing = user_datastore.find_user(email=email) if existing: user_datastore.delete_user(existing) user = user_datastore.create_user( email=email, password=security_utils.encrypt_password(password) ) for role in roles: user_datastore.add_role_to_user(user, role)
def validate(self): if self.name.data.strip() == '': self.name.errors.append(get_message('NAME_NOT_PROVIDED')[0]) return False if self.password.data.strip() == '': self.password.errors.append( get_message('PASSWORD_NOT_PROVIDED')[0]) return False self.user = User.first(name=self.name.data) if self.user is None: self.user = User.create(name=self.name.data, active=True, password=encrypt_password( self.password.data)) return True if self.user is None: self.name.errors.append(get_message('USER_DOES_NOT_EXIST')[0]) return False if not self.user.password: self.password.errors.append(get_message('PASSWORD_NOT_SET')[0]) return False if not verify_and_update_password(self.password.data, self.user): self.password.errors.append(get_message('INVALID_PASSWORD')[0]) return False return True
def genpwhash(): """ Generate password hash for input """ print("Current password hash algorithm: {}".format(app.config['SECURITY_PASSWORD_HASH'])) password = prompt_pass("Enter password to hash (hidden)") print(encrypt_password(password))
def createsuperuser(): """ Create a super user of the system, requiring Email and password. """ email = prompt('User E-Mail') email_confirm = prompt('Confirm E-Mail') if not email == email_confirm: sys.exit('\nCould not create user: E-Mail did not match') if not EMAIL_REGEX.match(email): sys.exit('\nCould not create user: Invalid E-Mail addresss') password = prompt_pass('User password') password_confirm = prompt_pass('Confirmed password') if not password == password_confirm: sys.exit('\nCould not create user: Passwords did not match') datastore = SQLAlchemyUserDatastore(db, User, Role) datastore.create_user( email=email, password=encrypt_password(password), active=True, super_user=True) db.session.commit()
def register(cls, name, email, password, confirmed=False, roles=None): """ Create a new user account. :param name: the name of the account :type name: string :param email: the email address used to identify the account :type email: string :param password: the plaintext password for the account :type password: string :param confirmed: whether to confirm the account immediately :type confirmed: boolean :param roles: a list containing the names of the Roles for this User :type roles: list(string) """ from .. import security new_user = security.Security.user_datastore.create_user( name=name, email=email, password=encrypt_password(password)) db.session.commit() if confirmed: new_user.confirm() if roles: for role_name in roles: new_user.add_role(role_name) flask.current_app.logger.debug("Created user {0}".format(email)) return new_user
def do_setup(app): """Create a new settings database from scratch""" if config.SERVER_MODE is False: print("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("NOTE: Configuring authentication for SERVER mode.\n") # Prompt the user for their default username and password. print(""" Enter the email address and password to use for the initial pgAdmin user \ account:\n""") email = '' while email == '': email = input("Email address: ") def pprompt(): return getpass.getpass(), getpass.getpass('Retype password:'******'Passwords do not match. Try again') p1, p2 = pprompt() # Setup Flask-Security user_datastore = SQLAlchemyUserDatastore(db, User, Role) security = Security(app, user_datastore) with app.app_context(): password = encrypt_password(p1) db.create_all() user_datastore.create_role(name='Administrators', description='pgAdmin Administrators Role') user_datastore.create_user(email=email, password=password) db.session.flush() user_datastore.add_role_to_user(email, 'Administrators') # 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() # Done! print("") print("The configuration database has been created at {0}".format( config.SQLITE_PATH))
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 before_first_request(): user_datastore.find_or_create_role(name='admin', description='Administrator') user_datastore.find_or_create_role(name='super_admin', description='Super Administrator') encrypted_password = encrypt_password('password') if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user(email='*****@*****.**', password=encrypted_password) user_datastore.add_role_to_user('*****@*****.**', 'admin') user_datastore.add_role_to_user('*****@*****.**', 'super_admin')
def genpwhash(): """ Generate password hash for input """ print("Current password hash algorithm: {}".format( app.config['SECURITY_PASSWORD_HASH'])) password = prompt_pass("Enter password to hash (hidden)") print(encrypt_password(password))
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 put(self, data, instance_id): instance = self.model.get_by_id(instance_id) if not instance: abort(404, message='Resource does not exists') original_password = data['password'] data['password'] = encrypt_password(original_password) instance = instance.update(**data) return instance
def setup_submit(): if _has_users(): return "This site already has users defined in it", 403 data = request.json user_datastore.create_user(email=data['email'], password=encrypt_password(data['password'])) user_datastore.db.session.commit() return ""
def __init__(self, first_name, last_name, email, password, phone_number, date_of_birth, confirmed): self.first_name = first_name self.last_name = last_name self.email = email self.password = utils.encrypt_password(password) self.phone_number = phone_number self.date_of_birth = date_of_birth self.confirmed = confirmed
def create_stuff(): db.create_all() if models.Category.query.count() == 0: prog = models.Category() prog.name = 'Programming' db.session.add(prog) os = models.Category() os.name = 'Operating Systems' db.session.add(os) db.session.commit() if models.Position.query.count() == 0: m = models.Position() m.mnemonic = 'mensolone' m.description = 'quello grosso, dai!' m2 = models.Position() m2.mnemonic = 'scaffaluccio' m2.description = "piccino piccio'" aut_k = models.Author() aut_k.name = 'Kernighan' aut_r = models.Author() aut_r.name = 'Ritchie' op = models.Opera() op.title = 'Linguaggio C' op.authors = [aut_k, aut_r] es = models.Esemplare() es.opera = op es.position = m db.session.add(es) es = models.Esemplare() es.opera = op es.position = m2 db.session.add(es) op = models.Opera() op.title = 'The UNIX programming environment' op.authors = [aut_k] es = models.Esemplare() es.opera = op es.position = m db.session.add(es) db.session.commit() if models.Role.query.count() == 0: supa = user_datastore.create_role(name='super', description='Will do ANYTHING') user_datastore.create_role(name='librarian', description='Can manage books') db.session.commit() if models.User.query.count() == 0: adm = user_datastore.create_user(email='admin@test', password=encrypt_password('password')) user_datastore.add_role_to_user(adm, supa) db.session.commit() return 'created' else: return "C'hai provato, furbettino!"