Beispiel #1
0
def create_app(config_name):
    app = Flask(__name__, template_folder='templates')

    app.secret_key = config.SECRET
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')
    app.config['SQLALCHEMY_DATABASE_URI'] = config.SQLALCHEMY_DATABASE_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['FLASK_ADMIN_SWATCH'] = 'yeti'

    db = SQLAlchemy(config.APP)
    start_views(app, db)
    Bootstrap(app)
    db.init_app(app)

    @app.after_request
    def after_request(response):
        response.headers.add('Access-Control-Allow-Origin', '*')
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
        response.headers.add('Access-Control-Allow-Methods',
                             'GET, PUT, POST, DELETE, OPTIONS')
        return response

    def auth_token_required(f):
        @wraps(f)
        def verify_token(*args, **kwargs):
            user = UserController()
            try:
                result = user.verify_auth_token(
                    request.headers['access_token'])
                if result['status'] == 200:
                    return f(*args, **kwargs)
                else:
                    abort(result['status'], result['message'])
            except KeyError as e:
                print(e)
                abort(401, 'Você precisa de enviar um token de acesso')

        return verify_token

    @app.route('/')
    def index():
        return 'Hello World'

    @app.route('/login/')
    def login():
        return render_template('login.html',
                               message="Essa é uma mensagem que\
                                veio da rota")

    @app.route('/login/', methods=['POST'])
    def login_post():
        user = UserController()

        email = request.form['email']
        password = request.form['password']

        result = user.login(email, password)

        if result:
            return redirect('/admin')
        else:
            return render_template('login.html',
                                   data={
                                       'status': 401,
                                       'msg': 'Dados de usuário incorretos',
                                       'type': None
                                   })

    @app.route('/recovery-password/')
    def recovery_password():
        return 'Aqui entrará a tela de recuperar senha'

    @app.route('/recovery-password/', methods=['POST'])
    def send_recovery_password():
        user = UserController()

        result = user.recovery(request.form['email'])

        if result:
            return render_template('recovery.html',
                                   data={
                                       'status':
                                       200,
                                       'msg':
                                       'E-mail de recuperacão enviado\
                                    com sucesso'
                                   })
        else:
            return render_template('recovery.html',
                                   data={
                                       'status':
                                       401,
                                       'msg':
                                       'Erro ao enviar e-mail de\
                                    recuperação'
                                   })

    @app.route('/product', methods=['POST'])
    def save_products():
        product = ProductController()

        result = product.save_product(request.form)

        if result:
            message = 'Inserido'
        else:
            message = 'Não inserido'

        return message

    @app.route('/product/', methods=['PUT'])
    def update_products():
        product = ProductController()

        result = product.update_product(request.form)

        if result:
            message = 'Editado'
        else:
            message = 'Não editado'

        return message

    @app.route('/products/', methods=['GET'])
    @app.route('/products/<limit>', methods=['GET'])
    @auth_token_required
    def get_products(limit=None):
        header = {
            'access_token': request.headers['access_token'],
            'token_type': "JWT"
        }

        product = ProductController()
        response = product.get_products(limit=limit)
        return Response(json.dumps(response, ensure_ascii=False),
                        mimetype='application/json'), response['status'],\
            header

    @app.route('/product/<product_id>', methods=['GET'])
    @auth_token_required
    def get_product(product_id):
        header = {
            'access_token': request.headers['access_token'],
            'token_type': "JWT"
        }

        product = ProductController()
        response = product.get_product_by_id(product_id=product_id)
        return Response(json.dumps(response, ensure_ascii=False),
                        mimetype='application/json'), response['status'],\
            header

    @app.route('/user/<user_id>', methods=['GET'])
    @auth_token_required
    def get_user_profile(user_id):
        header = {
            'access_token': request.headers['access_token'],
            'token_type': "JWT"
        }

        user = UserController()
        response = user.get_user_by_id(user_id=user_id)
        return Response(json.dumps(response, ensure_ascii=False),
                        mimetype='application/json'), response['status'],\
            header

    @app.route('/login_api/', methods=['POST'])
    def login_api():
        header = {}
        user = UserController()

        email = request.json['email']
        password = request.json['password']

        result = user.login(email=email, password=password)
        code = 401
        response = {"message": "Usuário não autorizado", "result": []}

        if result:
            if result.active:
                result = {
                    'id': result.id,
                    'username': result.username,
                    'email': result.email,
                    'date_created': result.date_created,
                    'active': result.active
                }

                header = {
                    "access_token": user.generate_auth_token(result),
                    "token_type": "JWT"
                }
                code = 200
                response["message"] = "Login realizado com sucesso"
                response["result"] = result

        return Response(json.dumps(response, ensure_ascii=False),
                        mimetype='application/json'), code, header

    return app
