Example #1
0
def view(report_id):
    logging_prefix = logger_prefix + "view({}) - ".format(report_id)
    log.info(logging_prefix + "Starting")

    editors = None

    try:
        form, editors = es_to_form(report_id)
        search_form = forms.searchForm()
    except Exception as e:
        error = "There was an error completing your request. Details: {}".format(e)
        flash(error, "danger")
        log.exception(logging_prefix + error)
        form = forms.reportForm()

    # render the template, passing the variables we need
    #   templates live in the templates folder
    return render_template(
        "report.html",
        page_title="View Report",
        role="VIEW",
        report_id=report_id,
        form=form,
        editors=editors,
        search_form=search_form,
    )
Example #2
0
def add(template=None):
    logging_prefix = logger_prefix + "add({}) - ".format(template)
    log.info(logging_prefix + "Starting")

    error = None
    try:
        populate_simple_choices()
        form = forms.actorForm(request.form)
        search_form = forms.searchForm()

        if request.method == 'POST':
            #trick the form validation into working with our dynamic drop downs
            for sub_form in form.actor_class:
                sub_form.a_id.choices = fetch_child_data('tpx_classification',sub_form.a_family.data)

            #convert the field that lists the related_element_choices 
            #choices = []
            #rec = json.loads(form.related_element_choices.data)
            #for k,v in rec.items():
            #    choices.append((v,k))

            if form.validate():
                log.info(logging_prefix + "Add Detected")

                #create an actor id
                actor_id = str(uuid.uuid4())

                #convert the form to ES format
                form_to_es(form, actor_id)
               
                #rebuild the form from ES
                #flash('Not requerying ES, this should change', 'warning')
                form, editors = es_to_form(actor_id)

                flash(Markup('<a href="/actor/view/'+actor_id+'" style="text-decoration:none; color:#3c763d;">New Actor Successfully Added. Click here to view this actor</a>') , "success")

                #return redirect("/add/{}/".format(actor_id), code=302)
            else:
                #if there was an error print the error dictionary to the console
                #   temporary help, these should also appear under the form field
                print(form.errors)
        
        elif template:
            form, editors = es_to_form(template)
        else:
            #populate certain fields with default data
            form.actor_class[0].a_family.data = 'Actors'
            form.actor_class[0].a_id.choices = fetch_child_data('tpx_classification','Actors')

    except Exception as e:
        error = "There was an error completing your request. Details: {}".format(e)
        flash(error,'danger')
        log.exception(logging_prefix + error)

    return render_template("actor.html",
                        page_title="Add New Actor",
                        role="ADD",
                        form=form,
                        search_form = search_form
            )
Example #3
0
 def cotacoes(self):
     try:
         rendas = self.dao.buscarTodos(Renda)
         return render_template('cotacoes.html', rendas=rendas)
     except Exception as e:
         log.exception('cotacoes | ' + str(e))
         return render_template('index.html')
Example #4
0
 def post(self):
     try:
         args = parser.parse_args()
         pass_md5 = hashlib.md5(
             args['password'].encode('utf-8')).hexdigest()
         user = User.query.filter(User.login == args['login'],
                                  User.password == pass_md5).one_or_none()
         if user is None:
             log.info("Invalid login/password")
             return {
                 'state': 'fail',
                 'message': 'No such user or password invalid'
             }
         new_token = Token(token=str(uuid.uuid4()),
                           user_id=user.id,
                           device=args['device'])
         if args['expires'] is not None:
             new_token.expires_at = datetime.fromtimestamp(args['expires'] /
                                                           1000.0)
         db.session.add(new_token)
         db.session.commit()
         log.info("Created new token: %s" % new_token.token)
         return {'token': new_token.token}
     except Exception as e:
         db.session.rollback()
         log.exception(e)
         return {'state': 'fail', 'message': str(e)}, 500
Example #5
0
def edit_favorite_thing(user_id, favorite_id):
    try:

        title = request.json.get("title")
        description = request.json.get("description")
        ranking = request.json.get("ranking")
        meta_data = request.json.get("meta_data")
        category = request.json.get("category")

        log.info(f"Editing new favorite thing:{favorite_id} for user:{user_id}")
        updates = {
            "title": title,
            "description": description,
            "ranking": ranking,
            "category": category,
            "meta_data": meta_data
        }
        filtered = {k: v for k, v in updates.items() if v is not None}
        updates.clear()
        updates.update(filtered)

        log.debug("Got item to update:{}".format(updates))

        favorite = core.update_favorite_thing(user_id, favorite_id, updates)

        resp = Response(json.dumps({"favorite": favorite}, default=str), status=200, mimetype='application/json')
    except Exception as ex:
        log.exception(ex)
        resp = Response(json.dumps(getattr(ex, "args", ex)), status=400, mimetype='application/json')
    return resp
