def forgot_password():
    """ Ggenerate unique token and store it in db """
    if request.method == 'POST':
        email = request.form['email']
        user = get_user_from_email(email)
        user_ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
        user_agent = request.headers.get('User-Agent')
        domain = request.headers['Host']
        token = str(uuid.uuid4())
        errors = []

        if email is None:
            errors.append('Email is required.')

        if user is None:
            errors.append('Email does not exist.')

        if errors:
            [flash(error) for error in errors]
            return jsonify(status='error')
        else:
            db = get_db()

            db.execute(
                'UPDATE user SET password_reset_token = ? WHERE email = ?',
                (token, email))

            db.commit()

            send_mail(
                send_from='*****@*****.**',
                send_to=[email],
                subject='Gatekeeping Forgotten Password',
                text='Hi,\n\n'
                'You recently notified us that you forgot your password.\n\n'
                'Kindly access the link below to reset your password.\n\n' +
                str(url_for('auth.reset', token=token, _external=True)),
                server='smtp.office365.com')

            # create audit trail in db
            create_audit_log(user_agent,
                             user_ip,
                             domain,
                             action='User requested password reset',
                             table='USER',
                             function='INSERT',
                             user_id=user['id'])

            return render_template('auth/forgot_password.html',
                                   show_modal=True)

    return render_template('auth/forgot_password.html')
def login():
    """Log in a registered user by adding the user id to the session."""
    if g.user:
        return redirect(url_for('home.index'))

    if request.method == 'POST':
        email = request.form['email']
        password = request.form['password']
        user_ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
        user_agent = request.headers.get('User-Agent')
        domain = request.headers['Host']
        errors = []

        user = get_user_from_email(email)

        if user is None:
            errors.append('Incorrect email.')

        if not check_password_hash(user['password'], password):
            errors.append('Incorrect password.')

        if errors:
            # create audit trail in db
            create_audit_log(
                user_agent,
                user_ip,
                domain,
                action='Unsuccessful login for email {}'.format(email),
                table='USER',
                function='READ')

            [flash(error) for error in errors]
            # return flashed messages
            return render_template('auth/login.html')
        else:
            # store the user id in a new session and return to the index
            session.clear()
            session['user_id'] = user['id']

            # create audit trail in db
            create_audit_log(user_agent,
                             user_ip,
                             domain,
                             action='Successful login',
                             table='USER',
                             function='READ',
                             user_id=session['user_id'])

            return redirect(url_for('index'))

    return render_template('auth/login.html')
def reset(token):
    if request.method == 'POST':
        password = request.form['password']
        confirm_password = request.form['confirmPassword']
        user_ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
        user_agent = request.headers.get('User-Agent')
        domain = request.headers['Host']
        user = get_user_from_password_reset_token(token)
        errors = []

        if password is None:
            errors.append('Email is required.')

        if confirm_password is None:
            errors.append('Email does not exist.')

        if password != confirm_password:
            errors.append('Passwords do not match.')

        if user['password'] == password:
            errors.append('New password cannot be the same as old password.')

        if errors:
            [flash(error) for error in errors]
            return jsonify(status='error')
        else:
            db = get_db()

            db.execute(
                'UPDATE user SET password = ?, password_reset_token = NULL WHERE password_reset_token = ?',
                (generate_password_hash(password), token))

            db.commit()

            # create audit trail in db
            create_audit_log(user_agent,
                             user_ip,
                             domain,
                             action='User reset password',
                             table='USER',
                             function='',
                             user_id=user['id'])

            return redirect(url_for('index'))

    return render_template('auth/reset.html')
def logout():
    """Clear the current session, including the stored user id."""
    if g.user is None:
        return redirect(url_for('index'))

    user_ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
    user_agent = request.headers.get('User-Agent')
    domain = request.headers['Host']
    user_id = session.get('user_id')

    # create audit trail in db
    create_audit_log(user_agent,
                     user_ip,
                     domain,
                     action='User logged out',
                     table='USER',
                     function='READ',
                     user_id=user_id)

    session.clear()

    return redirect(url_for('index'))