Beispiel #2
0
def create_app(config_name):
    app = Flask(__name__, template_folder="templates")

    login_manager = LoginManager()
    login_manager.init_app(app)

    app.secret_key = config.SECRET
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile("config.py")
    app.config["SQLALCHEMY_DATABASE_URI"] = config.SQLALCHEMY_DATABASE_URI
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    app.config["FLASK_ADMIN_SWATCH"] = "darkly"

    db = SQLAlchemy(config.APP)

    start_views(app, db)
    Bootstrap(app)
    db.init_app(app)

    @app.after_request
    def after_request(response):
        response.headers.add("Access-Control-Allow-Origin", "*")
        response.headers.add("Access-Control-Allow-Headers", "Content-Type")
        response.headers.add("Access-Control-Allow-Methods",
                             "GET,POST,PUT,DELETE,OPTIONS")

        return response

    def auth_token_required(f):
        @wraps(f)
        def verify_token(*args, **kwargs):
            user = UserController()
            try:
                result = user.verify_auth_token(
                    request.headers["access_token"])
                if result["status"] == 200:
                    return f(*args, **kwargs)
                else:
                    abort(result["status"], result["message"])
            except KeyError as e:
                abort(401, "Você precisa enviar um token de acesso")

        return verify_token

    @app.route("/")
    def index():
        return "Hello World"

    @login_manager.user_loader
    def load_user(user_id):
        user = UserController()

        return user.get_admin_login(user_id)

    @app.route("/login")
    def login():
        return render_template("login.html",
                               data={
                                   "status": 200,
                                   "msg": None,
                                   "type": None
                               })

    @app.route("/login", methods=["POST"])
    def login_post():
        user = UserController()

        email = request.form["email"]
        password = request.form["password"]

        result = user.login(email, password)

        if result:
            if result.role == 4:
                return render_template(
                    "login.html",
                    data={
                        "status": 401,
                        "msg":
                        "Seu usuário não tem permissão para acessar o admin",
                        "type": 2
                    })
            else:
                login_user(result)

                return redirect("/admin")
        else:
            return render_template("login.html",
                                   data={
                                       "status": 401,
                                       "msg": "Dados de usuário incorretos",
                                       "type": 1
                                   })

    @app.route("/logout")
    def logout_send():
        logout_user()

        return render_template("login.html",
                               data={
                                   "status": 200,
                                   "msg": "Usuário deslogado com sucesso!",
                                   "type": 3
                               })

    @app.route("/recovery-password")
    def recovery_password():
        return render_template("recovery.html",
                               data={
                                   "status": 200,
                                   "msg": None,
                                   "type": None
                               })

    @app.route("/recovery-password", methods=["POST"])
    def send_recovery_password():
        user = UserController()

        result = user.recovery(request.form["email"])

        if (result["status_code"] == 200) or (result["status_code"] == 202):
            return render_template(
                "recovery.html",
                data={
                    "status": result["status_code"],
                    "msg":
                    "Você receberá um e-mail em sua caixa para alteração de senha",
                    "type": 3
                })
        else:
            return render_template("recovery.html",
                                   data={
                                       "status": result["status_code"],
                                       "msg": result["body"],
                                       "type": 1
                                   })

    @app.route("/new-password/<recovery_code>")
    def new_password(recovery_code):
        user = UserController()
        result = user.verify_auth_token(recovery_code)

        if result["status"] == 200:
            res = user.get_user_by_recovery(str(recovery_code))
            if res is not None:
                return render_template("new_password.html",
                                       data={
                                           "status": result["status"],
                                           "msg": None,
                                           "type": None,
                                           "user_id": res.id
                                       })
            else:
                return render_template(
                    "recovery.html",
                    data={
                        "status": 400,
                        "msg":
                        "Erro ao tentar acessar os dados do usuário. Tente novamente mais tarde",
                        "type": 1
                    })
        else:
            return render_template(
                "recovery.html",
                data={
                    "status": result["status"],
                    "msg":
                    "Token expirado ou inválido, solicite novamente a alteração da senha",
                    "type": 1
                })

    @app.route("/new_password", methods=["POST"])
    def send_new_password():
        user = UserController()
        user_id = request.form["user_id"]
        password = request.form["password"]

        result = user.new_password(user_id, password)
        if result:
            return render_template("login.html",
                                   data={
                                       "status": 200,
                                       "msg": "Senha alterada com sucesso",
                                       "type": 3,
                                       "user_id": user_id
                                   })
        else:
            return render_template("new_password.html",
                                   data={
                                       "status": 401,
                                       "msg": "Erro ao alterar senha",
                                       "type": 1,
                                       "user_id": user_id
                                   })

    @app.route("/product", methods=["POST"])
    def save_products():
        product = ProductController()

        result = product.save_product(request.form)
        if result:
            message = "Inserido"
        else:
            message = "Não inserido"

        return message

    @app.route("/product", methods=["PUT"])
    def update_products():
        product = ProductController()

        result = product.update_product(request.form)
        if result:
            message = "Editado"
        else:
            message = "Não editado"

        return message

    @app.route("/product", methods=["DELETE"])
    def delete_products():
        product = ProductController()

        result = product.delete_product(request.form)
        if result:
            message = "Deletado"
        else:
            message = "Não deletado"

        return message

    @app.route("/products", methods=["GET"])
    @app.route("/products/<limit>", methods=["GET"])
    @auth_token_required
    def get_products(limit=None):
        header = {
            "access_token": request.headers["access_token"],
            "token_type": "JWT"
        }
        product = ProductController()

        response = product.get_products(limit=limit)

        return Response(
            json.dumps(response, ensure_ascii=False),
            mimetype="application/json"), response["status"], header

    @app.route("/product/<product_id>", methods=["GET"])
    @auth_token_required
    def get_product(product_id):
        header = {
            "access_token": request.headers["access_token"],
            "token_type": "JWT"
        }
        product = ProductController()

        response = product.get_product_by_id(product_id=product_id)

        return Response(
            json.dumps(response, ensure_ascii=False),
            mimetype="application/json"), response["status"], header

    @app.route("/user/<user_id>", methods=["GET"])
    @auth_token_required
    def get_user_profile(user_id):
        header = {
            "access_token": request.headers["access_token"],
            "token_type": "JWT"
        }
        user = UserController()

        response = user.get_user_by_id(user_id=user_id)

        return Response(
            json.dumps(response, ensure_ascii=False),
            mimetype="application/json"), response["status"], header

    @app.route("/login_api", methods=["POST"])
    def login_api():
        header = {}
        user = UserController()

        email = request.json["email"]
        password = request.json["password"]
        res = user.login(email, password)

        code = 401
        response = {"message": "Usuário não autorizado", "result": []}
        if res:
            if res.active:
                result = {
                    "id": res.id,
                    "username": res.username,
                    "email": res.email,
                    "date_created": res.date_created,
                    "active": res.active
                }
                header = {
                    "access_token": user.generate_auth_token(result),
                    "token_type": "JWT"
                }
                code = 200
                response["message"] = "Login realizado com sucesso"
                response["result"] = result

        return Response(json.dumps(response, ensure_ascii=False),
                        mimetype="application/json"), code, header

    return app
