def delete(journal_id): auth_header = request.headers.get('Authorization') if auth_header: token = auth_header.split(" ")[1] else: return jsonify([{ 'status': 'failed', 'message': 'Not authorization header.' }]) decoded = decode_auth_token(token) user = User.get(User.id == decoded) if user: journal = Journal.delete().where(Journal.id == journal_id) if journal.execute(): return jsonify([{ 'status': 'success', 'message': 'Successfully delete selected journal.', }]) else: return jsonify([{ 'status': 'failed', 'message': 'Unable to create this journal' }])
def index(): auth_header = request.headers.get('Authorization') if auth_header: token = auth_header.split(" ")[1] else: return jsonify([{ 'status': 'failed', 'message': 'Not authorization header.' }]) decoded = decode_auth_token(token) user = User.get(User.id == decoded) if user: journals = JournalEntry.select().where(JournalEntry.user_id == user.id) return jsonify({ 'message': 'Successfully retrieved user journal', 'status': 'success', 'journals': [{ 'id': journal.id, 'created_at': journal.created_at, 'updated_at': journal.updated_at, 'title': journal.title, 'content': journal.content, 'image_path': journal.image_path } for journal in journals], }) else: return jsonify([{ 'status': 'failed', 'message': 'Authentication failed.' }])
def show(id): auth_header = request.headers.get('Authorization') if auth_header: token = auth_header.split(" ")[1] else: return jsonify([{ 'status': 'failed', 'message': 'Not authorization header.' }]) decoded = decode_auth_token(token) user = User.get(User.id == decoded) if user: journal = JournalEntry.get(JournalEntry.id == id) return jsonify({ 'message': 'Successfully retrieved journal entry', 'status': 'success', 'journal': { 'id': journal.id, 'created_at': journal.created_at, 'updated_at': journal.updated_at, 'user_id': journal.user_id, 'title': journal.title, 'content': journal.content, 'image_path': journal.image_path } }) else: return jsonify([{ 'status': 'failed', 'message': 'Authentication failed.' }])
def destroy(id): auth_header = request.headers.get('Authorization') if auth_header: token = auth_header.split(" ")[1] else: return jsonify([{ 'status': 'failed', 'message': 'Not authorization header.' }]) decoded = decode_auth_token(token) user = User.get(User.id == decoded) if user: journal_entry = JournalEntry.get(JournalEntry.id == id) journal_entry.delete_instance() return jsonify({ 'message': 'Successfully deleted journal entry', 'status': 'success', 'redirect': 'https://journal-nyx.herokuapp.com/journals/' }) else: return jsonify([{ 'status': 'failed', 'message': 'Authentication failed.' }])
def update(project_id): auth_header = request.headers.get('Authorization') if not auth_header: return jsonify(status="failed", message="No authorization header found.") else: token = auth_header.split(" ")[1] user_id = decode_auth_token(token) user = User.get(User.id == int(user_id)) put_data = request.get_json() project = Project.get_by_id(project_id) ## if key exists in JSON, then iterate (currently not working): # for k, v in put_data.items(): # project.k = v project.name = put_data['name'] project.client_id = put_data['clientID'] project.project_type = put_data['projectType'] project.date = put_data['date'] project.currency = put_data['currency'] project.total = put_data['total'] if project.save(): return jsonify(status="success", message="Project details updated.") else: return jsonify(status="failed", message="Unable to update project details.")
def show(project_id): auth_header = request.headers.get('Authorization') if not auth_header: return jsonify(status="failed", message="No authorization header found.") else: token = auth_header.split(" ")[1] user_id = decode_auth_token(token) user = User.get(User.id == int(user_id)) project = Project.get_by_id(project_id) project_data = { "id": project.id, "name": project.name, "project_type": project.project_type, "client_id": str(project.client_id), "client_name": Client.get_by_id(project.client_id).name, "date": str(project.date), "currency": project.currency, "total": str(project.total) } if user: return jsonify(project_data) else: return jsonify(status="failed", message="Authentication failed.")
def delete_client(): auth_header = request.headers.get('Authorization') if auth_header: token = auth_header.split(" ")[1] else: return jsonify(status="failed", message="No authorization header found.") user_id = decode_auth_token(token) user = User.get(User.id == int(user_id)) post_data = request.get_json() id = post_data['id'] client = Client.get_or_none(Client.id == id) delete = Client.delete().where(Client.id == id) if not client: return jsonify(status="failed", message="Could not find client in database.") elif delete.execute(): return jsonify(status="success", message=f"{client.name} deleted.") else: return jsonify(status="failed", message=f"Unable to delete {client_name}")
def create(): auth_header = request.headers.get('Authorization') if auth_header: token = auth_header.split(" ")[1] else: return jsonify([{ 'status': 'failed', 'message': 'Not authorization header.' }]) decoded = decode_auth_token(token) user = User.get(User.id == decoded) if user: if request.method == "GET": contacts = PersonalContact.select().where( PersonalContact.user_id == user.id) return jsonify({ 'personalContacts': [{ 'id': contact.id, 'name': contact.name, 'relationship': contact.relationship, 'location': contact.location, 'priority': contact.priority, 'phone_number': contact.phone_number, 'email': contact.email } for contact in contacts] }) elif request.method == "POST": req_data = request.get_json() req_data['name'] req_data['email'] contact = PersonalContact(name=req_data['name'], email=req_data['email'], user=user) if contact.save(): return jsonify([{ 'status': 'success', 'message': 'Successfully created a contact.', 'contact': { 'id': contact.id, 'name': contact.name, 'email': contact.email } }]) else: return jsonify([{ 'status': 'failed', 'message': 'Unable to save contact.' }]) else: return jsonify([{ 'status': 'failed', 'message': 'Authentication failed.' }])
def show_current_user(): auth_header = request.headers.get('Authorization') if auth_header: token = auth_header.split(" ")[1] else: return jsonify([{ 'status': 'failed', 'message': 'Not authorization header.' }]) decoded = decode_auth_token(token) user = User.get(User.id == decoded) if user: if request.method == "GET": return jsonify({ 'id': user.id, 'first_name': user.first_name, 'last_name': user.last_name, 'dob': user.dob, 'passport_num': user.passport_num, 'nationality': user.nationality, 'language_primary': user.language_primary, 'language_secondary': user.language_secondary, 'verified': user.verified }) elif request.method == "PUT": req_data = request.get_json() user.first_name = req_data['firstName'] or user.first_name user.last_name = req_data['lastName'] or user.last_name user.email = req_data['email'] or user.email user.nationality = req_data['nationality'] or user.nationality user.passport_num = req_data['passportNum'] or user.passport_num user.language_primary = req_data[ 'languagePrimary'] or user.language_primary user.language_secondary = req_data[ 'languageSecondary'] or user.language_secondary if req_data['password']: user.password = generate_password_hash(req_data['password']) if user.save(): return jsonify([{ 'status': 'success', 'message': 'Successfully updated the user details.' }]) else: return jsonify([{ 'status': 'failed', 'message': 'Unable to update user.' }]) else: return jsonify([{ 'status': 'failed', 'message': 'Authentication failed.' }])
def update(id): auth_header = request.headers.get('Authorization') if auth_header: token = auth_header.split(" ")[1] else: return jsonify([{ 'status': 'failed', 'message': 'Not authorization header.' }]) decoded = decode_auth_token(token) user = User.get(User.id == decoded) journal_entry = JournalEntry.get(JournalEntry.id == id) if user and journal_entry: title = request.form.get('title') content = request.form.get('content') # check if request has file # if no new file uploaded, use current image_path if 'file' not in request.files: output = journal_entry.image_path else: file = request.files['file'] if file and allowed_file(file.filename): file.filename = secure_filename( str(user.id) + str(datetime.datetime.now()) + file.filename) output = upload_file_to_s3(file, 'journal-nyx') journal_entry.title = title journal_entry.content = content journal_entry.image_path = output if journal_entry.save(): return jsonify({ 'message': 'Successfully updated journal entry', 'status': 'success', 'journal': { 'id': journal_entry.id, 'created_at': journal_entry.created_at, 'updated_at': journal_entry.updated_at, 'user_id': journal_entry.user_id, 'title': journal_entry.title, 'content': journal_entry.content, 'image_path': journal_entry.image_path }, 'redirect': 'https://journal-nyx.herokuapp.com/journals/' }) else: errors = journal_entry.errors return jsonify([{'status': 'failed', 'message': errors}])
def downloadProject(project_id, token=None): try: if token is None: token = request.headers['Authorization'] except KeyError: abort(401) payload = decode_auth_token(token) if downloadFromS3(payload + project_id): return jsonify("OK")
def create(item_id): auth_header = request.headers.get('Authorization') if auth_header: token = auth_header.split(" ")[1] else: return jsonify([{ 'status': 'failed', 'message': 'Not authorization header.' }]) decoded = decode_auth_token(token) user = User.get(User.id == decoded) if user: item = Item.get(Item.id == item_id) if item: if request.method == "POST": req_data = request.get_json() title = req_data['title'] date = req_data['date'] reflection = req_data['reflection'] journal = Journal(title=title, date=date, reflection=reflection, item=item) if journal.save(): return jsonify([{ 'status': 'success', 'message': 'Successfully created a new item in your Bucket List', 'journal': { 'id': journal.id, 'title': journal.title, 'date': journal.date, 'reflection': journal.reflection, } }]) else: return jsonify([{ 'status': 'failed', 'message': 'Unable to create this journal' }]) elif request.method == "GET": journals = Journal.select().where(Journal.item_id == item.id) return jsonify({ 'journal': [{'id': journal.id, 'title': journal.title, 'date': journal.date, 'reflection': journal.reflection, 'item': journal.item_id} for journal in journals]})
def getTableSummary(project_id): try: token = request.headers['Authorization'] except KeyError: abort(401) payload = decode_auth_token(token) object_name = payload + "/" + project_id print(object_name) if downloadFromS3(object_name): df = pd.read_csv('./temp/' + project_id) return jsonify({"data": summary(df)}), 200 else: return jsonify("FAIL"), 500
def update(): auth_header = request.headers.get('Authorization') if auth_header: token = auth_header.split(" ")[1] else: return jsonify([{ 'status': 'failed', 'message': 'Not authorization header.' }]) decoded = decode_auth_token(token) user = User.get(User.id == decoded) req_data = request.get_json() first_name = req_data['firstName'] last_name = req_data['lastName'] date_of_birth = req_data['dateOfBirth'] first_language = req_data['firstLanguage'] second_language = req_data['secondLanguage'] passport_number = req_data['passportNum'] user_update = User.update( first_name=first_name, last_name=last_name, dob=date_of_birth, language_primary=first_language, language_secondary=second_language, passport_num=passport_number).where(User.id == user.id) if user_update.execute(): token = encode_auth_token(user) return jsonify({ 'auth_token': token, 'message': 'Successfully update account details.', 'status': 'success', 'user': { 'id': user.id, 'first_name': user.first_name, 'last_name': user.last_name, 'email': user.email, 'date_of_birth': user.dob, 'first_language': user.language_primary, 'second_language': user.language_secondary, 'passport_num': user.passport_num } }) elif user_update.errors: errors = user.errors return jsonify({'status': 'failed', 'message': errors})
def show_user(): auth_header = request.headers.get('Authorization') if auth_header: token = auth_header.split(" ")[1] else: return jsonify(status="failed", message="No authorization header found.") user_id = decode_auth_token(token) user = User.get(User.id == int(user_id)) if user: return jsonify(id=str(user.id), username=user.username, email=user.email) else: return jsonify(status="failed", message="Authentication failed")
def check_auth_token(): """Verifies requests using JWT token in headers.""" # /api/v1/authenticate_user is Open endpoint, and doesn't require Oauth token if 'authenticate_user' not in request.base_url: auth_header = request.headers.get('Authorization') try: if auth_header: auth_token = auth_header.split(" ")[1] decoded_token = helpers.decode_auth_token(auth_token) if not decoded_token: raise errors.AuthTokenInvalidError else: raise errors.AuthTokenMissingError except errors.AuthTokenInvalidError: return format_response("Invalid Auth Token", 403) except errors.AuthTokenMissingError: return format_response("Auth Token missing", 403)
def update(contact_id): auth_header = request.headers.get('Authorization') if auth_header: token = auth_header.split(" ")[1] else: return jsonify([{ 'status': 'failed', 'message': 'Not authorization header.' }]) decoded = decode_auth_token(token) user = User.get(User.id == decoded) if user: contact = PersonalContact.get(PersonalContact.id == contact_id, PersonalContact.user_id == user.id) req_data = request.get_json() contact.name = req_data['name'] or contact.name contact.relationship = req_data['relationship'] or contact.relationship # contact.location = req_data['location'] or contact.location # contact.priority = req_data['priority'] or contact.priority contact.email = req_data['email'] or contact.email contact.phone_number = req_data['phoneNumber'] or contact.phone_number if contact.save(): return jsonify([{ 'status': 'success', 'message': 'Successfully updated the contact details.' }]) else: return jsonify([{ 'status': 'failed', 'message': 'Unable to update contact.' }]) else: return jsonify([{ 'status': 'failed', 'message': 'Authentication failed.' }])
def show(image_id): auth_header = request.headers.get('Authorization') if auth_header: token = auth_header.split(" ")[1] else: return jsonify([{ 'status': 'failed', 'message': 'Not authorization header.' }]) decoded = decode_auth_token(token) user = User.get(User.id == decoded) query = Image.select().where(Image.id == image_id, Image.user_id == user.id) if user and query.exists(): image = Image.get(Image.id == image_id) return jsonify({ 'status': 'success', 'message': 'Image retrieved successfully.', 'imageId': image.id, 'imageURL': image.url, 'results': { 'weapon': image.weapon, 'alcohol': image.alcohol, 'drugs': image.drugs, 'male': image.male, 'female': image.female, 'minor': image.minor, 'sunglasses': image.sunglasses, 'scam': image.scam, 'nudity': image.nudity } }) else: return jsonify({ 'status': 'failed', 'message': 'Unable to retrieve this image for this user.' })
def upload(): if not request.json or 'filePath' not in request.json.keys(): return jsonify("Incorrect form submission"), 400 try: token = request.headers['Authorization'] print(token) except KeyError: abort(401) payload = decode_auth_token(token) # print(payload) file_path = request.json['filePath'] if uploadToS3(file_path, payload): df = pd.read_csv(file_path) return jsonify({ "status": "OK", "fileName": file_path, "data": df.to_dict(orient='records') }), 200 else: return jsonify({"status": "FAIL"}), 400
def delete(project_id): auth_header = request.headers.get('Authorization') if not auth_header: return jsonify(status="failed", message="No authorization header found.") else: token = auth_header.split(" ")[1] user_id = decode_auth_token(token) user = User.get(User.id == int(user_id)) if user: project = Project.get_or_none(Project.id == project_id) delete = Project.delete().where(Project.id == project_id) if not project: return jsonify(status="failed", message="Could not find project in database.") elif delete.execute(): return jsonify(status="success", message="Project deleted.") else: return jsonify(status="failed", message="Unable to delete project.")
def show(): auth_header = request.headers.get('Authorization') if auth_header: token = auth_header.split(" ")[1] else: return jsonify([{ 'status': 'failed', 'message': 'Not authorization header.' }]) decoded = decode_auth_token(token) try: user = User.get(User.id == decoded) images = Image.select().where(Image.user_id == user.id) return jsonify([image.url for image in images]) except: return jsonify([{ 'status': 'failed', 'message': 'Authentication failed.' }])
def message(): auth_header = request.headers.get('Authorization') if auth_header: token = auth_header.split(" ")[1] else: return jsonify([{ 'status': 'failed', 'message': 'Not authorization header.' }]) decoded = decode_auth_token(token) user = User.get(User.id == decoded) contacts = PersonalContact.get(PersonalContact.user_id == user.id) phone_number = contacts.phone_number req_data = request.get_json() latitude = req_data['latitude'] longitude = req_data['longitude'] account_sid = os.environ.get('TWILIO_ACCOUNT_SID') auth_token = os.environ.get('TWILIO_AUTH_TOKEN') client = Client(account_sid, auth_token) message = client.messages.create( to=phone_number, from_=os.environ.get('TWILIO_PHONE_NUMBER'), body= f"{contacts.name}, {user.first_name} {user.last_name} is in danger! Aunty very worried! Can you please help? Current latitude: {latitude}, longitude: {longitude}" ) if message.sid: return jsonify({'status': 'success', 'id': message.sid}) else: return jsonify({'status': 'failed', 'message': 'Will return ASAP.'})
def index(): auth_header = request.headers.get('Authorization') if auth_header: token = auth_header.split(" ")[1] else: return jsonify(status="failed", message="No authorization header found.") user_id = decode_auth_token(token) user = User.get(User.id == int(user_id)) clients = Client.select() client_data = [{ "id": int(c.id), "name": c.name, "industry": c.industry, "country": c.country } for c in clients] if user: return jsonify(client_data) else: return jsonify(status="failed", message="Authentication failed")
def update_user(): auth_header = request.headers.get('Authorization') if auth_header: token = auth_header.split(" ")[1] else: return jsonify(status="failed", message="No authorization header found.") user_id = decode_auth_token(token) user = User.get(User.id == int(user_id)) put_data = request.get_json() if user: if "password" in put_data: user.password = generate_password_hash(put_data['password']) user.username = put_data['username'] user_data = {"id": user.id, "username": user.username, "email": user.email} if user.save(): return jsonify(status="success", message="Profile successfully updated.", user=user_data) else: return jsonify(status="failed", message=user.errors)
def create_itinerary_pin(): if request.method == "POST": req_data = request.get_json() pin_name = req_data['pinName'] user_id = req_data['userId'] longitude = req_data['longitude'] latitude = req_data['latitude'] start_time = req_data['startTime'] user = User.get(User.id == user_id) if user: itinerary_pin = ItineraryPin(user=user, name=pin_name, longitude=longitude, latitude=latitude, start_time=start_time) if itinerary_pin.save(): return jsonify({ 'message': 'Successfully created the map pin.', 'status': 'success', 'pin': { 'id': itinerary_pin.id, 'userId': itinerary_pin.user_id, 'longitude': str(itinerary_pin.longitude), 'latitude': str(itinerary_pin.latitude), 'start_time': itinerary_pin.start_time, 'pinName': itinerary_pin.name } }) else: errors = itinerary_pin.errors return jsonify({'status': 'failed', 'message': errors}) else: return jsonify([{ 'status': 'failed', 'message': 'User cannot be found.' }]) elif request.method == "GET": auth_header = request.headers.get('Authorization') if auth_header: token = auth_header.split(" ")[1] else: return jsonify([{ 'status': 'failed', 'message': 'Not authorization header.' }]) decoded = decode_auth_token(token) user = User.get(User.id == decoded) if user: pins = ItineraryPin.select().where(ItineraryPin.user_id == user.id, ItineraryPin.resolved == False) return jsonify([{ 'id': pin.id, 'userId': pin.user_id, 'longitude': str(pin.longitude), 'latitude': str(pin.latitude), 'start_time': pin.start_time, 'pinName': pin.name } for pin in pins]) else: return jsonify([{ 'status': 'failed', 'message': 'Authentication failed.' }])
def create(): auth_header = request.headers.get('Authorization') if auth_header: token = auth_header.split(" ")[1] else: return jsonify([{ 'status': 'failed', 'message': 'Not authorization header.' }]) decoded = decode_auth_token(token) user = User.get(User.id == decoded) if user: # Retrieving image in data uri scheme dataUri = request.get_json()['dataUri'] # Decoding into an image decoded_img = base64.b64decode(dataUri.split(",")[1]) # Saving filename as user id and current datetime string current_time = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S") filename = f'{user.id}{current_time}.jpg' # Uploading image to AWS s3.put_object(Body=decoded_img, Bucket=app.config["S3_BUCKET"], Key=filename, ACL='public-read') # Creating an image pw instance image = Image(filename=filename, user=user) if image.save(): # If image saves in DB, send to SightEngine API client = SightengineClient(os.environ.get('SIGHTENGINE_USER'), os.environ.get('SIGHTENGINE_SECRET')) output = client.check('nudity', 'wad', 'offensive', 'scam', 'face-attributes').set_url(image.url) print(output) # Updating image with returned output from SightEngine image.weapon = output['weapon'] image.alcohol = output['alcohol'] image.drugs = output['drugs'] image.scam = output['scam']['prob'] image.nudity = output['nudity']['raw'] if output['faces']: image.male = output['faces'][0]['attributes']['male'] image.female = output['faces'][0]['attributes']['female'] image.minor = output['faces'][0]['attributes']['minor'] image.sunglasses = output['faces'][0]['attributes'][ 'sunglasses'] if image.save() and output['status'] == 'success': return jsonify({ 'status': 'success', 'message': 'Image analyzed successfully.', 'imageId': image.id, 'results': { 'weapon': image.weapon, 'alcohol': image.alcohol, 'drugs': image.drugs, 'male': image.male or 0, 'female': image.female or 0, 'minor': image.minor or 0, 'sunglasses': image.sunglasses or 0, 'scam': image.scam, 'nudity': image.nudity } }) else: return jsonify({ 'status': 'failed', 'message': 'Something went wrong. The image was unable to be analyzed.' }) else: return jsonify({ 'status': 'failed', 'message': 'Image was unsuccessfully uploaded.' }) else: return jsonify({'status': 'failed', 'message': 'No user found.'})
def create(): auth_header = request.headers.get('Authorization') if auth_header: token = auth_header.split(" ")[1] else: return jsonify([{ 'status': 'failed', 'message': 'Not authorization header.' }]) decoded = decode_auth_token(token) user = User.get(User.id == decoded) if user: user_id = request.form.get('user_id') title = request.form.get('title') content = request.form.get('content') # check if request has file if 'file' not in request.files: return jsonify({'status': 'failed', 'message': 'No file part'}) file = request.files['file'] # if user does not select file, browser also submit an empty part without filename if file.filename == '': return jsonify({'status': 'failed', 'message': 'No selected file'}) if file and allowed_file(file.filename): file.filename = secure_filename( str(user_id) + str(datetime.datetime.now()) + file.filename) output = upload_file_to_s3(file, 'journal-nyx') journal_entry = JournalEntry(user_id=user_id, title=title, content=content, image_path=output) if journal_entry.save(): return jsonify({ 'message': 'Successfully created journal entry.', 'status': 'success', 'user': { 'id': journal_entry.id, 'user_id': journal_entry.user_id, 'title': journal_entry.title, 'content': journal_entry.content, 'image_path': journal_entry.image_path, }, 'redirect': 'https://journal-nyx.herokuapp.com/journals/' }) else: errors = journal_entry.errors return jsonify({'status': 'failed', 'message': errors}) else: return jsonify([{ 'status': 'failed', 'message': 'Authentication failed.' }])
def create_map_pin(): if request.method == "POST": req_data = request.get_json() pin_name = req_data['pinName'] user_id = req_data['userId'] longitude = req_data['longitude'] latitude = req_data['latitude'] is_safe = req_data['isSafe'] category = req_data['category'] radius = req_data['radius'] source = req_data['source'] is_public = req_data['isPublic'] user = User.get(User.id == user_id) if user: map_pin = MapPin(user=user, name=pin_name, longitude=longitude, latitude=latitude, is_safe=is_safe, category=category, radius=radius, is_public=is_public, source=source) if map_pin.save(): return jsonify({ 'message': 'Successfully created the map pin.', 'status': 'success', 'pin': { 'id': map_pin.id, 'user_id': map_pin.user_id, 'longitude': map_pin.longitude, 'latitude': map_pin.latitude, 'name': map_pin.name, 'category': map_pin.category, 'is_public': map_pin.is_public, 'is_safe': map_pin.is_safe } }) else: errors = map_pin.errors return jsonify({'status': 'failed', 'message': errors}) else: return jsonify([{ 'status': 'failed', 'message': 'User cannot be found.' }]) elif request.method == "GET": auth_header = request.headers.get('Authorization') if auth_header: token = auth_header.split(" ")[1] else: return jsonify([{ 'status': 'failed', 'message': 'Not authorization header.' }]) decoded = decode_auth_token(token) user = User.get(User.id == decoded) if user: public_pins = MapPin.select().where(MapPin.is_public == True) private_pins = MapPin.select().where(MapPin.user_id == user.id, MapPin.is_public == False) return jsonify({ 'publicPins': [{ 'id': public_pin.id, 'longitude': str(public_pin.longitude), 'latitude': str(public_pin.latitude), 'is_safe': public_pin.is_safe, 'category': public_pin.category, 'name': public_pin.name, 'radius': public_pin.radius } for public_pin in public_pins], 'privatePins': [{ 'id': private_pin.id, 'longitude': str(private_pin.longitude), 'latitude': str(private_pin.latitude), 'is_safe': private_pin.is_safe, 'category': private_pin.category, 'name': private_pin.name, 'radius': private_pin.radius } for private_pin in private_pins] }) else: return jsonify([{ 'status': 'failed', 'message': 'Authentication failed.' }])
def index(): auth_header = request.headers.get('Authorization') if auth_header: token = auth_header.split(" ")[1] else: return jsonify(status="failed", message="No authorization header found.") user_id = decode_auth_token(token) user = User.get(User.id == int(user_id)) if user: project_count = Project.select().count() client_count = Client.select().count() currency_types = {} project_types = {} currency_revenue = {} project_revenue = {} currencies = Project.select(Project.currency.distinct()) pr_type_count = Project.select(Project.project_type.distinct()) countries = len(list(Client.select(Client.country.distinct()))) for c in currencies: count = Project.select().where( Project.currency == c.currency).count() cr = {c.currency: count} currency_types.update(cr) revenue = Project.select( Project.total).where(Project.currency == c.currency) crt = [] for r in revenue: crt.append(r.total) c_total = {c.currency: str(sum(crt))} currency_revenue.update(c_total) for t in pr_type_count: count = Project.select().where( Project.project_type == t.project_type).count() pt = {t.project_type: count} project_types.update(pt) revenue = Project.select( Project.total).where(Project.project_type == t.project_type) prt = [] for r in revenue: prt.append(r.total) t_total = {t.project_type: str(sum(prt))} project_revenue.update(t_total) db_basic_data = { "project_count": project_count, "client_count": client_count, "countries": countries, "currency_types": currency_types, "project_types": project_types, "currency_revenue": currency_revenue, "project_revenue": project_revenue, } return jsonify(db_basic_data) else: return jsonify(status="failed", message="Authentication failed")