Ejemplo n.º 1
0
def user_register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = UserRegisterForm()
    if not form.validate_on_submit():
        return render_template('register.html', form=form, testing=app.testing)
    else:
        username = form.username.data
        nickname = form.nickname.data
        password = form.password1.data
        email = form.email1.data
        print(username, nickname, password, email, flush=True)
        try:
            User.create(username=username,
                        nickname=nickname,
                        password=password,
                        email=email)
        except IntegrityError as e:
            app.logger.warning(f"Integrity Error: {e}")
            crx_flash('ERROR_USER_EXISTS')
            return redirect(url_for('user_register'))
        except Exception as e:
            app.logger.warning(f"Unknown Error: {e}")
            crx_flash('ERROR_UNKNOWN')
            return redirect(url_for('user_register'))

        app.logger.info(f"User created: {username}, {nickname}, {email}")
        crx_flash('ACCOUNT_CREATED', username)
        return redirect(url_for('user_login'))
Ejemplo n.º 2
0
def home():
    params = get_params(request.args)

    query = params.get('q')
    if query == None:
        return render('home.html', sample_queries=get_sample_queries())
    default_command = params.get('default')

    try:
        commands = builtin_commands
        if user_signed_in():
            user = get_current_user()
            commands = user.commands
            default_command = user.getDefaultCommand()

        return redirect(commands.getRedirectUrl(query, default_command))
    except (NotEnoughArgumentsException, UnknownCommandException,
            UnknownDefaultCommandException) as e:
        return render(
            'command_error.html',
            exception_type=e.__class__.__name__,
            exception=e,
        )
    except MalformedQueryException:
        return redirect(HOME)
Ejemplo n.º 3
0
def oauth_initiate(service):
    assert_user_signed_out()

    s = oauth_services.get(service)
    if s == None:
        return redirect(SIGN_IN)

    state = set_oauth_state()
    return redirect(s.getInitiateRedirectURL(state))
Ejemplo n.º 4
0
def break_candidate_ok(identifier):
    # Check that the program is broken
    program = Program.get_unbroken_or_broken_by_id(identifier)
    if program is None or not program.is_broken:
        return redirect(url_for('index'))
    # Check that the user indeed broke the challenge
    wb_break = WhiteboxBreak.get(current_user, program)
    if wb_break is None:
        return redirect(url_for('index'))
    # If we reach this point, the user indeed broke the challenge
    return render_template('challenge_break_ok.html',
                           wb_break=wb_break,
                           current_user=current_user)
Ejemplo n.º 5
0
def test_redirect():
    from app.utils import redirect

    assert redirect("https://www.google.com") == "https://www.google.com"
    assert (
        redirect(
            (
                "https://l.messenger.com/l.php?u=https%3A%2F%2Fwww.shopmyexchange.com%2F"
                "apple-ipad-pro-11-in-512gb-with-wifi%2F1726804&h=AT3GRFe-SvZbNUTx-"
                "XLVVEWhEy8eBs_QOtd13einBQXNWit63zN5UrP8H1GsR8Y8gdUr6MnH6ry7gvfSD5gH"
                "YeGlQZQkp7mJiLhQlJysrEmwA7jcfgJTDVYYJK8smh-ICJx1BcdvHQ"
            )
        )
        == "https://www.shopmyexchange.com/apple-ipad-pro-11-in-512gb-with-wifi/1726804"
    )
Ejemplo n.º 6
0
def server_error(e):
    if isinstance(e, RedirectException):
        return redirect(e.route)

    # Log the error and stacktrace.
    logging.exception('unhandled exception')
    return render('error.html')
def get_candidate_proof_of_knowledge(identifier):
    program = Program.get_by_id(identifier)
    if program is None:
        return redirect(url_for('index'))

    do_show = False
    if program.is_published:
        do_show = True
    if current_user is not None and \
       current_user.is_authenticated and \
       current_user == program.user:
        do_show = True
    if not do_show:
        return redirect(url_for('index'))

    return program.proof_of_knowledge
