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 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 put(self, member_id): if check_member_role(["admin"], current_user.email) == False: return { "message": 'Missing authorization to retrieve content', }, 401 if "application/json" in request.headers["Content-Type"]: username = request.json.get("username") suppliers = request.json.get("suppliers") contact = request.json.get("contact") company = request.json.get("company") active = request.json.get("active") address = request.json.get("address") role = request.json.get("role") user = User.query.filter_by(id=member_id).first() if user: if username is not None: user.username = username if company is not None: user.company = company if contact is not None: user.contact = str(contact) if suppliers is not None: user.suppliers = str(suppliers) if active is not None: user.active = active if address is not None: user.address = address if role is not None and Role.query.filter_by( name=role).first(): role_list = list(map(lambda x: x.name, user.roles)) user_datastore.remove_role_from_user( user.email, str(role_list[0])) db_session.commit() user_datastore.add_role_to_user(user.email, role) db_session.commit() user_updated = User.query.filter_by(id=member_id).first() return { "version": api_version, "message": "Update {}(id: {}) info".format(user_updated.email, user_updated.id), "data": { "id": user_updated.id, "email": user_updated.email, "username": user_updated.username, "suppliers": ast.literal_eval(user_updated.suppliers), "company": user_updated.company, "contact": user_updated.contact, "address": user_updated.address, "active": user_updated.active, "role": list(map(lambda x: x.name, user_updated.roles)) } }, 200 return { "version": api_version, "message": "Check header and data type", "data": {} }, 404
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 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): 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_user(self): ''' Create user. ''' form = CreateUserForm(request.form) if request.method == 'POST' and form.validate('creating'): user = Users( email=form.email.data, password=bcrypt.generate_password_hash(form.password.data, rounds=12), emri=form.emri.data, mbiemri=form.mbiemri.data, role=form.role.data ) user.save() default_role = user_datastore.find_role(form.role.data) user_datastore.add_role_to_user(user, default_role) return redirect(url_for('admin.users')) else: return render_template( 'mod_admin/form.html', heading="Create User", post_url=url_for('admin.create_user'), form=form)
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 give_role(role): try: giving_role = user_datastore.find_or_create_role(role) user_datastore.add_role_to_user( current_user, giving_role) #give role to new user IMMEDIATELY db.session.commit() return True except: return False
def bulkAddRoles(message): userList = message['users'] role = message['role'] if current_user.has_role('Admin'): for userID in userList: userQuery = Sec.User.query.filter_by(id=int(userID)).first() if userQuery is not None: user_datastore.add_role_to_user(userQuery, role) db.session.commit() db.session.close() return 'OK'
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 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 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 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 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 run(self, name, email, password, role): u = User(name=name, password=password, email=email) if role is not None: try: r = self._get_or_create_role(role) user_datastore.add_role_to_user(u, r) except: raise InvalidCommand("The role %s is not supported." % (role)) print('Creating user %s' % u) db.session.add(u) 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_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 post(self): """ Add a role to a user - **Admin API Key Required** """ if 'X-API-KEY' in request.headers: apiKey = request.headers['X-API-KEY'] adminKeyCheck = apiFunc.isValidAdminKey(apiKey) if adminKeyCheck is True: args = roleArgs.parse_args() if 'username' and 'role' in args: username = args['username'] role = (args['role']).title() userQuery = Sec.User.query.filter_by( username=username).first() if userQuery is not None: roleQuery = Sec.Role.query.filter_by(name=role).first() if roleQuery is not None: user_datastore.add_role_to_user( userQuery, roleQuery) db.session.commit() return { 'results': { 'message': 'Role ' + role + ' added to ' + username } } else: db.session.commit() return { 'results': { 'message': "No Such Role" } }, 400 else: db.session.commit() return { 'results': { 'message': "No Such Username" } }, 400 db.session.commit() return {'results': {'message': "Request Error"}}, 400
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 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 create_super_user(): username = input('Email address:') while username == '': print('Username is required!') username = input('Email address:') password = getpass.getpass('Password:'******'': print('Password is required!') password = getpass.getpass('Password:'******'Password again:') if password == password_again: user_object = user_datastore.create_user(email=username, password=password) role_object = user_datastore.create_role(name='Admin') user_datastore.add_role_to_user(user=user_object, role=role_object) db.session.commit() click.echo('ok') else: sys.exit('failed to create super user! Try again!')
def register_page(): email = request.form.get('email') password = request.form.get('password') password2 = request.form.get('password2') if request.method == 'POST': if not (email or password or password2): flash('Please, fill all fields!') elif password != password2: flash('Passwords are not equal!') else: try: new_user = user_datastore.create_user(email=email, password=password) role = Role.query.filter(Role.name == 'user').first() user_datastore.add_role_to_user(new_user, role) db.session.commit() return redirect(url_for('login_page')) except IntegrityError: flash('This email already registered!') return render_template('register.html')
def user_registered_handler(app, user, confirm_token): if not os.path.exists( os.path.join(app.config['UPLOAD_FOLDER'], str(user.email) + '_' + str(user.id))): os.makedirs( os.path.join(app.config['UPLOAD_FOLDER'], str(user.email) + '_' + str(user.id))) default_role = user_datastore.find_role('end-user') user_datastore.add_role_to_user(user, default_role) db.session.commit() id = user.id ############# Add user to NGS_onto ######################## UserURI = dbconAg.createURI(namespace=localNSpace, localname="users/" + str(id)) userType = dbconAg.createURI(namespace=dcterms, localname="Agent") dbconAg.add(UserURI, RDF.TYPE, userType)
def index(): if request.method == 'GET': return render_template('registration/index.html') elif request.method == 'POST' and recaptcha.verify(): full_name = request.form['full_name'] email = request.form['email'] login = request.form['login'] password = request.form['password'] confirm_password = request.form['confirm_password'] else: return render_template('registration/index.html', captcha_error='Recaptcha error!') if confirm_password != password: return render_template('registration/index.html', error_password="******") user_email = User.query.filter(User.email == email).first() user_login = User.query.filter(User.login == login).first() if user_email and user_email.email == email: return render_template('registration/index.html', error_email="This email is already exist!") elif user_login and user_login.login == login: return render_template('registration/index.html', error_login="******") elif full_name and email and login and password: try: user = user_datastore.create_user(full_name=full_name, email=email, login=login, password=password) role = Role.query.filter(Role.name == 'user').first() user_datastore.add_role_to_user(user, role) db.session.add(user) db.session.commit() except: return render_template('registration/index.html', error_message="Something wrong, please try again!") return redirect(url_for_security('login'))
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 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 user_registered_sighandler(app, user, confirm_token): default_role = user_datastore.find_role("User") user_datastore.add_role_to_user(user, default_role) db.session.commit()
def post(self): if "application/json" in request.headers["Content-Type"]: email = request.json["email"] password = request.json["password"] username = request.json.get("username") current_login_ip = request.remote_addr ####### NEED TO UPDATE TO DYNAMICALLY SEARCH AND INDEX INPUT FROM CLIENT ###### # try: # suppliers = request.json["suppliers"] # except: # suppliers_list = Supplier.query.order_by(Supplier.email).all() # data = [supplier.as_dict() for supplier in suppliers_list] # print(data) suppliers_list = Supplier.query.order_by(Supplier.email).all() data = [supplier.as_dict() for supplier in suppliers_list] company = request.json.get("company") contact = request.json.get("contact") content = render_user_client_structure() if user_datastore.get_user(email): return { "version": api_version, "message": "User {} exist. Please login".format(email), "data": {} }, 422 elif not re.match(r"[^@]+@[^@]+\.[^@]+", email): return { "version": api_version, "message": "Please check your email format.", "data": {} }, 422 elif len(password) < 6: return { "version": api_version, "message": "Password must be at least 6 characters long.", "data": {} }, 422 # create user and add user role as default user_datastore.create_user( email = email, password = hash_password(password), username = username, current_login_ip = current_login_ip, suppliers = { "data": data }, company = company, contact = contact, content = content, ) db_session.commit() user_datastore.add_role_to_user(email, "user") db_session.commit() roles = user_datastore.find_user(email=email).roles user = User.query.filter_by(email=email).first() return { "version": api_version, "message": "User {} created.".format(email), "data": { "email": "{}".format(email), "roles":list(map(lambda x: x.name, roles)), "suppliers": user.suppliers, "company": company, "contact": contact } }, 200
def post(self): if check_member_role(["admin"], current_user.email) == False: return { "message": 'Missing authorization to retrieve content', }, 401 if "application/json" in request.headers["Content-Type"]: email = request.json["email"] print('\n\n\n\n', email, '\n\n\n\n') password = request.json["password"] username = request.json.get("username") current_login_ip = request.remote_addr company = request.json.get("company") contact = request.json.get("contact") address = request.json.get("address") roles = request.json.get("role") ####### NEED TO UPDATE TO DYNAMICALLY SEARCH AND INDEX INPUT FROM CLIENT ###### try: suppliers = request.json["suppliers"] except: # suppliers_list = Supplier.query.order_by(Supplier.email).all() # data = [supplier.as_dict() for supplier in suppliers_list] suppliers = [] pass # suppliers_list = Supplier.query.order_by(Supplier.email).all() # data = [supplier.as_dict() for supplier in suppliers_list] if user_datastore.get_user(email): return { "version": api_version, "message": "User {} exist. Please login".format(email), "data": {} }, 422 elif not re.match(r"[^@]+@[^@]+\.[^@]+", email): return { "version": api_version, "message": "Please check your email format.", "data": {} }, 422 elif len(password) < 6 or not password: return { "version": api_version, "message": "Password must be at least 6 characters long.", "data": {} }, 422 # create user and add user role as default user_datastore.create_user(email=email, password=hash_password(password), username=username, current_login_ip=current_login_ip, suppliers=str(suppliers), company=company, contact=contact, address=address) db_session.commit() if roles and Role.query.filter_by(name=roles).first(): user_datastore.add_role_to_user(email, roles) else: user_datastore.add_role_to_user(email, "user") db_session.commit() roles = user_datastore.find_user(email=email).roles user = User.query.filter_by(email=email).first() return { "version": api_version, "message": "User {} created.".format(email), "data": { "id": user.id, "email": user.email, "roles": list(map(lambda x: x.name, roles)), "suppliers": ast.literal_eval(user.suppliers), "company": user.company, "contact": user.contact, "address": user.address, "active": user.active } }, 200
def 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 _post_user_registration(app, **other_fields): """Handler to handle post user registration """ default_role = user_datastore.find_role("User") user_datastore.add_role_to_user(other_fields.get('users'), default_role) db.session.commit()
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 oAuthAuthorize(provider): oAuthClient = oauth.create_client(provider) oAuthProviderQuery = settings.oAuthProvider.query.filter_by( name=provider).first() if oAuthProviderQuery is not None: try: token = oAuthClient.authorize_access_token() except: return redirect('/login') userData = oAuthClient.get(oAuthProviderQuery.profile_endpoint) userDataDict = userData.json() userQuery = Sec.User.query.filter_by( oAuthID=userDataDict[oAuthProviderQuery.id_value], oAuthProvider=provider, authType=1).first() # Default expiration time to 365 days into the future if 'expires_at' not in token: if 'expires_in' in token: token['expires_at'] = datetime.timedelta(seconds=int( token['exipires_in'])) + datetime.datetime.utcnow() else: token['expires_at'] = time() + (365 * 24 * 3600) # If oAuth ID, Provider, and Auth Type Match - Initiate Login if userQuery is not None: existingTokenQuery = Sec.OAuth2Token.query.filter_by( user=userQuery.id).all() for existingToken in existingTokenQuery: db.session.delete(existingToken) db.session.commit() newToken = None if 'refresh_token' in token: newToken = Sec.OAuth2Token(provider, token['token_type'], token['access_token'], token['refresh_token'], token['expires_at'], userQuery.id) else: newToken = Sec.OAuth2Token(provider, token['token_type'], token['access_token'], None, token['expires_at'], userQuery.id) db.session.add(newToken) db.session.commit() if userQuery.active is False: flash( "User has been Disabled. Please contact your administrator", "error") return redirect('/login') else: login_user(userQuery) if oAuthProviderQuery.preset_auth_type == "Discord": discord_processLogin(userDataDict, userQuery) elif oAuthProviderQuery.preset_auth_type == "Reddit": reddit_processLogin(userDataDict, userQuery) elif oAuthProviderQuery.preset_auth_type == "Facebook": facebook_processLogin(oAuthProviderQuery.api_base_url, userDataDict, userQuery) if userQuery.email is None or userQuery.email == 'None': flash("Please Add an Email Address to your User Profile", "error") return redirect(url_for('settings.user_page')) else: return redirect(url_for('root.main_page')) # If No Match, Determine if a User Needs to be created else: existingEmailQuery = None hasEmail = False if oAuthProviderQuery.email_value in userDataDict: existingEmailQuery = Sec.User.query.filter_by( email=userDataDict[ oAuthProviderQuery.email_value]).first() hasEmail = True else: flash("Please Add an Email Address to your User Profile", "error") # No Username Match - Create New User if existingEmailQuery is None: convertedUsername = userDataDict[ oAuthProviderQuery.username_value].replace(" ", "_") userDataDict[ oAuthProviderQuery.username_value] = convertedUsername existingUsernameQuery = Sec.User.query.filter_by( username=convertedUsername).first() requestedUsername = convertedUsername if existingUsernameQuery is not None: requestedUsername = requestedUsername + str( random.randint(1, 9999)) if hasEmail is True: user_datastore.create_user( email=userDataDict[oAuthProviderQuery.email_value], username=requestedUsername, active=True, confirmed_at=datetime.datetime.utcnow(), authType=1, oAuthID=userDataDict[oAuthProviderQuery.id_value], oAuthProvider=provider) else: user_datastore.create_user( email=None, username=requestedUsername, active=True, confirmed_at=datetime.datetime.utcnow(), authType=1, oAuthID=userDataDict[oAuthProviderQuery.id_value], oAuthProvider=provider) db.session.commit() user = Sec.User.query.filter_by( username=requestedUsername).first() defaultRoleQuery = Sec.Role.query.filter_by(default=True) for role in defaultRoleQuery: user_datastore.add_role_to_user(user, role.name) user.uuid = str(uuid.uuid4()) user.xmppToken = str(os.urandom(32).hex()) if oAuthProviderQuery.preset_auth_type == "Discord": discord_processLogin(userDataDict, user) elif oAuthProviderQuery.preset_auth_type == "Reddit": reddit_processLogin(userDataDict, user) elif oAuthProviderQuery.preset_auth_type == "Facebook": facebook_processLogin(oAuthProviderQuery.api_base_url, userDataDict, user) newToken = None if 'refresh_token' in token: newToken = Sec.OAuth2Token(provider, token['token_type'], token['access_token'], token['refresh_token'], token['expires_at'], user.id) else: newToken = Sec.OAuth2Token(provider, token['token_type'], token['access_token'], None, token['expires_at'], user.id) db.session.add(newToken) db.session.commit() login_user(user) runWebhook("ZZZ", 20, user=user.username) newLog( 1, "A New User has Registered - Username:"******"An existing OAuth User exists under this email address with another provider", "error") return redirect('/')
# -*- coding: utf-8 -*- from app import db from app import user_datastore from models import User from app import user_datastore user = User.query.first() user_datastore.create_role(name='admin', description='Administrator') db.session.commit() from models import Role role = Role.query.first() user_datastore.add_role_to_user(user, role) db.session.commit() ''' p = Post(title = 'Заголовок первого поста', body='Контент первого поста') db.session.add(p) db.session.commit() p p1 = Post(title = 'Заголовок второго поста', body='Контент второго поста') db.session.add(p1) db.session.commit() p1 p2 = Post(title = 'Заголовок третьего поста', body='Контент третьего поста') db.session.add(p2) db.session.commit() p2 '''
#!flask/bin/python import pymongo from app import user_datastore, app, utils from app import db from config import plotdir,poordirectory, indexdir, MAX_SEARCH_RESULTS,PER_PAGE, SNIPPET_LENGTH mongo_db = pymongo.MongoClient() annotations=mongo_db.annotations def create_roles(): user_datastore.create_role(name='admin', description='The admin-role, provides full access to all databases and pages') db.session.commit() def add_articles(): for event in annotations.reference_events.find({'query':{'$exists':True},'articles':{'$exists':False}}): print event["name"] utils.add_reference_articles(event["name"]) if __name__ == '__main__': #create_roles() user_datastore.add_role_to_user(user_datastore.get_user(2),'admin') db.session.commit() add_articles()
def push_user_to_database_and_set_role(self): from app import user_datastore user_datastore.create_user(name=self.name, last_name=self.last_name, email=self.email, password_hash=self.password_hash, active=False) user_datastore.add_role_to_user(self.email, 'user')
def new_user_registered(sender, **extra): user = extra["user"] role = user_datastore.find_role("user") user_datastore.add_role_to_user(user, role)
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
def add_role_to_user(email,role): user = user_datastore.find_user(email=email) user_datastore.add_role_to_user(user,role) db.session.commit()