Example #6
0
def view(actor_id):
    logging_prefix = logger_prefix + "view({}) - ".format(actor_id)
    log.info(logging_prefix + "Starting")

    editors = None
    
    try:
        populate_simple_choices()
        form, editors = es_to_form(actor_id)

        search_form = forms.searchForm()
    except Exception as e:
        error = "There was an error completing your request. Details: {}".format(e)
        flash(error,'danger')
        log.exception(logging_prefix + error)
        form = forms.actorForm()

    #render the template, passing the variables we need
    #   templates live in the templates folder
    return render_template("actor.html",
                        page_title="View Actor",
                        role="VIEW",
                        actor_id=actor_id,
                        form=form,
                        editors=editors,
                        search_form = search_form
            )
Example #7
0
def user_delete(user_id, user_id_hash):
    logging_prefix = logger_prefix + "user_delete({},{}) - ".format(user_id, user_id_hash)
    log.info(logging_prefix + "Starting")

    redirect_url = "/admin/"
    try:
        redirect_url = request.args.get("_r")
        if not redirect_url:
            log.warning(logging_prefix + "redirect_url not set, using default")
            redirect_url = "/admin/"

        #check user_id against user_id_hash and perform delete if match
        if user_id_hash == sha256( SALTS['user'], user_id ):
            #now delete the user
            conn=get_mysql().cursor(DictCursor)
            conn.execute("DELETE FROM users WHERE id=%s", (user_id,))
            conn.close()
            flash("The user has been deleted", "success")
        else:
            flash("Unable to delete user", "danger")
        
    except Exception as e:
        error = "There was an error completing your request. Details: {}".format(e)
        flash(error,'danger')
        log.exception(logging_prefix + error)
        
    return redirect(redirect_url)
def populate_simple_choices():
    '''
    Populates the SIMPLE_CHOICES dictionary with options
    '''

    global SIMPLE_CHOICES

    SIMPLE_CHOICES = {}
    try:
        body = {
            "query" : {
                "match_all" : {}
            },
            "size" : 1000
        }
        results = get_es().search(ES_PREFIX + 'threat_actor_simple', 'data', body)

        for r in results['hits']['hits']:
            c_type = r['_source']['type']
            c_value = r['_source']['value']

            if c_type not in SIMPLE_CHOICES:
                SIMPLE_CHOICES[c_type] = []

            SIMPLE_CHOICES[c_type].append(c_value)

        for k,v in SIMPLE_CHOICES.items():
            SIMPLE_CHOICES[k] = sorted(v)

        #print(SIMPLE_CHOICES)

    except Exception as e:
        error = "There was an error fetching choices. Details: {}".format(t, e)
        flash(error,'danger')
        log.exception(logging_prefix + error)
Example #9
0
def main():
    logging_prefix = logger_prefix + "main() - "
    log.info(logging_prefix + "Starting")

    try:
        conn=get_mysql().cursor(DictCursor)
        conn.execute("SELECT id, name, email, company, justification, email_verified, approved, write_permission, delete_permission, admin, created, last_login FROM users ORDER BY created DESC")

        users = conn.fetchall()
        for user in users:
            user['id_hash'] = sha256( SALTS['user'], str(user['id']) )

        conn.close()

        email_user_form = forms.sendUserEmailForm()

    except Exception as e:
        error = "There was an error completing your request. Details: {}".format(e)
        flash(error,'danger')
        log.exception(logging_prefix + error)


    return render_template("admin.html",
                        page_title="Admin",
                        url = "/admin/",
                        users=users,
                        email_user_form = email_user_form
            )