Ejemplo n.º 8
0
def get_item_info(url):
    soup = make_soup(url)
    title = get_title(soup)
    item = soup.find("div", {"class": "aafes-pdp-price mt-1 jsRenderedPrice"})
    try:
        price = "".join(
            item.find("div", {
                "class": "aafes-price-sale"
            }).text.strip().replace(" Sale", "").split())
    except:
        try:
            price = check_num(
                item.find("div", {
                    "class": "aafes-price"
                }).text.strip())
        except:
            try:
                price = check_num(
                    item.find("div", {
                        "class": "aafes-price-sm"
                    }).text.strip())
            except:
                raw_price = item.find("span", {
                    "class": "aafes-price-list"
                }).text.strip()
                price = check_num(raw_price[raw_price.find("$"):])
    return title, floatify(price), redirect(url)
Ejemplo n.º 9
0
def pick_commands():
    assert_user_signed_in()

    checkbox_prefix = 'checkbox_'
    checked = {}
    error = None
    if request.method == 'POST':
        try:
            params = get_params(request.form)

            user = get_current_user()
            for k in params.iterkeys():
                if k.startswith(checkbox_prefix):
                    command = builtin_commands.get(k[len(checkbox_prefix):])
                    if command != None:
                        checked[command.name] = True
            for k in sorted(checked.keys()):
                user.commands.add(builtin_commands.get(k))
            user.put()
            return redirect(COMMANDS)
        except ParamException as e:
            error = e.message

    return render(
        'pick_commands.html',
        builtin_command_groups=builtin_command_groups,
        checkbox_prefix=checkbox_prefix,
        checked=checked,
        error=error,
        csrf_token=get_csrf_token(),
    )
Ejemplo n.º 10
0
def on_revert(request, page_name):
    """Revert an old revision."""
    rev_id = request.args.get('rev', type=int)

    old_revision = page = None
    error = 'No such revision'

    if request.method == 'POST' and request.form.get('cancel'):
        return redirect(href(page_name))

    if rev_id:
        old_revision = Revision.query.filter(
            (Revision.revision_id == rev_id) &
            (Revision.page_id == Page.page_id) &
            (Page.name == page_name)
        ).first()
        if old_revision:
            new_revision = Revision.query.filter(
                (Revision.page_id == Page.page_id) &
                (Page.name == page_name)
            ).order_by(Revision.revision_id.desc()).first()
            if old_revision == new_revision:
                error = 'You tried to revert the current active ' \
                        'revision.'
            elif old_revision.text == new_revision.text:
                error = 'There are no changes between the current ' \
                        'revision and the revision you want to ' \
                        'restore.'
            else:
                error = ''
                page = old_revision.page
                if request.method == 'POST':
                    change_note = request.form.get('change_note', '')
                    change_note = 'revert' + (change_note and ': ' +
                                              change_note or '')
                    session.add(Revision(page, old_revision.text,
                                         change_note))
                    session.commit()
                    return redirect(href(page_name))

    return Response(generate_template('action_revert.html',
        error=error,
        old_revision=old_revision,
        page=page
    ))
def down_candidate(identifier):
    program = Program.get_by_id(identifier)
    if program is None:
        return redirect(url_for('index'))

    do_show = False
    if program.is_published:
        do_show = True
    if current_user is not None and \
       current_user.is_authenticated and \
       current_user == program.user:
        do_show = True
    if not do_show:
        return redirect(url_for('index'))

    # If we reach this point, we can show the source code
    upload_folder = app.config['UPLOAD_FOLDER']
    return send_from_directory(upload_folder, program.filename)
def get_candidate_pubkey(identifier):
    program = Program.get_by_id(identifier)
    if program is None:
        return redirect(url_for('index'))

    do_show = False
    if program.is_published:
        do_show = True
    if current_user is not None and \
       current_user.is_authenticated and \
       current_user == program.user:
        do_show = True
    if not do_show:
        return redirect(url_for('index'))

    if not program.pubkey:
        return "Public key was erased for some reason, contact administrator."
    else:
        return program.pubkey