def create_app(config_name):

    # A variável app recebe uma instância de Flask, passando a configuração da localização dos templates. Pode
    # receber diversas configurações.
    app = Flask(__name__, template_folder='templates')

    # O atributo secret_key da aplicação app, recebe a configuração da chave secreta do arquivo config.py, por meio da variável config e atributo SECRET.
    app.secret_key = config.SECRET

    # Efetua o carregamento do arquivo config.py
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')

    ### BDD ###
    # Adicionando configurações necessárias para utilizarmos o SQLAlchemy.
    # A constante SQLALCHEMY_DATABASE_URI foi definida no arquivo config.py, a qual indica o caminho do banco de dados.
    app.config['SQLALCHEMY_DATABASE_URI'] = config.SQLALCHEMY_DATABASE_URI

    # Configuração indicando que as modificações do banco de dados poderão ser exclusivamente pela aplicação.
    # Se True, permite outras formas.
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    # A variável db receberá a atribuição de uma instância do SQLAlchemy passando a aplicação app criada.
    db = SQLAlchemy(config.APP)

    # Adicionado a inicialização das visualizações das views Admin. Ativa a área admin do Flask.
    # A Admin será criada dentro do arquivo admin/Admin.py
    start_views(app, db)

    # Inicializando o banco de dados para a aplicação.
    db.init_app(app)

    # Primeira rota a ser criada. A rota principal root.
    # Quando se cria duas ou mais rotas seguidas antes do método, isso indica ao navegador que qualquer uma delas acessa o método a seguir. Neste exemplo tanto http://localhost:8000/ e http://localhost:8000/login/ acessam o médtodo index(). Que retorna uma string.
    @app.route('/')
    @app.route('/index/')
    def index():
        return render_template("index.html")

    @app.route("/about-us")
    def about():
        return render_template("about-us.html")

    @app.route("/agendamento")
    def agendamento():
        return render_template("agendamento.html")

    @app.route("/listaAventuras")
    def listaAventuras():
        return render_template("listaAventuras.html")

    @app.route("/login/")
    def login():
        return render_template("login.html")

    # Rota adicionada para verificar o login do Usuário por meio do controllers: UsuarioController()
    @app.route('/login/', methods=['POST'])
    def login_post():
        usuario = UsuarioController()
        email = request.form['email']
        password = request.form['password']
        resultado = usuario.login(email, password)
        if resultado:
            return redirect('/admin')
        else:
            return render_template('login.html',
                                   data={
                                       'status': 401,
                                       'msg': 'Dados de usuário incorretos',
                                       'type': None
                                   })

    # Rota adicionada para recuperação de senha
    @app.route('/recuperar-senha/')
    def recuperar_senha():
        return '<h1>Aqui entrará a tela de recuperar senha. </h1>'

    # Rota adicionada para recuperação de senha por meio do método POST.
    @app.route('/recuperar-senha/', methods=['POST'])
    def enviar_recuperar_senha():
        # Instância do Usuario Controller atribuída a variável usuario.
        usuario = UsuarioController()
        resultado = usuario.recuperar(request.form['email'])
        # Se o resultado for preenchido, executa o email de recuperação com status 200 de sucesso.
        if resultado:
            return render_template(
                'recuperar.html',
                data={
                    'status': 200,
                    'msg': 'E-mail de recuperação enviado com sucesso'
                })
        else:
            # Se o resultado for vazio, executa o email de recuperação com status 200 de sucesso.
            return render_template('recuperar.html',
                                   data={
                                       'status':
                                       401,
                                       'msg':
                                       'Erro ao enviar e-mail de recuperação'
                                   })

    @app.route("/cadastro")
    def cadastro():
        return render_template("cadastro.html")

    # Retorno do método create_app(). Retorna a instância do app criada.
    return app
Beispiel #4
0
def create_app(config_name):
    app = Flask(__name__, template_folder="templates")
    app.secret_key = config.SECRET
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile("config.py")
    app.config["SQLALCHEMY_DATABASE_URI"] = config.SQLALCHEMY_DATABASE_URI
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    app.config["FLASK_ADMIN_SWATCH"] = "paper"

    Bootstrap(app)

    db = SQLAlchemy(config.APP)
    start_views(app, db)

    db.init_app(app)

    @app.after_request
    def after_request(response):
        response.headers.add("Access-Control-Allow-Origin", "*")
        response.headers.add("access-Control-Allow-Headers", "Content-Type")
        response.headers.add("Access-Control-Allow-Methods",
                             "GET,PUT,POST,DELETE,OPTIONS")

        return response

    def auth_token_required(f):
        @wraps(f)
        def verify_token(*args, **kwargs):
            user = UserController()

            try:
                result = user.verify_auth_token(
                    request.headers["access_token"])

                if result["status"] == 200:
                    return f(*args, **kwargs)

                else:
                    abort(result["status"], result["message"])

            except KeyError as e:
                abort(401, "Você precisa enviar um token de acesso")

        return verify_token

    @app.route("/")
    def index():
        return "Hello world!"

    # Login
    @app.route("/login")
    def login():
        return render_template("login.html",
                               message="Essa é uma mensagem que veio da rota")

    @app.route("/login", methods=["POST"])
    def login_post():
        user = UserController()
        email = request.form["email"]
        password = request.form["password"]
        result = user.login(email, password)

        if result:
            return redirect("/admin")
        else:
            return render_template(
                "login.html",
                data={
                    "status": 401,
                    "msg": "Dados incorretos",
                    "type": None
                },
            )

    # Produtos
    @app.route("/product", methods=["POST"])
    def save_products():
        product = ProductController()
        result = product.save_product(request.form)
        message = "Inserido" if result else "Não inserido"

        return message

    @app.route("/product", methods=["PUT"])
    def update_products():
        product = ProductController()
        result = product.update_product(request.form)
        message = "Editado" if result else "Não editado"

        return message

    # Recuperação de senha
    @app.route("/recovery-password")
    def recovery_password():
        return "Aqui entrará a tela de recuperar senha"

    @app.route("/recovery-password/", methods=["POST"])
    def send_recovery_password():
        user = UserController()
        result = user.recovery(request.form["email"])

        if result:
            return render_template(
                "recovery.html",
                data={
                    "status": 200,
                    "msg": "E-mail de recuperação enviado com sucesso",
                },
            )

        else:
            return render_template(
                "recovery.html",
                data={
                    "status": 401,
                    "msg": "Erro ao enviar o e-mail de recuperação"
                },
            )

    @app.route("/products", methods=["GET"])
    @app.route("/products/<limit>", methods=["GET"])
    @auth_token_required
    def get_products(limit=None):
        header = {
            "access_token": request.headers["access_token"],
            "token_type": "JWT"
        }

        product = ProductController()
        response = product.get_products(limit=limit)

        return (
            Response(json.dumps(response, ensure_ascii=False),
                     mimetype="application/json"),
            response["status"],
            header,
        )

    @app.route("/product/<product_id>", methods=["GET"])
    @auth_token_required
    def get_product(product_id):
        header = {
            "access_token": request.headers["access_token"],
            "token_type": "JWT"
        }

        product = ProductController()
        response = product.get_product_by_id(product_id=product_id)

        return (
            Response(json.dumps(response, ensure_ascii=False),
                     mimetype="application/json"),
            response["status"],
            header,
        )

    @app.route("/user/<user_id>", methods=["GET"])
    @auth_token_required
    def get_user_profile(user_id):
        header = {
            "access_token": request.headers["access_token"],
            "token_type": "JWT"
        }

        user = UserController()
        response = user.get_user_by_id(user_id=user_id)

        return (
            Response(json.dumps(response, ensure_ascii=False),
                     mimetype="application/json"),
            response["status"],
            header,
        )

    @app.route("/login_api", methods=["POST"])
    def login_api(self):
        header = {}
        user = UserController()

        email = request.json["email"]
        password = request.json["password"]

        result = user.login(email, password)
        code = 401

        response = {"message": "Usuário não autorizado", "result": []}

        if result:
            if result.active:
                result = {
                    "id": result.id,
                    "username": result.username,
                    "email": result.email,
                    "date_created": result.date_created,
                    "active": result.active,
                }

                header = {
                    "access_token": user.generate_auth_token(result),
                    "token_type": "JWT",
                }

                code = 200
                response["message"] = "Login realizado com sucesso"
                response["result"] = result

                return (
                    Response(
                        json.dumps(response, ensure_ascii=False),
                        mimetype="application/json",
                    ),
                    code,
                    header,
                )

    return app