Example #10
0
def add(template=None):
    logging_prefix = logger_prefix + "add({}) - ".format(template)
    log.info(logging_prefix + "Starting")

    error = None
    try:
        form = forms.reportForm(request.form)
        search_form = forms.searchForm()

        if request.method == "POST":
            # trick the form validation into working with our dynamic drop downs
            for sub_form in form.report_class:
                sub_form.a_id.choices = fetch_child_data("tpx_classification", sub_form.a_family.data)

            # convert the field that lists the related_element_choices
            # choices = []
            # rec = json.loads(form.related_element_choices.data)
            # for k,v in rec.items():
            # choices.append((v,k))

            if form.validate():
                log.info(logging_prefix + "Add Detected")

                # create a ttp id
                report_id = str(uuid.uuid4())

                # convert the form to ES format
                form_to_es(form, report_id)

                # rebuild the form from ES
                form, editors = es_to_form(report_id)

                flash(
                    Markup(
                        '<a href="/report/view/'
                        + report_id
                        + '" style="text-decoration:none; color:#3c763d;">New Report Successfully Added. Click here to view this Report</a>'
                    ),
                    "success",
                )
            else:
                # if there was an error print the error dictionary to the console
                #   temporary help, these should also appear under the form field
                print(form.errors)

        elif template:
            form, editors = es_to_form(template)
        else:
            # populate certain fields with default data
            form.report_class[0].a_family.data = "Actors"
            form.report_class[0].a_id.choices = fetch_child_data("tpx_classification", "Actors")

    except Exception as e:
        error = "There was an error completing your request. Details: {}".format(e)
        flash(error, "danger")
        log.exception(logging_prefix + error)
        form = forms.reportForm()

    return render_template("report.html", page_title="Add New Report", role="ADD", form=form, search_form=search_form)
Example #11
0
def password_reset(user_id=None, expiration_ts=None, password_reset_hash=None):
    logging_prefix = logger_prefix + "password_reset({},{},{}) - ".format(user_id, expiration_ts, password_reset_hash)
    log.info(logging_prefix + "Starting")
    
    try:
        if sha256(SALTS['user'],user_id+expiration_ts) != password_reset_hash:
            flash("There was an error completing your request", 'danger')
            return redirect("/user/password/request_reset/")

        form = forms.passwordPerformResetForm(request.form)
        search_form = forms.searchForm()

        now = int(time.time())

        if now > int(expiration_ts): # passworD1!
            flash("This link has expired", 'danger')
            return redirect("/user/password/request_reset/")

        conn=get_mysql().cursor(DictCursor)
        conn.execute("SELECT COUNT(*) as count FROM password_reset_hashes WHERE hash = %s AND user_id = %s", (password_reset_hash,user_id))
        result = conn.fetchone()
        conn.close()

        if not result:
            flash("This link has expired", 'danger')
            return redirect("/user/password/request_reset/")

        if result['count'] == 0:
            flash("This link has expired", 'danger')
            return redirect("/user/password/request_reset/")

        if request.method == 'POST':
            if form.validate():
                password = form.user_password.data
                salted_password = sha256(SALTS['user'],password)

                conn=get_mysql().cursor()
                conn.execute("UPDATE users SET password = %s WHERE id = %s", (salted_password,user_id))
                conn.execute("DELETE FROM password_reset_hashes WHERE user_id = %s", (user_id,))
                get_mysql().commit()
                conn.close()

                flash("Your password has been updated", "success")
                return redirect("/user/login")
            else:
                print(form.errors)

    except Exception as e:
        error = "There was an error completing your request. Details: {}".format(e)
        flash(error,'danger')
        log.exception(logging_prefix + error)

    log.info(logging_prefix + "Rendering")
    return render_template("password_reset.html",
                        page_title="Reset Your Password",
                        page_type="PERFORM",
                        form=form,
                        search_form=search_form
            )
Example #12
0
def get_class_full_name(obj):
    try:
        full_name = obj.__class__.__module__ + "." + obj.__class__.__name__
    except Exception as e:
        msg = 'ERROR in function app.app_utils.get_class_full_name().'
        log.exception(msg)
        raise e
    return full_name
 def get(self, token):
     try:
         user = token.user
         favourites = Favourite.query.filter(
             Favourite.user_id == user.id).all()
         return {'all': favourites}
     except Exception as e:
         log.exception(e)
         return {'state': 'fail', 'message': str(e)}, 500
Example #14
0
 def _erro(self, msg, erro):
     """ 
     Método executado quando ocorre erro nas ações com DB. 
     :param msg: Mensagem de erro.
     :param erro: Exception que causou o erro.
     :return:
     """
     log.exception(msg + str(erro))
     flash(msg, 'alert-danger')
Example #15
0
def get_audit_logs(user_id: str, favorite_id: str):
    try:
        log.info(f"Get all log related to favorite item:{favorite_id} for user:{user_id}")
        logs = core.get_logs_of_favorite_thing(user_id, favorite_id)
        resp = Response(json.dumps({"logs": logs}, default=str), status=200, mimetype='application/json')
    except Exception as ex:
        log.exception(ex)
        resp = Response(json.dumps(getattr(ex, "args", ex)), status=400, mimetype='application/json')
    return resp
