Ejemplo n.º 1
0
def upload(request):
    c = {}
    c.update(csrf(request))
    if request.method == 'POST':
        form = forms.UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'], request.POST['name'])
            return HttpResponseRedirect('/top/')
        else:
            folder = ""
            if(request.GET.has_key('folder')):
                folder = request.GET['folder']
            c['form'] = form
            c['folder'] = folder
            return render_to_response('test1/upload.html', c)

    else:
        print c
        form = forms.UploadFileForm()
        folder = ""
        if(request.GET.has_key('folder')):
            folder = request.GET['folder']
        print form
        c['form'] = form
        c['folder'] = folder
        return render_to_response('test1/upload.html', c)
Ejemplo n.º 2
0
def plugin(request, *kw, **kwargs):
    if request.method == 'GET':
        form = forms.UploadFileForm()
        return django.shortcuts.render(request, 'bots/plugin.html',
                                       {'form': form})
    else:
        if 'submit' in request.POST:  #coming from ViewIncoming, go to outgoing form using same criteria
            form = forms.UploadFileForm(request.POST, request.FILES)
            if form.is_valid():
                #write backup plugin first
                plugout_backup_core(request, *kw, **kwargs)
                #read the plugin
                try:
                    if pluglib.read_plugin(
                            request.FILES['file'].temporary_file_path()):
                        messages.add_message(request, messages.INFO,
                                             _(u'Overwritten existing files.'))
                except Exception as msg:
                    notification = -(u'Error reading plugin: "%s".') % unicode(
                        msg)
                    botsglobal.logger.error(notification)
                    messages.add_message(request, messages.INFO, notification)
                else:
                    notification = _(u'Plugin "%s" is read successful.'
                                     ) % request.FILES['file'].name
                    botsglobal.logger.info(notification)
                    messages.add_message(request, messages.INFO, notification)
                finally:
                    request.FILES['file'].close(
                    )  #seems to be needed according to django docs.
            else:
                messages.add_message(request, messages.INFO,
                                     _(u'No plugin read.'))
        return django.shortcuts.redirect('/home')
Ejemplo n.º 3
0
def plugin(request, *kw, **kwargs):
    if request.method == 'GET':
        form = forms.UploadFileForm()
        return django.shortcuts.render_to_response(
            'bots/plugin.html', {'form': form},
            context_instance=django.template.RequestContext(request))
    else:
        if 'submit' in request.POST:  #coming from ViewIncoming, go to outgoing form using same criteria
            form = forms.UploadFileForm(request.POST, request.FILES)
            if form.is_valid():
                botsglobal.logger.info(_(u'Start reading plugin "%s".'),
                                       request.FILES['file'].name)
                try:
                    if pluglib.load(
                            request.FILES['file'].temporary_file_path()):
                        request.user.message_set.create(
                            message='Renamed existing files.')
                except botslib.PluginError, txt:
                    botsglobal.logger.info(u'%s', str(txt))
                    request.user.message_set.create(message='%s' % txt)
                else:
                    botsglobal.logger.info(_(u'Plugin "%s" read succesful.'),
                                           request.FILES['file'].name)
                    request.user.message_set.create(
                        message='Plugin %s read succesful.' %
                        request.FILES['file'].name)
                request.FILES['file'].close()
            else:
                request.user.message_set.create(message=_(u'No plugin read.'))
        return django.shortcuts.redirect('/')
Ejemplo n.º 4
0
def new_file(request, bulletin_id):
    user = request.user
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('existing_user'), {
                'logged_in': False,
                'form': forms.LoginForm(),
                })

    incorrect_password = False

    if request.method == 'POST':
        form = forms.UploadFileForm(request.POST, request.FILES)

        if form.is_valid():
            password = request.POST['encrypt']

            if password != '':
                r, c, iv, encryption_key = get_encryption_params(password, str(user.userkeys.rand), str(user.userkeys.check), user.userkeys.encryption_params)

                if r == c:
                    AES.new(encryption_key, AES.MODE_CFB, iv).decrypt(urlsafe_b64decode(str(user.userkeys.private_key)))

                    handle_new_file(user, request.FILES['file'], bulletin_id, password)
                    folder = Folder.objects.get(bulletin = bulletin_id)
                    return HttpResponseRedirect(reverse('get_bulletin', args=(bulletin_id,)), {
                            'bulletin_id': bulletin_id,
                            'logged_in': user.is_authenticated(),
                            'folder': folder,
                            'folder_id': folder.pk,
                            'bulletin': get_object_or_404(Bulletin, pk = bulletin_id),
                            })
                else:
                    incorrect_password = True

            else:
                handle_new_file(user, request.FILES['file'], bulletin_id, None)
                folder = Folder.objects.get(bulletin = bulletin_id)
                return HttpResponseRedirect(reverse('get_bulletin', args=(bulletin_id,)), {
                        'bulletin_id': bulletin_id,
                        'logged_in': user.is_authenticated(),
                        'folder': folder,
                        'folder_id': folder.pk,
                        'bulletin': get_object_or_404(Bulletin, pk = bulletin_id),
                        })

    else:
        form = forms.UploadFileForm()
    return render(request, 'secure_witness/upload.html', {
            'form': form,
            'user': user,
            'bulletin': get_object_or_404(Bulletin, pk = bulletin_id),
            'bulletin_id': bulletin_id,
            'folder': Folder.objects.get(bulletin = bulletin_id),
            'folder_id': Folder.objects.get(bulletin = bulletin_id).pk,
            'logged_in': user.is_authenticated(),
            'incorrect_password': incorrect_password,
            })
