Exemple #1
0
def loginOrSignUp(form):
    db = Database()
    username = form.data['username']
    password = form.data['password']
    #get hashed pass from db
    hashedPass = db.get_user_pass(username)
    if (hashedPass):
        if (pwd_context.verify(password, hashedPass)):
            #login
            user = get_user(username)
            login_user(user)
            form.errors['username'] = '******'
            return True
        else:
            form.errors['password'] = '******'
            return False
    else:
        form.errors[
            'noUser'] = '******'
        if (form.data['addUser'] == 'true'):
            hashedPass = pwd_context.encrypt(password)
            result = db.add_user(username, hashedPass)
            #login user
            user = get_user(username)
            login_user(user)
            return True
    return False
 def post(self):
     try:
         post_data = request.get_json()
         database = Database(dbtype=post_data['dbtype'],
                             username=post_data['username'],
                             password=post_data['password'],
                             hostname=post_data['hostname'],
                             dbname=post_data['dbname'])
         ping = database.ping_connection()
         if ping is 1:
             db.session.add(database)
             db.session.commit()
             task = save_metadata.delay(database.id)
             return make_response(
                 jsonify({
                     'data': database.to_json,
                     'task': {
                         'task_id': task.task_id
                     },
                     '_links': {
                         'task':
                         url_for('api.task_progress_api',
                                 task_id=task.id,
                                 _external=True)
                     }
                 })), 201
     except exc.DBAPIError as e:
         current_app.logger.error(str(e))
         msg = str(e.orig.args[1]).split('(')[0].rstrip(' ')
         response_object = {
             'status': 'fail',
             'message': 'Some error occurred. Please try again.',
             'reason': f'{msg}'
         }
         return make_response(jsonify(response_object)), 401
     # except exc.IntegrityError as e:
     #     # current_app.logger.error(str(e.orig.args))
     #     msg = str(e.orig.args[1]).split('(')[0].rstrip(' ')
     #     response_object = {
     #         'status': 'fail',
     #         'message': 'Some error occurred. Please try again.',
     #         'reason': f'{msg}'
     #     }
     #     return make_response(jsonify(response_object)), 401
     except AssertionError as err:
         response_object = {
             'status': 'fail',
             'message': 'Some error occurred. Please try again.',
             'reason': f'{str(err)}'
         }
         return make_response(jsonify(response_object)), 401
     except Exception as e:
         current_app.logger.error(str(e))
         response_object = {
             'status': 'fail',
             'message': 'Some error occurred. Please try again.',
             'reason': f'{e}'
         }
         return make_response(jsonify(response_object)), 401
Exemple #3
0
def edit_message_page(message_id):
    if current_user.is_admin:
        form = AddMessageForm()
        db = Database()
        message = db.get_message(message_id)
        if form.validate_on_submit():
            message = Message(form.data['title'], form.data['text'])
            message.id = message_id
            db.edit_message(message)
            flash('message edited')
            return redirect(url_for('site.home_page'))
        return render_template('message.html', form=form, message=message)
    return redirect(url_for('site.home_page'))
Exemple #4
0
def home_page():
    db = Database()
    form = AddMessageForm()
    answerForm = AddAnswerForm()
    if form.validate_on_submit():
        title = form.data['title']
        text = form.data['text']
        message = Message(title, text)
        message.username = current_user.username
        db.add_message(message)
        flash('message added')
        return redirect(url_for('site.home_page'))
    if answerForm.validate_on_submit():
        text = answerForm.data['text']
        messageId = answerForm.data['messageID']
        db.add_message_answer(
            MessageAnswer(text, 0, current_user.username, messageId))
        flash('answer added')
        return redirect(url_for('site.home_page'))
    messages = db.get_messages()
    messageAnswer = db.get_message_answers()
    return render_template('home.html',
                           answers=messageAnswer,
                           answerForm=answerForm,
                           form=form,
                           messages=messages)
Exemple #5
0
def edit_answer_page(answer_id):
    if current_user.is_admin:
        form = AddAnswerForm()
        db = Database()
        answer = db.get_message_answer(answer_id)
        print(answer.text)
        if form.validate_on_submit():
            answer = MessageAnswer(form.data['text'])
            answer.id = answer_id
            db.edit_message_answer(answer)
            flash('answer edited')
            return redirect(url_for('site.home_page'))
        return render_template('answer.html', form=form, answer=answer)
    return redirect(url_for('site.home_page'))
Exemple #6
0
    def __init__(
        self,
        name: str = "",
        nutriscore: str = "",
        brand: str = "",
        stores: str = "",
        url: str = "",
        pk: int = None,
        substituted_id: int = None,
        substitutes_id: int = None,
    ):
        """Init."""
        self.name = name
        self.nutriscore = nutriscore
        self.brand = brand
        self.stores = stores
        self.url = url
        self.pk = pk
        self.substituted_id = substituted_id
        self.substitutes_id = substitutes_id

        self.page_index = 1
        self.limit = 30
        self.total_lines = 0

        self.db = Database(off_user, off_password, off_database)
        self.category: Category = Category()
