def get_mentee_data(current_user_id): """curate data used by /mentee view""" from .models import Mentees user = user_datastore.get_user(current_user_id) # in case no user currently logged in, fetch user from mentee model if user is None: user = Mentees.query.filter_by(id=current_user_id).first() user_email = user.mentee_email else: user_email = user.email try: is_admin = True if user.roles[0].name == 'admin' else False except AttributeError: is_admin = False except IndexError: is_admin = False user_tasks = get_mentee_tasks(current_user_id) user_obj = { 'user_id': user.id, 'user_email': user_email, 'user_tasks': user_tasks, 'user_mentors': get_mentee_mentors(current_user_id), 'is_admin': is_admin } return user_obj
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 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 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 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 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 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
#!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 session_service(): resp = jsonify(success=False) if request.method == 'DELETE': resp = jsonify(success=True) resp.set_cookie(key="token", expires=0) return set_debug_response_header(resp) if request.method == 'POST': username, password = request.json['username'], request.json['password'] user = user_datastore.get_user(username) password_hash = user.password if verify_password(password, password_hash): print('user login: %s' % user.user_name + ' verified') resp = jsonify(success=True, userID=user.id) resp.set_cookie(key="token", value=str({ "id": user.id, "deadline": (time.time() + 86400) * 1000 }), max_age=7200, httponly=True) return set_debug_response_header(resp) else: resp = jsonify(success=False, loginError='用户名或密码错误') return set_debug_response_header(resp) elif request.method == 'GET': token, deadline, user_id, user = None, None, None, None if not request.cookies: resp = jsonify(success=False, loginError='未登录') return set_debug_response_header(resp) else: cookies = request.cookies if not cookies.get('token'): resp = jsonify(success=False, loginError='未登录') return set_debug_response_header(resp) else: token = json.loads(cookies['token'].replace('\'', '"')) if not token.get('deadline') or not token.get('id'): resp = jsonify(success=False, loginError='未登录') return set_debug_response_header(resp) else: deadline = int(token['deadline']) user_id = int(token['id']) user = app_models.User.query.get(user_id) if time.time() > (deadline / 1000): resp = jsonify(success=False, loginError='会话过期') return set_debug_response_header(resp) if user: result = { 'success': True, 'user': { 'userID': user.id, 'userName': user.user_name, 'permissions': [p.name for p in user.roles] } } resp = Response(json.dumps(result)) return set_debug_response_header(resp) elif request.method == 'OPTIONS': pass return set_debug_response_header(resp)
def load_user_from_request(request): if request.method == 'POST' and "/outputs/" not in request.base_url: username = request.form.get('email') password = request.form.get('password') if LOGIN_METHOD != "None": try: result = User.try_login(username, password) if not result: do_flash(*get_message('INVALID_PASSWORD')) return None except ldap.INVALID_CREDENTIALS, e: do_flash(*get_message('INVALID_PASSWORD')) return None user = User.query.filter_by(username=result['uid'][0]).first() if not user: encrypted_password = utils.encrypt_password(password) if not user_datastore.get_user(result['mail'][0]): user = user_datastore.create_user( email=result['mail'][0], password=encrypted_password, username=result['uid'][0], name=result['cn'][0], gid=result['gidNumber'][0], homedir=result['homeDirectory'][0]) db.session.commit() user = User.query.filter_by(username=result['uid'][0]).first() else: user = User.query.filter_by(username=LOGIN_USERNAME).first() if username != LOGIN_USERNAME or LOGIN_PASSWORD != password: do_flash(*get_message('INVALID_PASSWORD')) return None if not user: encrypted_password_config = utils.encrypt_password( LOGIN_PASSWORD) if not user_datastore.get_user(LOGIN_EMAIL): user = user_datastore.create_user( email=LOGIN_EMAIL, password=encrypted_password_config, username=LOGIN_USERNAME, name=LOGIN_USERNAME, gid=LOGIN_GID, homedir=LOGIN_HOMEDIR) db.session.commit() if not os.path.exists(os.path.join(LOGIN_HOMEDIR, "jobs")): os.makedirs(os.path.join(LOGIN_HOMEDIR, "jobs")) user = User.query.filter_by(username=LOGIN_USERNAME).first() login_user(user) return user
def 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