Example #16
0
def get_favorite_categories(user_id):
    try:
        log.info(f"get all favorite categories of user:{user_id}")
        categories = core.get_categories_of_a_user(user_id)
        resp = Response(json.dumps({"categories": categories}, default=str), status=200, mimetype='application/json')
    except Exception as ex:
        log.exception(ex)
        resp = Response(json.dumps(getattr(ex, "args", ex)), status=400, mimetype='application/json')
    return resp
Example #17
0
def get_user_by_id(user_id):
    try:
        log.info("GET user by id")
        user = core.get_user_by_id(user_id)
        resp = Response(json.dumps({"user": user}), status=200, mimetype='application/json')
    except Exception as ex:
        log.exception(ex)
        resp = Response(json.dumps({"message": "No such user. "}), status=400,
                        mimetype='application/json')
    return resp
Example #18
0
 def load_config(self):
     options: dict = {}
     with open(settings.DEPLOYMENT_CONFIG_FILE) as fd:
         exec(fd.read(), None, options)
     for key, value in options.items():
         try:
             self.cfg.set(key, value)
         except Exception as exc:
             log.exception(f'Error gunicorn config key: {key!r}. '
                           f'Exception: {exc}')
Example #19
0
 def login(self):
     try:
         if request.method == 'POST':
             return redirect(url_for('admin.login'))
         else:
             return render_template('admin/login.html')
     except Exception as e:
         flash('Usuário ou senha inválido!', 'alert-danger')
         log.exception('Erro ao fazer login! | ' + str(e))
         return redirect(url_for('admin.login'))
Example #20
0
def edit_user_permissions(action,value,user_id,user_c):
    logging_prefix = logger_prefix + "edit_user_permissions({},{},{},{}) - ".format(action,value,user_id,user_c)
    log.info(logging_prefix + "Starting") 

    action_column_map = {}
    action_column_map['approve'] = "approved"
    action_column_map['write_perm'] = "write_permission"
    action_column_map['delete_perm'] = "delete_permission"
    action_column_map['admin_perm'] = "admin"

    success = 1
    try:
        #make sure the value is valid
        if value not in ["0","1"]:
            raise Exception("Invald value: {}".format(value))

        #make sure the action is valid    
        try:
            column = action_column_map[action]
        except Exception as f:
            log.warning(logging_prefix + "Action '{}' not found in action_column_map".format(action))
            raise f

        #check the hash
        if user_c == sha256(SALTS['user'], str(user_id)):

            #if action is approve, emails need to be sent
            if action == "approve":
                conn = get_mysql().cursor(DictCursor)
                conn.execute("SELECT name, email FROM users WHERE id = %s", (user_id,))
                user = conn.fetchone()
                conn.close()

                if value == "1":
                    log.info(logging_prefix + "Setting approved=1 for user {}".format(user_id))
                    sendAccountApprovedEmail(user['email'])
                else:
                    log.info(logging_prefix + "Setting approved=0 for user {}".format(user_id))
                    sendAccountDisapprovedEmail(user['email'])

            #now update the desired setting
            conn = get_mysql().cursor()
            conn.execute("UPDATE users SET "+column+" = %s WHERE id = %s", (value,user_id))
            get_mysql().commit()
            conn.close()
            log.info(logging_prefix + "Successfully update {} to {} for user id {}".format(column,value,user_id))

        else:
            log.warning(logging_prefix + "Hash mismatch {} {}".format(user_id, user_c))
    except Exception as e:
        success = 0
        error = "There was an error completing your request. Details: {}".format(e)
        log.exception(logging_prefix + error)

    return jsonify({ "success" : success, "new_value" : value })
Example #21
0
def edit(report_id):
    logging_prefix = logger_prefix + "edit({}) - ".format(report_id)
    log.info(logging_prefix + "Starting")

    error = None
    try:
        search_form = forms.searchForm()
        editors = None
        if request.method == "POST":
            form = forms.reportForm(request.form)

            # trick the form validation into working with our dynamic drop downs
            for sub_form in form.report_class:
                sub_form.a_id.choices = fetch_child_data("tpx_classification", sub_form.a_family.data)

            # convert the field that lists the related_element_choices
            # choices = []
            # rec = json.loads(form.related_element_choices.data)
            # for k,v in rec.items():
            # choices.append((v,k))

            if form.validate():
                log.info(logging_prefix + "Edit Detected")

                # convert the form to ES format
                form_to_es(form, report_id)

                # rebuild the form from ES
                form, editors = es_to_form(report_id)

                flash("Report Update Successful!", "success")
            else:
                # if there was an error print the error dictionary to the console
                #   temporary help, these should also appear under the form field
                print(form.errors)
        else:
            form, editors = es_to_form(report_id)

    except Exception as e:
        error = "There was an error completing your request. Details: {}".format(e)
        flash(error, "danger")
        log.exception(logging_prefix + error)
        form = forms.reportForm()

    # render the template, passing the variables we need
    #   templates live in the templates folder
    return render_template(
        "report.html",
        page_title="Edit Report",
        role="EDIT",
        report_id=report_id,
        form=form,
        editors=editors,
        search_form=search_form,
    )