Ejemplo n.º 13
0
def set_default_command():
    assert_user_signed_in()

    params = get_params(request.form)
    default_command = params.get('default_command')

    user = get_current_user()
    user.setDefaultCommand(default_command)
    user.put()

    return redirect(COMMANDS)
Ejemplo n.º 14
0
def delete_command():
    assert_user_signed_in()

    params = get_params(request.form)

    user = get_current_user()
    command = user.commands.get(params.get('delete'))
    if command != None:
        user.commands.remove(command.name)
        user.put()

    return redirect(COMMANDS)
Ejemplo n.º 15
0
def submit_candidate():
    now = int(time.time())
    if now < app.config['STARTING_DATE']:
        return render_template('submit_candidate_before_starting_date.html',
                               active_page='submit_candidate',
                               starting_date=format_timestamp(
                                   app.config['STARTING_DATE']))

    if now > app.config['POSTING_DEADLINE']:
        return render_template('submit_candidate_deadline_exceeded.html',
                               active_page='submit_candidate',
                               posting_deadline=format_timestamp(
                                   app.config['POSTING_DEADLINE']))

    form = WhiteboxSubmissionForm()
    if request.method != 'POST':
        return render_template('submit_candidate.html',
                               form=form,
                               active_page='submit_candidate',
                               testing=app.testing)
    elif not form.validate_on_submit():
        crx_flash("CHALLENGE_INVALID")
        return render_template('submit_candidate.html',
                               form=form,
                               active_page='submit_candidate',
                               testing=app.testing), 400
    else:
        upload_folder = app.config['UPLOAD_FOLDER']
        basename = ''.join(
            random.SystemRandom().choice(string.ascii_lowercase +
                                         string.digits) for _ in range(32))
        filename = basename + '.c'
        pubkey = form.pubkey.data
        proof_of_knowledge = form.proof_of_knowledge.data
        form_data = form.program.data
        form_data.save(os.path.join(upload_folder, filename))
        Program.create(basename=basename,
                       pubkey=pubkey,
                       proof_of_knowledge=proof_of_knowledge,
                       user=current_user)
        try:
            db.session.commit()
        except sqlalchemy.exc.IntegrityError as e:
            db.session.rollback()
            crx_flash("DUPLICATE_KEY")
            app.logger.error(e)
            new_form = WhiteboxSubmissionForm()
            return render_template('submit_candidate.html',
                                   form=new_form,
                                   active_page='submit_candidate',
                                   testing=app.testing), 400
        else:
            return redirect(url_for('submit_candidate_ok'))
Ejemplo n.º 16
0
def edit_command(command_name=None):
    assert_user_signed_in()

    if command_name == None:
        return redirect(NEW_COMMAND_ONLY)

    user = get_current_user()
    command = user.commands.get(command_name)
    if command == None:
        return redirect(NEW_COMMAND_ONLY + command_name)

    params = None
    if request.method == 'POST':
        # remove command, it might be renamed
        user.commands.remove(command.name)
        params = get_params(request.form)
        try:
            save_command(**params)
            return redirect(COMMANDS)
        except ParamException as e:
            params['error'] = e.message
            # add the command back, some other code might use it
            # before response is finalized
            user.commands.add(command)
    else:
        params = {
            'name': command.name,
            'description': command.description,
            'url_pattern': command.url_pattern,
            'default_url': command.default_url,
        }

    params['action'] = EDIT_COMMAND_ONLY + command_name
    params['original_command'] = command_name
    params['csrf_token'] = get_csrf_token()
    params['modifiers'] = modifiers

    return render('new_command.html', **params)