Beispiel #5
0
def create_app(config):
    app = Flask(__name__)

    login_manager = LoginManager()
    login_manager.init_app(app)

    app.secret_key = config.SECRET
    app.config.from_object(config)
    app.config.from_pyfile('config.py')
    app.config['SQLALCHEMY_DATABASE_URI'] = config.SQLALCHEMY_DATABASE_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    app.config['FLASK_ADMIN_SWATCH'] = 'paper'
    db = SQLAlchemy(app)

    start_views(app, db)
    Bootstrap(app)

    db.init_app(app)
    config.APP = app

    @app.after_request
    def after_request(response):
        # response.header.add('Access-Control-Allow-Origin', '*')
        # response.header.add('Access-Control-Allow-Headers', 'Content-Type')
        # response.header.add('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS')
        return response

    @app.route('/report', methods=['GET', 'POST'])
    def report():
        state = request.form['state']
        disease = request.form['disease']
        patients = ctrl.reportByState(state, disease)

        return Response(json.dumps(patients, ensure_ascii=False), mimetype='application/json'), 200, {}

    @app.route('/', methods=['POST', 'GET'])
    @app.route('/login', methods=['POST', 'GET'])
    def login():
        form = LoginForm(request.form)
        if request.method == 'GET':
            data = {'status': 200, 'msg': None, 'type': None, 'form': form}
        else:
            if form.validate():
                result = ctrl.login(form.email.data, form.password.data)
                if result:
                    if result.role == 2:
                        data = {'status': 401, 'msg': 'Seu usuário não tem permissão para acessar o admin', 'type': 2, 'form': form}
                    else:
                        login_user(result, remember=True, duration=datetime.timedelta(minutes=5), fresh=True)
                        return redirect('/admin')
                else:
                    data = {'status': 401, 'msg': 'Dados de usuário incorretos', 'type': 1, 'form': form}
            else:
                data = {'status': 401, 'msg': 'Formulário inválido', 'type': 1, 'form': form}
        return render_template('/login.html', data=data)

    @login_manager.user_loader
    def load_user(user_id):
        return ctrl.getUserById(user_id)

    # Tentativa de implementar o logout
    @app.route('/logout', methods=['POST', 'GET'])
    def logout():
        logout_user()
        form = LoginForm(request.form)
        data = {'status': 200, 'msg': None, 'type': None, 'form': form}
        return render_template('/login.html', data=data)
Beispiel #6
0
def create_app(config_name):
    app = Flask(__name__, template_folder='templates')

    app.secret_key = config.SECRET
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')
    app.config['SQLALCHEMY_DATABASE_URI'] = False
    app.config['FLASK_ADMIN_SWATCH'] = 'paper'
    db = SQLAlchemy(config.APP)
    Bootstrap(app)
    start_views(app, db)
    db.init_app(app)

    @app.after_request
    def after_request(response):
        response.headers.add('Access-Control-Allow-Origin', '*')
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
        response.headers.add('Access-Control-Allow-Methods',
                             'GET,PUT,POST,DELETE,OPTIONS')
        return response

    def auth_token_required(f):
        @wraps(f)
        def verify_token(*args, **kwargs):
            user = UserController()
            try:
                result = user.verify_auth_token(
                    request.headers['access_token'])
                if result['status'] == 200:
                    return f(*args, **kwargs)
                else:
                    abort(result['status'], result['message'])
            except KeyError as e:
                abort(401, 'Access Token is required')

        return verify_token

    @app.route('/')
    def index():
        return render_template('login.html')

    @app.route('/login/', methods=['POST'])
    def login():
        user = UserController()

        email = request.form['email']
        password = request.form['password']
        result = user.login(email, password)
        if result:
            return redirect('/admin')
        else:
            return render_template('login.html',
                                   message="This message came from route")

    @app.route('/recovery-password')
    def recovery_password():
        return 'Here is the recover screen'

    @app.route('/recovery-password/', methods=['POST'])
    def send_recovery_password():
        user = UserController()
        result = user.recovery(request.form['email'])
        if result:
            return render_template('recovery.html',
                                   data={
                                       "status": 200,
                                       "message":
                                       "recovery email has been sent",
                                   })
        else:
            return render_template('recovery.html',
                                   data={
                                       "status": 401,
                                       "message":
                                       "Fail to send the recovery email"
                                   })

    @app.route('/profile/<int:id>/action/<action>')
    def profile(id, action):
        if action == 'action1':
            return f'action choose:{action}'
        elif action == 'action2':
            return f'action choose:{action}'
        else:
            return f'Here is the ID:{id} and the action:{action} '

    @app.route('/profile/<int:id>', methods=['POST'])
    def create_profile():
        username = request.form['username']
        password = request.form['password']
        return f'This route has a put method and will edit the user name to {username} and pass to {password}'

    @app.route('/product', methods=['POST'])
    def save_products():
        product = ProductController()
        result = product.save_product(request.form)
        if result:
            message = "Insert"
        else:
            message = "Fail"
        return message

    @app.route('/product', methods=['PUT'])
    def update_products():
        product = ProductController()
        result = product.update_product(request.form)
        if result:
            message = "Updated"
        else:
            message = "Fail"
        return message

    #API endpoints :

    @app.route('/products/', methods=['GET'])
    @app.route('/products/<limit>', methods=['GET'])
    @auth_token_required
    def get_products(limit=None):
        header = {
            'access_token': request.headers['access_token'],
            "token_type": "JWT"
        }
        product = ProductController()
        response = product.get_products(limit=limit)
        return Response(
            json.dumps(response, ensure_ascii=False),
            mimetype='application/json'), response['status'], header

    @app.route('/product/<product_id>', methods=['GET'])
    @auth_token_required
    def get_product(product_id):
        header = {
            "access_token": request.headers['access_token'],
            "token_type": "JWT"
        }
        product = ProductController()
        response = product.get_product_by_id(product_id=product_id)
        return Response(
            json.dumps(response, ensure_ascii=False),
            mimetype='application/json'), response['status'], header

    @app.route('/user/<user_id>', methods=['GET'])
    @auth_token_required
    def get_user_profile(user_id):
        header = {
            "access_token": request.headers['access_token'],
            "token_type": "JWT"
        }
        user = UserController()
        response = user.get_user_by_id(user_id=user_id)
        return Response(
            json.dumps(response, ensure_ascii=False),
            mimetype='application/json'), response['status'], header

    return app