Ejemplo n.º 5
0
def upload_points(request):
    if request.method == 'POST':
        form = forms.UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            file_content = request.FILES['file'].read()
            counter = handle_file(file_content)
            message = u'Из файла успешно добавлено строчек: %d' % counter
            return render_to_response("admin/upload_points.html", {'message': message})
    else:
        form = forms.UploadFileForm()
    return render_to_response("admin/upload_points.html", {'form': form})
def workshop_files(workshop_id):
    form = forms.UploadFileForm(CombinedMultiDict(
        (request.files, request.form)),
                                csrf_enabled=False)
    if form.validate_on_submit():
        f = form.upload.data
        print(f.filename)
        filename = secure_filename(f.filename)
        base_dir = "static/files/{}".format(workshop_id)
        if not os.path.exists(base_dir):
            os.makedirs(base_dir)
        file_path = "{}/{}".format(base_dir, filename)
        if not os.path.isfile(file_path):
            f.save(file_path)
            if request.form['file_title']:
                file_title = request.form['file_title']
            else:
                file_title = secure_filename(f.filename)
            database.add_workshop_file(file_title, file_path,
                                       request.form['file_permission'],
                                       workshop_id)
            flash("File upload successful.", "success")
        else:
            flash("Failed to upload - File of same name already exists.",
                  "danger")
        return redirect(
            url_for('admin_routes.workshop_files', workshop_id=workshop_id))

    workshop = database.get_workshop_from_workshop_id(workshop_id)
    return render_template("admin/workshop_files.html",
                           workshop=workshop,
                           form=form)
Ejemplo n.º 7
0
def workshop_details(workshop_id):
    file_form = forms.UploadFileForm(CombinedMultiDict((request.files, request.form)))
    if file_form.validate_on_submit():
        f = file_form.upload.data
        print(f.filename)
        filename = secure_filename(f.filename)
        base_dir = "static/files/{}".format(workshop_id)
        if not os.path.exists(base_dir):
            os.makedirs(base_dir)
        file_path = "{}/{}".format(base_dir, filename)
        if not os.path.isfile(file_path):
            f.save(file_path)
            if request.form['file_title']:
                file_title = request.form['file_title']
            else:
                file_title = secure_filename(f.filename)
            database.add_workshop_file(file_title, file_path, request.form['file_permission'], workshop_id)
            flash("File upload successful.", "success")
        else:
            flash("Failed to upload - File of same name already exists.", "danger")
        return redirect(url_for('admin_routes.workshop_details', workshop_id=workshop_id))

    equipment_form = forms.EquipmentAddToWorkshopForm()
    if equipment_form.validate_on_submit():
        equipment_id = int(request.form['equipment_name'])
        equipment_quantity = int(request.form['equipment_quantity_needed'])
        per_attendee = False
        if request.form['per_attendee'] == "True": per_attendee = True
        database.add_equipment_to_workshop(equipment_id, workshop_id, equipment_quantity, per_attendee)

    workshop = database.get_workshop_from_workshop_id(workshop_id)
    return render_template("admin/workshop_details.html", workshop=workshop, file_form=file_form, equipment_form=equipment_form, equipments=database.get_all_equipment_for_workshop(workshop_id))
Ejemplo n.º 8
0
def index():
    form = forms.UploadFileForm()
    data = {}
    if form.validate_on_submit():
        data = import_file_content(request.form["balance_date"],
                                   request.files["file"])
        if data["upload_result"] == 'Success':
            report = make_report(data['uploaded_file_name'],
                                 data["balance_date"])
            data["report_result"] = report['report_result']
            data["report_result_msg"] = report['report_result_msg']
            data["report_directory"] = report['directory']
            data["report_filename"] = report['filename']
    return render_template('index.html', form=form, data=data)
Ejemplo n.º 9
0
def number():
    """Render add number/ add by file page."""

    add_number_form = forms.AddNumberForm()
    upload_file_form = forms.UploadFileForm()

    if add_number_form.validate_on_submit():
        normalized_number = utils.normalize_number(add_number_form.number.data)
        try:
            number_repo.create_one(number=normalized_number,
                                   subscription_id=int(
                                       add_number_form.subscription.data))
            flash('Number added!', 'success')
        except DuplicateError as e:
            print e
            flash('Number already exists!', 'error')
            pass

        # reset form
        add_number_form.number.data = None
        add_number_form.subscription.data = '1'

    if upload_file_form.validate_on_submit():
        f = upload_file_form.number_file.data
        subscription_id = int(upload_file_form.subscription.data)
        extension = os.path.splitext(f.filename)[1]

        if extension == '.csv':
            numbers = utils.read_from_csv_file(f)
        elif extension == '.txt':
            numbers = utils.read_from_txt_file(f)

        for num in numbers:
            try:
                number_repo.create_one(number=num,
                                       subscription_id=subscription_id)
            except DuplicateError as e:
                flash(
                    'Number {number} already exists!'.format(number=e.number),
                    'error')
                print e
                pass

        flash('Numbers added!', 'success')

    return render_template('number.html',
                           add_number_form=add_number_form,
                           upload_file_form=upload_file_form)