Ejemplo n.º 17
0
def user_login():
    if current_user.is_authenticated:
        return redirect(url_for('user_show'))
    form = LoginForm()
    if not form.validate_on_submit():
        return render_template('login.html', form=form, testing=app.testing)
    else:
        username = form.username.data
        password = form.password.data
        user = User.validate(username, password)
        if user is None:
            crx_flash('BAD_USERNAME_OR_PWD')
            return render_template('login.html',
                                   form=form,
                                   testing=app.testing)
        else:
            login_user(user, remember=False)
            crx_flash('WELCOME_BACK', user.username)
            next = request.args.get('next')
            if next is not None and is_safe_url(request, next):
                return redirect(next)
            else:
                return redirect(url_for('user_show'))
Ejemplo n.º 18
0
def new_command(command_name=None):
    assert_user_signed_in()

    params = {}
    if command_name != None:
        user = get_current_user()
        if user.commands.get(command_name) != None:
            return redirect(EDIT_COMMAND_ONLY + command_name)
        params['name'] = command_name

    if request.method == 'POST':
        params = get_params(request.form)
        try:
            save_command(**params)
            return redirect(COMMANDS)
        except ParamException as e:
            params['error'] = e.message

    params['action'] = NEW_COMMAND_ONLY
    params['csrf_token'] = get_csrf_token()
    params['modifiers'] = modifiers

    return render('new_command.html', **params)
Ejemplo n.º 19
0
def on_edit(request, page_name):
    """Edit the current revision of a page."""
    change_note = error = ''
    revision = Revision.query.filter(
        (Page.name == page_name) &
        (Page.page_id == Revision.page_id)
    ).order_by(Revision.revision_id.desc()).first()
    if revision is None:
        page = None
    else:
        page = revision.page

    if request.method == 'POST':
        text = request.form.get('text')
        if request.form.get('cancel') or \
           revision and revision.text == text:
            return redirect(href(page.name))
        elif not text:
            error = 'You cannot save empty revisions.'
        else:
            change_note = request.form.get('change_note', '')
            if page is None:
                page = Page(page_name)
                session.add(page)
            session.add(Revision(page, text, change_note))
            session.commit()
            return redirect(href(page.name))

    return Response(generate_template('action_edit.html',
        revision=revision,
        page=page,
        new=page is None,
        page_name=page_name,
        change_note=change_note,
        error=error
    ))
def candidate(identifier):
    program = Program.get_by_id(identifier)
    if program is None or not program.is_published:
        return redirect(url_for('index'))

    programs_broken_by_current_user = None
    if current_user and current_user.is_authenticated:
        wb_breaks_by_current_user = WhiteboxBreak.get_all_by_user(current_user)
        programs_broken_by_current_user = [
            wb_break.program for wb_break in wb_breaks_by_current_user
        ]
    # If we reach this point, we can show the source code
    return render_template(
        'candidate.html',
        program=program,
        programs_broken_by_current_user=programs_broken_by_current_user,
    )
Ejemplo n.º 21
0
def break_candidate(identifier):
    now = int(time.time())
    if now < app.config['STARTING_DATE']:
        crx_flash('BEFORE_STARTING_DATE')
        return redirect(url_for('index'))
    if now > app.config['FINAL_DEADLINE']:
        crx_flash('EXCEED_DEADLINE')
        return render_template('break_candidate_deadline_exceeded.html',
                               final_deadline=format_timestamp(
                                   app.config['FINAL_DEADLINE']))

    # Only published programs can be broken
    program = Program.get_unbroken_or_broken_by_id(identifier)
    if program is None or not program.is_published:
        return redirect(url_for('index'))

    # If the current user is the one who submitted the program, redirect to index
    if program.user == current_user:
        crx_flash('CANNOT_BREAK_OWN')
        return redirect(url_for('index'))

    # A user cannot break the same challenge twice
    wb_break = WhiteboxBreak.get(current_user, program)
    if wb_break is not None:
        crx_flash('CANNOT_BREAK_TWICE')
        return redirect(url_for('index'))

    form = WhiteboxBreakForm()
    if request.method != 'POST' or not form.validate_on_submit():
        return render_template('break_candidate.html',
                               form=form,
                               strawberries=program.strawberries_last,
                               identifier=identifier,
                               testing=app.testing)

    submitted_prikey = form.prikey.data

    if program.pubkey is None:
        return redirect(url_for('index'))

    if validate_private_key(submitted_prikey, program.pubkey):
        app.logger.info(f"Implementation is broken at {now}")
        program.set_status_to_broken(current_user, now)
        db.session.commit()

        return redirect(url_for('break_candidate_ok', identifier=identifier))
    else:
        app.logger.info("Invalid private key")
        return render_template('challenge_break_ko.html',
                               identifier=identifier,
                               current_user=current_user,
                               submitted_prikey=submitted_prikey,
                               pubkey=program.pubkey)