Beispiel #7
0
def create_app(config_name):
    app = Flask(__name__, template_folder='templates')

    login_manager = LoginManager()
    login_manager.init_app(app)

    app.secret_key = config.SECRET
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')
    app.config['SQLALCHEMY_DATABASE_URI'] = config.SQLALCHEMY_DATABASE_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['FLASK_ADMIN_SWATCH'] = 'paper'
    db = SQLAlchemy(config.APP)
    migrate = Migrate(app, db)
    start_views(app,db)
    Bootstrap(app)

    db.init_app(app)

    @app.after_request
    def after_request(response):
        response.headers.add('Access-Control-Allow-Origin', '*')
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
        response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
        return response

    def auth_token_required(f):
        @wraps(f)
        def verify_token(*args, **kwargs):
            user = UserController()
            try:
                result = user.verify_auth_token(request.headers['access_token'])
                if result['status'] == 200:
                    return f(*args, **kwargs)
                else:
                    abort(result['status'], result['message'])
            except KeyError as e:
                abort(401, 'Você precisa enviar um token de acesso')

        return verify_token

    @app.route('/')
    def index():
        return 'Meu primeiro run'

    @app.route('/login/')
    def login():
        return render_template('login.html', data={'status': 200, 'msg': None, 'type': None})

    @app.route('/login/', methods=['POST'])
    def login_post():
        user = UserController()

        email = request.form['email']
        password = request.form['password']

        result = user.login(email, password)

        if result:
            if result.role == 4:
                return render_template('login.html', data={'status': 401, 'msg': 'Seu usuário não tem permissão para acessar o admin', 'type':2})
            else:
                login_user(result)
                return redirect('/admin')
        else:
            return render_template('login.html', data={'status': 401, 'msg': 'Dados de usuário incorretos', 'type': 1})

    @app.route('/recovery-password/')
    def recovery_password():
        # Capítulo 11
        return render_template('recovery.html', data={'status': 200, 'msg': None, 'type': None})

    @app.route('/recovery-password/', methods=['POST'])
    def send_recovery_password():
        user = UserController()

        result = user.recovery(request.form['email'])

        # Capítulo 11 - Alterar parâmetros
        if result['status_code'] == 200 or result['status_code'] == 202:
            return render_template('recovery.html', data={'status': result['status_code'], 'msg': 'Você receberá um e-mail em sua caixa para alteração de senha.', 'type': 3})
        else:
            return render_template('recovery.html', data={'status': result['status_code'], 'msg': result['body'], 'type': 1})
    
    @app.route('/new-password/<recovery_code>')
    def new_password(recovery_code):
        user = UserController()
        result = user.verify_auth_token(recovery_code)
        
        if result['status'] == 200:
            res = user.get_user_by_recovery(str(recovery_code))
            if res is not None:
                return render_template('new_password.html', data={'status': result['status'], 'msg': None, 'type': None, 'user_id': res.id})
            else:
                return render_template('recovery.html', data={'status': 400, 'msg': 'Erro ao tentar acessar os dados do usuário. Tente novamente mais tarde.', 'type': 1})
        else:
            return render_template('recovery.html', data={'status': result['status'], 'msg': 'Token expirado ou inválido, solicite novamente a alteração de senha', 'type': 1})

    @app.route('/new-password/', methods=['POST'])
    def send_new_password():
        user = UserController()
        user_id = request.form['user_id']
        password = request.form['password']

        result = user.new_password(user_id, password)

        if result:
            return render_template('login.html', data={'status': 200, 'msg': 'Senha alterada com sucesso!', 'type': 3, 'user_id': user_id})
        else:
            return render_template('new_password.html', data={'status': 401, 'msg': 'Erro ao alterar senha.', 'type': 1, 'user_id': user_id})

    @app.route('/products/', methods=['GET'])
    @app.route('/products/<limit>', methods=['GET'])
    @auth_token_required
    def get_products(limit=None):
        header = {
            'access_token': request.headers['access_token'],
            "token_type": "JWT"
        }

        product = ProductController()
        response = product.get_products(limit=limit)
        return Response(json.dumps(response, ensure_ascii=False), mimetype='application/json'), response['status'], header

    @app.route('/product/<product_id>', methods=['GET'])
    @auth_token_required
    def get_product(product_id):
        header = {
            'access_token': request.headers['access_token'],
            "token_type": "JWT"
        }
        
        product = ProductController()
        response = product.get_product_by_id(product_id = product_id)

        return Response(json.dumps(response, ensure_ascii=False), mimetype='application/json'), response['status'], header

    @app.route('/user/<user_id>', methods=['GET'])
    @auth_token_required
    def get_user_profile(user_id):
        header = {
            'access_token': request.headers['access_token'],
            "token_type": "JWT"
        }

        user = UserController()
        response = user.get_user_by_id(user_id=user_id)

        return Response(json.dumps(response, ensure_ascii=False), mimetype='application/json'), response['status'], header

    @app.route('/login_api/', methods=['POST'])
    def login_api():
        header = {}
        user = UserController()

        email = request.json['email']
        password = request.json['password']

        result = user.login(email, password)
        code = 401
        response = {"message": "Usuário não autorizado", "result": []}

        if result:
            if result.active:
                result = {
                    'id': result.id,
                    'username': result.username,
                    'email': result.email,
                    'date_created': result.date_created,
                    'active': result.active
                }

                header = {
                    "access_token": user.generate_auth_token(result),
                    "token_type": "JWT"
                }
                code = 200
                response["message"] = "Login realizado com sucesso"
                response["result"] = result

        return Response(json.dumps(response, ensure_ascii=False), mimetype='application/json'), code, header
    
    @app.route('/logout')
    def logout_send():
        logout_user()
        return render_template('login.html', data={'status': 200, 'msg': 'Usuário deslogado com sucesso!', 'type':3})

    @login_manager.user_loader
    def load_user(user_id):
        user = UserController()
        return user.get_admin_login(user_id)

    return app
