def exist(name, code): wbs_code = Database.find_one(table='wbs', data={'code': self.code}) wbs_name = Database.find_one(table='wbs', data={'code': self.code}) if wbs_code or wbs_name: return True else: return False
def edit_profile(): if 'user' in session: form = updateProfileForm() if form.validate_on_submit(): Database.update_one(collection="users", query=[{'user_id': session['user'].uid}, {"$set": {"uname": form.username.data, "fname": form.fname.data, "lname": form.lname.data, "bio": form.bio.data, "phone": form.phone.data, "address": form.address.data, "city": form.city.data, "zipcode": form.zipcode.data, "state": form.state.data}}]) flash('Your profile has been updated.') # change session username to newone once update the database session['user'].name = form.username.data # print(session['user'].name) # return to myprofile page userProfile = User.get_by_id(session['user'].uid) return render_template('/myprofile.html', user=userProfile) elif request.method == 'GET': userProfile = User.get_by_id(session['user'].uid) form.username.data = userProfile.uname form.fname.data = userProfile.fname form.lname.data = userProfile.lname form.bio.data = userProfile.bio form.phone.data = userProfile.phone form.address.data = userProfile.address form.city.data = userProfile.city form.zipcode.data = userProfile.zip form.state.data = userProfile.state return render_template('/updateProfile.html', title='Update', form=form) else: return redirect(url_for('web.index'))
def get_recovery_by_email(cls, user_email): """ Finds the Recovery object with the given user email :param user_email: user object to be updated :return: Recovery object """ Database.find_one(COLLECTION, {'user_email': user_email})
def start_train(project_id): if not current_user.is_authenticated: print('not logged in') return redirect(url_for('login')) content = None data = None data = Project.from_user(current_user.user_id) project_specific_data = [] html = None titles = None if Project.check_auth(current_user.user_id, int(project_id)): project_specific_data = Project.get_one(current_user.user_id, int(project_id)) if project_specific_data[0]['model_available']: return jsonify(result='trained') q.enqueue(DLModel.train_model, project_specific_data[0]['dataset'][0]['name'], int(project_id), app.config['UPLOAD_FOLDER']) Database.update_one(collection='projects', query=[{ 'project_id': int(project_id) }, { "$set": { "in_training": True } }]) return jsonify(result='done') else: return jsonify(result='error')
def start_train(project_id): """ STRICT API To allow ADMIN user to force sart training for the Deep Leanring Model Allows an ADMIN user to start traning the user Deep LEarning model customer's activities. \n\n API/URL must be accessed with GET request and supply project_id the URL\n method: GET\n Args: project_id (str): ID of the poject/Customer need to be sent in url. It is made to do so via Front end href Returns: response: JSON object On Success \n response = { 'result': 'done' } \n On Fail:\n response = { 'result': 'error' } \n """ if not current_user.is_authenticated: print('not logged in') return redirect(url_for('login')) content = None data = None data = Project.from_user(current_user.user_id) project_specific_data = [] html = None titles = None if Project.check_auth(current_user.user_id, int(project_id)): project_specific_data = Project.get_one(current_user.user_id, int(project_id)) if project_specific_data[0]['model_available']: return jsonify(result='trained') q.enqueue(DLModel.train_model, project_specific_data[0]['dataset'][0]['name'], int(project_id), app.config['UPLOAD_FOLDER']) Database.update_one(collection='projects', query=[{ 'project_id': int(project_id) }, { "$set": { "in_training": True } }]) return jsonify(result='done') else: return jsonify(result='error')
def updatefname(uname, fname): Database.update_one(collection="users", query=[{ 'uname': uname }, { "$set": { "fname": fname } }])
def exist(name, code): account_code = Database.find_one(table='controlaccounts', data={'code': self.code}) account_name = Database.find_one(table='controlaccounts', data={'code': self.code}) if account_code or account_name: return True else: return False
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) db.initialize(config[config_name].DATABASE_NAME) from app.models import main as main_blueprint app.register_blueprint(main_blueprint) return app
def recover_in_db(cls, recovery_id, email): """ Recovers the password in the database with a unique recovery ID :param recovery_id: ID to ensure a secure recuperation of the password :return: Boolean """ recovery_in_DB = cls( **Database.find_one(COLLECTION, {'_id': recovery_id})) if recovery_in_DB is None: return False else: Database.remove(COLLECTION, {'_id': recovery_id}) return True
def get_recovery(cls, _id=None): """ Fetches a list of the all the Recovery objects in the given collection :param _id: The specific ID of a particular collection :return: List of Recovery objects or one specific Recovery object """ if _id is None: return [ cls(**recovery) for recovery in Database.find(COLLECTION, {}) ] else: return [cls(Database.find_one(COLLECTION, {'_id': _id}))]
def change_password(): if 'user' in session: form = changePasswordForm() if form.validate_on_submit(): #update the password Database.update_one(collection="users", query=[{'uname':session['user'].name},{"$set":{"password":form.password.data}}]) flash('Your password has been changed.') #back to profile page userProfile = User.get_by_username(session['user'].name) return render_template('/myprofile.html', user=userProfile) return render_template('/changePassword.html', title='Change Password', form=form) else: return redirect(url_for('web.index'))
def auth_verify_email(user_id, email_token): """ This is used to verfiy user via the link the receive on their email. \n\n API/URL must be accessed with GET request and supply user_id and email_token in the URL\n method: GET\n Args: user_id (str): ID of the poject/Customer need to be sent in url. It is made to do so via email template email_token (str): UUID generated email token need to be sent in url. It is made to do so via email template Returns: response: JSON object On Success \n response = { 'status': 'success', 'message': 'Email verified' } \n On Fail:\n response = { 'status': 'fail', 'message': 'Email already verified' } \n """ user = User.get_by_id(int(user_id)) if user.is_email_verified: responseObject = { 'status': 'fail', 'message': 'Email already verified' } return make_response(jsonify(responseObject)), 202 email_auth_data = Database.find_one(collection='email_token', query={'user_id': int(user_id)}) if email_auth_data['email_token'] == email_token: Database.update_one(collection="users", query=[{ 'user_id': int(user_id) }, { "$set": { "is_email_verified": True } }]) responseObject = {'status': 'success', 'message': 'Email verified'} return make_response(jsonify(responseObject)), 201
def check_blacklist(auth_token): # check whether auth token has been blacklisted res = Database.find_one(collection='blacklist_tokens', query={'token': auth_token}) if res: return True else: return False
def predictions_dashboard(project_id): if not current_user.is_authenticated: print('not logged in') return redirect(url_for('login')) content = None data = None model_info = None data = Project.from_user(current_user.user_id) if Project.check_auth(current_user.user_id, int(project_id)): project_specific_data = Project.get_one(current_user.user_id, int(project_id)) if project_specific_data[0]['model_available']: model_info = Database.find_one( collection="models", query={"project_id": project_specific_data[0]['project_id']}) print(model_info) try: # try to match the pages defined in -> pages/<input file> return render_template('pages/prediction_dashboard.html', data=data, project_specific_data=project_specific_data, model_info=model_info) except: return render_template('pages/error-404.html')
def validate_username(self, username): if username.data != session['user'].name: user = Database.find_one(collection="users", query={'uname': username.data}) print(user) if user is not None: raise ValidationError('Please use a different username.')
def auth_verify_email(user_id, email_token): user = User.get_by_id(int(user_id)) if user.is_email_verified: responseObject = { 'status': 'fail', 'message': 'Email already verified' } return make_response(jsonify(responseObject)), 202 email_auth_data = Database.find_one(collection='email_token', query={'user_id': int(user_id)}) if email_auth_data['email_token'] == email_token: Database.update_one(collection="users", query=[{'user_id': int(user_id)}, {"$set": { "is_email_verified": True }} ]) responseObject = { 'status': 'success', 'message': 'Email verified' } return make_response(jsonify(responseObject)), 201
def project_dashboard(project_id): """ Admin Dashboard \n ALlows ADMIN to access project/CUSTOMER user ALlows ADMIN to access project/CUSTOMER user dashboard with all the admin tools to vefiy user pipeline this allows admin to oversee if the user data is present or not Allow to see the status of user Deep Learning model.\n\n method: GET\n API/URL must be accessed with GET request and supply project_id in the URL\n Args: project_id (str): ID of the poject need to be sent in url. It is made to do so via Front end href Returns: view: a url VIEW the project's/CUSTOMER's required params such as Dataset, dataset voliation if present, Deep leanring model status, Deep learning model metrics, predication metreics. OR if the user is not logged in or CUSTOMER user does not exists then 404 redirect """ if not current_user.is_authenticated: print('not logged in') return redirect(url_for('login')) content = None data = None data = Project.from_user(current_user.user_id) project_specific_data = [] html = None titles = None model_info = None if Project.check_auth(current_user.user_id, int(project_id)): project_specific_data = Project.get_one(current_user.user_id, int(project_id)) print(project_specific_data) if project_specific_data[0]['model_available']: model_info = Database.find_one( collection="models", query={"project_id": project_specific_data[0]['project_id']}) print(model_info) try: # try to match the pages defined in -> pages/<input file> return render_template('pages/project_dashboard.html', data=data, project_specific_data=project_specific_data, model_info=model_info) except: return render_template('pages/error-404.html')
def get_by_id(cls, _id: str, collection: str): """ Returns the user object with the given id, or raises an exception if that user was not found :param _id: id of the user to find :param collection: DB that contains all the users :return: user object """ user = Database.find_one(collection, {'_id': _id}) if user: return cls(**user)
def login(): # cut the page for authenticated users if current_user.is_authenticated: return redirect(url_for('index')) # Declare the login form form = LoginForm(request.form) # Flask message injected into the page, in case of any errors msg = None # check if both http method is POST and form is valid on submit if form.validate_on_submit(): # assign form data to variables username = request.form.get('username', '', type=str) password = request.form.get('password', '', type=str) # filter User out of database through username user = User.get_by_username(username) if user: #if bc.check_password_hash(user.password, password): if user.password == password and user.is_admin: print("password matched") login_user(user) Database.insert(collection="login_log", data={ "user_name": username, "date_time": str(datetime.datetime.utcnow()), "ip": request.remote_addr }) return redirect(url_for('index')) else: msg = "Wrong password or not Admin. Please try again." else: msg = "Unknown user" return render_template('pages/auth-login.html', form=form, msg=msg)
def email_auth(self): print("Creating registration email") token = uuid.uuid4().hex links = [ 'http://ec2-3-19-30-128.us-east-2.compute.amazonaws.com/auth/verify_email/' + str(self.user_id) + '/' + token, 'http://ec2-3-19-30-128.us-east-2.compute.amazonaws.com:5000/auth/verify_email/' + str(self.user_id) + '/' + token, 'http://127.0.0.1:5000/auth/verify_email/' + str(self.user_id) + '/' + token ] Database.insert(collection='email_token', data={ 'user_id': self.user_id, 'email_token': token }) msg = Message('Verify Email', sender='*****@*****.**', recipients=[self.email]) msg.html = render_template('pages/verify_email.html', name=self.fname, links=links) mail.send(msg)
def predictions_dashboard(project_id): """ Predictions Dashboard \n To allow ADMIN user see all necessary metrics for the project/CUSTOMER user Allows an ADMIN user visualize the Deep Learning model's performance, along side customer's activities.\n\n method: GET\n API/URL must be accessed with GET request and supply project_id in the URL\n Args: project_id (str): ID of the poject need to be sent in url. It is made to do so via Front end href Returns: view: a url VIEW the project's/CUSTOMER's all required prediction values and visulization data give user login status. If project CUSTOMER not found then redirect 404. """ if not current_user.is_authenticated: print('not logged in') return redirect(url_for('login')) content = None data = None model_info = None data = Project.from_user(current_user.user_id) if Project.check_auth(current_user.user_id, int(project_id)): project_specific_data = Project.get_one(current_user.user_id, int(project_id)) if project_specific_data[0]['model_available']: model_info = Database.find_one( collection="models", query={"project_id": project_specific_data[0]['project_id']}) print(model_info) try: # try to match the pages defined in -> pages/<input file> return render_template('pages/prediction_dashboard.html', data=data, project_specific_data=project_specific_data, model_info=model_info) except: return render_template('pages/error-404.html')
def reset_token(token): """ This is used to reset user/admin password after they click rest link method: POST, GET\n GET: will render the web page Args: token (token): UUID generated token Returns: redirect: for login """ user = User.verify_reset_token(token) if user is None: flash('An invalid token', 'warning') return redirect(url_for('web.reset_request')) form = ResetPasswordForm() if form.validate_on_submit(): pw_hash = form.password.data Database.update_one(collection="users", query=[{ 'user_id': user.user_id }, { "$set": { "password": pw_hash } }]) flash('Your password has been updated! you are now able to login') return redirect(url_for('web.login')) return render_template('pages/reset_token.html', title='Reset password', form=form)
def user_view(): """ Returns the user health info when Authorization token is present in the heeader """ # get the auth token auth_header = request.headers.get('Authorization') data = request.get_json() if data is None: data = request.form if auth_header: try: auth_token = auth_header.strip() except IndexError: responseObject = { 'status': 'fail', 'message': 'Bearer token malformed.' } return make_response(jsonify(responseObject)), 401 else: auth_token = '' if auth_token: resp = User.decode_auth_token(auth_token) if not isinstance(resp, str): user = User.get_by_id(resp) stats = Database.find_one(collection='user_stats', query={ 'user_id': resp, 'date': data.get('date') }) responseObject = { 'status': 'success', 'data': { 'user_id': user.user_id, 'email': user.email, 'fname': user.fname, 'lname': user.lname }, 'user_stats': stats } return make_response(jsonify(responseObject)), 200 responseObject = {'status': 'fail', 'message': resp} return make_response(jsonify(responseObject)), 401 else: responseObject = { 'status': 'fail', 'message': 'Provide a valid auth token.' } return make_response(jsonify(responseObject)), 401
def get_db_connection(): if not db_has_connection(): try: g.db = Database( host=current_app.config['MYSQL']['HOST'], db=current_app.config['MYSQL']['DB'], user=current_app.config['MYSQL']['USER'], passwd=current_app.config['MYSQL']['PASS'], ) except Exception as e: abort( 500, status=0, message='Failed to connect to CORE Database.', errors=dict( application='There was a problem connecting to MySQL.', validation=None), http_status=500) return g.db
def customer_dashboard(project_id): if not current_user.is_authenticated: print('not logged in') return redirect(url_for('login')) content = None data = None data = Project.from_user(current_user.user_id) project_specific_data = [] html = None titles = None model_info = None if Project.check_auth(current_user.user_id, int(project_id)): project_specific_data = Project.get_one(current_user.user_id, int(project_id)) print(project_specific_data) if project_specific_data[0]['model_available']: model_info = Database.find_one( collection="models", query={"project_id": project_specific_data[0]['project_id']}) print(model_info) try: # try to match the pages defined in -> pages/<input file> responseObject = { "data": data, "project_specific_data": project_specific_data, "model_info": model_info } return make_response(jsonify(responseObject)), 201 except: responseObject = { 'status': 'fail', 'message': 'Some error occurred with database. Please try again.' } return make_response(jsonify(responseObject)), 201
def get_by_id(cls, _id): data = Database.find_one(collection='users', query={'user_id': _id}) if data is not None: # return the object user return cls(**data)
def get_by_username(cls, uname): # check the database, users collection for the pair email, password data = Database.find_one(collection='users', query={'uname': uname}) if data is not None: # return the object user return cls(**data)
def get_by_email(cls, email): # check the database, users collection for the pair email, password data = Database.find_one(collection='users', query={'email': email}) if data is not None: # return the object user return cls(**data)
def save_to_mongo(self): Database.insert(collection='users', data=self.json())
def get_by_user(cls, date, email): data = Database.find_one("baseball", {"date": date, "email": email}) if data is not None: return cls(**data)