Exemple #7
0
 def find_best_category(cls, pk, offset):
     """Find the best category."""
     cls.db = Database(off_user, off_password, off_database)
     cls.db.cursor.execute(
         "SELECT p.name, ns.type, p.brand, p.stores, p.url, p.id,\
                          c.id as category_with_the_fewest_products, (\
                     SELECT COUNT(p_in.id) tot_in\
                     FROM products p_in\
                     JOIN categories_products cp_in\
                     ON p_in.id = cp_in.products_id\
                     JOIN categories c_in\
                     ON c_in.id = cp_in.categories_id\
                     where c_in.id in (category_with_the_fewest_products) \
                     GROUP BY c_in.name\
                 ) as tot_produtcs_in_fewest_category\
         FROM products p\
         JOIN categories_products cp\
         ON cp.products_id = p.id\
         JOIN categories c\
         ON cp.categories_id = c.id\
         JOIN nutriscore ns\
         ON p.nutriscore_id = ns.id\
         WHERE p.id = %s\
         GROUP BY tot_produtcs_in_fewest_category\
         ORDER BY tot_produtcs_in_fewest_category ASC LIMIT 1 OFFSET %s",
         (
             pk,
             offset,
         ),
     )
     return [Category(*line) for line in cls.db.cursor.fetchall()]
Exemple #8
0
 def find_substitute_from_category(cls, best_category_id):
     """Find substitute."""
     cls.db = Database(off_user, off_password, off_database)
     cls.db.cursor.execute(
         "SELECT products.name, nutriscore.type, products.brand, products.stores,\
     products.url, products.id\
     FROM products\
     JOIN nutriscore\
     ON nutriscore.id = products.nutriscore_id\
     JOIN categories_products\
     ON categories_products.products_id = products.id\
     JOIN categories\
     ON categories_products.categories_id = categories.id\
     WHERE categories.id = %s and nutriscore.type < (\
         SELECT GROUP_CONCAT(DISTINCT nutriscore.type SEPARATOR ', ') AS liste\
         FROM products\
         JOIN nutriscore\
         ON nutriscore.id = products.nutriscore_id\
         JOIN categories_products\
         ON categories_products.products_id = products.id\
         JOIN categories\
         ON categories_products.categories_id = categories.id\
         WHERE categories.id = %s  )\
         ORDER BY RAND() LIMIT 1",
         (
             best_category_id,
             best_category_id,
         ),
     )
     return [Product(*line) for line in cls.db.cursor.fetchall()]
Exemple #9
0
def get_user(username):
    db = Database()
    userArray = db.get_user(username)
    user = None
    if len(userArray) == 1:
        user = User(username)
        if (len(userArray[0]) <= 2 or userArray[0][2] == None):
            user.is_admin = True  #old database, allow reset
        else:
            user.is_admin = userArray[0][2]
        if (len(userArray[0]) >= 4):
            user.picture = userArray[0][3]
    elif (len(userArray) < 1):
        user = User('vita')
        user.is_admin = True  #no user, allow reset
    return user
Exemple #10
0
def login_page():
    db = Database()
    form = LoginForm()
    if form.validate_on_submit() and loginOrSignUp(form):
        flash('login succesfull')
        return redirect(url_for('site.home_page'))
    else:
        print('fail to sign in')
        return render_template('login.html', form=form)
Exemple #11
0
 def retrieve_substitute(cls):
     """Retrieve the saved substitute."""
     cls.db = Database(off_user, off_password, off_database)
     cls.db.cursor.execute(
         "SELECT p.name, ns.type, p.brand, p.stores, p.url, p.id, substituted.id\
             FROM substitutes s\
             JOIN products substitute\
             ON s.substitute_id = substitute.id\
             JOIN products substituted\
             ON s.substituted_id = substituted.id\
             JOIN products p\
             ON p.id = substitute.id\
             JOIN nutriscore ns\
             ON ns.id = p.nutriscore_id", )
     return [Product(*line) for line in cls.db.cursor.fetchall()]
Exemple #12
0
 def list(cls, pk, limit, offset):
     """List the products."""
     cls.db = Database(off_user, off_password, off_database)
     cls.db.cursor.execute(
         "SELECT p.name, ns.type, p.brand, p.stores, p.url, p.id\
             FROM categories c\
             JOIN categories_products cp\
             ON c.id = cp.categories_id\
             JOIN products p\
             ON cp.products_id = p.id\
             JOIN nutriscore ns\
             ON p.nutriscore_id = ns.id\
             WHERE c.id = %s LIMIT %s OFFSET %s",
         (pk, limit, offset),
     )
     return [Product(*line) for line in cls.db.cursor.fetchall()]
Exemple #13
0
 def retrieve(cls, pk: int):
     """Retrieve the products."""
     cls.db = Database(off_user, off_password, off_database)
     cls.db.cursor.execute(
         "SELECT p.name, ns.type, p.brand, p.stores, p.url, p.id\
             FROM products p\
             JOIN categories_products cp\
             ON p.id = cp.products_id\
             JOIN categories c\
             ON cp.categories_id = c.id\
             JOIN nutriscore ns\
             ON p.nutriscore_id = ns.id\
             WHERE p.id = (%s) LIMIT 1",
         (pk, ),
     )
     return [Product(*line) for line in cls.db.cursor.fetchall()]