Example #22
0
def edit(ttp_id):
    logging_prefix = logger_prefix + "edit({}) - ".format(ttp_id)
    log.info(logging_prefix + "Starting")

    error = None
    try:
        editors = None
        search_form = forms.searchForm()
        if request.method == 'POST':
            form = forms.ttpForm(request.form)

            #trick the form validation into working with our dynamic drop downs
            for sub_form in form.ttp_class:
                sub_form.a_id.choices = fetch_child_data(
                    'tpx_classification', sub_form.a_family.data)

            #convert the field that lists the related_element_choices
            #choices = []
            #rec = json.loads(form.related_element_choices.data)
            #for k,v in rec.items():
            #choices.append((v,k))

            if form.validate():
                log.info(logging_prefix + "Edit Detected")

                #convert the form to ES format
                form_to_es(form, ttp_id)

                #rebuild the form from ES
                form, editors = es_to_form(ttp_id)

                flash("TTP Update Successful!", "success")
            else:
                #if there was an error print the error dictionary to the console
                #   temporary help, these should also appear under the form field
                print(form.errors)
        else:
            form, editors = es_to_form(ttp_id)

    except Exception as e:
        error = "There was an error completing your request. Details: {}".format(
            e)
        flash(error, 'danger')
        log.exception(logging_prefix + error)
        form = forms.ttpForm()

    #render the template, passing the variables we need
    #   templates live in the templates folder
    return render_template("ttp.html",
                           page_title="Edit TTP",
                           role="EDIT",
                           ttp_id=ttp_id,
                           form=form,
                           editors=editors,
                           search_form=search_form)
Example #23
0
def user_authorization():
    try:
        url = oauth.getAuthorizationUrl()
        log.info("Redirecting user to {} for authorization...".format(url))
        return redirect(url)
    except Exception as e:
        log.exception(
            "Error occurred while getting the authorization url: {}".format(e))
        flash("An error occurred while getting the authorization url",
              'danger')
        return render_template("/admin/home.html")
Example #24
0
def save_new_user():
    try:
        log.info("signup new user")
        email = request.json["email"]
        password = hashlib.md5(request.json["password"].encode()).hexdigest()
        user = service.create_new_user(email=email, password=password)
        resp = Response(json.dumps({"user": user}), status=200, mimetype='application/json')
    except Exception as ex:
        log.exception(ex)
        resp = Response(json.dumps(getattr(ex, "args", ex)), status=400, mimetype='application/json')
    return resp
Example #25
0
def session_scope():
    """Provide a transactional scope around a series of operations."""
    session = Session()
    try:
        yield session
        session.commit()
    except Exception as e:
        log.exception(e)
        session.rollback()
        raise
    finally:
        session.close()
Example #26
0
def _clientes():
    """
        Método para consulta com todos os clientes cadastrados.
        :return: json com todos os clientes cadastrados. 
    """
    try:
        with sessao() as session:
            clientes = Dao(session).todos(Cliente)
            clientes = [{"id": str(i.id), "nome": i.nome} for i in clientes]
            return jsonify(clientes=clientes)
    except Exception as e:
        log.exception('Erro ajax clientes!' + str(e))
Example #27
0
def login_user():
    try:
        log.info("login new user")
        email = request.json["email"]
        password = hashlib.md5(request.json["password"].encode()).hexdigest()
        user = core.validate_user_credentials(email=email, password=password)
        resp = Response(json.dumps({"user": user}), status=200, mimetype='application/json')
    except Exception as ex:
        log.exception(ex)
        resp = Response(json.dumps({"message": "No such user. please check email or password."}), status=400,
                        mimetype='application/json')
    return resp
Example #28
0
def insertNewToken():
    try:
        log.info("Getting new token...")
        oauth.insertNewToken(oauth.getNewAccessToken())
        flash("A new access token was successfuly inserted into the database.",
              'success')
    except Exception as e:
        log.exception("Error occurred while inserting new token: {}".format(e))
        flash(
            "An error occurred while inserting a new acccess token into the database.",
            'danger')
    return render_template("about.html")