Exemplo n.º 5
0
def update_position(id):
    position = get_position_by_id(id)
    pillars = get_pillars()
    companies = [(company['id'], company['name'])
                 for company in get_companies()]
    departments = get_departments()
    functions = get_functions()
    position_statuses = get_position_statuses()
    recruitment_statuses = get_recruitment_statuses()

    data = {
        "position": dict(position),
        "pillars": dict(pillars),
        "companies": dict(companies),
        "departments": dict(departments),
        "functions": dict(functions),
        "positionStatuses": dict(position_statuses),
        "recruitmentStatuses": dict(recruitment_statuses)
    }

    if request.method == 'POST':
        status_id = get_position_status_by_name(
            request.form['positionStatuses'])['id']
        recruitment_status_id = get_recruitment_status_by_name(
            request.form['recruitmentStatuses'])['id']
        number = request.form['number']
        pillar_id = get_pillar_by_name(request.form['pillars'])['id']
        company_id = get_company_by_name(request.form['companies'])['id']
        department_id = get_department_by_name(
            request.form['departments'])['id']
        function_id = get_function_by_name(request.form['functions'])['id']
        title = request.form['title']
        functional_reporting_line = request.form['functionalReportingLine']
        disciplinary_reporting_line = request.form['disciplinaryReportingLine']
        holder = request.form['holder']
        hours = request.form['hours']
        start_date = request.form['startDate']
        end_date = request.form['endDate']
        salary = request.form['salary']
        social_security_contribution = request.form[
            'socialSecurityContribution']
        fringe_benefit = request.form['fringeBenefit']
        performance_bonus = request.form['performanceBonus']
        super_bonus = request.form['superBonus']
        management_bonus = request.form['managementBonus']
        user_ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
        user_agent = request.headers.get('User-Agent')
        domain = request.headers['Host']
        errors = []

        if not status_id:
            errors.append('Status is required.')

        if not recruitment_status_id:
            errors.append('Recruitment Status required.')

        if not number:
            errors.append('Number is required.')

        if not pillar_id:
            errors.append('Pillar is required.')

        if not department_id:
            errors.append('Department Status required.')

        if not function_id:
            errors.append('Function is required.')

        if not title:
            errors.append('Title is required.')

        if not functional_reporting_line:
            errors.append('Functional  is required.')

        if not disciplinary_reporting_line:
            errors.append('Disciplinary Reporting Line is required.')

        if errors:
            [flash([error, id], category='update') for error in errors]
            return jsonify(status='error')
        else:
            db = get_db()
            db.execute(
                'UPDATE position set status_id = ?, recruitment_status_id = ?, number = ?, pillar_id = ?, company_id = ?, department_id = ?,'
                'function_id = ?, title = ?, functional_reporting_line = ?, disciplinary_reporting_line = ?, holder = ?,'
                'hours = ?, start_date = ?, end_date = ?, salary = ?, social_security_contribution = ?,'
                'fringe_benefit = ?, performance_bonus = ?, super_bonus = ?, management_bonus = ?'
                'WHERE number = ?',
                (status_id, recruitment_status_id, number, pillar_id,
                 company_id, department_id, function_id, title,
                 functional_reporting_line, disciplinary_reporting_line,
                 holder, hours, start_date, end_date, salary,
                 social_security_contribution, fringe_benefit,
                 performance_bonus, super_bonus, management_bonus))

            db.commit()

            # create audit trail in db
            create_audit_log(user_agent,
                             user_ip,
                             domain,
                             action='Successful position update',
                             table='POSITION',
                             function='UPDATE',
                             user_id=g.user['id'])

            return jsonify(status='ok')

    return jsonify(data)
def register():
    """Register a new user.
    Validates that the email is not already taken. Hashes the
    password for security.
    """
    if g.user:
        return redirect(url_for('home.index'))

    if request.method == 'POST':
        email = request.form['email']
        password = request.form['password']
        user_ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
        user_agent = request.headers.get('User-Agent')
        domain = request.headers['Host']
        errors = []

        db = get_db()

        if not email:
            errors.append('Email is required.')

        if email.split('@')[1] != 'gaucimaistre.com':
            errors.append('Not a valid gaucimaistre email address')

        if db.execute('SELECT id'
                      ' FROM user'
                      ' WHERE email = ?', (email, )).fetchone() is not None:
            errors.append('User {} is already registered.'.format(email))

        if not password:
            errors.append('Password is required.')

        if errors:
            [flash(error) for error in errors]
            # return flashed messages
            return render_template('auth/register.html')
        else:
            # the name is available, store it in the database and go to
            # the login page
            db.execute('INSERT INTO user (email, password) VALUES (?, ?)',
                       (email, generate_password_hash(password)))

            db.commit()

            # create audit trail in db
            create_audit_log(user_agent,
                             user_ip,
                             domain,
                             action='Successful registration',
                             table='USER',
                             function='INSERT')

            send_mail(
                send_from='*****@*****.**',
                send_to=list([user['email'] for user in get_admin_users()]),
                subject='New user requesting account activation',
                text='Hi,\n\n'
                'The following user has requested to access the gatkeeping application.\n\n'
                + email,
                server='smtp.office365.com')

            return redirect(url_for('auth.login', show_modal=True))

        # create audit trail in db
        create_audit_log(user_ip,
                         user_agent,
                         domain,
                         action='Unsuccessful registration',
                         table='USER',
                         function='READ')

    return render_template('auth/register.html')