def save_uploaded_file(): """ Receives files on the server side """ fchunk = FileChunk.init_from_request() logger.info("User uploaded chunk: {}".format(fchunk)) file_name = fchunk.file_name if not fchunk.afile: err = utils.pack_error("No file specified.") logger.error(err) return err chunk_path = get_chunk_path(file_name, fchunk.number) try: # For every request recived we store the chunk to a temp folder fchunk.afile.save(chunk_path) except Exception as exc: logger.error("Problem saving: {} due: {}".format(fchunk, exc)) return utils.pack_error("Unable to save file chunk: {}" .format(fchunk.number)) # When all chunks are recived we merge them if not all_chunks_received(fchunk): return utils.jsonify_success('Request completed successfully.') # When all chunks are received we merge them subject_file = merge_files(fchunk) if subject_file is not None: prefix = app.config['REDIDROPPER_UPLOAD_SAVED_DIR'] file_path = subject_file.get_full_path(prefix) delete_temp_files(fchunk) hash_matches = verify_file_integrity(fchunk) if hash_matches: LogEntity.file_uploaded(session['uuid'], file_path) return utils.jsonify_success('File {} uploaded successfully.' .format(file_name)) else: logger.error("md5 sum does not match for: {}".format(fchunk)) LogEntity.file_uploaded(session['uuid'], 'Checksum mismatch for file: {}' .format(file_path)) return utils.jsonify_error('Checksum mismatch for file: {}' .format(file_name)) else: LogEntity.file_uploaded(session['uuid'], 'Unable to merge chunks for file: {}' .format(file_path)) return utils.jsonify_error('Unable to merge chunks for file: {}' .format(file_name))
def save_uploaded_file(): """ Receives files on the server side """ fchunk = FileChunk.init_from_request() logger.info("User uploaded chunk: {}".format(fchunk)) file_name = fchunk.file_name if not fchunk.afile: err = utils.pack_error("No file specified.") logger.error(err) return err chunk_path = get_chunk_path(file_name, fchunk.number) try: # For every request recived we store the chunk to a temp folder fchunk.afile.save(chunk_path) except Exception as exc: logger.error("Problem saving: {} due: {}".format(fchunk, exc)) return utils.pack_error("Unable to save file chunk: {}".format( fchunk.number)) # When all chunks are recived we merge them if not all_chunks_received(fchunk): return utils.jsonify_success('Request completed successfully.') # When all chunks are received we merge them subject_file = merge_files(fchunk) if subject_file is not None: prefix = app.config['REDIDROPPER_UPLOAD_SAVED_DIR'] file_path = subject_file.get_full_path(prefix) delete_temp_files(fchunk) hash_matches = verify_file_integrity(fchunk) if hash_matches: LogEntity.file_uploaded(session['uuid'], file_path) return utils.jsonify_success( 'File {} uploaded successfully.'.format(file_name)) else: logger.error("md5 sum does not match for: {}".format(fchunk)) LogEntity.file_uploaded( session['uuid'], 'Checksum mismatch for file: {}'.format(file_path)) return utils.jsonify_error( 'Checksum mismatch for file: {}'.format(file_name)) else: LogEntity.file_uploaded( session['uuid'], 'Unable to merge chunks for file: {}'.format(file_path)) return utils.jsonify_error( 'Unable to merge chunks for file: {}'.format(file_name))
def api_send_verification_email(): """ @TODO: allow POST only @TODO: Send Verification Email to user_id :rtype: Response :return the success or failed in json format """ user_id = get_safe_int(request.form.get('user_id')) user = UserEntity.get_by_id(user_id) user = UserEntity.get_by_id(1) user.email = app.config['MAIL_SENDER_SUPPORT'] try: emails.send_verification_email(user) return jsonify_success({"message": "Verification email was sent."}) except Exception as exc: details = "Connection config: {}/{}:{}".format( app.config['MAIL_USERNAME'], app.config['MAIL_SERVER'], app.config['MAIL_PORT']) app.logger.debug(details) return jsonify_error({ "message": "Unable to send email due: {} {}".format(exc, details) })
def api_save_user(): """ Save a new user to the database TODO: Add support for reading a password field """ request_data = __extract_user_information(request) credentials = __generate_credentials(request_data["email"]) date_data = __get_date_information() if __check_is_existing_user(request_data["email"]): return utils.jsonify_error( {'message': 'Sorry. This email is already taken.'}) user = UserEntity.create(email=request_data["email"], first=request_data["first"], last=request_data["last"], minitial=request_data["minitial"], added_at=date_data["added_at"], modified_at=date_data["added_at"], access_expires_at=date_data["access_expires_at"], password_hash="{}:{}" .format(credentials["salt"], credentials["password_hash"])) __assign_roles(request_data["roles"], user) app.logger.debug("saved user: {}".format(user)) LogEntity.account_created(session['uuid'], user) return utils.jsonify_success({'user': user.serialize()})
def api_verify_email(): """ @TODO: add counter/log to track failed attempts :rtype: Response :return the success or failed in json format """ if 'POST' == request.method: token = utils.clean_str(request.form.get('tok')) else: token = utils.clean_str(request.args.get('tok')) if not token: return utils.jsonify_error({'message': 'No token specified.'}) try: email = utils.get_email_from_token(token, app.config["SECRET_KEY"], app.config["SECRET_KEY"]) except Exception as exc: # @TODO: add dedicated log type app.logger.error("api_verify_email: {}".format(exc.message)) return utils.jsonify_error({'message': exc.message}) app.logger.debug("Decoded email from token: {}".format(email)) user = UserEntity.query.filter_by(email=email).first() if user is None: app.logger.error("Attempt to verify email with incorrect token: {}" .format(token)) return utils.jsonify_error({'message': 'Sorry.'}) user = UserEntity.update(user, email_confirmed_at=datetime.today()) app.logger.debug("Verified token {} for user {}".format(token, user.email)) # @TODO: add dedicated log type LogEntity.account_modified(session['uuid'], "Verified token {} for user {}".format( token, user.email)) return utils.jsonify_success( {"message": "Email was verified for {}.".format(email)})
def api_save_user(): """ Save a new user to the database TODO: Add support for reading a password field """ email = request.form['email'] first = request.form['first'] last = request.form['last'] minitial = request.form['minitial'] roles = request.form.getlist('roles[]') email_exists = False try: existing_user = UserEntity.query.filter_by(email=email).one() email_exists = existing_user is not None except: pass if email_exists: return utils.jsonify_error( {'message': 'Sorry. This email is already taken.'}) # @TODO: use a non-gatorlink password here password = email salt, password_hash = utils.generate_auth(app.config['SECRET_KEY'], password) added_date = datetime.today() access_end_date = utils.get_expiration_date(180) # Note: we store the salt as a prefix user = UserEntity.create(email=email, first=first, last=last, minitial=minitial, added_at=added_date, modified_at=added_date, access_expires_at=access_end_date, password_hash="{}:{}".format(salt, password_hash)) user_roles = [] try: for role_name in roles: role_entity = RoleEntity.query.filter_by(name=role_name).one() user_roles.append(role_entity) except Exception as exc: app.logger.debug("Problem saving user: {}".format(exc)) [user.roles.append(rol) for rol in user_roles] user = UserEntity.save(user) app.logger.debug("saved user: {}".format(user)) LogEntity.account_created(session['uuid'], user) return utils.jsonify_success({'user': user.serialize()})
def api_save_user(): """ Add New User to the database """ email = request.form['email'] first = request.form['first'] last = request.form['last'] minitial = request.form['minitial'] roles = request.form.getlist('roles[]') app.logger.debug("roles: {}".format(roles)) email_exists = False try: existing_user = UserEntity.query.filter_by(email=email).one() email_exists = existing_user is not None except: pass if email_exists: return jsonify_error( {'message': 'Sorry. This email is already taken.'}) # @TODO: fix hardcoded values # password = '******' # salt, hashed_pass = generate_auth(app.config['SECRET_KEY'], password) added_date = datetime.today() access_end_date = get_expiration_date(180) user = UserEntity.create(email=email, first=first, last=last, minitial=minitial, added_at=added_date, modified_at=added_date, access_expires_at=access_end_date, password_hash="") # roles=user_roles) user_roles = [] try: for role_name in roles: role_entity = RoleEntity.query.filter_by(name=role_name).one() user_roles.append(role_entity) except Exception as exc: app.logger.debug("Problem saving user: {}".format(exc)) [user.roles.append(rol) for rol in user_roles] user = UserEntity.save(user) app.logger.debug("saved user: {}".format(user)) return jsonify_success({'user': user.serialize()})
def api_save_user(): """ Add New User to the database """ email = request.form['email'] first = request.form['first'] last = request.form['last'] minitial = request.form['minitial'] roles = request.form.getlist('roles[]') app.logger.debug("roles: {}".format(roles)) email_exists = False try: existing_user = UserEntity.query.filter_by(email=email).one() email_exists = existing_user is not None except: pass if email_exists: return jsonify_error({'message': 'Sorry. This email is already taken.'}) # @TODO: fix hardcoded values # password = '******' # salt, hashed_pass = generate_auth(app.config['SECRET_KEY'], password) added_date = datetime.today() access_end_date = get_expiration_date(180) user = UserEntity.create(email=email, first=first, last=last, minitial=minitial, added_at=added_date, modified_at=added_date, access_expires_at=access_end_date, password_hash="") # roles=user_roles) user_roles = [] try: for role_name in roles: role_entity = RoleEntity.query.filter_by(name=role_name).one() user_roles.append(role_entity) except Exception as exc: app.logger.debug("Problem saving user: {}".format(exc)) [user.roles.append(rol) for rol in user_roles] user = UserEntity.save(user) app.logger.debug("saved user: {}".format(user)) return jsonify_success({'user': user.serialize()})
def api_delete_file(): """ Deletes the passed file """ #get the file from the response subject_file_id = request.form.get('file_id') try: ret_value = file_manager.delete_file(subject_file_id) deleted_id = ret_value[0] deleted_path = ret_value[1] app.logger.debug("deleted file id: {}".format(subject_file_id)) LogEntity.file_deleted(session['uuid'], deleted_path) response = utils.jsonify_success({"file_id": deleted_id}) except: response = utils.jsonify_error({"exception": ret_value}) return response
def api_verify_email(): """ @TODO: add column for verification hash @TODO: add counter/log to track failed attempts :rtype: Response :return the success or failed in json format """ token = request.form.get('tok') # user = UserEntity.query.filter_by(email_token=token).first() user = UserEntity.get_by_id(1) if user is None: app.logger.error( "Attempt to verify email with incorrect token: {}".format(token)) return jsonify_error({'message': 'Sorry.'}) app.logger.debug("Verified token {} for user {}".format(token, user.email)) # implement update User set usrEmailConfirmedAt = NOW() return jsonify_success({"message": "Verification email was sent."})
def api_verify_email(): """ @TODO: add column for verification hash @TODO: add counter/log to track failed attempts :rtype: Response :return the success or failed in json format """ token = request.form.get('tok') # user = UserEntity.query.filter_by(email_token=token).first() user = UserEntity.get_by_id(1) if user is None: app.logger.error("Attempt to verify email with incorrect token: {}" .format(token)) return jsonify_error({'message': 'Sorry.'}) app.logger.debug("Verified token {} for user {}".format(token, user.email)) # implement update User set usrEmailConfirmedAt = NOW() return jsonify_success({"message": "Verification email was sent."})
def api_send_verification_email(): """ @TODO: Send Verification Email to user_id :rtype: Response :return the success or failed in json format """ user_id = utils.get_safe_int(request.form.get('user_id')) user = UserEntity.get_by_id(user_id) try: emails.send_verification_email(user) return utils.jsonify_success( {"message": "Verification email was sent."}) except Exception as exc: details = "Connection config: {}/{}:{}".format( app.config['MAIL_USERNAME'], app.config['MAIL_SERVER'], app.config['MAIL_PORT']) app.logger.debug(details) return utils.jsonify_error( {"message": "Unable to send email due: {} {}".format(exc, details)})