Exemple #14
0
    def retrieve(cls):
        """Select 30 categories."""
        cls.db = Database(off_user, off_password, off_database)
        cls.db.cursor.execute(
            "SELECT categories.name, categories.id, COUNT(products.id) as total_products\
                        FROM categories_products\
                        INNER JOIN products\
                        ON categories_products.products_id = products.id\
                        JOIN categories\
                        ON categories.id = categories_products.categories_id\
                        GROUP BY categories.name\
                        ORDER BY total_products  DESC LIMIT 30")

        return [
            Category(name=line[0], pk=line[1])
            for line in cls.db.cursor.fetchall()
        ]
Exemple #15
0
 def get_total_lines(self, pk):
     """Get total product per category."""
     self.db = Database(off_user, off_password, off_database)
     self.db.cursor.execute(
         "SELECT COUNT(products.id) as total_lines\
             FROM categories\
             JOIN categories_products\
             ON categories.id = categories_products.categories_id\
             JOIN products\
             ON categories_products.products_id = products.id\
             JOIN nutriscore\
             ON nutriscore.id = products.nutriscore_id\
             WHERE categories.id = %s",
         (pk, ),
     )
     self.total_lines = self.db.cursor.fetchone()[0]
     return self.total_lines
Exemple #16
0
def login():

    if request.method == 'POST':
        email = request.form.get('email')
        #recebe o email e passa para o init de Database
        gerenciadoDb = Database(email)
        #insere os dados recebido na base de dados
        gerenciadoDb.gravaDadosTabela()
        #cria a tabela de dados caso não tenha 
        gerenciadoDb.dbContato()
        
        return redirect(url_for('bemvindo'))
    return render_template('login.html')
Exemple #17
0
def profile_page():
    if current_user.is_authenticated:
        db = Database()
        users = db.get_usernames()
        bestfriend = db.get_bestFriend(current_user.username)
        friends = db.get_friends(current_user.username)
        form = ChangePassForm()
        picForm = ChangePictureForm()
        if form.validate_on_submit():
            hashedPass = pwd_context.encrypt(form.data['password'])
            db.update_pass(current_user.username, hashedPass)
            flash('Updated Password')
        if picForm.validate_on_submit():
            db.change_user_picture(current_user.username,
                                   picForm.data['picture'])
            flash('Updated Picture')
        form = ChangePassForm()
        return render_template('profile.html',
                               users=users,
                               form=form,
                               bestfriend=bestfriend,
                               friends=friends,
                               picForm=picForm)
    return redirect(url_for('site.home_page'))
Exemple #18
0
def up_answer_page(answer_id):
    if current_user.is_authenticated:
        db = Database()
        db.up_answer(answer_id)
    return redirect(url_for('site.home_page'))
Exemple #19
0
from flask_mail import Mail
from apscheduler.schedulers.background import BackgroundScheduler
import pytz
import logging
import datetime
import os
from dotenv import load_dotenv
load_dotenv()
DATABASE = os.getenv("DATABASE")
SECRET_KEY = os.getenv("SECRET_KEY")
USERNAME_EMAIL = os.getenv("USERNAME_EMAIL")
PASSWORD_EMAIL = os.getenv("PASSWORD_EMAIL")
#### Limite diário de busca padrão na API para novos usuários ####
SEARCH_LIMIT = 20

database = Database(DATABASE)

#agendador de tarefas
def job_function():
    list_users_db = database.filter_by("users", {"role": "standard"})
    for user in list_users_db:
        user_temp = user
        user['search_limit'] = SEARCH_LIMIT
        database.update("users", user_temp, user)
    scheduler.reschedule_job('1', trigger='cron', hour=00, minute=00, second=10)

job_defaults = {
    'coalesce': False,
    'max_instances': 1
}
Exemple #20
0
 def __init__(self):
     """Init."""
     self.db = Database(db_user, db_password)
Exemple #21
0
def adminize_page(username):
    if current_user.is_admin and username != 'admin':
        db = Database()
        db.adminize(username)
    return redirect(url_for('site.home_page'))
Exemple #22
0
def add_bestFriend_page(username):
    if current_user.is_authenticated:
        db = Database()
        db.set_as_bestFriends(current_user.username, username)
    return redirect(url_for('site.profile_page'))
Exemple #23
0
 def __init__(self):
     """Init."""
     self.db = Database(user, password, DB_NAME)
Exemple #24
0
def remove_friend_page(username):
    if current_user.is_authenticated:
        db = Database()
        db.remove_friendship(current_user.username, username)
    return redirect(url_for('site.profile_page'))
Exemple #25
0
def del_message_page(message_id):
    if current_user.is_admin:
        db = Database()
        db.del_message(message_id)
    return redirect(url_for('site.home_page'))