Example #29
0
def insertAllAthletesApp():
    try:
        log.info("Inserting all athletes into database...")
        numAthletesInserted = db_filler.insertAllAthletesIntoDB()
        flash(
            "Successfully inserted {} athletes into the database.".format(
                numAthletesInserted), 'success')
    except Exception as e:
        log.exception(
            "Error occurred while inserting all athletes: {}".format(e))
        flash("Error while inserting athletes into database.", 'danger')
    return render_template("/admin/home.html")
Example #30
0
 def __init__(self, controller_uid):
     super().__init__()
     self._controller_uid = controller_uid
     # We are considering that only Controller class objects
     # can create View class objects. Then, we must verify it
     UIM_class = self.get_manager_class()
     UIM = UIM_class()
     view_class = UIM.get_view_class(controller_uid[0])
     if self.__class__ != view_class:
         msg = 'Error! Only the controller can create the view.'
         log.exception(msg)
         raise Exception(msg)
Example #31
0
def session_scope():
    """Provide um escopo de transações para várias operações no banco de dados."""
    session = sessionmaker(bind=_engine)()
    try:
        yield session
        session.commit()
    except Exception as e:
        session.rollback()
        log.exception('db.py session_scope. Erro: ' + str(e))
        raise e
    finally:
        session.close()
Example #32
0
 def get(self, token):
     try:
         args = parser.parse_args()
         user = token.user
         tokens = Token.query.filter(Token.user_id == user.id)
         if args['self'] == 0:
             tokens = tokens.filter(Token.token != token.token)
         tokens = tokens.order_by(Token.created_at.desc()).all()
         return {'devices': tokens}
     except Exception as e:
         log.exception(e)
         return {'state': 'fail', 'message': str(e)}, 500
Example #33
0
def consulta():
    """
        Método para exibição da página com consulta por período.
        :return: view com a página consultas.html 
    """
    try:

        return render_template('agro/consultas.html')
    except Exception as e:
        msg = 'Erro ao exibir consultas!'
        log.exception(msg + str(e))
        flash(msg, 'alert-danger')
        return render_template('index.html')
def fetch_related_choices(t):
    logging_prefix = logger_prefix + "fetch_related_choices({}) - ".format(t)

    choices = [('_NONE_', 'n/a')]

    if t == 'actor':
        index = ES_PREFIX + "threat_actors"
        doc_type = "actor"
    elif t == 'report':
        index = ES_PREFIX + "threat_reports"
        doc_type = "report"
    elif t == 'ttp':
        index = ES_PREFIX + "threat_ttps"
        doc_type = "ttp"
    else:
        raise Exception("Invalid type '{}'. Expected 'actor', 'ttp' or 'report'")

    es_query = {
            "query": {
                "match_all": {}
            },
            "size": 1000,
            "fields" : ["name"],
            "sort": {
                "name": {
                    "order": "asc"
                }
            }
        }

    try:
        results = get_es().search(index, doc_type, es_query)
        for r in results['hits']['hits']:
            choices.append((r['_id'] + ":::" + r['fields']['name'][0],r['fields']['name'][0]))

    except TransportError as te:

        #if the index was not found, this is most likely becuase theres no data there
        if te.status_code == 404:
            log.warning("Index '{}' was not found".format(index))
        else:
            error = "There was an error fetching related {}s. Details: {}".format(t, te)
            flash(error,'danger')
            log.exception(logging_prefix + error)

    except Exception as e:
        error = "There was an error fetching related {}s. Details: {}".format(t, e)
        flash(error,'danger')
        log.exception(logging_prefix + error)

    return choices
Example #35
0
def export(report_id):
    logging_prefix = logger_prefix + "export({}) - ".format(report_id)
    log.info(logging_prefix + "Starting")

    try:
        tpx = es_to_tpx(report_id)
    except Exception as e:
        error = "There was an error completing your request. Details: {}".format(e)
        log.exception(logging_prefix + error)

        tpx = {"error": error}
        return jsonify(tpx), 500

    return jsonify(tpx), 200
Example #36
0
def save_new_favorite_categories(user_id):
    try:
        category = request.json["category"].lower()
        log.info(f"Save new favorite category:{category} of user:{user_id}")

        if category not in core.get_all_favorite_items(user_id):
            core.create_a_new_category_for_a_user(user_id, category)

        categories = core.get_categories_of_a_user(user_id)
        resp = Response(json.dumps({"categories": categories}, default=str), status=200, mimetype='application/json')
    except Exception as ex:
        log.exception(ex)
        resp = Response(json.dumps(getattr(ex, "args", ex)), status=400, mimetype='application/json')
    return resp