def show_candidate_sample(identifier):
    program = Program.get_by_id(identifier)
    if program is None or not program.is_published:
        return redirect(url_for('index'))

    number_of_test_vectors = int(len(program.hashes) / 32)
    test_vectors = list()
    for i in range(number_of_test_vectors):
        test_vectors.append({
            "hash":
            program.hashes[i * 32:(i + 1) * 32].hex().upper(),
            "signature":
            program.signatures[i * 64:(i + 1) * 64].hex().upper()
        })

    res = {
        "id": program._id,
        "public_key": program.pubkey,
        "proof_of_knowledge": program.proof_of_knowledge,
        "test_vectors": test_vectors
    }
    return jsonify(res)
Ejemplo n.º 23
0
def oauth_callback(service):
    assert_user_signed_out()

    s = oauth_services.get(service)
    if s == None:
        return redirect(SIGN_IN)

    token = None
    if s.name == 'twitter':
        oauth_token = request.args.get('oauth_token', '')
        oauth_verifier = request.args.get('oauth_verifier', '')
        token = s.getAccessToken(oauth_token, oauth_verifier)
        if token == None:
            return redirect(SIGN_IN)
    else:
        state = request.args.get('state', '')
        code = request.args.get('code', '')
        if not verify_oauth_state(state):
            return redirect(SIGN_IN)
        token = s.getAccessToken(state, code)
        if token == None:
            return redirect(SIGN_IN)

    user_id = s.getUserID(token)
    if user_id == None:
        return redirect(SIGN_IN)

    username = '******' % (service, user_id)
    user = User.fromUsername(username)
    if user == None:
        user = User(
            service=service,
            username=username,
            commands=Commands(),
        )
        user.put()
    user_key = user.key.urlsafe()

    route = COMMANDS
    if user.commands.size() == 0:
        route = PICK_COMMANDS

    set_current_user_key(user_key)
    return redirect(route)
Ejemplo n.º 24
0
def logout(request):
    logout_user(request)
    return redirect('index')
Ejemplo n.º 25
0
def logout(request):
    logout_user(request)
    return redirect('index')
Ejemplo n.º 26
0
def sign_out():
    assert_user_signed_in()

    set_current_user_key(None)
    return redirect(HOME)
Ejemplo n.º 27
0
def submit_candidate_ok():
    """ This route is called directly when the user has js activated (see file-progress.js)"""
    crx_flash('CHALLENGE_SUBMITTED')
    return redirect(url_for('user_show'))
Ejemplo n.º 28
0
def logout():
    logout_user()
    crx_flash('LOGOUT')
    return redirect(url_for('index'))
Ejemplo n.º 29
0
def make_soup(url):
    url = redirect(url)
    page = requests.get(url)
    return bs4.BeautifulSoup(page.text, "lxml")
Ejemplo n.º 30
0
def unauthorized_handler():
    crx_flash('PLEASE_SIGN_IN')
    try:
        return redirect(url_for('user_login', next=url_for(request.endpoint)))
    except:
        return redirect(url_for('index'))