Beispiel #8
0
def create_app(config_name):
    app = Flask(__name__, template_folder='templates')

    login_manager = LoginManager()
    login_manager.init_app(app)

    app.secret_key = config.SECRET
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')
    app.config['SQLALCHEMY_DATABASE_URI'] = config.SQLALCHEMY_DATABASE_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['FLASK_ADMIN_SWATCH'] = 'flatly'
    db = SQLAlchemy(config.APP)
    start_views(app, db)
    Bootstrap(app)
    db.init_app(app)

    @app.route("/")
    def index():
        return render_template('base.html')

    @app.route('/login/')
    def login():
        return render_template('login.html',
                               data={
                                   'status': 200,
                                   'msg': None,
                                   'type': None
                               })

    @app.route('/login/', methods=['POST'])
    def login_post():
        user = UserController()

        email = request.form['email']
        password = request.form['password']

        result = user.login(email, password)

        if result:
            if result.role == 3:
                return render_template(
                    'login.html',
                    data={
                        'status': 401,
                        'msg':
                        'Seu usuário não tem permissão para acessar o admin',
                        'type': 2
                    })
            else:
                login_user(result)
                return redirect('/admin')
        else:
            return render_template('login.html',
                                   data={
                                       'status': 401,
                                       'msg': 'Dados de usuário incorretos',
                                       'type': 1
                                   })

    @app.route('/recupere-senha')
    def recovery_password():
        return 'Recuperação de Senha'

    @app.route('/recupere-senha', methods=['Post'])
    def send_recovery_password():
        user = UserController()

        result = user.recovery(request.form['email'])

        if result:
            return render_template(
                'recovery.html',
                data={
                    'status': 200,
                    'msg': 'E-mail de confirmação enviado com sucesso'
                })
        else:
            return render_template('recovery.hmtl',
                                   data={
                                       'status':
                                       401,
                                       'msg':
                                       'Erro ao enviar e-mail de confirmação'
                                   })

    @app.route('/cadastro/', methods=['GET', 'POST'])
    def cadastro_salvar():
        """
        Função para salvar os dados do formulário no banco de dados.
        Caso envie dados, o sistesma guarda a data atual e o tipo de registro
        que há no formulário. Em seguida faz uma pesquisa na tabela 'Documents'
        no banco de dados. Próximo passo aciona a função 'get_count' que se
        encontra na model Documentos.py e soma mais 1 para ter a número atual
        incluindo o novo registro. Ao validadr o formulário, ele salva no banco
        os dados do formulários equivalentes ao campo. O campo 'num_reg', chama
        a função 'cont_reg', localizada em static/cadastro.py para transformar
        os dados obtidos e guardados em 'data_created' e 'n_rows' no formato
        string utilizado como númeração padrão: 00X/aaaa (ex: 001/2021)
        """
        form = FormCadastro()

        if request.method == 'POST':
            date_created = datetime.now()
            tipo = form.tipo_reg.data.name
            q = db.session.query(Documents).filter(Documents.type == tipo)
            n_rows = get_count(q) + 1

            if form.validate_on_submit():
                doc = Documents(num_reg=cont_reg(date_created, n_rows),
                                objeto=form.objeto.data,
                                origen=form.origem.data,
                                destiny=form.destino.data,
                                date_created=form.date_criacao.data,
                                requester=form.solicitante.data,
                                creator=form.criador.data,
                                type=form.tipo_reg.data)
                db.session.add(doc)
                db.session.commit()
                flash('Sucesso ao gravar')

                return render_template('base.html')

        return render_template('cadastro.html', form=form)

    @app.route('/destino/<get_destino>', methods=['GET'])
    def destino_opcoes(get_destino):
        destinos = Department.query.filter_by(tipo=get_destino).all()

        destinos_conj = []

        for destino in destinos:
            destinobj = {}
            destinobj['id'] = destino.id
            destinobj['name'] = destino.name
            destinobj['tipo'] = destino.tipo
            destinobj['description'] = destino.description
            destinos_conj.append(destinobj)

        return jsonify({'destinos': destinos_conj})

    @app.route('/documents', methods=['POST', 'GET'])
    def save_documents():
        document = DocumentController

        result = document.save_document(request.form)

        if result:
            message = 'Editado'
        else:
            message = "Não editado"
        return message

    @app.route('/documents', methods=['PUT'])
    def update_documents():
        document = DocumentController

        result = document.update_document(request.form)

        if result:
            message = 'Editado'
        else:
            message = "Não editado"
        return message

    @app.route('/documents/', methods=['GET'])
    @app.route('/documents/<limit>', methods=['GET'])
    def get_documents(limit=None):
        header = {}

        documents = DocumentController()
        response = documents.get_documents(limit=limit)

        return Response(
            json.dumps(response, ensure_ascii=False),
            mimetype='application/json'), response['status'], header

    @app.route('/documents/<documents_id>', methods=['GET'])
    def get_document(doc_id):
        header = {}

        documents = DocumentController()
        response = documents.get_documents_by_id(documents_id=doc_id)

        return Response(
            json.dumps(response, ensure_ascii=False),
            mimetype='application/json'), response['status'], header

    @app.route('/user/<user_id>', methods=['GET'])
    def get_user_profile(user_id):
        header = {
            'access_token': request.headers['access_token'],
            "token_type": "jwt"
        }

        user = UserController()
        response = user.get_user_by_id(user_id=user_id)

        return Response(
            json.dumps(response, ensure_ascii=False),
            mimetype='application/json'), response['status'], header

    @app.route('/login_api/', methods=['POST'])
    def login_api():
        header = {}
        user = UserController()

        email = request.json['email']
        password = request.json['password']

        result = user.login(email, password)
        code = 401
        response = {"message": "Usuário não autorizado", "result": []}

        if result:
            if result.active:
                result = {
                    'id': result.id,
                    'username': result.username,
                    'email': result.email,
                    'date_created': result.date_created,
                    'active': result.active
                }

                header = {
                    "access_token": user.generate_auth_token(result),
                    "token_type": "JWT"
                }
                code = 200
                response["message"] = "Login realizado com sucesso"
                response["result"] = result

        return Response(json.dumps(response, ensure_ascii=False),
                        mimetype='application/json'), code, header

    @app.route('/logout')
    def logout_send():
        logout_user()
        return render_template('login.html',
                               data={
                                   'status': 200,
                                   'msg': 'Usuário deslogado com sucesso',
                                   'type': 3
                               })

    @login_manager.user_loader
    def loader(user_id):
        user = UserController()
        return user.get_admin_login(user_id)

    return app