Example #37
0
def password_request_reset():
    logging_prefix = logger_prefix + "password_request_reset() - "
    log.info(logging_prefix + "Starting")
    try:
        form = forms.userEmailForm(request.form)
        search_form = forms.searchForm()

        if request.method == 'POST':
            if form.validate():
                email = form.user_email.data

                #make sure the email exists in the system
                conn=get_mysql().cursor(DictCursor)
                conn.execute("SELECT id FROM users WHERE email = %s", (email,))
                user = conn.fetchone()
                conn.close()

                if user:
                    expiration_ts = int(time.time()) + 3600
                    password_reset_hash = sha256(SALTS['user'],str(user['id']) + str(expiration_ts))

                    #set this value in the database, so it can be expired after the password is changed
                    conn=get_mysql().cursor(DictCursor)
                    conn.execute("INSERT INTO password_reset_hashes (user_id,hash) VALUES (%s,%s)", (user['id'],password_reset_hash))
                    get_mysql().commit()
                    conn.close()

                    password_reset_link = "/user/password/reset/{}/{}/{}/".format(user['id'],expiration_ts,password_reset_hash)

                    sendPasswordResetEmail(email, password_reset_link)

                    flash("An email has been sent to '{}' with a link to reset your password. This link expires in 1 hour.".format(email),'success')
                else:
                    flash("The email you entered was not found", "danger")

            else:
                print(form.errors)

    except Exception as e:
        error = "There was an error completing your request. Details: {}".format(e)
        flash(error,'danger')
        log.exception(logging_prefix + error)

    return render_template("password_reset.html",
                        page_title="Reset Your Password",
                        page_type="REQUEST",
                        form=form,
                        search_form=search_form
            )
Example #38
0
def verify(email, verification_hash):
    logging_prefix = logger_prefix + "verify() - "
    log.info(logging_prefix + "Starting")

    email = unquote_plus(email)

    print(email)
    print(verification_hash)

    try:
        conn=get_mysql().cursor(DictCursor)
        conn.execute("SELECT id, email, name, company, justification FROM users WHERE verification_hash = %s", (verification_hash,))
        r = conn.fetchone()
        if not r:
            log.error(logging_prefix + "User with email '{}' was not found".format(email))
            flash("Your user was not found, try registering again",'danger')
        elif r['email'] == email:
            log.info(logging_prefix + "Successful validation of {}".format(email))
            flash("Your email address have been verified, you will not be able to log in until you get approved by the Site Admin",'success')

            #update the database marking this user active
            user_id = r['id']
            conn.execute("UPDATE users SET email_verified=1 WHERE id = %s", (user_id,))
            get_mysql().commit()

            #id, email, name, company
            sendNewUserToApproveEmail(r['id'], r['email'],r['name'],r['company'],r['justification'])
        else:
            log.warning(logging_prefix + "Unsuccessful validation of {}".format(email))
            flash("We were unable to verify your account",'danger')

    except Exception as e:
        error = "There was an error completing your request. Details: {}".format(e)
        flash(error,'danger')
        log.exception(logging_prefix + error)
    finally:
        conn.close()

    return redirect("/", code=307)
Example #39
0
def reverify():
    logging_prefix = logger_prefix + "reverify() - "
    log.info(logging_prefix + "Starting")
    try:
        form = forms.userEmailForm(request.form)
        search_form = forms.searchForm()

        if request.method == 'POST':
            if form.validate():
                email = form.user_email.data

                #make sure the email exists in the system
                conn=get_mysql().cursor(DictCursor)
                conn.execute("SELECT verification_hash FROM users WHERE email = %s", (email,))
                user = conn.fetchone()
                conn.close()

                if user:
                    sendAccountVerificationEmail(email, user['verification_hash'])

                    flash("A verification email has been sent to '{}' with a link to verify your account.".format(email),'success')
                else:
                    flash("The email you entered was not found", "danger")

            else:
                print(form.errors)

    except Exception as e:
        error = "There was an error completing your request. Details: {}".format(e)
        flash(error,'danger')
        log.exception(logging_prefix + error)

    return render_template("account_reverify.html",
                        page_title="Verify Account",
                        form=form,
                        search_form=search_form
            )
