import os import psycopg2 from dotenv import load_dotenv from functools import wraps import datetime import jwt import project.validate.validate as validate #import project.models.members as Members from project.models.members import Members #from models.models import User from flask import ( Flask, jsonify, send_from_directory, request, ) from flask_sqlalchemy import SQLAlchemy #from werkzeug.utils import secure_filename load_dotenv() app = Flask(__name__) app.config.from_object("project.config.Config") db = SQLAlchemy(app) app.config['SECRET_KEY'] ='thisisourwondefulkey' def token_required(f): @wraps(f) def decorated(*args, **kwargs): token = request.args.get('token') if not token: return jsonify({'message': 'Error - missing token'}), 403 try: data = jwt.decode(token, app.config['SECRET_KEY']) except: return jsonify({'message': 'Token is invalid'}),403 return f(*args, **kwargs) return decorated class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(128), unique=True, nullable=False) active = db.Column(db.Boolean(), default=True, nullable=False) def __init__(self, email): self.email = email dataUrl = os.getenv("DATABASE_URL") connection = psycopg2.connect(dataUrl) @app.route("/") def hello_world(): GLOBAL_AVG = """SELECT * FROM members WHERE id = 1;""" with connection: with connection.cursor() as cursor: cursor.execute(GLOBAL_AVG) account = cursor.fetchone() #return jsonify(hello="ameye world") return {"account": account} @app.route("/panel/auth/login", methods=["POST"]) def start_login(): try: data = request.json if not data: return { "message": "Please provide user details", "data": None, "error": "Bad request" }, 400 # validate input is_validated = validate.validate_username_and_password(data.get('username'), data.get('password')) if is_validated is not True: return dict(message='Invalid data', data=None, error=is_validated), 400 member = Members().login( data["username"], data["password"] ) if member: try: # token should expire after 24 hrs member["token"] = jwt.encode( {"member_id": member[0], 'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=30)}, app.config["SECRET_KEY"], algorithm="HS256" ) return { "message": "Successfully fetched auth token", "data": member } except Exception as e: return { "error": "Something went wrong", "message": str(e) }, 500 return { "message": "Error fetching auth token!, invalid email or password", "data": None, "error": "Unauthorized" }, 404 # GLOBAL_AVG = """SELECT * FROM members WHERE id = 1;""" # with connection: # with connection.cursor() as cursor: # cursor.execute(GLOBAL_AVG) # account = cursor.fetchone() # #return jsonify(hello="ameye world") # token = jwt.encode({'user': 'account', 'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=30)},app.config['SECRET_KEY'] ) # # return {"account": account} # return {"token": token} except Exception as e: return { "message": "Something went wrong!", "error": str(e), "data": None }, 500 @app.route("/panel/auth/register") def start_register(): return jsonify(hello="ameye world") @app.route("/panel/auth/resetpass") def start_resetpass(): return jsonify(hello="ameye world") @app.route("/panel/account") @token_required def account(): return jsonify(hello="ameye world") @app.route("/panel/account/dash") @token_required def dashboard(): return jsonify(hello="ameye world") @app.route("/panel/account/products") @token_required def panel_products(): return jsonify(hello="ameye world") @app.route("/panel/account/actions") @token_required def recent_actions(): return jsonify(hello="ameye world")