Beispiel #9
0
def create_app(config_name):
    app = Flask(__name__, template_folder='templates')

    app.secret_key = config.SECRET
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')

    # database
    app.config['SQLALCHEMY_DATABASE_URI'] = config.SQLALCHEMY_DATABASE_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    db = SQLAlchemy(config.APP)

    # start admin
    app.config['FLASK_ADMIN_SWATCH'] = 'united'
    start_views(app, db)

    db.init_app(app)

    @app.route('/')
    def index():
        return 'Hello World'

    @app.route('/login')
    def login():
        return 'tela de login'

    @app.route('/login', methods=['POST'])
    def login_post():
        user = UserController()

        email = request.form['email']
        password = request.form['password']

        login_response = user.login(email, password)

        if login_response:
            return redirect('/admin')
        else:
            return render_template('login.html',
                                   data={
                                       'status': 401,
                                       'message':
                                       'Dados de usuário incorretos',
                                       'type': None
                                   })

    @app.route('/recovery-passowrd')
    def recovery_password():
        return 'recovery password'

    @app.route('/recovery-password', methods=['POST'])
    def recovery_password_post():
        user = UserController()

        email = request.form['email']
        recovery_response = user.recovery(email)

        return render_template(
            'recovery.html',
            data={
                'status':
                200,
                'message':
                'Se o e-mail informado estiver correto o e-mail de recuperção foi enviado. Confira o SPAM'
            })

    return app
Beispiel #10
0
def create_app(config_name):
    app = Flask(__name__, template_folder='templates')
    login_manage = LoginManager()
    login_manage.init_app(app)
    app.secret_key = config.SECRET
    app.config.from_object(app_config[app_active])
    app.config.from_pyfile('config.py')
    app.config['SQLALCHEMY_DATABASE_URI'] = config.SQLALCHEMY_DATABASE_URI
    app.config['SQLACHEMY_TRACK_MODIFICATIONS'] = False
    app.config['FLASK_ADMIN_SWATCH'] = 'superhero'
    db = SQLAlchemy(config.APP)
    start_views(app, db)
    Bootstrap(app)
    db.init_app(app)

    @app.after_request
    def after_request(response):
        response.headers.add('Access-Control-Allow-Origin', '*')
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
        response.headers.add('Access-Control-Allow-Methods',
                             'GET, PUT, POST, DELETE, OPTIONS')
        return response

    def auth_token_required(f):
        @wraps(f)
        def verify_token(*args, **kwargs):
            user = UserController()

            try:
                result = user.verify_auth_token(
                    request.headers['access_token'])

                if result['status'] == 200:
                    return f(*args, **kwargs)
                else:
                    abort(result['status'], result['message'])

            except KeyError as e:
                abort(401, 'Você precisa enviar um token de acesso')

        return verify_token

    @app.route('/')
    def index():
        return "Flask app runing..."

    @app.route('/login/')
    def login():
        return render_template('login.html',
                               data={
                                   'status': 200,
                                   'msg': None,
                                   'type': None
                               })

    @app.route('/login/', methods=['POST'])
    def login_post():
        user_controller = UserController()
        email = request.form['email']
        password = request.form['password']

        result = user_controller.login(email, password)
        if result:
            if result.role == 2:
                return render_template(
                    'login.html',
                    data={
                        'status': 401,
                        'msg':
                        'Seu usuário não tem permissão para acessar o admin',
                        'type': 2
                    })
            else:
                login_user(result)
                return redirect('/admin')
        else:
            return render_template('login.html',
                                   data={
                                       'status': 401,
                                       'msg': 'Dados de usuário incorretos',
                                       'type': 1
                                   })

    @app.route('/recovery-password/')
    def recovery_password():
        return 'Tela de recuperar a senha'

    @app.route('/recovery-password/', methods=['POST'])
    def send_recovery_password():
        user_controller = UserController()
        result = user_controller.recovery(request.form['email'])

        if result:
            return render_template(
                'recovery.html',
                data={
                    'status': 200,
                    'msg': 'E-mail de recuperação enviado com sucesso'
                })
        else:
            return render_template('recovery.html',
                                   data={
                                       'status':
                                       401,
                                       'msg':
                                       'Erro ao enviar e-mail de recuperação'
                                   })

    @app.route('/product/', methods=['POST'])
    def save_products():
        product_controller = ProductController()
        result = product_controller.save_product(request.form)

        if result:
            return 'Inserido'
        else:
            return 'Não inserido'

    @app.route('/product/', methods=['PUT'])
    def update_products():
        product = ProductController()
        result = product.update_product(request.form)

        if result:
            return 'Editado'
        else:
            return 'Não editado'

    @app.route('/product/<int:id>', methods=['DELETE'])
    def delete_product(id):
        product = ProductController()
        result = product.delete_product(id)

        if result:
            return 'Deletado'
        else:
            return 'Não deletado'

    @app.route('/products/', methods=['GET'])
    @app.route('/products/<limit>', methods=['GET'])
    @auth_token_required
    def products(limit=None):
        header = {
            'access_token': request.headers['access_token'],
            'token_type': 'JWT'
        }
        product_controller = ProductController()
        response = product_controller.get_products(limit)

        return Response(json.dumps(response, ensure_ascii=False),
                        mimetype='application/json',
                        status=response['status'],
                        headers=header)

    @app.route('/product/<product_id>', methods=['GET'])
    @auth_token_required
    def get_product(product_id):
        header = {
            'access_token': request.headers['access_token'],
            'token_type': 'JWT'
        }
        product_controller = ProductController()
        response = product_controller.get_product_by_id(product_id)
        return Response(json.dumps(response, ensure_ascii=False),
                        mimetype='application/json',
                        status=response['status'],
                        headers=header)

    @app.route('/user/<user_id>', methods=['GET'])
    @auth_token_required
    def get_user(user_id):
        header = {
            'access_token': request.headers['access_token'],
            'token_type': 'JWT'
        }
        user_controller = UserController()
        response = user_controller.get_user_by_id(user_id)
        return Response(json.dumps(response, ensure_ascii=False),
                        mimetype='application/json',
                        status=response['status'],
                        headers=header)

    @app.route('/login_api', methods=['POST'])
    def login_api():
        header = {}
        user_controller = UserController()

        email = request.json['email']
        password = request.json['password']

        result = user_controller.login(email, password)
        code = 401
        response = {'message': 'Usuário não autorizado', 'result': []}

        if result:
            if result.active:
                result = {
                    'id': result.id,
                    'username': result.username,
                    'email': result.email,
                    'date_created': result.date_created,
                    'active': result.active
                }

                header = {
                    'access_token':
                    user_controller.generate_auth_token(result),
                    'token_type': 'JWT'
                }

                code = 200

                response['message'] = 'Login realizado com sucesso'
                response['result'] = result

        return Response(json.dumps(response, ensure_ascii=False),
                        mimetype='application/json',
                        status=code,
                        headers=header)

    @app.route('/logout')
    def logout_send():
        logout_user()
        return render_template('login.html',
                               data={
                                   'status': 200,
                                   'msg': 'Usuário deslogado com sucesso',
                                   'type': 3
                               })

    @login_manage.user_loader
    def load_user(user_id):
        user = UserController()
        return user.get_admin_login(user_id)

    return app