Example #40
0
def login():
    logging_prefix = logger_prefix + "login() - "
    log.info(logging_prefix + "Starting")

    try:
        form = forms.loginForm(request.form)
        search_form = forms.searchForm()

        if request.method == 'POST':
            if form.validate():
                email = form.user_email.data 
                password = form.user_password.data

                hashed_password = sha256(SALTS['user'], password)

                conn=get_mysql().cursor(DictCursor)
                #since email is unique
                conn.execute("SELECT id, password, name, email_verified, approved, write_permission, delete_permission, admin FROM users WHERE email = %s", (email,))
                user = conn.fetchone()
                

                if user:
            
                    if user['password'] == hashed_password:
                        #we have found a valid user

                        if user['email_verified']==0:
                            #the user has not verified their email address
                            flash("Your email address has not been verified. Click here if you did not receive a verification email", "danger")

                        elif user['approved']==0:
                            #the user has not been approved, or their access has been disapproved
                            flash("Your account has been approved yet, you will receive an email when your account has been approved", "danger")

                        else:
                            #woohoo successful login, set up session variables
                            session['logged_in']    =   True
                            session['id']           =   user['id']
                            session['name']         =   user['name']
                            session['email']        =   email
                            session['approved']     =   (user['approved'] == 1)
                            session['write']        =   (user['write_permission'] == 1)
                            session['delete']       =   (user['delete_permission'] == 1)
                            session['admin']        =   (user['admin'] == 1)
                            session['expires']      =   math.ceil(time.time()) + SESSION_EXPIRE
                                                                            #now + 10 minutes of inactivity
                                                                            #each time this user loads a page
                                                                            #the expiration time gets now + 10m

                            #update last login timestamp
                            conn=get_mysql().cursor(DictCursor)
                            conn.execute("UPDATE users SET last_login=%s WHERE id = %s", (datetime.now(), user['id']))
                            get_mysql().commit()
                            conn.close()

                            flash("You have been logged in", "success")

                            if request.args.get("r"):
                                return redirect(request.args.get("r"))
                            else:
                                return redirect("/") 
                    else:
                        log.warning(logging_prefix + "Invalid login attempt for {}".format(email))
                        flash("The username or password is incorrect", "danger")
                else:
                    log.warning(logging_prefix + "Invalid login attempt for {}".format(email))
                    flash("The username or password is incorrect", "danger")
            else:
                print(form.errors)

    except Exception as e:
        error = "There was an error completing your request. Details: {}".format(e)
        flash(error,'danger')
        log.exception(logging_prefix + error)

    return render_template("login.html",
                        page_title="Login",
                        form=form,
                        search_form=search_form
            ) 
Example #41
0
def register():
    logging_prefix = logger_prefix + "register() - "
    log.info(logging_prefix + "Starting")
    try:

        form = forms.registerForm(request.form)
        search_form = forms.searchForm()

        if request.method == 'POST':

            #verify captcha
            perform_validate = True
            try:
                if RECAPTCHA_ENABLED:
                    captcha_value = request.form['g-recaptcha-response']
                    r = requests.post("https://www.google.com/recaptcha/api/siteverify", data={
                            'secret': RECAPTCHA_PRIVATE_KEY,
                            'response': request.form['g-recaptcha-response']
                        })
                    r_json = json.loads(r.text)

                    if not r_json['success']:
                        flash("Bots are not allowed",'danger')
                        perform_validate = False

            except Exception as s:
                log.exception(logging_prefix + "Error preforming captcha validation")
                raise s

            if perform_validate and form.validate():
                log.info(logging_prefix + "Sign up Detected")

                #get data from form
                name = form.user_name.data
                email = form.user_email.data 
                password = form.user_password.data
                company = form.user_company.data
                reason = form.user_reason.data

                #create the necessary hashes
                salted_password = sha256(SALTS['user'],password)
                verification_hash = sha256(SALTS['email_verification'], email)

                #insert data into mysql
                insert = "INSERT INTO users (email, password, name, company, justification, email_verified, verification_hash) VALUES (%s,%s,%s,%s,%s,%s,%s)"
                values = (email, salted_password, name, company, reason, 0, verification_hash)
                log.info(logging_prefix + "Adding new user {}".format(values))

                try:
                    conn=get_mysql().cursor()
                    conn.execute(insert, values)
                    get_mysql().commit()
                    conn.close()
                except Exception as s:
                    conn.close()
                    raise s

                #email the user to verify email
                try:
                    sendAccountVerificationEmail(email, verification_hash)
                except Exception as s:
                    log.exception(logging_prefix + "Unable to send email to {} with verification_hash {}".format(email, verification_hash))
                    raise s

                flash("You have been registered. A verification email with an actviation link has been sent to {} from [email protected]".format(email),'success')
            else:

                print(form.errors)
        else:
            pass

    except Exception as e:
        error = "There was an error completing your request. Details: {}".format(e)
        flash(error,'danger')
        log.exception(logging_prefix + error)


    return render_template("register.html",
                        page_title="Register",
                        form=form,
                        recaptcha_enabled=RECAPTCHA_ENABLED,
                        recaptcha_key=RECAPTCHA_PUBLIC_KEY,
                        search_form=search_form
            )