Beispiel #11
0
def create_app(config_name):
    app = Flask(__name__, template_folder='templates')

    login_manager = LoginManager()
    login_manager.init_app(app)

    app.secret_key = config.SECRET
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')

    app.config['SQLALCHEMY_DATABASE_URI'] = config.SQLALCHEMY_DATABASE_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['FLASK_ADMIN_SWATCH'] = 'paper'
    db = SQLAlchemy(config.APP)

    """adicionando a linha a seguir do start_view"""

    start_views(app, db)
    Bootstrap(app)
    db.init_app(app)

    @app.after_request
    def after_request(response):
        response.headers.add('Access-Control-Allow-Origin', '*')
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
        response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
        return response

    def auth_token_required(f):
        @wraps(f)
        def verify_token(*args, **kwargs):

            user = UserController()
            try:
                result = user.verify_auth_token(request.headers['access_token'])
                if result['status'] == 200:
                    return f(*args, **kwargs)
                else:
                    abort(result['status'], result['message'])
            except KeyError as e:
                abort(401, 'Você precisa enviar um token de acesso')

        return verify_token

    @app.route('/')
    def index():
        return 'Hello World!'

    @app.route('/login/')
    def login():
        return render_template('login.html', data={'status': 200, 'msg': None, 'type': None})

    @app.route('/login/', methods=['POST'])
    def login_post():
        user = UserController()

        email = request.form['email']
        password = request.form['password']

        result = user.login(email, password)
 
        if result:
            if result.role == 4:
                return render_template('login.html', data={'status': 401, 'msg': 'Seu usuário '
                                        'não tem permissão para acessar o admin', 'type':2})
            else:
                login_user(result)
                return redirect('/admin')
        else:
            return render_template('login.html', data={'status':401, 'msg': 'Dados de usuário incorretos', 'type': None})

    @app.route('/recovery-password/')
    def recovery_password():
        return 'aqui entraá a tela de recuperar senha'

    @app.route('/recovery-password', methods=['POST'])
    def send_recovery_password():
        user = UserController()

        result = user.recovery(request.form['email'])

        if result:
            return render_template('recovery.html', data={'status':200, 'msg': 'E-mail de recuperação enviado com sucesso'})
        else:
            return render_template('recovery.html', data={'status': 401, 'msg':'Erro ao enviar e-mail de recuperação'})

    @app.route('/profile/<int:id>/action/<action>/')
    def profile(id, action):
        if action == 'action1':
            return 'Ação action1 usuário ID %d' % id
        elif action == 'action2':
            return 'Ação action2 usuário ID %d' % id
        elif action == 'action3':
            return 'Ação action3 usuário ID %d' % id

    @app.route('/profile', methods=['POST'])
    def create_profile():
        username = request.form['username']
        password = request.form['password']
        return 'Essa rota possui um POST e criará um usuário com os dados de usuário %s e senha %s' % (username, password)

    @app.route('/profile/<int:id>', methods=['PUT'])
    def edit_total_profile(id):
        username = request.form['username']
        password = request.form['password']
        return 'Essa rota possui um PUT e editará o nome do usuário para %s e a senha para %s ' % (username. password)

    @app.route('/product', methods=['POST'])
    def save_products():
        product = ProductController()

        result = product.save_product(request.form)

        if result:
            message = "Inserido"
        else:
            message = 'Não Inserido'

        return message

    @app.route('/product', methods=['PUT'])
    def update_products():
        product = ProductController()

        result = product.update_product(request.form)

        if result:
           message = "Editado"
        else:
            message = 'Não Editado'

        return message

    @app.route('/products/', methods=['GET'])
    @app.route('/products/<limit>', methods=['GET'])
    @auth_token_required
    def get_products(limit=None):
        header = {
            # 'access_token': request.headers['access_token'],
            # "token_type": "JWT"
        }

        product = ProductController()
        response = product.get_products(limit=limit)
        return Response(json.dumps(response, ensure_ascii=False), mimetype='application/json'), response['status'], header

    @app.route('/product/<product_id>', methods=['GET'])
    @auth_token_required
    def get_product(product_id):
        header = {
            'access_token': request.headers['access_token'],
            "token_type": "JWT"
        }

        product =ProductController()
        response = product.get_product_by_id(product_id=product_id)
        return Response(json.dumps(response, ensure_ascii=False), mimetype='application/json'), response['status'], header

    @app.route('/user/<user_id>', methods=['GET'])
    @auth_token_required
    def get_user_profile(user_id):
        header = {
            'access_token': request.headers['access_token'],
            "token_type": "JWT"
        }

        user = UserController()
        response = user.get_user_by_id(user_id=user_id)
        return Response(json.dumps(response, ensure_ascii=False), mimetype='application/json'), response['status'], header

    @app.route('/login_api/', methods=['POST'])
    def login_api():
        header = {}
        user = UserController()

        email = request.json['email']
        password = request.json['password']

        result = user.login(email, password)
        code = 401
        response = {"message": "Usuário não autorizado", "result": []}

        if result:
            if result.active:
                result = {
                    'id': result.id,
                    'username': result.username,
                    'email': result.email,
                    'date_created': result.date_created,
                    'active': result.active
                }

                header = {
                    "access_token": user.generate_auth_token(result),
                    "token_type": "JWT"
                }
                code = 200
                response["message"] = "Login realizado com sucesso"
                response["result"] = result

        return Response(json.dumps(response, ensure_ascii=False), mimetype='application/json'), code, header

    return app